Skip to content

Instantly share code, notes, and snippets.

@cyphunk
Last active July 19, 2023 10:30
Show Gist options
  • Save cyphunk/a8be63a6bbfced4b105e9f23b45f564e to your computer and use it in GitHub Desktop.
Save cyphunk/a8be63a6bbfced4b105e9f23b45f564e to your computer and use it in GitHub Desktop.

Useful Commands

Some of it related to embedded analysis, some of it not.

Table of Contents

Dump or copy via nc

On destination: nc -l 4444 > incoming.tar.bz2 On source: tar -jcv files dirs files | nc <client> 4444

Alternatives

On destination: nc -l 4444 | tar -jxvk
On source: tar -jcv /[^p]* | nc <client> 4444 (avoid proc)
or source: tar -zxcv / --one-file-system / | nc <client> 4444 (full gnu tar, restrict to disk)
or source: dd if=/dev/mtdblock0 bs=2048 | nc <client> 4444 (block device)

If destination cannot listen you can also reverse the order with:

On destination: nc <source_ip> 4444 > incoming
On source: cat outgoing | nc -l 4444

Check rules on destination firewall (iptables/ufw linux/ubuntu, 'ipfw add allow 4444 from any to any' osx) and source (iptables -A OUTPUT -j ACCEPT)

Dump or copy via ssh

From destination: ssh root@source "tar -czpf - /" > sshfs.tar.gz
Or from destination: for b in $(ssh root@source ls /dev/mtd*); do echo $b; /usr/sbin/ssh root@source dd if=$b bs=2048 > $(basename $b); done
From source: tar -cpf - / | ssh user@destination "tar xpf - -C dest_dir"
Or from source: cd /; tar -czpf - $(ls /|grep -v proc|grep -v sys) | ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password user@dest "cat > fs.tar.gz"

If you need to open your firewall (iptables -A OUTPUT -j ACCEPT same on INPUT if you really do not care about your target). Check with a packet sniffer.

For source to destination method, add temporary user:

dir=$(mktemp --dry-run)
date=$(date -d tomorrow +%Y-%m-%d)
echo "user added will expire in on \"$date\" with home at \"$dir\""
sudo userdel tmpuser
sudo useradd --expiredate $date --no-user-group \
	-c "Tmp user" --create-home --home "$dir" \
	--shell /bin/bash tmpuser
sudo passwd tmpuser

Dump or copy via serial

First login to target serial and set stty raw. to dump faster also stty $((115200*4))

(stty raw 115200; cat > recieved.txt) < /dev/ttyUSB0
echo "dd if=etc.tar.gz          " > /dev/ttyUSB0
#echo "dd if=etc.tar.gz conv=swab" > /dev/ttyUSB0

# monitor rate of file transfer
tail -f recieved.txt | pv > /dev/null

Examine the output file and check for proper endianness using hexdump on the target itself. When dump is correct then remove command string from prefix and command output+prompt from suffix. Determine lengths by hand.

strings recieved.txt | head -1 | wc -c
strings recieved.txt | tail -3 | wc -c
dd if=recieved.txt of=recieved.cut.txt bs=1 skip=27 count=$(( `stat -c%s recieved.txt` - 27 - 54 ))
# check
xxd recieved.txt | head -2 && echo && xxd recieved.cut.txt | head -2 && echo
xxd recieved.txt | tail -5 && echo && xxd recieved.cut.txt | tail -5 && echo

If you still have issues, such as seeing 0x0d0x0a, or 0x0a0x0a, it is likely you need to change the stty settings on the target itself stty raw and then continue. You may also need to use the conv=swab swaps bytes dd command instead.

Copy proc or sys

SRC=/proc
DST=/var/tmp
MAXDEPTH="-maxdepth 4" #blank for no max
mkdir -p $DST/$SRC
find $SRC $MAXDEPTH | while read F ; do
   echo $F | grep "proc/kmsg"     && continue #blocking
   echo $F
   test -L $F && cp -a $F $DST/$F && continue #symlink
   test -d $F && mkdir $DST/$F    && continue #directory
   test -f $F && cat $F > $DST/$F && continue #file
done

TFTP walk

Given a file list

for file in file1 file2 file3
do
	echo get $file | tftp <TARGET_IP>
done 

tcpdump filters

tcpdump -i <inteface> not port 22
tcpdump -n -w output.cap -i <inteface> not port 22 (-n ignore hostname, add -s 0 to save full packet)

Check SSL Certificates

Using cut+paste of cert: openssl x509 -text -noout
Using file: openssl x509 -text -noout -in /tmp/file
Checking priv key: openssl rsa -text -noout -in /tmp/privkey.pem
For public keys add: -pubin

Comparing to values of the modulos to see that they correspond to eachother.

-noout: write result to stdout
-text: output information about in plaintext form.

Get rsa pubkey from priv: openssl rsa -text -pubout -in /tmp/privkey

OSX DHCPD/TFTPD

# Add host:
sudo gvim /etc/bootptab
sudo /bin/launchctl load -w /System/Library/LaunchDaemons/bootps.plist
sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/bootps.plist
sudo /bin/launchctl load -w /System/Library/LaunchDaemons/tftp.plist
sudo /bin/launchctl unload -w /System/Library/LaunchDaemons/tftp.plist

Optionbally bootpd will start when enabling internet sharing.

Linux DHCP Server

alias s=sudo
s killall dhclient
s ifconfig eth0 192.168.1.1 netmask 255.255.255.0
d=`mktemp -d`
cat >$d/dnsmasq.conf << EOF
 dhcp-option=option:router,192.168.1.1
 dhcp-range=192.168.1.10,192.168.1.254,255.255.255.0,96h
EOF
dnsmasq -d -i eth0 \
 --conf-file=$d/dnsmasq.conf \
 --leases-file=$d/leases \
 --pid-file=$d/pid

s sysctl .net.ipv4.ip_forward
s sysctl .net.ipv4.ip_forward=1
# NAT
s iptables -A FORWARD -i wlan0 -o eth0 -s 192.168.1.0/24 -m conntrack --ctstate NEW -j ACCEPT
s iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
s iptables -A POSTROUTING -t nat -j MASQUERADE
# OR
#s iptables -A POSTROUTING -t nat -o eth0 -j MASQUERADE

OSX DNS

The DNS proxy used with internet sharing for pre Mavericks used named zones. For > Mavericks mDNSResponder is used (source code). It might be possible to configure the zones somehow but I could not figure it out yet (dig around /etc/dnsextd.conf). Instead I'm using dnsmasq (discussions 1 2). In fact you should use dnsmasq anyway. Apple appear to change their DNS/Bootp/InternetSharing configurations every release:

#execute this interface before executing dhcpd or internet sharing
sudo ifconfig en0 192.168.2.1
sudo dnsmasq --no-daemon -listen-address=192.168.2.1 \
     --address=/localtest./192.168.2.22

Test passthrough dig @192.168.2.1 google.com and localtest dig @192.168.2.1 localtest.

To configure InternetSharing or bootpd to provide clients with your IP edit /etc/bootpd.plist and /etc/bootptab if you want to provide a file.

<key>dhcp_domain_name_server</key>
<array>
        <string>192.168.2.1</string>
</array>

Remote Wireshark

Only works on wireshark installations that support the option to pipe input. Tcpdump output of <remote_listener> eth0 over SSH to local wireshark:

ssh <remote_listener> tcpdump -s0 -w - 'not port 22' | wireshark -k -i -

Embedded Tcpdump

If a target device does not provide TCP dump, or any other bin for that matter, you can attempt to find one mostly compatible with the target linux system using a distro's cross platform packages, such as debian.

Download:

Just download copy some tcpdump for the platform. When you execute you should get some errors telling you the version of libc you need, or libpcap. Then walk back through different distro releases until you find a tcpdump with prerequisites that seem to match those required on the platform.

Extract packages, such as: ar -x libpcap0.8_0.9.5-1_mipsel.deb && tar zxvf data.tar.gz. Then Copy over somehow.

On target:

  • ln -s libpcap.so.0.8 libpcap.so.0.9.8

Update: [canexe](https://github.com/cyphunk/humanism.sh/commit/8f77d2b16681b4112d3b6c24a67b8cb4ba81cd1e) automates this

Unix Socket debug

Can use either Netcat-openbsd, socat or strace. These methods, except for strace, allow you to debug and connect (see):

  • nc -U /path/to/unixsocket
  • socat UNIX-CONNECT:/path/to/unixsocket STDIN
  • strace -e trace=read,write -e read=29,30 -e write=29,30 -p <pid> 29,30 are file descriptors (lsof or proc)

For embedded target example - netcat-openbsd:

wget http://ftp.de.debian.org/debian-archive/debian/pool/main/n/netcat-openbsd/netcat-openbsd_1.89-3_mipsel.deb
wget http://ftp.de.debian.org/debian-archive/debian/pool/main/g/glib2.0/libglib2.0-0_2.16.6-3_mipsel.deb
wget http://ftp.de.debian.org/debian-archive/debian/pool/main/p/pcre3/libpcre3_7.6-2.1_mipsel.deb
wget http://ftp.de.debian.org/debian-archive/debian/pool/main/v/vim/vim-common_7.0-122+1etch5_mipsel.deb
for deb in ./*.deb; do ar -x $deb; tar zxvf data.tar.gz; done
tar -cf nc.tar bin/nc.openbsd usr/lib/libglib-2.0.so.0* usr/lib/libpcre.so.3* usr/bin/xxd
cat nc.tar | nc -l 4444

target:

nc 192.168.2.1 4444 > /var/tmp/nc.tar
cd /var/tmp
tar xvf nc.tar
LD_LIBRARY_PATH=/var/tmp/usr/lib /var/tmp/bin/nc.openbsd -U /path/to/unixsocket | /var/tmp/usr/bin/xxd

Or socat:

wget http://ftp.de.debian.org/debian-archive/debian/pool/main/s/socat/socat_1.4.3.1-1_mipsel.deb
wget http://ftp.de.debian.org/debian-archive/debian/pool/main/r/readline5/libreadline5_5.2-2_mipsel.deb
wget http://ftp.de.debian.org/debian-archive/debian/pool/main/n/ncurses/libncurses5_5.5-5_mipsel.deb
for deb in ./*.deb; do ar -x $deb; tar zxvf data.tar.gz; done
tar -cf socat.tar usr/bin/socat lib/libreadline* lib/libncurses* 
cat socat.tar | nc -l 4444

target (plugin.ctl socket in question):

nc 192.168.2.1 4444 > /var/tmp/socat.tar
cd /var/tmp
tar xvf socat.tar
SOCKET=/var/run/plugin.ctl
mv $SOCKET /var/run/sock.original && \
LD_LIBRARY_PATH=/var/tmp/lib /var/tmp/usr/bin/socat -t100 -x -v UNIX-LISTEN:$SOCKET,mode=777,reuseaddr,fork UNIX-CONNECT:/var/run/sock.original && \
mv /var/run/sock.original $SOCKET

Gigbit Sniffing

The world of devices are moving to gigabit only interfaces. A simple hub for sniffing might be due. Using a 2nd gigabit network card setup a bridge (linux/osx) with:

sudo ifconfig bridge0 create
sudo ifconfig bridge0 addm en0 addm en6
sudo ifconfig bridge0 up

MiTM SSL

Via burp, Via apache, Via mitmproxy from cortesi, Via proxystrike. In firefox might set in about:config to true: browser.xul.error_pages.enabled and browser.xul.error_pages.expert_bad_cert.

  • Burpsuite:
    • Import a given cert from target
    • Export burp's self signed cert
      • import to browser
      • import to java: keytool -import -alias burl -file <exportedburpcertfile>
    • PS: if require upstream proxy fill in under burp Options / Connections / Upstream Proxy Servers. eg.: Dest *, host , port . Likely do NOT require transparent proxying then in the Proxy / Options

Proxy all packets per program

Force all packets from programs running with group ID through a proxy on port 8080

GRP=proxy-all
iptables -t mangle -A OUTPUT -m owner --gid-owner $GRP -j MARK --set-mark 2
iptables -t mangle -A OUTPUT -m owner --gid-owner $GRP -j CONNMARK --save-mark
iptables -t nat -A OUTPUT -m mark --mark 2 -p tcp --dport 1:65535 -j DNAT --to 127.0.0.1:8088
iptables -A OUTPUT -m mark --mark 2 -p tcp --dport 1:65535 -j LOG --log-prefix 'PACKETPROX' --log-level 0
sg -c "firefox"

Quick split of file into parts

for i in 0x06171cb4 0x06671547; do splitfile.sh <filename> $i 0xffffffff <filename>_$i; done

or

for i in 0x06171cb4 0x06671547; do dd bs=1 if=<filename> skip=$(($i)) of=<filename>_$i; done

Connecting to onioned ssh

Using Tor to remotely connect to a SSH host behind iron-curtains.

On server:

mkdir /var/lib/tor/ssh and set in torrc HiddenServiceDir /var/lib/tor/ssh/ and HiddenServicePort 22 127.0.0.1:22. To find onionhostname cat /var/lib/tor/ssh.

On client:

Add to ~/.ssh/config Host *.onion and ProxyCommand socat STDIO SOCKS4A:localhost:%h:%p,socksport=9050. Optionally add a helpfull alias that uses netcat to route through tor alias tor-ssh='ssh -o ProxyCommand="nc -X 4 -x localhost:9050 %h %p"'. now ssh [email protected]

Binary Edit on Shell

  • Example with base64 encoded binary:
    echo "cSEk" | base64 -d | xxd -p | sed 's/71/72/' | xxd -p -r | base64
    turns "q!$" into "r!$"
    "cSEk" is base64 for "q!$"
    xxd turns the binary hex string
    sed changes the hex (0x71=q, 0x72=r)
    xxd turns modified hex into binary

  • Example using known offsets
    check char:
    dd if=<file> bs=1 skip=<offset> count=1
    replace with char:
    echo -n "A" | dd of=<file> bs=1 seek=<offset> count=1 conv=notrunc
    replace with bin:
    echo -n "30" | xxd -r -p | dd of=<file> bs=1 seek=<offset> count=1 conv=notrunc
    replace with sed:
    dd if=<file> bs=1 skip=<offset> count=1 | sed 's/e/E/' | dd of=<file> bs=1 seek=<offset> count=1 conv=notruc
    check:
    dd if=<file> bs=1 skip=<offset> count=1
    example find and replace 0.12. with 0.13:
    offsets=$(bgrep $(echo -n "0.12"|xxd -p) $FILE -C 0 | sed 's/.*offset:\(.*\) find.*/\1/')
    echo check; for o in $offsets; do echo offset $o; dd if=$FILE bs=1 skip=$((0x$o)) count=10;done
    echo change; for o in $offsets; do echo offset $o; echo -n "3" | dd of=$FILE bs=1 seek=$((0x$o + 3)) count=1 conv=notrunc; done
    echo check; for o in $offsets; do echo offset $o; dd if=$FILE bs=1 skip=$((0x$o)) count=10;done

Dynamic Assisted RE

Find PIDs with known thread or process name

(also try sched in addition to comm):

find /proc -name comm | while read F; do 
  grep -q gps $F && echo $F; 
done

Find PIDs that load a library

show offset:

find /proc -name maps | while read F; do 
  grep -i driver.so $F && echo $F
done

Find PID responsible for network port

# Monitor on target with:
for pid in `ls`; do
  echo -en "\n\n$pid\n";
  strace -i -v -p $pid 2>&1 \
   | egrep -v 'read|mmap|fstat|open|time|ioctl|write|lseek|pselect|munmap|close|sigreturn|tgkill|nanosleep|rt_sig|restart_|select|pause|futex|SIGUSR1|gettid|madvise|exit|get_robus|clone|child_stack|detached|unfinished' &
  sleep 5 && killall strace;
done

# Stimulate from other host with:
while [ 1 ]; do 
  echo "qwerty" | nc $IP $PORT & p=$!; 
  sleep 1 && kill $p; 
done

Static Assisted RE

Find all server (c++)
grep -r -l socket . | xargs grep -l bind | xargs grep -l listen | xargs grep -l accept

Find all client (C++)
grep -r -l socket . | xargs grep -l connect

MITM Layer 2

Ettercap: s ettercap -T -Q -i wlan0 -o -M arp /<ROUTER>/ /<TARGET>/ (T text interface, Q superquiet, o onlymitm)

Examples (from man)

ettercap -T -M arp // //
   Perform the ARP poisoning attack against all the hosts in the LAN.
ettercap -T -M arp:remote /192.168.1.1/ /192.168.1.2-10/
   Perform  the  ARP poisoning against the gateway and the host in the
   lan between 2 and 10. The 'remote' option is needed to be able to 
   sniff the remote traffic the hosts make through the gateway.

Netcat without netcat

1 2 3 but to emulating checking a header, such as ssh server version, perhaps just this

Netstat without netstat

Using proc. Busybox text

Small version:

dir=/proc
cat $dir/net/tcp | while read _ loc rem _ _ _ _ _ _ inode _; do
  echo "$loc $rem ($inode)"
  # find pid's with fd links to inode
  for pid in `ls $dir`; do
    test -r $dir/$pid/fd || continue
    ls -l $dir/$pid/fd | grep -q ":\[$inode\]" || continue
    name=$(test -r $dir/$pid/cmdline && cat $dir/$pid/cmdline | tr '\000' ' ')
    echo " pid $pid $name"
  done
done

More structured output:

dir="/proc"
UDP=$(cat $dir/net/udp | tail -n +2)
TCP=$(cat $dir/net/tcp | tail -n +2) 
# echo "$list" | while read _ loc rem _ _ _ _ _ _ inode _; 
# do echo "$loc - $rem - $inode"; done
echo "$TCP" | while read _ loc rem _ _ _ _ _ _ inode _; do
  loc_ip=$(printf "%d.%d.%d.%d" "0x${loc:6:2}" "0x${loc:4:2}" "0x${loc:2:2}" "0x${loc:0:2}")
  loc_port=$(printf "%d" "0x${loc:9:4}")
  rem_ip=$(printf "%d.%d.%d.%d" "0x${rem:6:2}" "0x${rem:4:2}" "0x${rem:2:2}" "0x${rem:0:2}")
  rem_port=$(printf "%d" "0x${rem:9:4}")

  printf "(inode %-7d) %16s:%-5d %16s:%-5d\n" $inode $loc_ip $loc_port $rem_ip $rem_port

  # find pid's with fd links to inode
  for pid in `ls $dir`; do
    test -r $dir/$pid/fd || continue
    ls -l $dir/$pid/fd 2>/dev/null | grep -q ":\[$inode\]" || continue
    command -v strings >/dev/null &&
      name=$(test -r $dir/$pid/cmdline && strings $dir/$pid/cmdline | xargs) || name=$(test -r $dir/$pid/cmdline && cat $dir/$pid/cmdline | tr '\000' ' ')
    printf "(inode %-7d) %16s:%-5d %16s:%-5d" $inode $loc_ip $loc_port $rem_ip $rem_port
    echo " pid $pid $name"
  done
done

Better would be iterate over pid's from lowest to highest caching inodes. According to net-tools netstat.c the first pid to associate with inode should be the winning pid

SMTP TLS Test Mail

With auth

# change USER, -host and email addrs
USER="foo"
read -p "password for $USER" PASSWORD
AUTH=$(printf "$USER\0$USER\0$PASSWORD" | base64)
(
sleep 1; echo "EHLO MAIL";
sleep 1; echo "AUTH PLAIN";
sleep 1; echo "$AUTH"
sleep 1; echo "MAIL FROM: <[email protected]>";
sleep 1; echo "RCPT TO: <[email protected]>";
sleep 1; echo "RCPT TO: <[email protected]>";
sleep 1; echo "DATA";
sleep 1; echo "Subject: tls587 authed > remote - $(date +%s)"; sleep 1; echo;
sleep 1; echo "Message"; sleep 1; echo "."; sleep 1;
) | openssl s_client -host bar.eu -port 587 -starttls smtp

Without auth

(
sleep 1; echo "EHLO MAIL";
sleep 1; echo "MAIL FROM: <[email protected]>";
sleep 1; echo "RCPT TO: <[email protected]>";
sleep 1; echo "DATA";
sleep 1; echo "Subject: tls25 public > local - $(date +%s)"; sleep 1; echo;
sleep 1; echo "Message"; sleep 1; echo "."; sleep 1;
) | openssl s_client -host bar.eu -port 25 -starttls smtp

Strace cheat sheet

  • -s 65535 strsize prevents argument truncation. eg. see full recvfrom sendto packet
  • strace -e trace=read,write -e read=29,30 -e write=29,30 -p <pid> to debug sockets. 29,30 are file descriptors (lsof or proc) (from Unix Socket debug)
  • see Find PID responsible for network port

Mount NAND Image

Mount image through loop

sudo fdisk -lu ./mmcblk0_image
# same as:
sudo losetup /dev/loop0 mmcblk0
fdisk -l /dev/loop0
# then
mount /dev/loop0p1 /mnt/

Nandsim and ubifs

modprobe nandsim first_id_byte=0x20 second_id_byte=0xaa \
third_id_byte=0x00 fourth_id_byte=0x15
modprobe mtdblock
cat /proc/mtd
dd if=mmcblk0_image of=/dev/mtdblock0 bs=2048
modprobe ubi mtd=0
ubinfo
ubinfo /dev/ubi0 -a
mkdir -p /mnt/tmp
for l in /dev/ubi0*; do \
	name=`basename $l`; mkdir /mnt/tmp/$name; \
	dd if=/dev/$name of=/tmp/$name; mount -o /tmp/$name /mnt/tmp/$name; \
done

For instruction on nandsim first_id_byte, etc, http://www.linux- mtd.infradead.org/faq/nand.html#L_nand_nandsim

Inverted Serial UART

When a target appears to have inverted serial uart.

  • Change FTDI USB2Serial configuration. Set RX and TX lines to inverted with the FT PROG windows utility or on linux use ftx-prog or ftdi_prog. (alternatively the ftdi_eeprom utility that comes with libftdi: sudo ftdi_eeprom --read-eeprom /usr/share/doc/libftdipp1/example.conf. That will write eeprom to eeprom.new (filename value in the conf file) but this is a binary file you must then modify and write back)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment