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'