Saturday, October 29, 2011

.exe file String extractor.

I recently had the need to quickly and dirtily find some strings from a Windows .exe file on Linux.

Going through with HexEditor was a pain in the arse. There seemed to be a few programs for this on windows, which would work messily under Wine. It was easier to write my own.

The Rules:
  • Strings must be ASCII.
  • Strings must be greater than 4 characters.
  • Strings must be at least 50% different characters. (i.e. www.com.com fails, while www.google.com succeeds)
This still leaves you with a lot of junk, but at least you can easily see what is junk and not.

#!/usr/bin/env python
'''A program that extracts strings from binary files.

Usage: reader.py path/to/file
'''

import sys

numstrs = 0
with open(sys.argv[1]) as j:
j = j.read()
mystr = ""
for i in range(0,len(j)):
if 31 < ord(j[i]) < 127:
mystr += j[i]
else:
# If the string isn't that long discard it.
if len(mystr) > 4:
uniqs = set()
for char in mystr:
uniqs.add(char)

# If duplicate chars are less than half the string
if len(uniqs) > .5 * len(mystr):
print mystr
numstrs += 1

mystr = ""

print "==========\n\nOutput: %s strings" % numstrs

Some of you may be thinking, why do you care? Well, this is a great way to quickly see the human interactions going on within a binary: what libraries are being loaded, what websites are being accessed, what programs are being called, or even give you cheats by allowing you to look at some dialogs not normally shown.

Sample: SimAnt
Extended sections of junk have been replaced by "...".


...
Copyright (C)1990, Daniel Goldman
...
96|yr
y, <Xw
<st'<ntQ<pt`<Et
...
eov0001:
Cannot find overlay file "
eov0002:
eov0003:
eov0007:
Commit error - section
eov0009:
eov0004:
-- use RELOAD to increase size
...
Expanded Memory
Extended Memory
Conventional Memory
eca0001:
.RTLink CACHE -
Handling
Function code
, Error code
RTVMEXP
RTVMEXT
RTVMCONV
RTOVEXP
RTOVEXT
RTOVCONV
eov0010:
evm0019:
Environment syntax error --
(last char is erroneous)
Fatal Error $
Press any key to terminate.$PQWV
...
pError!!
pNOTE: SimAnt
runs radically
p faster in 16-color mode!
pPlease refer to the
pSimAnt
manual.
pSave Game As:
pThe name 'SimAnt
' is reserved
pfor this application.
...
"'*'%"
pSimAnt
Saved Game
how to edit/create one.
HIGHLIGHTED
CHITIN
MAXILLAE
OCELLI
INFRABUCCAL
MIDGUT
TROPHALLAXIS
CASTE
LARVAE
PUPATE
CASTES
PUPAE
ECLOSE
CALLOWS
PHEROMONES
BROOD
HONEYDEW
APHIDS
BREEDERS
RECRUIT
FORAGE
FORAGING
QUEENCHAMBER
NURSERIES
MS Run-Time Library - Copyright (c) 1990, Microsoft Corp
...
DACsample
FREELIST > 38
winheaders
Sound Driver reports driver: %d
%d DAC channels
%d FM channels
%d TANDY PSG channels
%d PS1 PSG channels
%d COVOX PSG channels
and %d MIDI channels
MUSIC INIT!
UPDATEEVERYTHING!
WAIT YES
result=%d
Yardmode=%d, newMode=%d
i=%d, j=%x
= %x
EMS version: %x
total pages: %d
free pages: %d
TILESXXX
emstiles
Tile >= 256 in PutLifeAndTile
Tile >= 256 in PutLifeAndTile
PutTile grndTile > 0x100
Y>MAXAY
SimAnt
Vis message %s at %d,%d
balbuf
Cannot GetResource (HEX, %d), ResErr %d
MemDeath
Warning: Can't load strings: %d
strptrs
NewPtr argument too large
%-ld%%
BAD SWITCH
USAGE: SimAnt [/d{EeTHMm2V}] [/s{NABCI}]
SimAnt configuration file missing
simant.cfg
install.exe
DOS Error %d: %s
sound
SimAnt cancelled.
BAD font in MakeBaloon
balloon
@tdyballoon
clrbln
Balloon Size=%d, %d
ePtr->mouse_flags=%x, MRPRESSED=%x
Map window image
Generated map window
ITEM=%x, startTool=%x
tileNum=%d
ANTMENU
L: item=%x, openSub=%x
E=%x, openSub=%x
Last sub state = %x
X: item=%x, openSub=%x
~zwsolhea^[
<@DHLPTX\`dhlptx|
[^aehloswz~
|xtplhd`\XTPLHD@<
TPLHD@<84.,
,.48<@EINRV
<@DIII]c
]IID@
CHEAT %d
Load Game
game not loaded
CITYMCRP
Save Game
lastFileName==%s
OVERWRITE
TOTALLEN=%u
COPYING DATA INTO BUFFER!
WRITING
Saved correctly
File list
Cannot read drive %c
Can't read disk
Aborting
Cannot read drive %c
<PATH=%s>
%s*.*
*.ant
%-12s
0No Files
%d:%s
-> %s
Event=%x,%x
DEFAULT:Event=%x,%x
%c:%s
CHDIR(%s)
Filename:%s
PathName=%s, iniPath=%s
:;,.=+-_\/*
Unpause
Pause
FREE+SOFT AT INITMAP=%ld
Generated buffer window
Map window image
Generated map window
Draw map - yard
YMAXCOUNT =%d!!!!!
GOT Scenario %x
StrnID=%d
Pict=%d
line %d:%s
PictStrnDialog: %d
MePLane=%d
Malloc
()*+,-./0
1234567
EVENT=%x
FLUSH
User Request
Keypress=%x
COMMAND KEY:%c
%ld bytes @ startup
%ld bytes free now
%ld bytes discardable stuff
%ld AVAILABLE
KEYEVENT=%x, %x
ePtr->mouse_flags=%x
MapPlane=%d
len = %d
%d(%d)(%d): [%s]
ERROR: Cannot file text rez(%s)
DisplayCard(cardRez)(%d)
Card Resource not found.
INFO TEXT REC: %d
Unknown Resource.
AnimYellowInsane
MemPunt @%s after %s
RALLOCXX
DISCARDED
SYSTEM
Free illegal type
ralloc.dmp
Ralloc dump at %s, %s
By handles:
By location:
%p->%p:
size=%x, %ld, type=%c%s
age=%5ld name=%s
DiscardEntry
ALL MEMORY HANDLES USED
OLDESTH=%p
<SPLIT>
<WHOLE>
Cannot find a big enough space! (%ld bytes)
<FO2>
ALLOC 0 BYTES
NOEMS - memPtr=%p
RL5: Invalid handle index
LOCKED FREED %s
RL5: Invalid handle index
REALLOC 0 BYTES
{DIS}
Lock depth exceeded 100
Locked discarded!!
RU: Bad handle in unlock
RL5: Invalid handle index
malloc
_ffree: Could not find memory ptr
_frealloc: Could not find memory ptr
EMS Error
%s.ndx
Index file missing
WINLABEL
BITMAP
CSRMASK
CSRPIC
ANIMDLT
SCREEN
PALETTE
CARDTITLE
STYLE
U%s,%d
%d:%d
DBRecall Unpack error!!! - object=%d, type=%d
Attempt to ADD during a READ-ONLY run
Attempt to DELETE during a READ-ONLY run
Attempt to PACK during a READ-ONLY run
DBEMSXXX
DBEMSLIST
Handle mismatch
Database error
Out of handles.
%s.dat
Cannot create data file.
for more information.
Dos error: %d: %s
%s.dat
Cannot open database %s
Purge attempt with database closed
Release %d not in cache!
Unhook attempt with database closed
cachetable
no memory over 0 in age!
MouseHide < 0
HPKMGOIQLRS9;
HotBox overflow
Continue
Continue
%s: Are you sure?
Cancel
Retry
Cancel
Unknown unit
Drive not ready
Unknown command
Data error (bad CRC)
Bad request structure length
seek error
unknown media type
sector not found
printer out of paper
write fault
read fault
general failure
abort request
GSaveRect
Color picture in mono file
PutPackedBuf
GPutPacked
PutPackedBuf
WARNING: i>=MAXWINDOWS-1 in KillWin(%d)
SetWin: Window open but clip is NULL
ERROR MEMNULL winClipHandle
tmprects
clipout
winClipList
C097: Clip overflow %d
C098: Clip overflow %d
winClipList
C099: Clip overflow %d
subinclude
CL074:Temp clip overflow in SubInclude
Sub include NULL rect!!
Clip out of memory!!!
subinclude
CL074:Temp clip overflow in SubInclude
Sub include NULL rect!!
Clip out of memory!!!
subexclude
CL074:Temp clip overflow in SubExclude
Sub exclude NULL rect!!
Clip out of memory!!!
include
CL174:Temp clip overflow in SubExclude
include NULL rect!!
clip_Push
Cannot allocate memory in clip_Push
Error CL98463: Pushed it too far
Clip_Pop w/ nothing on the stack: E9073
Could not find fonts
Could not find fonts!
Font loaded!
Could not find fonts
Could not find fonts!
FATAL: %s
%%-%ds
%%c%%-%ds
Menu data too long
MSMOUSE
language.dat
language
shared
lrshare
Cannot load menu
bmcmBad 'Display Mode' in configuration file
Hires EGA
Tandy
Hercules
Lores EGA
Mono EGA
MCGA/VGA Color
MCGA/VGA mono
VGA Color
hcega
tdyga
lcega
hcega
MDA system detected. Cannot run graphics.
Couldn't load resource %x,%x
CANNOT LOAD WINDOW %03x
Cannot load resource
please try another
Could not load purge list
!!W:%x
QQW:%x
##W:%x
**W:%x
w:%x, i:%x
xxw:%x, i:%x
zzw:%x, i:%x
ppw:%x, i:%x
%%w:%x, i:%x
!!i:%x
@@i:%x
formatStr
formatStr
Illegal win num %x at lock
win_Lock > 10 levels deep!!
Attemp to unlock when discarded win %x
Bad object type in win_DrawElevator
eleTop= %d
PrevListLine punt
SS=%d, line=%d
Bad object type in win_ProcSliderEvent
fontBuf
fontBuf
fontBuf
font1
font2
font3
font4
WINDOW %x NOT LOCKED DURING CALL TO win_WinRectAddr!!
WINDOW %x NOT LOCKED DURING CALL TO win_ObjAddr!!
GGetPic - trans @ %d, %d (%d, %d), bytes=%u
GPutPic size AA %d, %d, tag=%x
GPutPic size %d, %d, tag=%x
Couldn't find resize icoN!!
FontHeader
FONTIMAGE
locTable
owTable
Printset @ %s %d objects
Buffer in set too small!!
animbufs
anim_Remove objects not found
anim_hide object not found
anim_hide object not found
anim_Remove objects not found
animHandle
animobjs
to flush
Bad pic type in ANIM.C
...
music failure
Seg=%x, buf=%p, handle=%p
_C_FILE_INFO=
0PX
000WP
(null)
USunMonTueWedThuFriSat
JanFebMarAprMayJunJulAugSepOctNovDec
Error 0
No such file or directory
Arg list too long
Exec format error
Bad file number
Not enough core
Permission denied
File exists
Cross-device link
Invalid argument
Too many open files
No space left on device
Math argument
Result too large
Unknown error
...
P<<NMSG>>
R6000
- stack overflow
R6003
- integer divide by 0
R6009
- not enough space for environment
run-time error
R6002
R6001
- null pointer assignment
...
06/13/90
==========

Output: 828 strings

It is interesting looking at some of the common problems that plagued early computer programs.

Wednesday, October 26, 2011

Sleep Sort

A kind of neat sorting algorithm if, for some reason, you had a machine that had unlimited interrupts, and unlimited running time, but had almost no CPU power to do other sorts, perhaps biological computing?


 1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
function f() {
sleep "$1"
echo "$1"
}
while [ -n "$1" ]
do
f "$1" &
shift
done
wait

Wednesday, October 19, 2011

Real Time Header Editing with Paros

Sometimes it is advantageous to modify headers as they are sent by a website, let's say you're looking for SQL injection vulnerabilities on your server or want to see what happens when non validated information escapes your javascript validation.

But what to use to easily view/modify/drop headers and incoming connections?

Introducing Paros, a web proxy written entirely in Java so it is cross platform, just set your browser or operating system to use 127.0.0.1:8080 as a proxy after firing it up. Basic functionality shown after the break.





Paros has many advanced features, I'll just discuss trapping requests and responses and using the history.


When you begin using Paros, any websites you visit will be left in the sites pane on the left hand side, from there you can click on each requested item for a site, and view the reqest and response for that item in the appropriate tabs.

If you want to modify the request or response, head over to the Trap tab, and check the appropriate boxes. If there is POST information sent along with the HTTP request, then it will be displayed below; I changed the view to "tabular" to more easily see/edit the data.

Aside: In this instance my browser is pointed at a site called conjuguemos.com teachers us it to test their students' ability to conjugate verbs, when students are done, unencrypted javascript headers are sent containing the session information, not very bright in my book, as any student could quickly and easily modify their scores to have 10,000 words right in thirty-eight seconds.

Once a header/response is trapped you may edit it by hand in the panel given, or drop it (say you wanted to test a timeout for your web widget, like a Twitter reader if Twitter were down).

Sessions can also be saved and restored through the File menu. Overall the tool is easy to use, fast to learn, and very effective.

Sunday, October 16, 2011

Ubuntu 11.10

Whenever a new OS comes out, there are always improvements, but lots of compromises. After trying out Ubuntu 11.10 I'm, quite frankly, disappointed.

The Good
The upgrade was painless, the boot time is much improved, and the lightDM looks beautiful.

The Bad
Grub has failed on me four times in two days, I have to hit the power button and start again to get a non-blinky cursor.

In two days of use, my mouse cursor has frozen on screen twice, I can't move it afterwards.

The new software center only allows you to install one piece of software before searching for another.

Unity (still) doesn't allow me to drag and drop shortcuts to my folders to the dock.

The Ugly
Nautilus (if you still are nautilus beneath your new exterior) doesn't show breadcrumbs unless in full screen.

The menu in the upper right of the screen is excessivly large for people like me that never use the person switcher, a desktop email client, or social networks outside our browsers.

You can't uninstall zeitgeist without completely removing the ability to launch applications.

After installing compiz-config-settings manager to try and resize the dock to be smaller, and to show up immediately when I mouse over to it (so it doesn't destroy my workflow) I couldn't, compiz also disabled by alt+tab, and my Aero snap.

With the newest gnome desktop build (ubuntu-classic) the desktop looks like crap, lots of vertical lines, and no configuration for how the layout is done (i.e. I want to remove the bottom panel and install docky without going to gconf, that would be fine).

How to fix it
Install xfce or KDE (yes, even I am willing to switch to KDE after