Showing posts with label Networking. Show all posts
Showing posts with label Networking. Show all posts

Friday, April 12, 2013

Covertly Sending Messages Using DNS Queries

I won't be the first to post about this, but I read it a while back and thought it sounded fun: note, this post will be more technical in nature than most, but I hope it will be a fun read, and a fun toy.

Let's say you want to send short messages that are very covert and not persistent. You could, of course use Twitter, sending strange cryptographic tweets, but that may be too obvious for your tastes, plus they can more easily be traced back to an IP/Person if just one slip-up is made. Somehow using DNS would be an awesome way to do this because:

  • It can be accessed by anyone
  • Messages expire over known intervals
  • No accounts are necessary
  • There are huge amounts of data to go through and junk requests that will look just like yours if someone wanted to find you out
  • Google has a very nice public DNS you can use for free at 8.8.8.8 or 8.8.4.4

Specifics

The two types of queries we'll be using here are standard and non-recursive DNS queries.

Standard queries are the ones that your computer normally does to change a hostname in to an IP address it can contact, to do this from a command line you'd type:

$ dig @8.8.8.8 www.google.com
To which the DNS server responds:

; <<>> DiG 9.8.1-P1 <<>> @8.8.8.8 www.google.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 5459
;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.google.com. IN A

;; ANSWER SECTION:
www.google.com. 300 IN A 74.125.225.179
www.google.com. 300 IN A 74.125.225.180
www.google.com. 300 IN A 74.125.225.176
www.google.com. 300 IN A 74.125.225.177
www.google.com. 300 IN A 74.125.225.178

;; Query time: 53 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Fri Apr 12 10:18:31 2013
;; MSG SIZE rcvd: 112
This shows you all of the numerical IP addresses you can reach google.com at, if you copy and paste the first one in to your browser, you'll see Google's home page.

That's all well and good, but how would you actually store information using DNS? For this you'll need to generate a domain name that doesn't exist, we'll be using www.testdnsflagsetting.com for the purposes of this article:

Now do a dig on it:

$ dig @8.8.8.8 www.testdnsflagsetting.com +norecurse
The response looks different this time, note that ANSWER: 0 and AUTHORITY: 0, this means the request is not authoratative (8.8.8.8 doesn't know this informatoin for sure), and there was no answer.

This is because we passed in the +norecurse flag to dig, asking the server to just reply with what was it had stored rather than asking higher up in the chain of command:

; <<>> DiG 9.8.1-P1 <<>> @8.8.8.8 www.testdnsflagsetting.com +norecurse
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 23556
;; flags: qr ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.testdnsflagsetting.com. IN A

;; Query time: 57 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Fri Apr 12 10:04:10 2013
;; MSG SIZE rcvd: 44
Now we'll do the same thing, but without the +norecursive:

$ dig @8.8.8.8 www.testdnsflagsetting.com

; <<>> DiG 9.8.1-P1 <<>> @8.8.8.8 www.testdnsflagsetting.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 22889
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;www.testdnsflagsetting.com. IN A

;; AUTHORITY SECTION:
com. 900 IN SOA a.gtld-servers.net. nstld.verisign-grs.com. 1365782647 1800 900 604800 86400

;; Query time: 82 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Fri Apr 12 10:04:21 2013
;; MSG SIZE rcvd: 117
Note that the AUTHORITY: 1 now is true, meaning that 8.8.8.8 checked with the server that knows about all .com addresses to see if ours existed. There is also a new section, note the number 900 in it, that means this response is going to be saved in Google's DNS (8.8.8.8) for 900 seconds.

If we go back and do the +norecurse version again, we now get the cached response, but with 890, meaning there are only 890 seconds left until the cache is cleared:

$ dig @8.8.8.8 www.testdnsflagsetting.com +norecurse

; <<>> DiG 9.8.1-P1 <<>> @8.8.8.8 www.testdnsflagsetting.com +norecurse
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 14832
;; flags: qr ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;www.testdnsflagsetting.com. IN A

;; AUTHORITY SECTION:
com. 890 IN SOA a.gtld-servers.net. nstld.verisign-grs.com. 1365782647 1800 900 604800 86400

;; Query time: 39 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Fri Apr 12 10:04:31 2013
;; MSG SIZE rcvd: 117
Put these together now, and say you want to send a true or a false to someone on the other side of the globe, you both just have to agree on a time to check, and a domain, then if you want to say true you do a recursive query, and the other person will get back an authoritative record when they do a non-recursive; if you don't do the query, they will not and they'll know you sent false

Sending a Whole Message

Now say you want to send a whole message! Convert the text to ASCII, and break it down to bits, use the first byte to tell how long the message will be (up to 255 characters).

Say you just wanted to send the message Hi, that means you'd send a 2 then Hi, but you can't use the same domain the whole way through, you'll have to agree on a bunch of domains, or a way of randomly generating them. Here we'll just append a number to the end:

Letter:       2        H        i
Binary: 00000010 01001000 01101001
POsition: 111111 11112222
01234567 89012345 67890123
Your queries would look something like this:

dig www.testdnsflagsetting6.com
dig www.testdnsflagsetting9.com
dig www.testdnsflagsetting12.com
dig www.testdnsflagsetting17.com
dig www.testdnsflagsetting18.com
dig www.testdnsflagsetting20.com
dig www.testdnsflagsetting23.com
You only actually dig for the 1s, because they are represented by true.

Getting The Message Back Out

Now to get the message back out, you just need to do a dig for positions 0-7, and convert that in to the number of letters in the message, multiply that by 8 to get the number of bits you need to check, and check the domains ending with all of those numbers.

First 8
dig www.testdnsflagsetting0.com

dig www.testdnsflagsetting1.com

...

dig www.testdnsflagsetting7.com


This would give us the number 2, meaning there were 2 more sections of 8, then you read on.

A program to do it!

This is a short Python script to do it, you may want to change the DOMAIN_NAME. in case other people are using the script too.

#!/usr/bin/env python3
''' A program to send messages via DNS queries.
Copyright 2013 Joseph Lewis <joehms22@gmail.com> | <joseph@josephlewis.net>

MIT License
'''

import subprocess

DNS_SERVER = '8.8.8.8'
DOMAIN_NAME = "www.testdnsflagsetting{}.com"
NORECURSE_OPT = "+norecurse"

msg = raw_input("Enter a message, or blank to receive: ")

def read_byte(byteno):
byte = "0b"
for i in range(byteno * 8, (byteno + 1) * 8):
output = subprocess.check_output(['dig','@{}'.format(DNS_SERVER), DOMAIN_NAME.format(i), NORECURSE_OPT])
if ";; AUTHORITY SECTION:" in output:
byte += '1'
else:
byte += '0'

return int(byte, 2) # converts binary to an int

def write_byte(byteno, byte):
to_write = bin(byte)[2:].zfill(8) # gets binary representation of a byte
for loc, b in enumerate(to_write):
if b == '1':
i = (byteno * 8) + loc
subprocess.check_output(['dig','@{}'.format(DNS_SERVER), DOMAIN_NAME.format(i)])
print "Wrote 1 at: {}".format(i)

if len(msg) == 0:
message = ""
for byte in range(1,read_byte(0) + 1): # first byte is length of message
message += chr(read_byte(byte))

if len(message) > 0:
print message
else:
print "[No Message]"

else:
total = len(msg)
write_byte(0, total)
for loc, char in enumerate(msg):
write_byte(loc + 1, ord(char))

print "Message written"

Thursday, December 20, 2012

A Tiny Java Mime Lookup Library

I couldn't find a nice and very tiny solution to looking up a mimetype based on file extension in Java, so I built one, it uses /etc/mime.types as the source for the information, after the first run, the library should be pretty fast due to the use of a HashMap for lookups.

Get a Mime by Extension

lookupMapping("doc");

Get a Mime by Path

getMime("/path/to/some/file.tar.gz"); // looks up extension "gz"

Full Code Listing

import java.util.HashMap;

/**
* Looks up a mimetype based upon a file extension.
*/
public class MimeType {
public static final String DEFAULT_MIME = "application/octet-stream";

/**
* A list of extensions and their appropriate mime mappings.
*/
private static final String[][] MIME_MAPPING = {{"323","text/h323"},
{"3gp","video/3gpp"},
{"7z","application/x-7z-compressed"},
{"abw","application/x-abiword"},
{"ai","application/postscript"},
{"aif","audio/x-aiff"},
{"aifc","audio/x-aiff"},
{"aiff","audio/x-aiff"},
{"alc","chemical/x-alchemy"},
{"amr","audio/amr"},
{"amr","audio/amr"},
{"anx","application/annodex"},
{"apk","application/vnd.android.package-archive"},
{"appcache","text/cache-manifest"},
{"~","application/x-trash"},
{"%","application/x-trash"},
{"art","image/x-jg"},
{"asc","text/plain"},
{"asf","video/x-ms-asf"},
{"asn","chemical/x-ncbi-asn1"},
{"asn","chemical/x-ncbi-asn1-spec"},
{"aso","chemical/x-ncbi-asn1-binary"},
{"asx","video/x-ms-asf"},
{"atom","application/atom+xml"},
{"atomcat","application/atomcat+xml"},
{"atomsrv","application/atomserv+xml"},
{"au","audio/basic"},
{"avi","video/x-msvideo"},
{"awb","audio/amr-wb"},
{"awb","audio/amr-wb"},
{"axa","audio/annodex"},
{"axv","video/annodex"},
{"bak","application/x-trash"},
{"bat","application/x-msdos-program"},
{"b","chemical/x-molconn-Z"},
{"bcpio","application/x-bcpio"},
{"bib","text/x-bibtex"},
{"bin","application/octet-stream"},
{"bmp","image/x-ms-bmp"},
{"book","application/x-maker"},
{"boo","text/x-boo"},
{"brf","text/plain"},
{"bsd","chemical/x-crossfire"},
{"c3d","chemical/x-chem3d"},
{"cab","application/x-cab"},
{"cac","chemical/x-cache"},
{"cache","chemical/x-cache"},
{"cap","application/vnd.tcpdump.pcap"},
{"cascii","chemical/x-cactvs-binary"},
{"cat","application/vnd.ms-pki.seccat"},
{"cbin","chemical/x-cactvs-binary"},
{"cbr","application/x-cbr"},
{"cbz","application/x-cbz"},
{"cc","text/x-c++src"},
{"cda","application/x-cdf"},
{"cdf","application/x-cdf"},
{"cdr","image/x-coreldraw"},
{"cdt","image/x-coreldrawtemplate"},
{"cdx","chemical/x-cdx"},
{"cdy","application/vnd.cinderella"},
{"cef","chemical/x-cxf"},
{"cer","chemical/x-cerius"},
{"chm","chemical/x-chemdraw"},
{"chrt","application/x-kchart"},
{"cif","chemical/x-cif"},
{"class","application/java-vm"},
{"cls","text/x-tex"},
{"cmdf","chemical/x-cmdf"},
{"cml","chemical/x-cml"},
{"cod","application/vnd.rim.cod"},
{"com","application/x-msdos-program"},
{"cpa","chemical/x-compass"},
{"cpio","application/x-cpio"},
{"cpp","text/x-c++src"},
{"cpt","application/mac-compactpro"},
{"cpt","image/x-corelphotopaint"},
{"cr2","image/x-canon-cr2"},
{"crl","application/x-pkcs7-crl"},
{"crt","application/x-x509-ca-cert"},
{"crw","image/x-canon-crw"},
{"csd","audio/csound"},
{"csf","chemical/x-cache-csf"},
{"csh","application/x-csh"},
{"csh","text/x-csh"},
{"csm","chemical/x-csml"},
{"csml","chemical/x-csml"},
{"css","text/css"},
{"csv","text/csv"},
{"ctab","chemical/x-cactvs-binary"},
{"c","text/x-csrc"},
{"c++","text/x-c++src"},
{"ctx","chemical/x-ctx"},
{"cu","application/cu-seeme"},
{"cub","chemical/x-gaussian-cube"},
{"cxf","chemical/x-cxf"},
{"cxx","text/x-c++src"},
{"dat","application/x-ns-proxy-autoconfig"},
{"davmount","application/davmount+xml"},
{"dcm","application/dicom"},
{"dcr","application/x-director"},
{"deb","application/x-debian-package"},
{"diff","text/x-diff"},
{"dif","video/dv"},
{"dir","application/x-director"},
{"djv","image/vnd.djvu"},
{"djvu","image/vnd.djvu"},
{"dll","application/x-msdos-program"},
{"dl","video/dl"},
{"dmg","application/x-apple-diskimage"},
{"dms","application/x-dms"},
{"doc","application/msword"},
{"docm","application/vnd.ms-word.document.macroEnabled.12"},
{"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dot","application/msword"},
{"dotm","application/vnd.ms-word.template.macroEnabled.12"},
{"dotx","application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"d","text/x-dsrc"},
{"dvi","application/x-dvi"},
{"dv","video/dv"},
{"dx","chemical/x-jcamp-dx"},
{"dxr","application/x-director"},
{"emb","chemical/x-embl-dl-nucleotide"},
{"embl","chemical/x-embl-dl-nucleotide"},
{"eml","message/rfc822"},
{"ent","chemical/x-ncbi-asn1-ascii"},
{"ent","chemical/x-pdb"},
{"eot","application/vnd.ms-fontobject"},
{"eps2","application/postscript"},
{"eps3","application/postscript"},
{"eps","application/postscript"},
{"epsf","application/postscript"},
{"epsi","application/postscript"},
{"erf","image/x-epson-erf"},
{"es","application/ecmascript"},
{"etx","text/x-setext"},
{"exe","application/x-msdos-program"},
{"ez","application/andrew-inset"},
{"fb","application/x-maker"},
{"fbdoc","application/x-maker"},
{"fch","chemical/x-gaussian-checkpoint"},
{"fchk","chemical/x-gaussian-checkpoint"},
{"fig","application/x-xfig"},
{"flac","audio/flac"},
{"fli","video/fli"},
{"flv","video/x-flv"},
{"fm","application/x-maker"},
{"frame","application/x-maker"},
{"frm","application/x-maker"},
{"gal","chemical/x-gaussian-log"},
{"gam","chemical/x-gamess-input"},
{"gamin","chemical/x-gamess-input"},
{"gan","application/x-ganttproject"},
{"gau","chemical/x-gaussian-input"},
{"gcd","text/x-pcs-gcd"},
{"gcf","application/x-graphing-calculator"},
{"gcg","chemical/x-gcg8-sequence"},
{"gen","chemical/x-genbank"},
{"gf","application/x-tex-gf"},
{"gif","image/gif"},
{"gjc","chemical/x-gaussian-input"},
{"gjf","chemical/x-gaussian-input"},
{"gl","video/gl"},
{"gnumeric","application/x-gnumeric"},
{"gpt","chemical/x-mopac-graph"},
{"gsf","application/x-font"},
{"gsm","audio/x-gsm"},
{"gtar","application/x-gtar"},
{"hdf","application/x-hdf"},
{"hh","text/x-c++hdr"},
{"hin","chemical/x-hin"},
{"hpp","text/x-c++hdr"},
{"hqx","application/mac-binhex40"},
{"hs","text/x-haskell"},
{"hta","application/hta"},
{"htc","text/x-component"},
{"h","text/x-chdr"},
{"h++","text/x-c++hdr"},
{"html","text/html"},
{"htm","text/html"},
{"hwp","application/x-hwp"},
{"hxx","text/x-c++hdr"},
{"ica","application/x-ica"},
{"ice","x-conference/x-cooltalk"},
{"ico","image/vnd.microsoft.icon"},
{"ics","text/calendar"},
{"icz","text/calendar"},
{"ief","image/ief"},
{"iges","model/iges"},
{"igs","model/iges"},
{"iii","application/x-iphone"},
{"info","application/x-info"},
{"inp","chemical/x-gamess-input"},
{"ins","application/x-internet-signup"},
{"iso","application/x-iso9660-image"},
{"isp","application/x-internet-signup"},
{"ist","chemical/x-isostar"},
{"istr","chemical/x-isostar"},
{"jad","text/vnd.sun.j2me.app-descriptor"},
{"jam","application/x-jam"},
{"jar","application/java-archive"},
{"java","text/x-java"},
{"jdx","chemical/x-jcamp-dx"},
{"jmz","application/x-jmol"},
{"jng","image/x-jng"},
{"jnlp","application/x-java-jnlp-file"},
{"jpeg","image/jpeg"},
{"jpe","image/jpeg"},
{"jpg","image/jpeg"},
{"js","application/javascript"},
{"json","application/json"},
{"kar","audio/midi"},
{"key","application/pgp-keys"},
{"kil","application/x-killustrator"},
{"kin","chemical/x-kinemage"},
{"kml","application/vnd.google-earth.kml+xml"},
{"kmz","application/vnd.google-earth.kmz"},
{"kpr","application/x-kpresenter"},
{"kpt","application/x-kpresenter"},
{"ksp","application/x-kspread"},
{"kwd","application/x-kword"},
{"kwt","application/x-kword"},
{"latex","application/x-latex"},
{"lha","application/x-lha"},
{"lhs","text/x-literate-haskell"},
{"lin","application/bbolin"},
{"lsf","video/x-la-asf"},
{"lsx","video/x-la-asf"},
{"ltx","text/x-tex"},
{"ly","text/x-lilypond"},
{"lyx","application/x-lyx"},
{"lzh","application/x-lzh"},
{"lzx","application/x-lzx"},
{"m3g","application/m3g"},
{"m3u8","application/x-mpegURL"},
{"m3u","audio/mpegurl"},
{"m3u","audio/x-mpegurl"},
{"m4a","audio/mpeg"},
{"maker","application/x-maker"},
{"man","application/x-troff-man"},
{"mbox","application/mbox"},
{"mcif","chemical/x-mmcif"},
{"mcm","chemical/x-macmolecule"},
{"md5","application/x-md5"},
{"mdb","application/msaccess"},
{"me","application/x-troff-me"},
{"mesh","model/mesh"},
{"mid","audio/midi"},
{"midi","audio/midi"},
{"mif","application/x-mif"},
{"mkv","video/x-matroska"},
{"mm","application/x-freemind"},
{"mmd","chemical/x-macromodel-input"},
{"mmf","application/vnd.smaf"},
{"mml","text/mathml"},
{"mmod","chemical/x-macromodel-input"},
{"mng","video/x-mng"},
{"moc","text/x-moc"},
{"mol2","chemical/x-mol2"},
{"mol","chemical/x-mdl-molfile"},
{"moo","chemical/x-mopac-out"},
{"mop","chemical/x-mopac-input"},
{"mopcrt","chemical/x-mopac-input"},
{"movie","video/x-sgi-movie"},
{"mov","video/quicktime"},
{"mp2","audio/mpeg"},
{"mp3","audio/mpeg"},
{"mp4","video/mp4"},
{"mpc","chemical/x-mopac-input"},
{"mpega","audio/mpeg"},
{"mpeg","video/mpeg"},
{"mpe","video/mpeg"},
{"mpga","audio/mpeg"},
{"mpg","video/mpeg"},
{"mph","application/x-comsol"},
{"mpv","video/x-matroska"},
{"ms","application/x-troff-ms"},
{"msh","model/mesh"},
{"msi","application/x-msi"},
{"mvb","chemical/x-mopac-vib"},
{"mxf","application/mxf"},
{"mxu","video/vnd.mpegurl"},
{"nb","application/mathematica"},
{"nbp","application/mathematica"},
{"nc","application/x-netcdf"},
{"nef","image/x-nikon-nef"},
{"nwc","application/x-nwc"},
{"o","application/x-object"},
{"oda","application/oda"},
{"odb","application/vnd.oasis.opendocument.database"},
{"odc","application/vnd.oasis.opendocument.chart"},
{"odf","application/vnd.oasis.opendocument.formula"},
{"odg","application/vnd.oasis.opendocument.graphics"},
{"odi","application/vnd.oasis.opendocument.image"},
{"odm","application/vnd.oasis.opendocument.text-master"},
{"odp","application/vnd.oasis.opendocument.presentation"},
{"ods","application/vnd.oasis.opendocument.spreadsheet"},
{"odt","application/vnd.oasis.opendocument.text"},
{"oga","audio/ogg"},
{"ogg","audio/ogg"},
{"ogv","video/ogg"},
{"ogx","application/ogg"},
{"old","application/x-trash"},
{"one","application/onenote"},
{"onepkg","application/onenote"},
{"onetmp","application/onenote"},
{"onetoc2","application/onenote"},
{"orc","audio/csound"},
{"orf","image/x-olympus-orf"},
{"otg","application/vnd.oasis.opendocument.graphics-template"},
{"oth","application/vnd.oasis.opendocument.text-web"},
{"otp","application/vnd.oasis.opendocument.presentation-template"},
{"ots","application/vnd.oasis.opendocument.spreadsheet-template"},
{"ott","application/vnd.oasis.opendocument.text-template"},
{"oza","application/x-oz-application"},
{"p7r","application/x-pkcs7-certreqresp"},
{"pac","application/x-ns-proxy-autoconfig"},
{"pas","text/x-pascal"},
{"patch","text/x-diff"},
{"pat","image/x-coreldrawpattern"},
{"pbm","image/x-portable-bitmap"},
{"pcap","application/vnd.tcpdump.pcap"},
{"pcf","application/x-font"},
{"pcf.Z","application/x-font"},
{"pcx","image/pcx"},
{"pdb","chemical/x-pdb"},
{"pdf","application/pdf"},
{"pfa","application/x-font"},
{"pfb","application/x-font"},
{"pgm","image/x-portable-graymap"},
{"pgn","application/x-chess-pgn"},
{"pgp","application/pgp-encrypted"},
{"pk","application/x-tex-pk"},
{"pls","audio/x-scpls"},
{"pl","text/x-perl"},
{"pm","text/x-perl"},
{"png","image/png"},
{"pnm","image/x-portable-anymap"},
{"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"pot","text/plain"},
{"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"ppm","image/x-portable-pixmap"},
{"pps","application/vnd.ms-powerpoint"},
{"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppt","application/vnd.ms-powerpoint"},
{"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"prf","application/pics-rules"},
{"prt","chemical/x-ncbi-asn1-ascii"},
{"ps","application/postscript"},
{"psd","image/x-photoshop"},
{"p","text/x-pascal"},
{"pyc","application/x-python-code"},
{"pyo","application/x-python-code"},
{"py","text/x-python"},
{"qgs","application/x-qgis"},
{"qtl","application/x-quicktimeplayer"},
{"qt","video/quicktime"},
{"ra","audio/x-pn-realaudio"},
{"ra","audio/x-realaudio"},
{"ram","audio/x-pn-realaudio"},
{"rar","application/rar"},
{"ras","image/x-cmu-raster"},
{"rb","application/x-ruby"},
{"rd","chemical/x-mdl-rdfile"},
{"rdf","application/rdf+xml"},
{"rdp","application/x-rdp"},
{"rgb","image/x-rgb"},
{"rm","audio/x-pn-realaudio"},
{"roff","application/x-troff"},
{"ros","chemical/x-rosdal"},
{"rpm","application/x-redhat-package-manager"},
{"rss","application/x-rss+xml"},
{"rtf","application/rtf"},
{"rtx","text/richtext"},
{"rxn","chemical/x-mdl-rxnfile"},
{"scala","text/x-scala"},
{"sce","application/x-scilab"},
{"sci","application/x-scilab"},
{"sco","audio/csound"},
{"scr","application/x-silverlight"},
{"sct","text/scriptlet"},
{"sd2","audio/x-sd2"},
{"sda","application/vnd.stardivision.draw"},
{"sdc","application/vnd.stardivision.calc"},
{"sd","chemical/x-mdl-sdfile"},
{"sdd","application/vnd.stardivision.impress"},
{"sdf","application/vnd.stardivision.math"},
{"sdf","chemical/x-mdl-sdfile"},
{"sds","application/vnd.stardivision.chart"},
{"sdw","application/vnd.stardivision.writer"},
{"ser","application/java-serialized-object"},
{"sfv","text/x-sfv"},
{"sgf","application/x-go-sgf"},
{"sgl","application/vnd.stardivision.writer-global"},
{"sha1","application/x-sha1"},
{"sh","application/x-sh"},
{"shar","application/x-shar"},
{"shp","application/x-qgis"},
{"sh","text/x-sh"},
{"shtml","text/html"},
{"shx","application/x-qgis"},
{"sid","audio/prs.sid"},
{"sig","application/pgp-signature"},
{"sik","application/x-trash"},
{"silo","model/mesh"},
{"sis","application/vnd.symbian.install"},
{"sisx","x-epoc/x-sisx-app"},
{"sit","application/x-stuffit"},
{"sitx","application/x-stuffit"},
{"skd","application/x-koan"},
{"skm","application/x-koan"},
{"skp","application/x-koan"},
{"skt","application/x-koan"},
{"sldm","application/vnd.ms-powerpoint.slide.macroEnabled.12"},
{"sldx","application/vnd.openxmlformats-officedocument.presentationml.slide"},
{"smi","application/smil"},
{"smil","application/smil"},
{"snd","audio/basic"},
{"spc","chemical/x-galactic-spc"},
{"spl","application/futuresplash"},
{"spl","application/x-futuresplash"},
{"spx","audio/ogg"},
{"sql","application/x-sql"},
{"src","application/x-wais-source"},
{"srt","text/plain"},
{"stc","application/vnd.sun.xml.calc.template"},
{"std","application/vnd.sun.xml.draw.template"},
{"sti","application/vnd.sun.xml.impress.template"},
{"stl","application/sla"},
{"stw","application/vnd.sun.xml.writer.template"},
{"sty","text/x-tex"},
{"sv4cpio","application/x-sv4cpio"},
{"sv4crc","application/x-sv4crc"},
{"svg","image/svg+xml"},
{"svgz","image/svg+xml"},
{"sw","chemical/x-swissprot"},
{"swf","application/x-shockwave-flash"},
{"swfl","application/x-shockwave-flash"},
{"sxc","application/vnd.sun.xml.calc"},
{"sxd","application/vnd.sun.xml.draw"},
{"sxg","application/vnd.sun.xml.writer.global"},
{"sxi","application/vnd.sun.xml.impress"},
{"sxm","application/vnd.sun.xml.math"},
{"sxw","application/vnd.sun.xml.writer"},
{"t","application/x-troff"},
{"tar","application/x-tar"},
{"taz","application/x-gtar-compressed"},
{"tcl","application/x-tcl"},
{"tcl","text/x-tcl"},
{"texi","application/x-texinfo"},
{"texinfo","application/x-texinfo"},
{"tex","text/x-tex"},
{"text","text/plain"},
{"tgf","chemical/x-mdl-tgf"},
{"tgz","application/x-gtar-compressed"},
{"thmx","application/vnd.ms-officetheme"},
{"tiff","image/tiff"},
{"tif","image/tiff"},
{"tk","text/x-tcl"},
{"tm","text/texmacs"},
{"torrent","application/x-bittorrent"},
{"tr","application/x-troff"},
{"tsp","application/dsptype"},
{"ts","video/MP2T"},
{"tsv","text/tab-separated-values"},
{"txt","text/plain"},
{"udeb","application/x-debian-package"},
{"uls","text/iuls"},
{"ustar","application/x-ustar"},
{"val","chemical/x-ncbi-asn1-binary"},
{"vcd","application/x-cdlink"},
{"vcf","text/x-vcard"},
{"vcs","text/x-vcalendar"},
{"vmd","chemical/x-vmd"},
{"vms","chemical/x-vamas-iso14976"},
{"vrml","model/vrml"},
{"vrml","x-world/x-vrml"},
{"vrm","x-world/x-vrml"},
{"vsd","application/vnd.visio"},
{"wad","application/x-doom"},
{"wav","audio/x-wav"},
{"wax","audio/x-ms-wax"},
{"wbmp","image/vnd.wap.wbmp"},
{"wbxml","application/vnd.wap.wbxml"},
{"webm","video/webm"},
{"wk","application/x-123"},
{"wma","audio/x-ms-wma"},
{"wmd","application/x-ms-wmd"},
{"wmlc","application/vnd.wap.wmlc"},
{"wmlsc","application/vnd.wap.wmlscriptc"},
{"wmls","text/vnd.wap.wmlscript"},
{"wml","text/vnd.wap.wml"},
{"wm","video/x-ms-wm"},
{"wmv","video/x-ms-wmv"},
{"wmx","video/x-ms-wmx"},
{"wmz","application/x-ms-wmz"},
{"woff","application/x-font-woff"},
{"wp5","application/vnd.wordperfect5.1"},
{"wpd","application/vnd.wordperfect"},
{"wrl","model/vrml"},
{"wrl","x-world/x-vrml"},
{"wsc","text/scriptlet"},
{"wvx","video/x-ms-wvx"},
{"wz","application/x-wingz"},
{"x3db","model/x3d+binary"},
{"x3d","model/x3d+xml"},
{"x3dv","model/x3d+vrml"},
{"xbm","image/x-xbitmap"},
{"xcf","application/x-xcf"},
{"xcos","application/x-scilab-xcos"},
{"xht","application/xhtml+xml"},
{"xhtml","application/xhtml+xml"},
{"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlb","application/vnd.ms-excel"},
{"xls","application/vnd.ms-excel"},
{"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xlt","application/vnd.ms-excel"},
{"xltm","application/vnd.ms-excel.template.macroEnabled.12"},
{"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xml","application/xml"},
{"xpi","application/x-xpinstall"},
{"xpm","image/x-xpixmap"},
{"xsd","application/xml"},
{"xsl","application/xml"},
{"xspf","application/xspf+xml"},
{"xtel","chemical/x-xtel"},
{"xul","application/vnd.mozilla.xul+xml"},
{"xwd","image/x-xwindowdump"},
{"xyz","chemical/x-xyz"},
{"zip","application/zip"},
{"zmt","chemical/x-mopac-input"}};

private final HashMap<String, String> m_mapping;
private static MimeType instance;

private MimeType()
{
m_mapping = new HashMap<String, String>();

for(int i = 0; i < MIME_MAPPING.length; i++)
{
m_mapping.put(MIME_MAPPING[i][0], MIME_MAPPING[i][1]);
}
}

private static MimeType getInstance()
{
if(instance == null)
instance = new MimeType();

return instance;
}

/**
* Returns a mime given the extension, or the default if none is found.
* @param ext - the extension to lookup the mime based upon.
* @return
*/
private String lookupMapping(String ext)
{
String mime = m_mapping.get(ext);

if(mime == null)
return DEFAULT_MIME;

return mime;
}

/**
* Looks up a mimetype.
*
* @param path - the path to look at the mime for.
* @return - the mime of the path.
*/
public static String getMime(String path)
{
String ext = path.substring(path.lastIndexOf('.') + 1);
return getInstance().lookupMapping(ext);
}
}

Friday, December 14, 2012

Netcat - Tool Tuesday

Netcat (nc) is an invaluable tool that makes working with network connections as easy as working with text files (for those of you on UNIX, that is pretty dang easy!)

Set Up a Chat Server

This is a very quick way to set up a person to person chat over the Internet. It isn't encrypted, but it is simple and always works.
Server
# nc -l 8080
Client (replace the IP with any other host)
# nc 127.0.0.1 8080

Clone a Harddisk Over the Web

This is a great free and dirty replacement to Norton Ghost which helps you clone a harddisk from one machine to another.
Machine to Clone to
# nc -l 2222 > /dev/sdb
Machine to Clone From
# nc FROM_HOSTNAME 2222 < /dev/sda
(Note that if a quit character is encountered somewhere in the disk it will kill netcat.)

Transfer a File

Need to transfer a file between a computer but don't have SSH or FTP?
Sender
# nc  -l 8080 < /path/to/some.file
Receiver
# nc localhost 8080 > output.file 

See Web Headers

Ever want to see what your web-browser is sending out as headers?
Server
# nc -l 8080
Then point your web-browser to http://localhost:8080/ and watch the netcat window show what your browser is telling all sites you visit.
Example Output
GET / HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:17.0) Gecko/20100101 Firefox/17.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Cookie: wp-settings-time-1=1348281280

Leave Yourself a Backdoor

Warning, this will totally leave your system open to attackers (and some netcat builds don't even allow this flag for that reason, like Ubuntu's.)
Server
# nc -l 8080 -e /bin/bash
With this example, as soon as you connect, you'll be communicating with a BASH instance running at whatever security level you opened nc with. If you want your users to at least have to authenticate, use /bin/login instead.

Run a Portscan

If you don't have nmap installed, and don't want to build something in Python, you can quickly tell which ports are being used on a host using the following:
# nc -zv localhost 1-5000 2>&1 | grep succeeded
This command checks ports 1-5000 on localhost, and looks for any ports that are open. The reason we redirect stderr to stdout is grep only works on stdout, while nc outputs the information we want on stderr.

Thursday, February 16, 2012

SSH Honeypot Using Kippo

Honeypots are an excellent way to get involved with learning about the computer underground. When implemented properly you can get a clear view of what is happening on your network overall, and some of the tricks attackers attempt to use against vulnerable systems; you may even end up picking up some nifty tricks along the way.

There are three general types of Honeypots:
  • Low Interaction
    • These generally just log break in attempts; the source, destination, username and password that the attacker attempted to use to get in to the machine.
    • Very safe
  • Medium Interaction
    •  A small program that runs on a server that provides a very limited contained environment for attackers to break in to and play with. These Honeypots generally log what the user tries to do, capture files, and provide re-playable sessions.
    • Mostly safe if done properly
  • High Interaction
    • These can be anything from entire servers left vulnerable to virtual machines sitting on a network. They generally allow all inbound and outbound connections and are full machine implementations.
    • Dangerous, and illegal in some places, as you are knowingly running malware.

The first type of honeypot works well for system administrators that just want to keep an eye on global traffic and perhaps even characteristics of different botnets that have sprung up.

The second type (medium interaction) when implemented properly can be an excellent tool for studying the first part of many hacks, while providing the network relative security.

The third type of honeypot, which allows full connections in and out is incredibly dangerous and irresponsible to run, as any mistake done when implementing them, and even things not seen as mistakes (such as full blown outbound connections) may cause dangers to other servers on the Internet.

Kippo
Kippo is a medium interaction honeypot that is written in Python using the Twisted framework. It provides what appears to attackers to be a Unix/Linux system, and allows those who run it to easily add new "commands" or files to the system through a simple plugin system (beyond the scope of this article).

One of Kippo's greatest benefits is its extensive logging capabilities; entire sessions can be played back and studied at a later time, and all files downloaded by attackers are stored and saved so you can look through them at your leisure.

Kippo should not be run as root (obviously) to avoid any potential breaks in the program from being able to execute code as an administrator. It can still be set up in three easy steps however:

  1. Download and extract kippo as a user (probably best if you create a new one for the kippo server)
  2. Add a line like the following to your crontab, this will make sure kippo reboots when the server does:
    @reboot cd /home/username/kippo-0.5/; ./start.sh 
  3. Port forward your SSH port to 2222 (where kippo lives)
    sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 22 -j REDIRECT --to-port 2222
  4. Start kippo by running "start.sh" in the extracted directory
  5. (Optional) Save your iptables configuration to be re-set up after reboot: http://www.debian-administration.org/articles/445

Wednesday, November 23, 2011

Database Password Hashing

Okay, so you want to make sure your database is secure, no matter what your front-end is? Here is a simple script that does exactly that, hashes passwords in the tables as they go in with a salt and provides an easy way to check logins against the user table. If you want, you can even hash user-names too, that way even if your database is completely stolen it isn't insecure:


-- Users is a table, password hash, up to 100 chars, currently used is
-- sha1 because it is nativly supported in PHP.
CREATE TABLE `Users` (
`usr_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(20) NOT NULL,
`usr_password` VARCHAR(100) NOT NULL
) ENGINE = INNODB;

-- Yes, secure things as they are added, using the username as a salt.
CREATE TRIGGER user_input BEFORE INSERT ON `Users` FOR EACH ROW SET NEW.usr_password = SHA1(CONCAT(NEW.usr_password, NEW.username));

CREATE TRIGGER user_update BEFORE UPDATE ON `Users` FOR EACH ROW SET NEW.usr_password = SHA1(CONCAT(NEW.usr_password, NEW.username));

-- Checks if a user with the given username and password exists in the
-- db, returns null if no and the ID if true.
delimiter |
CREATE FUNCTION CHECK_USER (usrname VARCHAR(20), password VARCHAR(1000))
RETURNS INT DETERMINISTIC
BEGIN
DECLARE tmp INT;
SELECT usr_id INTO tmp FROM Users WHERE username = usrname AND usr_password = SHA1(CONCAT(password,usrname));
RETURN tmp;
END|
delimiter ;

A small sample of the program in action:

    mysql> select * from Users;  
Empty set (0.00 sec)

mysql> INSERT INTO Users (username, usr_password) VALUES ("Cookie", "Monster"), ("Big", "Bird");
Query OK, 2 rows affected (0.07 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> select * from Users;
+--------+----------+------------------------------------------+
| usr_id | username | usr_password |
+--------+----------+------------------------------------------+
| 3 | Cookie | 00c66ad8335364be46f67da3699be142189b2aa9 |
| 4 | Big | 4e49d9c043ee8733f6019cc777d65421721333c7 |
+--------+----------+------------------------------------------+
2 rows in set (0.00 sec)

mysql> SELECT CHECK_USER("Big", "Bird");
+---------------------------+
| CHECK_USER("Big", "Bird") |
+---------------------------+
| 4 |
+---------------------------+
1 row in set (0.01 sec)

mysql> SELECT CHECK_USER("Oscar", "Grouch");
+-------------------------------+
| CHECK_USER("Oscar", "Grouch") |
+-------------------------------+
| NULL |
+-------------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> SELECT CHECK_USER("Big", "Baby");
+---------------------------+
| CHECK_USER("Big", "Baby") |
+---------------------------+
| NULL |
+---------------------------+
1 row in set, 1 warning (0.00 sec)

mysql>

Note that while all hashing may be done in the DB, it is still recommended you do it server side/client side too, as passwords may end up in SQL log files if not hashed beforehand. Everything will still work even if a password is hashed multiple times.

Wednesday, October 19, 2011

Real Time Header Editing with Paros

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

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

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





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


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

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

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

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

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

Tuesday, May 3, 2011

Protocols #6, Character Generator Protocol

In May of 1983, the Character Generator Protocol was introduced in RFC 864. It existed already on computers mainly as a test for terminals (TTYs in that image you can actually see a character test program) to make sure that they could properly display all of the characters in the vastly huge ASCII character set. Now ASCII is a bad joke. The protocol was introduced to do the same thing over networks (an early ping like utility).


In the modern day Internet, the original protocol needs to be amended slightly: the RFC states that the protocol will continue sending information until the client closes the connection; however I made it auto-close after 1000 outputs because eventually node.js runs out of memory and dies. It would also be nice not to have all of your Internet connection lines taken up by three people that never closed their chargen. Without further ado:
#!/usr/bin/nodejs

var net = require('net');
var dgram = require('dgram');

var linewidth = 72; //Width of a line of text on the console.
var str = "";

//Generate from: ! to ~
for(var i = 33; i < 127; i++) {
str += String.fromCharCode(i);
}

//Make sure length is at least 512 bytes (max for udp)
for(var i = str.length; i < 512; i += str.length)
{
str += str;
}


function getline(lineno) {
return str.substr(lineno % (127 - 33), linewidth ) + "\n";
}

//TCP
var tcpserver = net.createServer(function (socket) {
var j = 0;
while(j < 1000)
{
socket.write(getline(j));
j++;
}
socket.end();
})

//UDP
var udpserver = dgram.createSocket("udp4", function (msg, rinfo) {
var ret = new Buffer(str.substr(0, Math.floor(Math.random()*(513))));
udpserver.send(ret, 0, ret.length, rinfo.port, rinfo.address);
});

//Bind and serve (Port 19 is actual)
tcpserver.listen(8019, "127.0.0.1");
udpserver.bind(8019, "127.0.0.1");

As usual the port numbers have been boosted by 8000, so before actually using, change those and the host computer IP addresses.

Tuesday, April 19, 2011

Protocols #5, Quote of the Day

The quote of the day protocol, defined in RFC 865, specifies a standard that when implemented will return a quote when port 17 is connected to in TCP, or when a datagram is sent to it in UDP.

This implementation in Node.js, is similar to the daytime protocol I built earlier, it introduces an array of quotes of which one is randomly chosen to
#!/usr/bin/nodejs
var net = require('net');
var dgram = require('dgram');

var quotes = [
"Time is an illusion. Lunchtime doubly so.\n - Douglas Adams",
"The quieter you become the more you can hear.\n - Baba Ram Dass",
"Wisdom lies in knowing when to remember and when to forget.\n - Ayn Rand",
"Chance favors the prepared mind.\n - Louis Pasteur",
"The advertisement is the most truthful part of a newspaper.\n - Thomas Jefferson",
"To communicate through silence is a link between the thoughts of man.\n - Marcel Marceau",
"There are periods when...to dare, is the highest wisdom.\n - William Ellery Channing"
];

function getquote() {
randno = Math.floor ( Math.random() * quotes.length );
return quotes[randno] + "\n";
}

//TCP
var tcpserver = net.createServer(function (socket) {
socket.end(getquote());
})

//UDP
var udpserver = dgram.createSocket("udp4", function (msg, rinfo) {
var ret = new Buffer(getquote());
udpserver.send(ret, 0, ret.length, rinfo.port, rinfo.address);
});

//Bind and serve (Port 17 is actual)
tcpserver.listen(8017, "127.0.0.1");
udpserver.bind(8017, "127.0.0.1");