Javier's Blog

Mostly computers and other tech stuff,...

Sunday, December 05, 2010

We Won Capture the Flag

TwittBot

I got a bit bored during the SANS GIAC class so I decided to whip up a twitter bot. Nothing fancy, just a quick & dirty way to command a machine through twitter.

First, you have to register a new account which will house the application and register a new application at http://dev.twitter.com/apps once that is done, then make note of your API key, Consumer Secret, Access token and secret.

Second, get the required python packages: python-twitter & python-oauth2

hg clone http://python-twitter.googlecode.com/hg/ python-twitter
cd python-twitter/
python setup.py build
sudo python setup.py install 
git clone https://github.com/simplegeo/python-oauth2.git
cd python-oauth2/
python setup.py build
sudo python setup.py install

Third, execute the code below (python twitbot.py:

#!/usr/bin/python

import twitter, time, os

class TwitServ:
  api = None
  sleep_time=60*5
  def login(self):
    self.api = twitter.Api(consumer_key='***',
      consumer_secret='***',
      access_token_key='****',
      access_token_secret='****')

  def printFriends(self):
    friends = self.api.GetFriends()
    allfriends=''
    for f in friends:
      allfriends+=f.name + ' '
    print "All my friends are " +allfriends
    #print [u.name for u in users]
    #api.PostUpdates("I am Bot, hear me roar...")

  def getLastProcessedMsgId(self):
    f=open('lastmsgid', 'r')
    return f.readline()

  def saveLastMsgId(self, id):
    f=open('lastmsgid', 'w')
    f.write(str(id))
    f.close()

  def getLastMsg(self):
    dirmsgs=self.api.GetDirectMessages()
    print "Last message: " + dirmsgs[0].text
    return dirmsgs[0]

  # print str(lastmsg.id) + ' ' + str(lastmsgid)
  def reply(self):
    lastmsg=self.getLastMsg()
    if str(lastmsg.id) != self.getLastProcessedMsgId():
      cmd=lastmsg.text
      self.saveLastMsgId(lastmsg.id)
      result=os.popen(cmd).readlines()
      msg=""
      for i in result:
        msg+=i
      try:
        self.api.PostDirectMessage(lastmsg.sender_id, msg[:140])
        #self.api.PostUpdates(msg[:140]) # Use this if you want replies to be public
        print "Sending  messge to "+lastmsg.sender_id+": " + msg[:140]
      except twitter.TwitterError:
        print "Error sending message, possible duplicate message"
      self.saveLastMsgId(lastmsg.id)
    else:
      print "No new messages to process..."


  def serve(self):
    self.login()
    print "logged in..."
    self.printFriends()
    while True:
      self.reply()
      time.sleep(sleep_time)
    

if __name__ == "__main__":
  TwitServ().serve()


To command TwittBot simply send a direct msg to is:
d IamBot uname -a