Skip to main content

CS4238 Computer Security Practice "Cheatsheet"

Week 1

Unix

  • /var/: "variable" files, usually contain logs e.g. /var/log

  • Analysing processes

    • ps
    • lsof (list of files (incl. devices & net sockets))
      • -p [pid]
      • -i: idk, prof just rambled
      • +d: for a particular dir
      • +D: for a dir, recursive
  • Databases

    • User: /etc/passwd, /etc/shadow, Group: /etc/group
  • File permissions

      Displayed syntax:
    owner's owner's
    usr grp all
    [-|d] rw[x|s|S] rw[x|s|S] rwx[t|T]
    0-7 0-7 0-7

    [-|d]: [file | dir]
    [x|s|S]: [exe | SUID set | SUID set, but user triad cannot exe]
    [x|s|S]: [exe | SGID set | SGID set, but group triad cannot exe]
    [t|T]: [Sticky bit set | Sticky Bit set, but other triads cannot exe]

    * SUID / SGID
    SUID or SGID can be set to elevate permissions for execution.
    A SETUID or SETGID binary is executed respectively whilst the command is executed on the document in question.
    Usually an SUID or SGID is required where users need elevated privileges and do not have admin or root access.

    * Sticky Bit ensures only the owner/root can edit & delete the file/dir.

    * Chmod octal (4 groups of 3 bits):
    [SUID 4][SGID 2][Sticky 1] rws rws rws
    • setuid: change process' user ID to file owner
    • setgid: change process' user ID to group owner
  • find / -uid [uid] -perm [prefix][perm] -ls

    • /: root dir
    • [prefix]: None: Exact perms. -: All specified perms are set. / Any specified perms are set.
    • [perm]: See File permissions above.
    • -ls: list files found
  • man [section] cmd: but nowadays just google

    • [section]: 1: shell cmds 2: syscalls 3: lib calls 4: special files 5: file formats

Week 2

  • Highlights for TCP: ![](/img/tcpconnections.jpg" width="200" />

    • ISN: Initial Sequence Num
  • UDP:

  • Highlights of IP:

    • Flags: Don't Fragment bit, More Fragment bit (more fragments incoming if set)
      • ID: Identifies the packet
      • Fragment Offset: Fragment position during reassembly
      • Src IP: spoofable
    • Local: 127.0.0.1, Private: 10.0.0.0/8, 172.16.0.0/12 (16.0.0-31.255.255), 192.168.0.0/16, Auto-IP: 169.254.1.0 - 169.254.254.255 (when DHCP unavailable)
  • ICMP: TCP/UDP layer

    • Types: Echo Reply (0), Destination Unreachable (3), Redirect Message (5), Echo Request (8), Time Exceeded (11), Parameter Problem: Bad IP header (12)
  • NAT: Map Private to public IP

  • Firewalls: Network/IP Layer (Traditional packet filters, stateful packet filters, proxy-based firewalls). Filters check headers only

    • Usually block ICMP
  • Network-based IDS: real-time detection, also check if packet payload matches application

  • MAC address: sometimes can tell infrastructure from MAC. Not reliable because can be spoofed

  • traceroute (Unix UDP), tracert (Win ICMP), tcptraceroute, tctrace

  • Common Network Services: FTP (21), SSH (22), Telnet (23), HTTP (80), rlogin (513), rsh (rm shell 514), rcp, dns (53), nfs (2049), x windows (6000), ipp (ntwk printer 631)

    • SSH: systemctl {start | enable | reload} ssh
    • Apache: systemctl start apache, a2enmod, a2dismod
  • Manual network config:

    • ifdown <network-device>, Set network via /etc/network/interfaces, then ifup <network-device>
    • Setup with DHCP: auto lo \n iface lo inet loopback \n auto eth0 \n iface eth0 inet dhcp
    • ifconfig: check, start, stop network interfaces
      • List: ifconfig (up only) ifconfig -a / ip addr show (all), ifconfig eth0 / ip addr show eth0 (a specific interface), ip -4|-6 addr show (IPv4/IPv6 only)
      • Start/Stop: ifconfig eth0 {down | up} or ip link set eth0 {down | up}
    • Troubleshoot: Verify gateway, DNS server can be pinged, check domain name resolved with nslookup
    • nc ip_addr port: see if server can be connected to via port
    • route -n = ip route show
    • route add default gw <ip-addr> = ip route add default via <ip-addr>
    • DNS: nslookup, dig, host
      • DNS records
      • Zone transfer (usually disabled)
        • Replication of name server records from one DNS server (topo knowledge; spoof, poison etc)
        • w/ nslookup: nslookup ; server [target-name-server] ; set type=any ; ls -d [target-domain]
        • w/ dig: dig @[target-name-server] [target-domain] -t AXFR
      • Web-based DNS recon: ViewDNS.info, Central Ops, G Suite Toolbox's Dig
      • Countermeasure: Allow zone transfer only between pri & sec name servers
      • Develop split-horizon/split-view/split-brain DNS
    • Kali Linux tools
      • theHarvester (email addrs), Maltego, Netcraft, Centralops, Shodan (IoT), Kali NetHunter
  • VirtualBox

  • Compliance frameworks

    • Kill chain: Recon, Weapon, Delivery, Exploit, Install, Control, Actions
    • MITRE, PTES, OSSTM, OWASP, PCI DSS
  • Recon: profile target

    • Low-Tech: Dumpster diving, Social engineering, Spoofing, Spam, Phishing, Physical break-in
    • Google Hacking
      • not (-), plus (+),
      • Exact: "exact search",
      • Number ranges: 1..10,
      • info: info:url,
      • results under domain: site:[domain],
      • sites that link to: link:[page],
      • word in title: intitle[terms] (e.g. site:xxx intitle="index of"),
      • related:[site],
      • cache[site],
      • filetype:suffix,
      • inurl:wp-login.php
      • inurl examples: inurl:<domain-suffix>/[administrator|admin][password|user|login], inurl:view/index.[shtml|html] (cam), inurl:viewer_index/index.[shtml|html] (cam)
      • Google Hacking Database GHDB, Johnny Long's books "Google Hacking for Pen Testers"
      • Google cache, archive wayback machine
      • Metagoofil (metadata for public docs)
      • whois: 23% correct name and physical addr, 29% fake info
        • validation obligation on reigstras
      • OSINT (open source intelligence; info from freely-accessible sources)
    • Attackers' knowledge:
      • Phone #, Domain names, IP Addr, servers, tech contact info, people info
      • After scan: IP addr, network topo, list of open ports on live hosts, list of services & versions, OS types of live hosts, ports open through firewalls

Week 3

  • War driving ("drive-by"): find wireless APs

    • Attacks: active scanning, passive sniffing, forcing deauthentication
    • Defence: privacy in ESSID, wireless security protocols, VPN, detection
  • War dialing:

    • Look for modems in target networks
  • Network mapping: gain knowledge of target network topology

    • nmap ping (find live hosts using ICMP) nmap -sP; | -sn (no port scan) in newer nmap. Can use Zenmap for GUI
    • traceroute (exploit ttl & icmp TLE notif)
    • Defences:
      • block icmp with firewall (disable ping)
      • filter ICMP TLE messages leaving network (hinder traceroute)
      • Check open ports: netstat -na | grep "LISTENING" / lsof -i and closed unused ports
      • keep sys patched (may not be easy to patch)
      • scan sys/network periodically (find vuln before attackers do)
        • ensure it's safe to scan
        • will DoS tests crash machines?
        • will password tests lock out legit users?
    • port scanning: find active services of server (65,536 possible TCP/UDP ports)
      • Scan: nmap [--help] [-A] [-sT|-sS|-sA|-sF|-sX|-sN] [-oN|-oX|-oS|-oG <file>] [--packet-trace] [-v|-vv] [--reason] [-sV] [-T<0-5>] [-b ftp_relay] [-sI zombie[:probeport]] ip_addr
        • -A: Enable OS & version detection
        • -sT: Scan by Connection: Can be blocked by firewall, can be logged
        • -sS: SYN Scan. Svr Response:
          • (Do this because dir. connection can be logged)
          • SYN/ACK = port open
          • RST = port closed
          • None w/ retransmit or ICMP unreachable = filtered
        • -sA: ACK scan (bypass firewall that blocks incoming connections, may use common source port numbers)
        • -sF: FIN scan, -sX: Xmas tree (all flags set), -sN: Null scan (no flags)
      • -oN|-oX|-oS|-oG <file>: Output as normal/XML/skript kiddie/grepable to filename
      • --packet-trace: show packets sent and received
      • -v: verbosity
      • --reason: show reason why port is in a particular state
      • -sV: Identify services using non-standard port numbers
      • -T<0-5>: 0 slowest, 5 fastest
      • -b ftp_relay: Bounce/file-relaying/FTP-forwarding feature on old FTP servers, allow you to port scan using FTP server as proxy. If FTP server has access to internal hosts, can bypass firewall. Change ftp_relay with FTP server IP
      • -sI zombie[:probeport]: Idle scan: Target server non-responsive. If we can connect to a machine that is: 1. Able to talk to target 2. Is idle 3. Uses predictable (global) IP identification values (IP packet ID val), We can: 1. connect to zombie and get IP ID, 2. Ping target on port, spoofing our IP as the zombie. 3. Target talks to zombie and zombie replies, incrementing their IP ID. 4. Talk to zombie again and check if IP ID has jumped
  • Vulnerability

    • Weakness that can be exploited by an attacker to do unauthorized things
    • Refer to CVE (maintained by MITRE)
    • Exploit databases (older vulns for learning):
      • exploit database, rapid7, securityfocus
    • Zero-day: unknown exploit (Day-zero: vendor finds out).
    • Lifecycle: Vuln found, Exploit in wild, Discovered (by vendor), public disclosure, anti-virus signatures released, patch released, patch deployed
      • zero-day + follow-on attacks between exploit released and patch deployed
    • Common Vulnerability Scoring System (CVSS) for assessing severity of vulns
      • 3 metric groups: Base, temporal, environmental
      • Base metric: 0 - 10
    • Vulnerability Scanning tools can be used for:
      • common config errors
      • default config weaknesses
      • well-known sys vulnerabilities
      • Useful between vulnerability discovered - Patch deployment
      • General structure: User config tool - Scanning engine + vuln. DB on targets - knowledge base of current scan - report generation based on results
      • Free examples: Nessus / OpenVAS / Attack Tool Kit
        • Plugins &pre-built policies can be installed from tenable
        • Create Nessus policies based on policy templates (e.g. basic network scan), specify policy targets & scanning options, launch policy and check result
      • Antivirus vs vulnerability scanner
        • Differences: Goal, scope of detection, monitoring agent, info examined (servers), reference data, output (computer infected / service affected)
      • Useful for pentesting and compliance checking
      • Can vulnerability testing scan on Hackerdemia LiveCD (dl from hackingdojo) on another VM
    • Limitations
      • Only check for known vulnerabilities (zero days not accounted for)
      • Only check specified targets
      • Only snapshot (Nessus "Live Results": offline vulnerability assessment with every plugin update)
  • Metasploit: Acquired by Rapid7

    • Exploitation engine/framework: Assembly line for producing exploits
    • Best to refer to slides for image
    • Bind Shell: Attach listener on exploited system and connect to port
    • Reverse Shell: Make machine connect to attacking machine
    • Procedure for injecting exploit payload:
      • show exploits
      • use exploit-name-which-u-copy
      • show targets
      • set target id
      • show payloads
      • use payload name-u-copy
      • show options
      • set rhost target-IP
      • set lhost local-IP
      • exploit
      • run cmds on opened shell
    • Generate an exe to send to the target (standalone payload)
      • List: Msfvenom -l payloads
      • Specify: msfvenom -p payload
      • Formats: msfvenom --help-formats
    • Meterpreter: Metasploit attack payload that provides an interactive shell from which an attacker can explore the target machine and execute code.
    • Metasploit can:
      • Shorten exploit development time with high quality
      • Help validate reported vulnerabilities
      • Pen-test systems
      • Check security functionalities

Week 4: Buffer Overflow

  • Von Neumann: code treated as data (Code injection)

  • Prefixes: e = 32bit, r = 64bit

  • ip: instruction ptr, sp: stack ptr, *bp: base ptr

  • Intel: Little Endian (LSB in lower addresses)

    • Stack grows from larger to smaller addresses (downward)
    • Heap grows from smaller to larger (upward)
  • 64b memory:

    • Only least significant 48 bits used
    • Rest of the bits copied from most significant used bit
  • .data/.bss: Initialized/uninitialized global var.

  • Stack Frame ("Activation Record")

  • Caller and callee (function prolog & epilog)

  • GDB

    • [b]reak <fx_name | filename:line# | *<memory address> >: breakpoint
    • disassemble fx_name: See memory addr of each instruction
    • [d]elete <breakpoint #>. See breakpt numbers w/ info break
    • condition <breakpoint #> <condition>: Set condition for breakpoint to execute
    • [i]nfo <about>:
      • [f]rame: current stackframe
      • [s]tack: Stack backtrace. Same to backtrace [full] | where
      • [r]egisters: List every register. [all-r]egisters lists more.
      • [b]reak: breakpoints
      • [fu]nctions: lists all function signatures if gcc -g was used
    • [r]un (args): run w/ args
    • [c]ontinue: resume after breakpoint
    • [s]tep: Step 1 src code. [s]tepi: Step 1 asm code
    • [n]ext: Step over 1 src code. [n]exti: Step over 1 asm code
    • [k]ill: stop current session
    • [p]rint <var|reg|address|constant|c_expression>: print
      • Accessing value in reg: Use $ prefix. print *(char *)($esp + $eax + my_ptr_array[13])
      • [p]rint/x <c_expression>: print as hex
    • [x]/(num)(format)(unit_size) <address>: See data at address
      • num: # of contiguous blocks
      • format: printf
        • i: instruction
        • u|o|xX: unsigned decimal|unsigned octal|unsigned hexadecimal int
        • fF|eE|gG|aA: decimal float|scientific|shortest rep|hex float
        • c|s: char|string
        • p| ptr addr
      • unit_size: [b]ytes, [h]alfwords (2B), [w]ords, [g]iant words. Default is bytes.
      • Return addr: x/xw $ebp+4 or x/xw $rbp+8
    • list: Print lines from src. set listsize n configures # of instr printed
    • set <type> <address> = <value>: modify memory
    • dprintf srcLine,printf_template,args: (simulate) insert printf at certain address on the fly
      • Can be used to modify variables on the fly
    • Disable randomization: sudo sysctl -w kernel.randomize_va_space=0
    • Compile w/o optimization: gcc sample.c -fno-stack-protector -g -O0 -o sample
    • Show current instruction: x/i $pc
      * Show next n instructions: `x/ni $pc`
      * `set disassemble-next-line on`
      * `show disassemble-next-line`
  • AT&T: Linux, GCC

  • NASM: Windows

  • Memory Errors

    • Spatial: Access Out-of-bound areas
      • Buffer overflow / format string attacks
    • Temporal: Access undefined areas
      • Dangling pointers / Integer overflow
  • Buffer Overflow

    • Include shell code in input
    • Smash stack to modify return address to injected code
    • Address to smash:
      • $ebp - addr_of_buffer + 4 (+8 if 64b)
    • Defences:
      • Safe coding / safe libraries
      • Static Code checking (false positives / negative)
      • Canary (check if canary modified to protect stack overflow)
      • Randomization (not a guarantee)
      • Non-executable stack (can bypass using libcalls and rop)

Week 5 (Password attacks, Binary analysis, fuzzing)

Password Attacks (post-exploitation)

  • Default passwords: http://www.phenoelit-us.org/dpl/dpl.html

  • Password guessing using login (may result in acct lock)

  • Unix passwords

    • /etc/passwd: Each entry is login name, x, uid, gid, home directory, shell (x means the hashed pass is in /etc/shadow; otherwise it is the hashed password)
    • /etc/shadow: Each entry (delimited by :) is login name, hashed password, date of last password change, minimum password age, maximum password age, password warning period, password inactivity period, account expiration date, reserved field
    • hashed pass format: $id$salt$hashed-key id:ID of the hash-method used (1=MD5, 5=SHA-256, 6= SHA-512, …), salt: up to 16 chars drawn from the set [a-zA-Z0-9./]
  • Cracking passwords:

    • Make a guess, encrypt the guess and compare hashed value w/ guess
    • Dictionary | Brute force | Hybrid (if both dict & brute)
    • John the Ripper (free password cracker). Stores cracked entries in .john/john.pot
    • Usage:
    • unshadow /etc/passwd /etc/shadow > combined.txt: combine passwd with shadow
    • john [--users=<user>] [--wordlist=<file>] --show[=LEFT] [--single|--wordlist] combined.txt
      • --show: show cracked/uncracked passwords
      • --single: Single-crack mode. Derive passwords from login and user names, can mangle possible passwords to generate candidates
      • --wordlist: Ordering matters; put best candidate first. No sorting is done. Default is /usr/share/john/password.lst
      • --incremental: Incremental. Tries all char combinations
    • Defences: use strong passwords, protect your hashed password files, do your own pentesting
  • Vulnerability Discovery

    • White|Black Box
    • Gray box: binary auditing through reverse engineering
      • See file type: file <binary>
      • See header: xxd <bin> | head -n 20 or readelf -h <binary>
      • List symbols: readelf --syms <binary>
      • List sections: readelf --sections --wide <binary>
      • List read-only data: objdump -sj .rodata <binary>
      • List printable strings: strings <binary>
      • List shared obj/lib: ldd <binary>
      • Disassemble exe: objdump -d [-M intel] <binary>
  • Syscalls: interface between process and OS (kernel)

    • strace: trace syscall (like ptrace in GDB)
    • strace <command>: basic strace usage
    • strace -e <syscall> <command>: trace a syscall
    • strace -e trace=<syscall1,syscall2,…> <command>: trace a set of syscalls
    • strace -o <output-file> <command>: output to a file
    • sudo strace -p <pid>: trace a running process
    • strace -t <command>: print timestamps
    • strace -f <command>: follow children processes too
    • strace -c <command>: print syscall statistics
  • Lib functions: may/may not use syscalls (e.g. string manipulation)

  • Trace using ltrace (very similar to strace)

    • -C, --demangle: decode/demangle low-level symbol names into user-level names
    • -i: print the instruction pointer at the time of library call
  • Fuzzing: black-box testing

    • Mutation-based: mutate existing data to create test cases
    • Or generation-based: create from scratch based on protocol/file format
    • Steps:
      • Identify target
      • Identify input vectors
      • Generate, execute & monitor exceptions
      • Determine exploitability
    • Weaknesses:
      • Fuzzer has no logic of target program
      • Bad at discovering access-control flaws
      • Cannot identify good/bad designs
      • Cannot spot backdoors
      • Cannot handle memory corruptions that don't cause exceptions
      • Hard to automatically chain vulnerabilities
  • SPIKE (network protocol fuzzer) (not examinable in midterms)

    • Provide support for common tedious tasks e.g. field length & checksum calculation
    • API calls
    • TCP request: generic_send_tcp url port script_for_generatingdata.spk 0 0
    • String insertion: s_string(str) or s_string_repeat(str, n)
    • Binary insertion: s_binary(\\x41) or s_binary_repeat(bin, n)
    • Blocks: for automating the calculating of field length in your packet/protocol
      • Defining a block region: s_block_start(blk_name) and s_block_end(blk_name)
      • You can then have the script auto-calc the field length and replace it with this template:
        • s_blocksize_string(blk_name, n) (use n-str to represent) or s_block_size_byte(name) (use 1B to represent)
    • Variables: s_string_variable(var_name)
  • Firewall

    • Traditional Packet Filters (Rule-based, applied to header)
    • Stateful Packet Filters (Maintain state table of all active connections, filter by connection state)
    • Proxy-based: Acting as relay of application-level traffic
    • Netfliter: packet-filtering framework
      • Features:
      • stateless & stateful packet filtering
      • NAT & masquerading
      • Mangling (packet manipulation)
      • Hooks (filtering points)

  • Chains: PREROUTING, INPUT, FORWARD, POSTROUTING, OUTPUT

  • Each chain contains rules sorted by table (type of op)

  • Possible rule condition(s): IP addr, port, interface, connection state

  • Possible rule action(s):

    • terminating: ACCEPT, DROP, REJECT (drop & send err), change pkt info,
    • non-terminating: LOG
  • Firewall rules maintained by Netfilter framework & iptables

  • e.g. iptables -t filter -A INPUT -p icmp --icmp-type echo-request -j LOG --log-prefix="ICMPIN-REQ:"
  • iptables-extensions
  • state: allow for stateful filtering (INVALID, ESTABLISHED, NEW, RELATED, UNTRACKED)
    • e.g. iptables –A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
  • NAT: use sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  • Firewall stuff
  • sudo iptables -L -v --line-numbers: check firewall rules (chains etc)
  • ip route show: show routing paths
    • 10.1.40.0/24 via 10.255.115.1 dev eth1 10.255.114.0/23 dev eth1 proto kernel scope link src 10.255.115.18 default via 10.1.1.1 dev eth0 metric 100
    • proto kernel: Route was installed by the kernel during autoconfiguration
    • dev: "via" that port
    • scope link: packet is sent straight to interface as the destination is in the subnet; no gateway needed
    • metric: priority (lower=better)
  • ip route get <ip_addr>: get related routing rule
  • cat /etc/resolv.conf: file for DNS