Hacker Tools II

Brief overview

  • Browser and web tips and tricks
  • Security and privacy
  • Remoting
  • System and application introspection and debugging
  • Network debugging

This workshop is meant as an exposure to commonly-used tools; there is no intended link between everything mentioned today, although some stories will be thrown in here and there to provide some rationale and context.

Browser and web

Keyboard shortcuts

  • C-t: new tab
  • C-T: reopen closed tab
  • C-l/M-d/F6: jump to address bar
  • C-f: search in page
  • C-w/C-F4/Middle-click: close tab
  • F12: developer tools

More: Firefox; Chrome

Google search operators

  • "X": must appear and must appear exactly
  • site:xyz.com: results from xyz.com only
  • filetype:xyz: xyz filetype only
  • define:xyz: define xyz

More: Google docs; External docs

Firefox bookmark keywords

No real equivalent exists in Chrome/ium.

Browser extensions

Misc. useful web APIs

Security and privacy

Password managers

  • KeePass: open-source, offline, .NET
  • KeePassXC: open-source, C++ port of above (works better for Linux/Mac)
  • pass: open-source, CLI, GPG-based
  • Bitwarden: open-source, self-hostable cloud based (also see bitwarden_rs)
  • 1Password: commercial 👎, cloud-based
  • LastPass: commercial 👎, cloud-based

Full-disk encryption

Protect your data at rest

  • Windows: BitLocker (only available on Pro)
  • Linux: LUKS/dm-crypt
  • macOS: FileVault
  • Cross-platform: VeraCrypt

File-based encryption

Protect individual files

VPN services (paid)

Protect your online privacy

Comparison table

VPN software

Run your own VPN

Setting up a server is out of scope. Here are some guides: OpenVPN, WireGuard

WireGuard is a very modern (but very new) VPN. If you are setting up a new VPN, and it meets your needs, use it!

Messengers

There are many other messengers but most offer no privacy at all.

See privacytools.io for more privacy-focused alternatives to common software.

You could consider reducing your dependency on Google, for example, by moving to a different email provider.

Remoting

SSH and Windows Remote Desktop

SSH on Windows

Did you know? Microsoft ported OpenSSH to Windows.

It is included by default from Windows 10 1803 and up. Try it! If not, see here.

SSH keys

A more convenient and secure alternative to passwords.

Many servers nowadays are configured to reject allow password authentication by SSH.

If you use Git on the command line with GitHub/GitLab/etc., you already have an SSH key!

SSH key generation

  1. ssh-keygen -t ed25519
    (or -t rsa -b 4096 if you need RSA)
  2. Default location is OK
  3. Enter a passphrase

Your private key is in .ssh/id_ed25519 (KEEP THIS SAFE), and public key .ssh/id_ed25519.pub

SSH key generation

  • On Windows >=10 1803, you can just use ssh-keygen.
  • Alternatively, use PuTTY/PuTTYgen.

SSH key usage

Just ssh-copy-id username@server.

Alternatively, manually (on the remote): (if you use PuTTY/etc.)

mkdir .ssh
echo "<insert id_ed25519.pub here>" >> .ssh/authorized_keys
chmod 700 .ssh
chmod 600 .ssh/authorized_keys

(insert your public key into .ssh/authorized_keys on the remote and set the permissions correctly)

(For SoC students: try this with Sunfire!)

SSH key agents

A daemon that runs in the background and keeps your keys unlocked for use, so you don't have to keep keying in passwords.

Try:

eval $(ssh-agent)
ssh-add
ssh ...

Typically we configure our profile/bashrc/etc. to automatically start an agent if needed and include the environment variables in each shell.

SSH key agents

On Windows with PuTTY, use Pageant

SSH port forwarding

E.g. if you need to connect to a local service on the remote, or if you need the remote to connect to a service on your computer.

  • ssh -L 12345:localhost:56789: 12345 locally -> localhost:56789 from the remote
  • ssh -R 12345:localhost:56789: 12345 on remote -> localhost:56789 from local machine

You can connect to other hosts, of course.

  • ssh -L 12345:google.com:443: you can open https://localhost:12345, and it will forward to Google but from the remote

This is how SSH can be used as a proxy of sorts.

SSH SOCKS proxy

SSH can act as a SOCKS proxy and let any application forward its connections.

  • ssh -D 12345: open a SOCKS proxy locally, forward to remote
  • ssh -R 12345: open a SOCKS proxy on the remote, forward to local

You could even use this with your browser, if you needed to e.g. quickly bypass a firewall.

Windows with PuTTY

SSH X forwarding

Allow applications on the remote to access your local X server

This lets you interact with graphical programs on the remote.

ssh -X

(For SoC students: try this with Sunfire!)

(Windows: Cygwin with PuTTY; out of scope)

SSH configuration

Set settings for certain hosts so you can avoid specifying username/other settings every time

Insert to .ssh/config: (for SoC students, this example is for Sunfire)

Host xcn?? xcn??? sunfire sunfire0
  HostName %h.comp.nus.edu.sg
  User soc_username_here

Then you can just ssh sunfire in future!

Other common host options: LocalForward RemoteForward ForwardX11 ProxyJump

SSH configuration

ProxyJump causes "ssh(1) to connect to the target host by first making a ssh(1) connection to the specified ProxyJump host and then establishing a TCP forwarding to the ultimate target from there."

In .ssh/config: (for SoC students: try this with the compute cluster)

Host xcn?? xcn???
ProxyJump soc_username_here@sunfire.comp.nus.edu.sg
User soc_username_here

Then ssh xcnc7, etc.

SSHFS

Mount a remote directory that you can access via SSH

mkdir directory_name
sshfs user@sunfire.comp.nus.edu.sg: directory_name

Now your Sunfire home directory is accessible at directory_name/

To umount:

fusermount -u directory_name

Mosh

A shell (like SSH) that works with intermittent internet connections (like on your phone).

Needs to be installed on both client and server (but root not required!)

Just replace ssh by mosh. More details

Windows RDP

Remotely access a Windows computer.

RDP client included with all Windows versions.

Officially only Pro and above editions can be connected to.

But see rdpwrap.

Linux RDP server

Xrdp (Arch wiki setup)

Linux RDP client

FreeRDP

System and application introspection and debugging

GDB

Command line debugger: gdb myprogram

Common commands:

  • r: run program
  • start: run and break at entrypoint
  • c: continue program
  • bt: show backtrace/stacktrace
  • b line: set breakpoint at line
  • d n: delete breakpoint n
  • p expr: print the value of expr
  • l: dump source around current line
  • disas: dump machine code around current instruction
  • help cmd: show help for cmd

GDB

Stepping commands:

  • s: step one line
  • si: step one instruction
  • n: step one line, but don't follow calls
  • ni: step one instruction, but don't follow calls
  • finish: run until this function returns
  • c: continue a paused program
  • reverse-cmd: the above stepping commands, but in reverse; only after record
  • record: start recording execution

Example program

#include <stdio.h>

int access(int *array, int index) {
    return array[index];
}

int main() {
    int arr[] = { 0, 1, 2 };
    printf("%d\n", access(0, 1));
}

Compile: gcc -g -o test test.c

Run: ./test

Segmentation fault ☹️

Debug it

$ gdb test
GNU gdb (GDB) 8.2.1
(gdb) r
Starting program: test

Program received signal SIGSEGV, Segmentation fault.
0x0000000100001168 in access (array=0x0, index=1) at test.c:4
4	    return array[index];
(gdb) bt
#0  0x0000000100001168 in access (array=0x0, index=1) at test.c:4
#1  0x00000001000011a7 in main () at test.c:9
(gdb) b 4
Breakpoint 1 at 0x100001154: file test.c, line 4.
(gdb) r
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/angelsl/test

Breakpoint 1, access (array=0x0, index=1) at test.c:4
4	    return array[index];
(gdb) p array
$1 = (int *) 0x0
(gdb) p index
$2 = 1

Debug it in reverse!

$ gdb test
GNU gdb (GDB) 8.2.1
(gdb) start
...
(gdb) record
(gdb) c
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x0000000100001168 in access (array=0x0, index=1) at test.c:4
4	    return array[index];
(gdb) rs
4	    return array[index];
(gdb) rs
main () at test.c:9
9	    printf("%d\n", access(0, 1));
(gdb) rs
8	    int arr[] = { 0, 1, 2 };
(gdb) rs

No more reverse-execution history.
main () at test.c:7
7	int main() {
(gdb)

strace

Look at the syscalls a program is making

Example program:

#include <stdio.h>

int main() {
    printf("Hello world!\n");
}

Compile: gcc -g -o hello hello.c

strace

$ strace ./hello
execve("./hello", ["./hello"], 0x76f6e85d7ab0 /* 47 vars */) = 0
...
write(1, "Hello world!\n", 13)          = 13
exit_group(0)                           = ?
+++ exited with 0 +++

strace -f to follow child processes.

Syscalls are how programs interact with the operating system. Out of scope for today.

You can man 2 syscall to read the manpage for the syscall.

ltrace

Look at library calls a program is making

Using the same example program:

$ ltrace ./hello
puts("Hello world!")                    = 13
+++ exited (status 0) +++

ProcMon (Windows)

Windows alternative for ltrace/strace.

time

Time a program's execution

$ time sleep 5

real	0m5.004s
user	0m0.003s
sys	0m0.001s
$ time ./hello
Hello world!

real	0m0.003s
user	0m0.000s
sys	0m0.003s

Real: real time; user: CPU time in userspace; sys: CPU time in kernel

perf

Measure statistics about a program, and many other things

$ perf stat ./hello
Hello world!

Performance counter stats for './hello':

    1.24 msec task-clock         #    0.581 CPUs utilized
       0      context-switches   #    0.000 K/sec
       0      cpu-migrations     #    0.000 K/sec
      52      page-faults        #    0.042 M/sec
 982,828      cycles             #    0.793 GHz
 841,761      instructions       #    0.86  insn per cycle
 196,065      branches           #  158.177 M/sec
   7,276      branch-misses      #    3.71% of all branches

0.002133030 seconds time elapsed

0.002084000 seconds user
0.000000000 seconds sys
More usages

procfs

A virtual filesystem providing system and process information. Many tools we will mention take their information from procfs.

Some files in /proc:

  • cpuinfo: lists CPU information
  • cmdline: kernel command line
  • config.gz: gzipped kernel config

A lot of kernel information is in /sys instead.

procfs

Some files in /proc/pid:

(pid can be self, for current process)

  • cmdline: the command line provided to the process
  • cwd: the process's current working directory
  • exe: the executable being run
  • environ: environment variables seen by the process
  • status: process status
  • fd/fd: open file descriptors

Typically we use tools like top, ps when we want to view process information.

Logs

What's in logs?

  • Kernel errors
  • Network connection details
  • Application errors
  • ...

Many times, the first thing one does when something on the system doesn't work is look at logs.

dmesg

View the kernel log: dmesg

journalctl

View the system log (for systemd systems): journalctl

Common flags:

  • -b: current boot only
  • -k: kernel messages only (same as dmesg)
  • -f: follow/tail the log
  • -e: jump to end

/var/log

1

Log files of some applications: Xorg, CUPS, LightDM, ...

Also where systemd journal is stored (/var/log/journal)

tail

To tail a log file (or any file): tail -f file

Windows Event Viewer

(h)top

Two different tools, both to view processes on the system; choose your poison

Common top keys

  • h: help
  • V: tree mode
  • f: add/remove columns
  • z: toggle colours
  • c: toggle cmdline/task name
  • </>: change sort field

lsof/fuser

List open files: lsof

  • lsof file: list processes using file
  • lsof -p pid: list files used by process pid

List processes using file: fuser file

  • fuser -k file: Kill processes using file

Both tools are similar; lsof is more powerful, but fuser is slightly more common.

Windows: Process Hacker

Screenshots are from the website.

lsblk/df

View block devices (disk partitions, etc.)

$ lsblk
NAME     MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
sda        8:0    0 465.8G  0 disk
├─sda1     8:1    0   256M  0 part  /boot/efi
├─sda2     8:2    0 464.5G  0 part
│ └─root 254:0    0 464.5G  0 crypt /
└─sda3     8:3    0     1G  0 part

View disk free space

$ df -h
Filesystem        Size  Used Avail Use% Mounted on
dev               5.9G     0  5.9G   0% /dev
run               5.9G  1.1M  5.9G   1% /run
/dev/mapper/root  457G   58G  377G  14% /
tmpfs             5.9G   82M  5.8G   2% /dev/shm
tmpfs             5.9G     0  5.9G   0% /sys/fs/cgroup
tmpfs             5.9G   26M  5.8G   1% /tmp
/dev/sda1         253M   24M  229M  10% /boot/efi
tmpfs             1.2G   28K  1.2G   1% /run/user/1000

-h: human-readable sizes

Windows: Disk Management

Also diskpart; out of scope

du

View disk usage by folders

Dropbox/ $ du -hd1
250M	./Screenshots
66M	./Backup
2.5G	./Notes
8.0M	./Work
20K	./.dropbox.cache
2.8G	.
  • -h: human-readable sizes
  • -d n: summarise to n levels
  • -s: show only a total for each argument

Windows: WinDirStat

dstat

View system resource statistics

$ dstat
You did not select any stats, using -cdngy by default.
--total-cpu-usage-- -dsk/total- -net/total- ---paging-- ---system--
usr sys idl wai stl| read  writ| recv  send|  in   out | int   csw
  9   5  85   1   0|  28k   43k|   0     0 |   0     0 | 738  3086
  4   3  90   2   0|   0     0 | 336k 3190B|   0     0 |1979  9753
  5   3  91   0   0|   0     0 | 238B  178B|   0     0 |1919  9188
  6   5  87   2   0|   0     0 | 571B  356B|   0     0 |1916  9077
  5   3  92   0   0|   0   108k|1465B    0 |   0     0 |1863  8952
  4   3  91   2   0|   0     0 | 238B  178B|   0     0 |1716  9049

Windows: Use Process Hacker

ss

View network connections: ss

  • -t/-u: TCP/UDP only
  • -4/-6: IPv4/IPv6 only
  • -l: listening ports only
  • -a: all states (listening and non-listening)
  • -p: view process information

Windows: Process Hacker

Screenshots are from the website.

Network debugging

Traceroute

See the route a packet takes from you to a remote host

# traceroute -Tn 1.0.0.1
traceroute to 1.0.0.1 (1.0.0.1), 30 hops max, 60 byte packets
 1  172.24.212.1  0.509 ms  0.493 ms  0.516 ms
 2  172.18.20.145  0.498 ms  0.495 ms  0.612 ms
 3  172.18.20.5  0.475 ms  0.586 ms  0.592 ms
 4  172.18.20.202  0.581 ms  0.692 ms  0.691 ms
 5  172.18.20.98  0.552 ms  0.647 ms  0.631 ms
 6  172.18.20.102  0.615 ms  0.598 ms  0.729 ms
 7  * * *
...
11  * 1.0.0.1  3.384 ms *

Common flags

  • -n: don't resolve addresses
  • -4/-6: use IPv4/IPv6
  • -I/-T/-U: use ICMP/TCP/UDP

Some flags may require privileges. tracepath is an alternative that does not require root.

Ping

Send packets to a host and see if it responds

$ ping -A 1.0.0.1
PING 1.0.0.1 (1.0.0.1) 56(84) bytes of data.
64 bytes from 1.0.0.1: icmp_seq=2 ttl=54 time=2.100 ms
...
64 bytes from 1.0.0.1: icmp_seq=43 ttl=54 time=3.25 ms
^C
--- 1.0.0.1 ping statistics ---
43 packets transmitted, 29 received, 32.5581% packet loss, time 241ms
rtt min/avg/max/mdev = 2.740/3.476/10.983/1.466 ms, ipg/ewma 219.812/3.802 ms

NUS network was having problems ☹️

Common flags

  • -A: adaptive (send next packet on receiving response)
  • -q: quiet
  • -f: flood (don't wait for response); needs root
  • -n: don't resolve addresses
  • -4/-6: use IPv4/IPv6

nslookup

Perform DNS queries

$ nslookup google.com
Server:   1.0.0.1
Address:  1.0.0.1#53

Non-authoritative answer:
Name:     google.com
Address:  74.125.24.100
Name:     google.com
Address:  2404:6800:4003:c02::8b

$ nslookup -query=MX google.com
Server:   1.0.0.1
Address:  1.0.0.1#53

Non-authoritative answer:
google.com	mail exchanger = 40 alt3.aspmx.l.google.com.

nslookup

Use a different nameserver

$ nslookup google.com 8.8.8.8
Server:		8.8.8.8
Address:	8.8.8.8#53

Non-authoritative answer:
Name:	google.com
Address: 74.125.24.138
Name:	google.com
Address: 2404:6800:4003:c01::65

dig

$ dig @8.8.8.8 google.com MX

;; ANSWER SECTION:
google.com.		323	IN	MX	10 aspmx.l.google.com.

;; Query time: 5 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Sat Mar 30 02:28:35 +08 2019
;; MSG SIZE  rcvd: 147

What's the difference? nslookup uses the OS's resolver libraries; nslookup uses its own. They are otherwise used for the same purpose.

whois

Look up information on an IP or domain

$ whois nus.edu.sg

----------------------------------------------------------------------
 SGNIC WHOIS Server
----------------------------------------------------------------------

The following data is provided for information purposes only.

Registrar:   SINGNET PTE LTD

    Domain Name:		NUS.EDU.SG
    Creation Date:		03-Sep-1996 00:00:00
    Modified Date:		28-Aug-2018 09:31:22
    Expiration Date:		03-Sep-2019 00:00:00
    Domain Status:		OK
    Domain Status:		VerifiedID@SG-Not Required


    Registrant:

        Name:           NATIONAL UNIVERSITY OF SINGAPORE (SGNIC-ORGNA66731)

whois

$ whois 4.2.2.1

NetRange:       4.0.0.0 - 4.255.255.255
CIDR:           4.0.0.0/8
NetName:        LVLT-ORG-4-8
NetHandle:      NET-4-0-0-0-1
Parent:          ()
NetType:        Direct Allocation
OriginAS:
Organization:   Level 3 Parent, LLC (LPL-141)
RegDate:        1992-12-01
Updated:        2018-02-20
Ref:            https://rdap.arin.net/registry/ip/4.0.0.0

Linux containers

This is extra, and very brief, material (not going through live)

Why containers?

If you need another distribution's environment (e.g. you run Arch but need Debian), or if you need to test something in a clean environment, or just need some isolation, etc

Why not a VM?

A container is much lighter in terms of memory/storage/CPU resources, and will run faster, compared to a VM.

Plain chroot

The most basic "container".

Basic steps:

  1. Bootstrap the chroot: debootstrap, pacstrap, etc
  2. Chroot into it
  3. Done!

LXC/LXD

Tools to build and run containers.

Introduction guide

Docker

Powerful platform to build and run containers.

A topic for an entire workshop.

Introduction guide

Thank you!