Skip to content

Instantly share code, notes, and snippets.

@brandon15811
Created December 13, 2014 03:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brandon15811/4f451cc7c51b8ab5e0e7 to your computer and use it in GitHub Desktop.
Save brandon15811/4f451cc7c51b8ab5e0e7 to your computer and use it in GitHub Desktop.
Very basic DNS server written in bash
#!/bin/bash
#Based off of http://code.activestate.com/recipes/491264/
if [ "$1" == "startserver" ]; then
ncat -u -l 5355 -c $(readlink -f $0) -k
exit
fi
timeout 1s cat /dev/stdin > input
req=$(cat input | xxd -p)
#Functions from http://ubuntuforums.org/showthread.php?t=735140&p=4584216#post4584216
ord() {
printf '%d' "'$1"
}
chr() {
printf \\$(printf '%03o' $1)
}
#Modified to be like javascript slice()
slice() {
begin=$(($2 + 1))
end=$3
echo -n $1 | xxd -p -r | cut -b $begin-$end | tr -d '\n'
}
IP='192.168.1.1'
type=$(($(($(ord $(slice $req 2 3)) >> 3)) & 15))
if [ "$type" -eq 0 ]; then
ID=$(slice $req 0 2 | xxd -p )
#echo -en "'"$ID"'" | tr -d $'\n'
ini=12
lon=$(ord $(slice $req $ini $(($ini + 1))))
domain=''
while [ "$lon" -ne 0 ]; do
domain=${domain}$(slice $req $(($ini + 1)) $(($ini + $lon + 1)))'.'
#echo $domain
ini=$(($ini + $lon + 1))
#echo $ini
lon=$(ord $(slice $req $ini $(($ini + 1))))
done
if [ ! -z "$domain" ]; then
flags='8180'
question=$(slice $req 4 6 | xxd -p)
answer=$(slice $req 4 6 | xxd -p)
answer2='00000000'
domainQuestion=$(slice $req 12 | xxd -p)
domainPointer='c00c'
resType='0001' #A record
classType='0001' #IN, internet class
ttl='0000003c' #1 minute
resLength='0004' #Data length: > 4 bytes
resIP=''
for i in `seq 1 4`; do
resIP=${resIP}$(chr $(echo $IP | cut -d '.' -f $i) | xxd -p)
done
res=${ID}${flags}${question}${answer}${answer2}${domainQuestion}${domainPointer}
res=${res}${resType}${classType}${ttl}${resLength}${resIP}
echo -n $res | xxd -p -r
fi
fi
sleep 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment