Академический Документы
Профессиональный Документы
Культура Документы
Port scanning
scan all reserved TCP ports (well known + registered) in verbose mode
nmap -v <host>
Pings
ping with ICMP request to see whether host is up before probing
nmap -v <host> -PE
attempt to detect/discover targets operating system only if one open and one closed TCP port are found (more reliable)
nmap -O <host> --osscan-limit
attempt to detect/discover targets operating system and display imperfect matches by trying to guess the closest possible
OS (accuracy level expressed in %)
nmap -O <host> --osscan-guess --version-intensity <1to9>
Services version detection
attempt to detect/discover services versions
nmap -sV <host>
change the version detection intensity level (from 1 to 9, default is 7, the higher the more reliable but the more resources
consuming)
nmap -sV <host>
DNS resolution
disable reverse DNS resolution (reverse DNS resolution is enabled by default and can add dramatically increase total scan
time)
nmap -nv <host>
Idle/Zombie Scan
works by checking the zombie's IP ID, probing the target with the zombie's IP as source IP, checking the zombie's IP ID
again: if difference = 1, then port's closed, if different = 2, port's opened
nmap -sI <zombie> <target>
TCP scans
perform a TCP connect scan (SYN, SYN-ACK, ACK)
nmap -sT <host>
perform a TCP stealth SYN scan (SYN then RST, never complete handshake)
nmap -sS <host>
perform an TCP ACK scan (to detect presence of firewall with advanced rulesets)
nmap -sA <host>
UDP scans
nmap -sU <host>
T4 - aggressive: default mode + 5 minute min host timeout + 1.12sec max probe timeout)
T5 - insane: default mode + 75 sec min host timeout + 0.3 sec max probe timeout)
nmap -v <host> -T<0-5>
Timeouts/Delays
timeout in miliseconds unless a suffix is used ( 's' for seconds, 'm' for minutes, or 'h' for hours)
change/set the host timeout (time spent in total to probe a host before giving up)
nmap -v <host> --host-timeout <X>
change/set the probe max timeout (maximum time waiting for a response to a probe before giving up or retrying)
nmap -v <host> --max-rtt-timeout <X>
change/set the probe min timeout (minimum time waiting for a response to a probe before giving up or retrying)
nmap -v <host> --in-rtt-timeout <X>
Parallel probing
change/set the max number of hosts probed at the same time
nmap -v <network>/<mask> --max-hostgroup <X>
"intrusive": scripts that are likely to crash services, consume significant resources on target host or be perceived as
attacks
scan with scripts that are part of the "external" or "discovery" sets and are "safe
nmap --script "(<external> or <discovery>) and <safe>"
scan only with the scripts whose names start with "snmp"
nmap --script "<snmp>*"
update the scripts database ("scripts/script.db"). Use only if you have added,removed or modified scripts
nmap --script-updatedb
DIG one-liners
Basics
retrieve all information/records for a domain
dig <domain>
emulate the host command with dig to do reverse lookups (PTR records)
dig -x <ipaddress>
Client behaviour
set/change the query timeout (default it 5, min is 1)
dig <domain> +time=<timeInSec>
set/change the number of retries (default is 2, doesn't include the initial query)
dig <domain> +retry=<number>
set/change the source ip and port (must be one of the host's network interfaces)
dig -b "<sourceIp>#<sourcePort>" <domain>
use TCP instead of UDP
dig <domain> +tcp
Answer/Display formatting
retrieve only the short answer (for instance just the IP address)
dig <domain> A +short
clear all display flags (the answer will be empty at this stage)
dig <domain> +noall
show only the statistics (query time, DNS server that replied, date and size of the response)
dig <domain> +noall +stats
DNS servers
send DNS requests to a particular DNS server
dig @<DNSserverIPorHostname> <domain>
attempt to find the authoritative DNS servers and provide the SOA (Start Of Authority) records from each DNS server found.
dig <domain1> +nssearch
Debugging
trace/follow the DNS resolution (see requests to each intermediate DNS server)
dig <domain> +trace
Basics
capturing everything on a particular interface
tcpdump -i <interface>
limit the number of packets captured (tcpdump stops when limit is reached)
tcpdump -ni <interface> -s<0> -c<NbOfPackets>
limit the size of the output file (Size in MB, new output file created when limit reached, naming scheme is original filename
completed with the file number starting at 1)
tcpdump -ni <interface> -s<0> -C<SizeInMB> -w </path/to/file>
Networks
filter on a network range
tcpdump -ni <interface> -s<0> net <networkIP> mask <netmask>
LDAPSEARCH one-liners:
Basics
simple search without bind
ldapsearch -h <host> -b "<dc=example,dc=com>"
simple search and display result in ldif format (-L = ldifv1, -LL = no comments, -LLL = no version info)
ldapsearch -h <host> -b "<dc=example,dc=com>" -LLL
OR filter ( | operator)
ldapsearch -h <host> -b "<dc=example,dc=com>" "(|(<att1>=<val1>)(<ORatt2>=<val2>))"
Basics
listen on a port
nc -lp <portNumber>
Setting up a chat
open a socket on the first machine
nc -lvnp <portNumber>
File transfers
download a file from a server: 1st step: output a file to a socket
cat </path/to/file> | nc -lp <PortNumber>
download a file from a server: 2nd step a: connect to the socket and redirect the output to a file
nc <hostIP> <portNumber> > </path/to/downloaded/file>
download a file from a server: 2nd step b: show file transfer progress
nc <hostIP> <portNumber> | pv -b > </path/to/downloaded/file>
upload a file to a server: 2nd step a: send file content to the socket
nc <hostIP> <portNumber> < </path/to/file>
upload a file to a server: 2nd step b: show file transfer progress
nc -lp <PortNumber> | pv -b > </path/to/uploaded/file>
Port scanning
scan UDP ports
nc -vnzu <hostIp> <startPort>-<endPort>
Telnet server
associate bash with the socket on the linux machine
nc -lp <portNumber> -e </bin/bash>
Proxy
1st step: create a bi-directional pipe
mkfifo <pipeName>
Web server
create a simple webserver to serve the same page
while true; do nc -lp 80 -q 1 < </path/to/html>; done
File systems
backup files to a remote machine
tar -czvf - </path/to/dir> | nc <hostIp> <portNumber>
nc -lp <portNumber> | pv -b > <backup.tgz>
Basics
query a particular OID
snmpget -v <1|2c|3> -c <community> <host> <OID>
print the total time it took to collect the data (it does not include snmp library initialization, shutdown, argument processing,
and any other overhead)
snmpwalk -v <1|2c|3> -c <community> <host> <fromOID> -Ct
openssl one-liners:
Read a certificate
see/read certificate and output in clear text:
openssl x509 -text -noout -in <mycert>
RSA key
create a key
openssl genrsa -out <mykey> <keySize>
Self-signed certificate
create a self signed certificate:
openssl req -x509 -new -out <mycert> -keyout <mykey> -days <numberOfDays>
Signing a certificate
sign a csr (certificate signing request) with a certificate/key (can use a self signed certificate to emulate a CA). Validity must
be less than signer
openssl x509 -req -in <mycsr> -CA <signingCert> -CAkey <signingKey> -CAcreateserial -out <mycert> -days
<numberOfDays>
Converting/Exporting
convert/export certificate and key to pkcs12 (.pfx, .p12) format
openssl pkcs12 -export -in <mycert> -inkey <mykey> -out <mypkcs12.p12> -name "<friendlyName>"
Info
show openssl version
openssl version -a
Verify
verify that a key and a certificate match (output of both commands must match)
openssl x509 -noout -modulus -in <mycert> | openssl md5
openssl rsa -noout -modulus -in <mykey> | openssl md5
System
set/change the hostname
hostname <hostname>
set/change the enable secret password (encrypted password that replaces the enable password)
enable secret <mysecretpwd>
Configuration
show the running/current/active configuration
show running-config
Interfaces
show/list all the interfaces
show interface brief
disable/shutdown an interface
shutdown
enable/bring up an interface
no shutdown
remove/delete a static route (<command> is the command you used in the first place to add the route)
no <command>
RIP
enable/enter RIP mode
router rip
disable RIP
no router rip
delete/remove an ACL entry (<command> is the command you used in the first place to add the entry)
no <command>
1st) or create a capture buffer and export the capture to pcap format
monitor capture buffer <captureBufferName> export tftp://<ipAddress>/<path/to/file>
Basics
capture
ssldump -i <interface> host <ipAddress> and port <portNumber> > <outputFile>
decrypt
ssldump -r <inputFile> -k <keyFile> -d > <outputFile>
SQL one-liners:
OR logical operator
SELECT * FROM 'table' WHERE 'column1' = 'value1' OR 'column1' = 'value2';
select where string stars with ab and is 3 character long (_ for 1 character only)
SELECT * FROM 'table' WHERE 'column' LIKE 'ab_';
Aliases (AS)
create an alias name for a column
SELECT 'column' AS 'newcolumnName' FROM 'table';
remove/delete/drop a table
DROP TABLE 'table';
alter/modify a table and change the column data type with MySQL and Oracle
ALTER TABLE 'table' ADD 'column' 'newType';
alter/modify a table and change the column data type with SQL Server
ALTER TABLE 'table' ALTER COLUMN 'column' 'newType';
Connecting
mysql to local host
mysql -u<username> -p
Security
clear/delete mysql history
rm ~/.mysql_history
Databases
list all the databases
show databases;
create a database
create database <database>;
connect to a database
connect <database>;
delete/remove a database
drop database <database>;
Tables
list all the tables
show tables;
Users
Create a new user with mysql
mysql -u root -p
use mysql;
INSERT INTO user (Host,User,Password) VALUES('%','<username>',PASSWORD('<password>'));
flush privileges;
Backup / restore
save/backup all the databases
mysqldump -user <username> -password=<password> --all-databases > </path/to/file>
save/backup a database
mysqldump -user <username> -password=<password> <database> > </path/to/file>
Ruby examples:
Variables
create a local varaiable
localvar = 1 # integer
increment variables
x += 1 # increment by 1
decrement variables
x -= 1 # decrement by 1
puts "some text " + myvar # error: can't convert integer to string. convert
myvar with to_s() first
myvar2 = "abc"
Pre-defined variables
regular expressions variables
$& # string that matches the whole pattern
script name
$0 # script name
arguments
ARGV[0] # 1st argument
# do something on arg
end
Numbers
convert an integer to a string
int = 12
mynb.to_s(16) # "a"
255.to_s(16) # "ff"
puts fl.ceil # 1
puts 0.4.ceil # 1
Strings
upper case a string
myvar = "hello"
remove trailing line breaks/new lines characters (\r, \n, \r\n, \n\r)
"hello\n".chomp # "hello"
"hello\r".chomp # "hello"
"hello\r\n".chomp # "hello"
remove leading, trailing whitespaces, tabulations, new lines and lines breaks
" hello ".strip # "hello"
"hello".include?("ab") # false
str.split(//).each { |char|
puts char # first "a", then "b", then "c"
str.each_line() { |line|
Text files
open a file in read mode
myfile = File.new("/path/to/file","r")
close a file
myfile.close
write to a file
myfile.puts "some text"
# do something
end
line = myfile.gets
. # any character
\d # any digit
\D # any non-digit
position patterns
^ # start of line
$ # end of line
\A # start of string
\z # end of string
quantifiers
? # zero or one
* # zero or more
+ # one or more
Logical operatros
(red|black) # matches either "red" or "black"
options
/pattern/i # case insensitive
create groups
( ) # whatever is in brackets will be captured. see predefined
variables to reuse captured data
regular expressions variables (available once regular expression processing has been performed)
$& # string that matches the whole pattern
# do something
while (str.slice!(/(http[^\s]*)/))
end
Arrays
Creating an array
create an empty array
myarray = Array.new
Adding elements
add/append an element to the end of an array
myarray << "blue"
myarray.unshift(1) # [1,2,3]
Removing elements
remove an element from an array
myarray = [ "a", "b", "c", "d" ]
myarray.uniq # [ 1,2,3,4]
Accessing elements
access/get specific elements of an array
myarray = [ "a", "b", "c", "d" ]
Multidimensional arrays
create a multidimensional array
myarray = Array.new(5, Array.new(5)) # 5x5 array
alternatively you can just add array elements into your array
myarray[0] << [ "a" , "b"]
myarray[0]['color'] = 'red'
myarray[1]['color'] = 'blue'
accessing a multidimensional array.
myarray[0][3] # 1st colomn, 4th row
[ 1, 2] == [1,2] # true
Repetition
myarray = [ 1,2 ]
myarray * 2 # [ 1,2,1,2]
Difference
myarray1 = [ 1,2,3 ]
myarray2 = [ 1,2 ]
myarray1 - myarray2 = [ 3 ]
Sorting/Reversing arrays
sort array elements in ascending order
myarray = [ "b", "a", "c" ]
reverse an array
myarray = [ "b", "a", "c" ]
Searching elements
search/check if element exists in array
[ 1, 2, 3 ].include?(3) # true
[ 1, 2, 3 ].include?(4) # false
Array length
get the size/number of elements of an array
[ 1, 2, 3 ].length # 3
Iterations
get each element of an array
[ "a", "b", "c" ].each do |element|
end
end
end
get each element of an array with its index from the end
[ "a", "b", "c" ].reverse.each_with_index do |el, i|
puts "#{i}: #{el}" # "0: c", then "1: b", then "2: a"
end
Misc
extract all elements of an array and convert them into one single string
["Mike", "John", "Ben" ].join # "MikeJohnBen"
Loops
if loop
if condition
# do something
elseif anothercondition
# do something
else
# do something
end
while loop
while condition
# do something
end
case statement
case myvar
when 1,3,5
when 2,4,6
else
end
do until loop
begin
# do something
# do something
end
# do something
end
10.times do
i += 2 # increment by 2
# do something
end
Files
create a file
File.new("filename","r") # read mode
rename a file
File.rename("oldname","newname")
copy a file
require 'FileUtils'
FileUtils.copy("source","copy")
move a file
require 'FileUtils'
FileUtils.copy("source","copy")
remove/delete a file
File.delete("filename")
File.unlink("filename") # equivalent
Directories
create a directory
require 'ftools'
File.makedirs("dirname")
remove a directory
require 'fileutils'
FileUtils.rm_rf("dirname")
end
end
end
Statistics
to optimize performances first create a stat object then access stats information as follows
stats = File.stat("filename")
stats.atime
although you can get the stats directly from the file
File.atime("filename")
Symbolic links
check whether file is a symbolic link
File.symlink?("filename")
Permissions
set/change the file permissions
File.chmod(0777, "file1", "file2")
set/change the group and owner of a file (gid and uid as integers)
File.chown(gid,uid,"filename")
iptables one-liners:
Filtering at layer 3
filter on specific source/destination IPs on all interfaces
iptables -A <INPUT|FORWARD|OUTPUT> -s <sourceIP>/<mask> -d <destIp>/<mask> -j <DROP|ACCEPT|REJECT>
IP forwarding
first enable IP forwarding on the linux host, then write the rules as appropriate
sysctl -w net.ipv4.ip_forward=1
iptables -A FORWARD -i <sourceInt> -o <destInt> -j ACCEPT
NATing
use DNAT to change the destination IP
iptables -t nat -A PREROUTING -d <destIp> -j DNAT --to-destination <newDestIp>
SNATing / Masquerading
replace/change the source IP leaving out on specific outbound interface and specify the new source ip
iptables -t nat -A POSTROUTING -t nat -s <sourceIP>/<mask> -o <outboundInt> -j SNAT --to-source <newSourceIP>
replace/change the source IP leaving out on specific outbound interface and use this interface's IP as a new source
(masquerade)
iptables -t nat -A POSTROUTING -t nat -s <sourceIP>/<mask> -o <outboundInt> -j MASQUERADE
Filtering at layer 4
accept traffic to a particular TCP service
iptables -A INPUT -p tcp -d <serviceIp>/32 --destination-port <servicePort> -j ACCEPT
accept what is already part of an existing connection (works with "iptables -P OUTPUT ACCEPT")
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
awk one-liners:
Basics
use string as separator
awk -F"<string>" '{ print $<fieldId> }' <file>
Counting
count the number of lines (not number of occurences) that contain a specific pattern (+0 used if n = 0)
awk '/<pattern>/{n++}; END {print n+0}' <file>
count the number of fields per line and display result as "Nb:Line"
awk '{ print NF ":" $0 }' <file>
Selective Printing
print only lines that match a specific pattern
awk '/<regexp>/ { print }' <file>
Field manipulation
remove/delete a particular field
awk '{$<fieldId> = ""; print}' <file>
sed one-liners:
test the below sed one-liners first. Once you're happy with the result, use -i to modify the input file or > to
write to another file
Basic examples
replace/substitute only the first occurence of each line
sed 's/<replaceThis>/<withThis>/' <file>
Regular expressions
Create a group and make backreference to the value (for instance deleting everything before and after the group)
sed '/<before>\(.*\)<after>/\1/d'
Emulate non-greedy behaviour (not supported by sed) by excluding unwanted character from the match (here for instance
extract URL from href by excluding ")
file contains: <a href="/url" name="link">link</a>