Hide your ASSets the Python way

Posted in Uncategorized with tags , , , , , , on November 5, 2011 by Tech B.

Some of you may have seen the “trick” of using the command prompt to hide archives in images. Example: “C:>copy /b image1.jpg + stuff.zip newimage.jpg” This will hide stuff.zip in the picture image.jpg and output the merged file as newimage.jpg

As far as I know, this only works with jpeg’s. That’s cool and all, but how does it do that? And how can I do the same with python?

Well, it works by opening each file as it’s binary state and merges the two binaries into one. To view the image, just open it like normal. To view the archive, open it with an archive viewer like 7zip.

Now that we know how it works, lets try and do the same with python.

#open the image a=append, b=open as binary
image = open("test.jpg", "ab")

#open the archive as a binary
archive = open("test.zip","rb")

#write the archive data after a newline
#to our image
image.write("\n"+archive.read())

#close handles
image.close()
archive.close()

As you can see, it only took 5 lines of code. You can view the image as a regular image, or open as a zip file. Alliteratively, you could os.popen() or os.system() with the cmd version as well, but I like to do things the python way.

Short, sweet, and to the point.

Brute Forcing And Word List Attack Vector

Posted in Uncategorized with tags , , , , , , , , , , , , , , , on October 29, 2011 by Tech B.

So in my last post I mentioned brute forcing. I was going to add a password brute force function to try and get into a access point. Well, android doesn’t support the iwconfig command even rooted, so that would be have to be done in java (C++ if using the NDK). Even though I do develop Android apps, my focus here on my blog is in python.

As promised, I am going to go over brute forcing. What is brute forcing? It is when you try every combination of letters and numbers as a password. By doing this, you can break %100 of all passwords. There is a catch though. It can take a very long time and use exponential amounts of computing power. Brute forcing technical term would be permutation of combinations. You can find the background and technical stuff here and here.

What’s the difference between permutations and combinations? Well, a combination will give you every possible way you can group letters and numbers, but it also needs to know how many different combos you want to try. You can group 4 letters into 2′s or 3′s or 4′s. Example 3′s: abcd-> abc, abd, acd, bcd.

What if we needed all the letters in every order they could be in? This is where permutations come in. We need permutations of the combinations in order to get every single last way we could order, combine, and use the letters ever. Example of permutations of abcd with out the combinations: abcd, abdc, adbc, dabc, etc….

You might be thinking, it looks like permutations already does all the possible letter combinations. Well, yes it does, but that is if we have a fixed length of letters, and only 4 different letters to work with. Permutations of abcd isn’t going to contain z or x in it, nor will it give you just 2 combinations of all the letters. This is why we need to do permutation of ever combination we can.

Below is a script that will generate a word list with the supplied characters you give it, and a max length of combinations to try. When I say max length, I mean it will start combining letters from a group of two and work its way up to the max value specified. I.E. abcd-> ab, ac, ad, …. cba, adc, adb, …. dcba, acbd, cbda, etc… Be warned though, the list will grow very quick with large values. On my system 4Gb RAM, Dual Core 2GH each, 64bit Windows 7 it took 30 minutes to generate a text file of  15Gb, and still was not finished generating the list. I was of course trying to do a list of all the letters of the alphabet(lower case) with a length of 7 characters long. I started out by putting all the words into a list instead of writing to a file, but that raped my memory and would crash every time around 3.7Gb of memory being used. The garbage collector would not keep up, even with the forcing of deleting objects on my part.

So before you get too bored reading this here is the script:

import itertools, sys
def combList(charString, maxLength):
    """Genorate inital word list. This is just diff combinations"""
    #var to keepmtrack of how many times we've been through the loop
    times = 0
    #list to hold combinations
    poss = []
    for iteration in range(maxLength):
        #Use try statment to make sure the max length isn't longer
        #than the characters we're going to use
        try:
            #Iter genorator for combos
            comb = itertools.combinations(charString,times+1)
        except ValueError:
            print "Character string larger than max lenght\nplease try again"
            sys.exit()

        #Genorator gives tuple with seporated values ex: ('w','o','r','d')
        for word in comb:
            #join tupe as string and add to list
            s = ''.join(word)
            poss.append(s)
        times += 1

    return poss

def permList(combinations):
    """Genorates permutations of the genorated combonation list"""
    #going to write ultimate list to a file
    #if not, you can run into virtual memory errors if the list gets above 4Gb
    f = open("wordlist.txt","w")
    #var to hold how many words we have
    x = 0
    for word in combinations:
        #loop through combonations and genorate a list of all
        #possable ways to combine letters
        permutation = itertools.permutations(word)
        for permWord in permutation:
            f.write(''.join(permWord)+"\n")
            x += 1
        #del used permutation to free up some memory
        #not so much needed, but this script will rape memory if
		#appending to a list insteady of writing to a file
        del permutation
    #always close file handles
    f.close()
    return x

def main():
    """Main program, gets user info and computes the lists"""
    ch = raw_input("characters to try: ")
    num = input("max length: ")
    combo = combList(ch,num)
    print "list genorated"
    print "doing wordlist now"
    permTotal = permList(combo)
    f = open("wordlist.txt","r")
    print "working..."
    for i in range(permTotal+1):
        word = f.readline().strip()
        #This is where you would be doing the actule brute forcing
        #you could try and log into a website or crack a password protected
        #zip file, genorate md5's and crack a password dump
        #if linux, brute force WPA wifi with iwconfig
        #and any thing else you might need for a password
        print word
    f.close()
    print "done\n"
    raw_input(".....")

main()

Some issues with this method are that it is VERY processor heavy. Yeah it can be done on the GPU like hashcat, but the straight brute force is unreasonable. Other faults include the more characters you try, such as 8-10 password lengths, the longer it will take. Not to mention if the password is cAMel CaSeD and uses $p3c@l characters. That increases processing load 50 fold or more and will gangbang your memory.

A better option would be to generate a “tailored” wordlist. Like one full of birthdays, and 1337 speak. Other methods could be to gather information first, like crawling face book for significant names, dates, cars, hobbies and the like. People are very bad about choosing something easy to remember, like their favorite sports team followed by their favorite players jersey number or something.

The best method I have seen was at Hack3rcon in my home town last year. PureHate gave the lecture and was using hashcat and custom rule-sets to break hundreds of md5′s in 20 minuets. The video is posted at irongeek.com, but I will embed the vide from vimeo here.

Well, I hope you guys learned something. It was a lot of fun writing the script and figuring out how brute forcing works myself. I might extend the program and give it rules and turn it into something other than a teaching tool, but meh we’ll see.

Any way, thanks for reading and enjoy the video.

Android ASE: WiFi Scan with UI

Posted in Uncategorized with tags , , , , , , , , , , , on September 1, 2011 by Tech B.

Playing more with the Android Scripting Environment, I wrote a simple script to display any access points in wifi range. Once you select an SSID, it will display some basic info on that AP, such as the MAC address and encryption type. If you have a rooted phone, you could theoretically brute force an APs password using *nix iwconfig commands. The next post I will show some quick and dirty code to brute force passwords. But for now here is the script for some UI WiFi scanning.

#imports and get an object of android
import android, time
droid = android.Android()

#scan the wifi and assign vars to hold the results
#this is dirty, making sure WiFi is on, and
#toggling on if not would be better; API Browser =)
droid.wifiStartScan()
ap = droid.wifiGetScanResults()
aps = ap.result

#lists to hold the data from scan
x = []
o = []

#loop through results and grab the data we are interested in
#format the strings to be displayed in the UI
for point in aps:
  x.append(point["ssid"])
  #capabilities are the encryption, if blank there is no encryption
  if point["capabilities"] == "":
    o.append("MAC: "+point["bssid"]+"\nFreq: "+str(point["frequency"])+"\nEencryp: [OPEN]")
  else:
    o.append("MAC: "+point["bssid"]+"\nFreq: "+str(point["frequency"])+"\nEencryp: "+point["capabilities"])

#set up UI dialog, populate, and present
droid.dialogCreateAlert("WiFi Scan", None)
droid.dialogSetItems(x)
droid.dialogShow()
#this grabs what the user has selected
result = droid.dialogGetResponse().result

#if selection not null, create new UI, populate, and present
if result.has_key("item"):
  item = result["item"]
  droid.dialogCreateAlert("Basic Info", o[item])
  droid.dialogShow()

=-=-=-EDIT-=-=-=

I just rooted my phone and turns out android doesn’t have iwconfig. They use the stack some how; didn’t find a whole lot of info on it. So no bruteforcing via the terminal… I am going to look into some other method. Anyway, I’ll at least post some code going over permutations.

Android Twisted SpyCam

Posted in Uncategorized with tags , , , , , , , , , , , , , on August 31, 2011 by Tech B.

I have been playing around with Androids ASE(android scripting environment). ASE allows you to run scripts on your android powered device. You can use Python, PHP, Javascript, Pearl, Ruby and much more. To install ASE on your device you must either have root, allow third party apps install,, or know how to sideload apk’s using android’s SDK tools like adb.

You can find the apk along with install instructions and more info on ASE at their website.

Here is an example of using python as a remote spycam. I am using the Twisted Framework as the server, and it gets interesting because I embed the captured image from the phone as base64 data on the webpage Twisted is serving up. You can choose to install the Twisted libs when you install python on your device. This is a fairly new feature.

To learn more about twisted, you can visit their website.

import android, os, base64
from twisted.internet import protocol, reactor

droid = android.Android()
os.chdir('/sdcard/webserver/')

def imgb64():
  droid.cameraCapturePicture('/sdcard/webserver/latest.jpg', True)
  im = open("latest.jpg","rb")
  ime = base64.b64encode(im.read())
  im.close()
  os.remove("latest.jpg")
  return ime

class ServeImage(protocol.Protocol):
  def connectionMade(self):
    data = imgb64()
    self.transport.write("""<html><head><title>Android Camera</title></head><body><img src="data:image/jpg;base64,%s" alt="image"/>test</body></html>""" % data)
    self.transport.loseConnection()

class ServeImageFactory(protocol.ServerFactory):
  protocol = ServeImage

reactor.listenTCP(8080, ServeImageFactory())
reactor.run()

More Fun With MindFlex

Posted in Uncategorized with tags , , , , , , , , , , , , , , on March 8, 2011 by Tech B.

Last Fire Bender

After my last article, I was thinking it wasn’t impressive enough. Sure, lighting a match that is on the computer screen is cool and all, but what if it where a real flame.

In fear of catching my house on fire, or blowing off an appendage or two, I decided to go small scale for the moment. I needed something with a controllable flame and was small enough to use inside. So I decided on using an adjustable lighter.

The MindFlex hardware portion will not be covered, you can read my last post to get that going.

The new stuff consists of hacking the lighter. I dissembled the lighter and took the swing arm off and super-glued a broke off clip to a ballpoint pen. I poked a hole through the end of the clip so I could fit a paperclip in it. Next was to attach another clip to the servo. After I had both pieces sturdy enough for use, I was off to find a base to put them in. I ended up with a cylinder shaped packaging that was holding some paperclips. I cut a square big enough to fit the servo in, and taped the lighter to the outside of the base. Next I fitted a paperclip on both clips so the servo could controlled the lighters flame adjuster. Pictures below:

Base Of Unit

Base Unit Front View

I have to manually hold the lighter on. Although, adding a riser or jamming something in it to keep it on wouldn’t be to hard.  You can also adjust the max height of the flame by lifting the adjuster arm up off the gear and turn it up.

The code is pretty simple, just a miner adjustment to the SerialOut example from Eric Mika.

// Arduino Brain Library
// Eric Mika, 2010
// Edit by Tech B. to interface with a lighter, 2011

#include <Brain.h>
#include <Servo.h>
Servo myservo;

int pos;
int servoMap;
int atten;
// Set up the brain parser, pass it the hardware serial object you want to listen on.
Brain brain(Serial);

void setup() {
   // Start the hardware serial.
   Serial.begin(9600);
   // data pin to servo
   myservo.attach(13);
}

void loop() {
   // Expect packets about once per second.
   // I played around to find the max and min servo values
   if (brain.update()) {
       atten = brain.readAttention();
       // Map atten to angle of servo horn
       servoMap = map(atten, 0, 100, 150, 70);
       myservo.write(servoMap);
   }
}

It is interesting to play with this. The hard part of this whole project is making your mind do what you want. It varies person to person on the responsiveness.  For example, my wife keeps a steady meditative state and finds it hard to bring focus up; while I seem to keep a low focus and a steady mid attentive level .  I would be interested to see the results on some one who is ADD or ADHD, and compare the data to some one who is a monk, or practices meditation on a religious routine.

Here is a quick demo of me controlling the lighter:

Fun With MindFlex

Posted in Uncategorized with tags , , , , , , , , , , , on March 5, 2011 by Tech B.

For this valentines day, my wife got me a MindFlex from Mattel. I have been wanting one of these since they have been on the market. It is a really interesting game where you control a foam ball with your mind. The ball will rise with the more focused you are. Letting your mind wonder and as Morphius likes to say “free your mind”, the ball will lower.

MindFlex doesn’t read your thoughts, rather it picks up on level of activity. There has been fuss about the legitimacy of how this thing works. The popular video of it being placed on a foam head with a damp cloth gives readings. If you would do the same with a medical grade EEG, you would receive random values.

MindFlex uses a NeuroSky chip to compute the brain data. You can have 8 channels of raw wave activity:

Along with connection quality, and the proprietary attention and meditation values.

Inspired by Eric Mika’s post, I set out to replicate and extend his project. He wrote a library to get the data using an Arduino. He also wrote graphic software to aid in the visuals of the activity in your mind.  Eric go’s into better detail about the data the chip gives off. He has a video about the hardware hack, and it is very informative.

Basically, you need a shared ground and a wire extending the Tx pin for the NeuroSky chip circuit. Using images from this teardown of the MindFlex I point out which pins they are. This is in the left pod of the headset:

Ground

Tx Pin

I have affixed the Arduino to the headset using Velcro, opposed to zip ties. Also I have noticed it is better for the usb port to be facing the back of the head when you wear it. This keeps the cords away from your face. Here are some pictures of the finished mod:

Top View

Front View

My Inspector Mazy, she aproves.

After copying the BrainLibrary into the Arduinos lib, I loaded the BrainSerialOut example that came with the library, I immediately  got python reading from the COM port. The data comes as a string containing 11 values: signal strength, attention, meditation, delta, theta, low alpha, high alpha, low beta, high beta, low gamma, high gamma.

When the signal strength is at 0 it is at its strongest. The next two values are the ones I am interested in. If the signal strength isn’t strong enough, you will not get the attention or meditative values.

The next step on my list was to make this data available to what ever can handle sockets like Blender, Android, Iphone, and I think Flash can even handle sockets.

I wrote a server in Python2.6 to forward the data to any connection. It takes the headset a few seconds to give good data. I have also noticed, the connection signal can be finicky.

import serial, sys, socket

s = serial.Serial('COM8')

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('',1002))

while 1:
 sock.listen(5)
 conn, addr = sock.accept()
 while 1:
     try:
         sread = s.readline()
         conn.send(sread)
     except:
         print "connection at %s lost" % addr
         break

Next was to write a quick game using my new toy. I chose PyGame because it was easy to get going quickly. I plan to switch to 3d when I have the time for it. The game uses the attention value to light a match. There is also a bar on the left side representing the activity in the users mind. Future work includes snuffing the flame with meditative values.

New Years Ball Drop Replica

Posted in Uncategorized with tags , , , , , , , on January 18, 2011 by Tech B.

I was asked to build a replica ball drop for a friend. I had 3 days to get this thing working. It was a fun build, and took a lot of headaches to get it setup. In the end it worked out great.

The ball itself is a Christmas ornament that has been cut in half and stuffed with 14 LEDs, a 9V and a switch. I hot glued the thing back together and cut a hole in the bottom for the rod to come through. My wife decorated it for me; she also decorated the building.

Parts used:

  • Christmas ornament
  • Pill bottle (base of rod)
  • 2 boxes
  • Spent soldier spool
  • Plastic clothes hanger (rod)
  • Yarn
  • Paperclip
  • Arduino
  • LCD shield (key pad)
  • LED’s
  • Components for relay circuit
  • Paint
  • Glitter
  • Tiny mirrors
  • Servo (mod for continues rotation)

The next thing was to make it go down the rod. There is several ways of doing this, the best in my opinion to use a screw like device and have the ball mounted on it for the linear motion. But I did not have the supplies or money for that. So I used a moded servo for a pulley type system.

I took a spent soldier spool and glued it to the horn of the servo. That’s where the yarn is tied. The yarn goes up the rod, through a looped paperclip and attached to the ball. When the servo “unwinds” the spool, the ball is lowered.

Besides the arduino and LCD shield, there is a circuit to control the servo. It is a simple 5V regulated relay transistor setup. I used the same schematics as the IRC controlled air freshener.

The trickiest part of the build was to lower the ball at a timed rate and have it hit the bottom on count 0. It took some trial and error with delay times in the code, but it worked out nicely.

<pre>
<pre>
//up == 130
//down == 306
//right == 0
//left == 480
#include <Servo.h>
#include <LCD4Bit_mod.h>
#include <stdlib.h>

Servo myservo;  // servo object
LCD4Bit_mod lcd = LCD4Bit_mod(2);

int key_in;

void setup()
{
 Serial.begin(9600);
 lcd.init();
 lcd.printIn(" Time Square    ");
 lcd.cursorTo(2,0);
 lcd.printIn("  New Years Eve ");
 myservo.attach(12);
 pinMode(3, OUTPUT);
 digitalWrite(3,HIGH);
}

void loop()
{
 lcd.cursorTo(1,0);
 key_in = analogRead(0);
 if (key_in == 0){
 lcd.clear();
 myservo.write(90);
 digitalWrite(3, LOW);
 lcd.printIn("Coming Down");
 key_in = 0;
 }

 else if (key_in == 480){
  lcd.clear();
  lcd.printIn("Going Up");
  myservo.write(0);
  digitalWrite(3,LOW);
  key_in = 0;
 }

 else if (key_in == 306){
  lcd.clear();
  lcd.printIn("Count Down Start");
  delay(3000);
  lcd.clear();
  lcd.printIn("***1:00***");
  delay(1000);
  count_down();
 }

 else {
  digitalWrite(3,HIGH);
 }

}

void count_down(){
 myservo.write(90);
 for (int i=59; i>0; i--){
  lcd.clear();
  char count [21];
  char* r;
  r = itoa(i,count,10);
  lcd.printIn("*****");
  lcd.printIn(r);
  lcd.printIn("*****");
  if (i <= 10){
   digitalWrite(3,LOW);
   delay(130);
   digitalWrite(3,HIGH);
   delay(870);
   continue;
   }
  delay(1000);

 }
 lcd.clear();
 lcd.printIn("      2011      ");
 delay(5000);
 lcd.clear();
 lcd.printIn("Happy New Year!!");
 lcd.cursorTo(2,0);
 lcd.printIn("_,~*`~2011~*`~,_");
 }

Android on IRC

Posted in Uncategorized with tags , , , , , , , , , , , , , , , on October 29, 2010 by Tech B.

I recently gave a lecture on DDoS in my Network OS class. I demonstrated a simple bot on the computers in the class. I also demonstrated how portable devices are capable of running bots as well.

I used Android Scripting Environment (ASE) for the demo. The commands I gave it where text, call, speak aloud, and vibrate. The only draw back ASE has is no real GUI support. I can’t wait for the day when OpenGL ES is ported to python. Anyway, ASE allows access to almost all of the phones featurtes. Here is a link to the API ref: http://code.google.com/p/android-scripting/wiki/ApiReference


#-------------------------------------------------------------------------------
# Name:        AndroidIRC
# Purpose:     Android based IRC bot
#
# Author:      K.B. Carte (techb)
#
# Created:     10/26/2010
#
# Copyright:   (c) K.B. Carte (techb) 2010
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import socket, string, time, os, sys, android
droid = android.Android()
os.chdir(&quot;sdcard&quot;)

droid.makeToast(&quot;AndroidBot Started&quot;)
droid.vibrate(300)

chan = 'AndroidBot'
ircsite = 'irc.freenode.net'
port = 6667

irc = socket.socket()
irc.connect((ircsite, port))
n = 'AndroidBotV1'
irc.send('NICK %s\r\n' %  n)
irc.send(&quot;USER %s %s bla :%s\r\n&quot; % (&quot;Ohlook&quot;, 'itsnotmy', 'Realname'))
time.sleep(4)
irc.send(&quot;JOIN #%s\r\n&quot; % chan)

readbuffer = ''
while True:
    readbuffer= irc.recv(1024)
    temp=string.split(readbuffer, &quot;\n&quot;)
    Check = readbuffer.split(':')
    print readbuffer

    if 'PING' in readbuffer:
        &quot;&quot;&quot;PIN/PONG connection echo response&quot;&quot;&quot;
        irc.send(&quot;PONG :%s&quot; % Check[1])

    if 'JOIN' in readbuffer:
        &quot;&quot;&quot;Greet people that join the channel&quot;&quot;&quot;
        na = Check[1].split('!')
        irc.send(&quot;PRIVMSG #%s :Hello %s\r\n&quot; % (chan, str(na[0])))

    if '^call' in readbuffer:
        number = readbuffer.split(':')
        droid.phoneCallNumber(number[3].strip())

    if '^text' in readbuffer:
        &quot;texts the number 5 times with given message&quot;
data = readbuffer.split(&quot;:&quot;)
        number = data[3].strip()
        message = data[4].strip()
        print number, message
        cnt = 0
        while cnt &lt; 5:
            droid.smsSend(number, message)
            cnt += 1

    if '^vibe' in readbuffer:
        droid.vibrate(300)

    if '^say' in readbuffer:
        say = readbuffer.split(&quot;:&quot;)
        droid.ttsSpeak(say[3].strip()

Plasma Caster [UPDATE Sept. 24, 2010]

Posted in Uncategorized on September 21, 2010 by Tech B.

I finaly started working on a moc Plasma Caster like the one attached to the Predators shoulder.

Here are some pictures of the first setup. I plan to make changes.The range finder you see will judge the distance from my face, if I turn my head and it goes too far away, the servo will move in the direction I moved my head to get back in its original position; hence, it will follow my head looking where I look. Tilted head position will be judged from an accelerometer and mapped to the servos as well.

Later plans include:

  • Coil gun
  • Strobe light from disposable camera
  • Camera for Facial Recognition
  • Movement detection
  • Fiberglass shoulder mount
  • Bluetooth and controlled via HTC

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-[UPDATE]=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

I now have my Ping))) mapping to the servo movements. It is kinda twitchy, but it is working better than I had planned. The Ping))) is going to be mounted on the shoulder mount itself, not on the servos. This is because if it was on the servos, my face could get too close and supply outrages and false data. There is no error checking it this verson of code, it is very gritty and proves concept.

Follow

Get every new post delivered to your Inbox.