Packets don't have 'http' layer available - python-3.x

**Hi all,
I am learning online about network packets. I came across 'Scapy' in python. I am supposed to have 'Http' section the packet results available in terminal. For some reason I don't see '###[ HTTP ]###' for some sites. In the video that I am learning from, the tutor is using the same code but he sees 'http' for every single site he browses on, but I can't duplicate his results.
I have python 2.7.18 and python 3.9.9 in my Kali. I tried using both 'python' and 'python3' header when calling the program in terminal(no change in finding 'http' layer in packers).
I am capturing some of the http packets but not all. I have been working on a python code on my Kali VM that would look for the packets transmission for Urls and login info and display those URL of in the Terminal. The Tutorial had pretty much my expected result but I don't have the same result. In Tutorial coach was doing the same as I did(Go to Bing, open a random image )
Am I doing something wrong...? I would appreciate help on this issue please.**
...
# CODE:
#!/usr/bin/env python
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet) #prn = call back function, udp= audio and
def get_url(packet):
return packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path
def get_login_info(packet):
if packet.haslayer(scapy.Raw): # When used, it will only show the packet with username and password.
load = packet[scapy.Raw].load
keywords = ["uname", "username", "user", "pass", "password", "login", "Email"]
for keyword in keywords:
if keyword in str(load):
return load
def process_sniffed_packet(packet):
#print(packet.show())
if packet.haslayer(http.HTTPRequest):
#print(packet.show())
URL = get_url(packet)
print("[+] HTTP >> " + str(URL))
login_info = get_login_info(packet)
if login_info:
print("\n\nPossible username and Password > " + str(login_info) + "\n\n")
sniff("eth0") # This is connected to the internet
...
RESULT IN TERMINAL: I was browsing to Bing.com and opening a random Image.
I have used print(packet.show()) for Final Image that I browsed. In tutorial there was a ###HTTP### Layer, but I didn't have that layer.Image of Packer info for a randowm Image
โ”Œโ”€โ”€(venv)โ”€(root๐Ÿ’€kali)-[~/PycharmProjects/hello]
โ””โ”€# python packet_sniffer.py
[+] HTTP >> b'ocsp.digicert.com/'
[+] HTTP >> b'ocsp.pki.goog/gts1c3'
[+] HTTP >> b'ocsp.pki.goog/gts1c3'
[+] HTTP >> b'ocsp.pki.goog/gts1c3'
[+] HTTP >> b'ocsp.pki.goog/gts1c3'
[+] HTTP >> b'ocsp.pki.goog/gts1c3'
[+] HTTP >> b'ocsp.pki.goog/gts1c3'
[+] HTTP >> b'ocsp.digicert.com/'
^C
My Expectation: These are exactly the URLs That I visited for above result.
โ”Œโ”€โ”€(venv)โ”€(root๐Ÿ’€kali)-[~/PycharmProjects/hello]
โ””โ”€# python packet_sniffer.py
[+] HTTP >> file:///usr/share/kali-defaults/web/homepage.html
[+] HTTP >> https://www.google.com/search?client=firefox-b-1-e&q=bing
[+] HTTP >> https://www.bing.com/
[+] HTTP >> https://www.bing.com/search?q=test&qs=HS&sc=8-0&cvid=75111DD366884A028FE0E0D9383A29CD&FORM=QBLH&sp=1
[+] HTTP >> https://www.bing.com/images/search?`view=detailV2&ccid=3QI4G5yZ&id=F8B496EB517D80EFD809FCD1EF576F85DDD3A8EE&thid=OIP.3QI4G5yZS31HKo6043_GlAHaEU&mediaurl=https%3a%2f%2fwww.hrt.org%2fwp-content%2fuploads%2f2018%2f01%2fGenetic-Testing-Test-DNA-for-Genetic-Mutations-Telomeres-Genes-and-Proteins-for-Risk-1.jpg&cdnurl=https%3a%2f%2fth.bing.com%2fth%2fid%2fR.dd02381b9c994b7d472a8eb4e37fc694%3frik%3d7qjT3YVvV%252b%252fR%252fA%26pid%3dImgRaw%26r%3d0&exph=3500&expw=6000&q=test&simid=608028087796855450&FORM=IRPRST&ck=326502E72BC539777664412003B5BAC2&selectedIndex=80&ajaxhist=0&ajaxserp=0`
^C
...

I was running into a similar issue, which turned out to be that the HTTP/1.0 packets I was attempting to analyze were not being sent over PORT 80. Instead, my packets were being sent over PORT 5000.
It appears that the scapy implementation by default only interprets packets as http when they are sent on PORT 80.
I found the following snippet in this response to a GitHub Issue (for a package which should not be installed, per Cukic0d in their answer to a similar question here).
scapy.packet.bind_layers(TCP, HTTP, dport=5000)
scapy.packet.bind_layers(TCP, HTTP, sport=5000)
Adding this snippet before my call to sniff() resolved my issue and allowed me to proceed.
Hope this helps.

Related

How to run an XMLRPC server and an XMLRPC client on Mininet hosts through a python script?

I am trying to run an XMLRPC server and an XMLRPC client on Mininet hosts, using the script below.
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import OVSController
class MyTopo(Topo):
def __init__(self):
# Initialize topology
Topo.__init__(self)
# Add hosts
server1 = self.addHost('server1')
server2 = self.addHost('server2')
# Add switch
s1 = self.addSwitch('s1')
# Add links
self.addLink(server1, s1)
self.addLink(server2, s1)
if __name__ == '__main__':
net = Mininet(topo=MyTopo(), controller=OVSController)
net.start()
print(net.hosts[0].cmd('python3 xmlrpc_server.py'))
print(net.hosts[1].cmd('python3 xmlrpc_client.py'))
The file xmlrpc_server.py is:
from xmlrpc.server import SimpleXMLRPCServer
import threading
def is_even(n):
return n%2 == 0
server = SimpleXMLRPCServer(("0.0.0.0", 8000), logRequests=True, allow_none = True)
server.register_function(is_even, "is_even")
print("Listening on port 8000...")
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
The file xmlrpc_client.py is:
import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://10.0.0.1:8000/")
print("3 is even: %s" % str(proxy.is_even(3)))
print("100 is even: %s" % str(proxy.is_even(100)))
The problem is that although I have used a thread, when I run the xmlrpc_server.py script on server1, the execution pauses at line server_thread.start() waiting for the script execution to be completed before moving on and thus never goes on to the next line, which means that the XMLRPC client script never runs. How do I overcome this problem?
P.S.: xmlrpc_server.py and xmlrpc_client.py can be executed through the server terminals (by using the commands xterm server1 and xterm server2 on Mininet CLI and then using the commands python3 xmlrpc_server.py and python3 xmlrpc_client.py on the xterm terminals that open), but I need to start the server and client through a python script so as to perform some further calculations after the communication between the two servers.
Replace print(net.hosts[0].cmd('python3 xmlrpc_server.py')) with print(net.hosts[0].sendCmd('python3 xmlrpc_server.py')). Connection is sometimes refused, but that issue can be resolved with exception handling on the client script.

LetsEncrypt-ACMESharp http-01 challenge on IIS invalid

On server A (non-IIS) I executed:
Import-Module ACMESharp
Initialize-ACMEVault
New-ACMERegistration -Contacts mailto:somebody#derryloran.com -AcceptTos
New-ACMEIdentifier -Dns www.derryloran.com -Alias dns1
Complete-ACMEChallenge dns1 -ChallengeType http-01 -Handler manual
Response back asked:
* Handle Time: [08/05/2017 22:46:27]
* Challenge Token: [BkqO-eYZ5sjgl9Uf3XpM5_s6e5OEgCj9FimuyPACOhI]
To complete this Challenge please create a new file
under the server that is responding to the hostname
and path given with the following characteristics:
* HTTP URL: [http://www.derryloran.com/.well-known/acme-challenge/BkqO-eYZ5sjgl9Uf3XpM5_s6e5OEgCj9FimuyPACOhI]
* File Path: [.well-known/acme-challenge/BkqO-eYZ5sjgl9Uf3XpM5_s6e5OEgCj9FimuyPACOhI]
* File Content: [BkqO-eYZ5sjgl9Uf3XpM5_s6e5OEgCj9FimuyPACOhI.X-01XUeWTE-LgpxWF4D-W_ZvEfu6ue2fAd7DJNhomQM]
* MIME Type: [text/plain]
Server B is serving www.derryloran.com a page at http://www.derryloran.com/.well-known/acme-challenge/BkqO-eYZ5sjgl9Uf3XpM5_s6e5OEgCj9FimuyPACOhI correctly I believe but when I then, back on Server A execute:
Submit-ACMEChallenge dns1 -ChallengeType http-01
(Update-ACMEIdentifier dns1 -ChallengeType http-01).Challenges | Where-Object {$_.Type -eq "http-01"}
...but the status goes invalid after a few seconds. FWIW I've tried this several times always with same result. Why? What am I doing wrong?
I appreciate there's a lot more to go once I've got the certificate but the site is being served in a docker container hence the Server A/B complexities...
Omg, how many times?!? The file had a BOM when created in VS. Recreating using Notepad++ and saving as UTF-8 (without BOM) and I'm getting a valid response now.

Controlling a minecraft server with python

I've searched a lot for this and have not yet found a definitive solution. The closest thing I've found is this:
import shutil
from os.path import join
import os
import time
import sys
minecraft_dir = ('server diectory')
world_dir = ('server world driectory')
def server_command(cmd):
os.system('screen -S -X stuff "{}\015"'.format(cmd))
on = "1"
while True:
command=input()
command=command.lower()
if on == "1":
if command==("start"):
os.chdir(minecraft_dir)
os.system('"C:\Program Files\Java\jre1.8.0_111\bin\java.exe" -Xms4G -Xmx4G -jar craftbukkit-1.10.2.jar nogui java')
print("Server started.")
on = "0"
else:
server_command(command)
When I launch this program and type 'start' the CMD flashes up and closes instantly. Instead I want the CMD to stay open with the minecraft sever running from it. I'm not sure why this happens or what the problem is, any help would be greatly appreciated.
p.s. I have edited this to my needs (such as removing a backup script that was unnecessary) but it didn't work before. The original link is: https://github.com/tschuy/minecraft-server-control
os.system will simply run the command then return to your python script with no way to further communicate with it.
On the other hand using subprocess.Popen gives you access to the process while it runs, including writing to it's .stdin which is how you send data to the server:
def server_command(cmd):
process.stdin.write(cmd+"\n") #just write the command to the input stream
process = None
executable = '"C:\Program Files\Java\jre1.8.0_111\bin\java.exe" -Xms4G -Xmx4G -jar craftbukkit-1.10.2.jar nogui java'
while True:
command=input()
command=command.lower()
if process is not None:
if command==("start"):
os.chdir(minecraft_dir)
process = subprocess.Popen(executable, stdin=subprocess.PIPE)
print("Server started.")
else:
server_command(command)
you can also pass stdout=subprocess.PIPE so you can also read it's output and stderr=subprocess.PIPE to read from it's error stream (if any)
As well instead of process.stdin.write(cmd+"\n") you could also use the file optional parameter of the print function, so this:
print(cmd, file=process.stdin)
Will write the data to process.stdin formatted in the same way that print normally does, like ending with newline for you unless passing end= to override it etc.
Both of the above answers do not work in the environment I tried them in.
I think the best way is to use RCON, not sending keys to a window.
RCON is the protocol used by games to run commands.
Many python libraries support Minecraft RCON, and the default server.properties file has an option for RCON.
We will use the python module: MCRON.
Install it. It works for windows, mac, linux.
Type:
pip install mcrcon
Lets configure your server to allow RCON.
In server.properties, find the line 'enable-rcon' and make it look like this:
enable-rcon=true
Restart and stop your server.
Find the line 'rcon.password' and set it to any password you will remember.
You can leave the port default at 25575.
Now, open your terminal and type:
mcron localhost
Or your server ip.
You will be prompted to enter the password you set.
Then you can run commands and will get the result.
But we are doing this with python, not the PYPI MCRON scripts - so do this.
from mcrcon import MCRcon as r
with r('localhost', 'insertyourpasswordhere') as mcr:
resp = mcr.command('/list')
print(resp) #there are 0/20 players online: - This will be different for you.

Unable to run python cgi scripts using CGIHTTPRequestHandler in Python 3.3

I am a noob; trying to create and use a simple webserver in Python that executes CGI scripts written in Python. I am using Windows XP and Python v3.3.0. I have a "myserver" directory which contains "myserver.py","sample.html" and the directory "cgi-bin" which in turn contains "cgi_demo.py"
myserver.py
from http.server import HTTPServer
from http.server import CGIHTTPRequestHandler
port = 8080
host = '127.0.0.1'
server_address = (host,port)
httpd = HTTPServer(server_address,CGIHTTPRequestHandler)
print("Starting my web server on port "+str(port))
httpd.serve_forever()
cgi_demo.py
import cgi
import cgitb; cgitb.enable()
print("Content-type: text/html")
print
print("<html><body>")
for i in range(0,100):
print(i,"<br>")
print("</body></html>")
Now the directory listing works fine for "myserver" but not for "cgi-bin"; maybe that is how it is coded - I don't have a problem here. "sample.html" is retrieved fine too. However, the execution of "cgi_demo.py" is not proper. I get a blank page in the browser; and the console window (which is blank too) appears and disappears. Moreover, on the server's console I get the message
127.0.0.1 - - [29/Nov/2012 12:00:31] "GET /cgi-bin/cgi_demo.py HTTP/1.1" 200 -
127.0.0.1 - - [29/Nov/2012 12:00:31] command: C:\Python33\python.exe -u "D:\python apps\my web server\cgi-bin\cgi_demo.py" ""
127.0.0.1 - - [29/Nov/2012 12:00:32] CGI script exited OK
Please tell me what is wrong! I get the feeling that the output stream of my script is not connected to the server. What am I doing wrong? Don't say that I have to extend CGIHTTPRequestHandler!!
SORRY for the trouble!
Well, it is my fault. 2 things to note:
[1]The console window that appeared and disappeared; it only happens when I use IDLE to execute the server. If the script is already running in a normal windows console then this does not happen. My Feeling was WRONG.
[2]There is an bug/error in my cgi script. After printing the HTTP header; the print statement that I wrote was just "print" instead of actually being "print()".This is so embarrassing! But, even then why didn't the interpreter catch this error?

Send file and information about attack from honeypot to central repository trough HTTP

Hello people someone knows Dionaea honeypot?
I'm trying to send binary information collected locally and attack collected locally on the honeypot to a central server and I can not get it.
I've tried using HTTP Post, Python CGI, and I can not get it.
The honeypot has a service that lets you send data via HTTP (submit_http.py: http://src.carnivore.it/dionaea/commit/?id=cfd2be8cf7484c781384648cf1c9223afc2bd3c1) and I have a PHP file on the central server which was originally developed for nepenthes (submit.php: http://www.remoteroot.net/2008/07/21/nepenthes-submit-http-server-with-file-upload/) and wanted to receive the files as well as information about each attack associated parameters through HTTP POST.
Why does the submit.php is not working?!
I have my dionaea.conf like this:
submit_http = {
url = "http://central_machine_IP/submit.php"
email = "zzzzzzzz#yyyyy.com"
user = "uuuuuuu"
pass = "xxxxxxxxxxx"
}
Thank you guys.
dionaea log error:
[10022011 17:51:14] curl module.c:202: DOWNLOAD DONE:
http://xxx.xxx.xxx.xxx/yyy => (0)
[10022011 17:51:14] logsql dionaea/logsql.py:601: complete for attackid 5241
[10022011 17:51:14] test dionaea/test.py:51: your configuration lacks urls
to submit to defaults
[10022011 17:51:14] python module.c:959: NameError at NameError("global name
'submithttp_report' is not defined",)
[10022011 17:51:14] python module.c:984:
/opt/dionaea/lib/dionaea/python/dionaea/submit_http.py:56 in
handle_incident_dionaea_download_complete_unique
[10022011 17:51:14] python module.c:985: mr =
submithttp_report(i.sha512, i.md5, icd.file)
[10022011 17:51:14] python module.c:984: binding.pyx:975 in
dionaea.core.c_python_ihandler_cb (binding.c:8605)
[10022011 17:51:14] python module.c:985: None
I hid the original ip by xxx.xxx.xxx.xxx

Resources