Modified file for BSD Cafe Fork
This commit is contained in:
parent
795c04e6df
commit
ebd866659e
1 changed files with 63 additions and 48 deletions
111
checkmyip.py
111
checkmyip.py
|
@ -1,10 +1,11 @@
|
||||||
#!/usr/bin/python
|
#!/usr/local/bin/python3.9
|
||||||
|
|
||||||
|
|
||||||
##### CheckMyIP Server #####
|
##### BSD Cafe CheckMyIP Server #####
|
||||||
##### Written by John W Kerns #####
|
##### Originally written by John W Kerns #####
|
||||||
##### http://blog.packetsar.com #####
|
##### http://blog.packetsar.com #####
|
||||||
##### https://github.com/packetsar/checkmyip #####
|
##### Forked to BSD Cafe by Stefano Marinelli #####
|
||||||
|
##### https://brew.bsd.cafe/BSDCafe/checkmyip #####
|
||||||
|
|
||||||
|
|
||||||
##### Inform version here #####
|
##### Inform version here #####
|
||||||
|
@ -37,18 +38,18 @@ j2send = """{
|
||||||
"port": "{{ port }}",
|
"port": "{{ port }}",
|
||||||
"protocol": "{{ proto }}",
|
"protocol": "{{ proto }}",
|
||||||
"version": "%s",
|
"version": "%s",
|
||||||
"website": "https://github.com/packetsar/checkmyip",
|
"website": "https://brew.bsd.cafe/BSDCafe/checkmyip",
|
||||||
"sponsor": "Sponsored by ConvergeOne, https://www.convergeone.com/"
|
"sponsor": "Served by BSD Cafe, https://bsd.cafe/"
|
||||||
}""" % version
|
}""" % version
|
||||||
|
|
||||||
|
|
||||||
##### Handles all prnting to console and logging to the logfile #####
|
##### Handles all prnting to console and logging to the logfile #####
|
||||||
class log_management:
|
class log_management:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.logpath = "/etc/checkmyip/" # Log file directory path
|
self.logpath = "/var/log/checkmyip/" # Log file directory path
|
||||||
self.logfile = "/etc/checkmyip/%scheckmyip.log" % \
|
self.logfile = "/var/log/checkmyip/%scheckmyip.log" % \
|
||||||
time.strftime("%Y-%m-%d_") # Log file full path
|
time.strftime("%Y-%m-%d_") # Log file full path
|
||||||
self.paramikolog = "/etc/checkmyip/%sssh.log" % \
|
self.paramikolog = "/var/log/checkmyip/%sssh.log" % \
|
||||||
time.strftime("%Y-%m-%d_") # SSH log file path
|
time.strftime("%Y-%m-%d_") # SSH log file path
|
||||||
self.thread = threading.Thread(target=self._change_logfiles)
|
self.thread = threading.Thread(target=self._change_logfiles)
|
||||||
self.thread.daemon = True
|
self.thread.daemon = True
|
||||||
|
@ -89,9 +90,9 @@ class log_management:
|
||||||
def _change_logfiles(self, thread=True):
|
def _change_logfiles(self, thread=True):
|
||||||
while True:
|
while True:
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
self.logfile = "/etc/checkmyip/%scheckmyip.log" % \
|
self.logfile = "/var/log/checkmyip/%scheckmyip.log" % \
|
||||||
time.strftime("%Y-%m-%d_") # Log file full path
|
time.strftime("%Y-%m-%d_") # Log file full path
|
||||||
self.paramikolog = "/etc/checkmyip/%sssh.log" % \
|
self.paramikolog = "/var/log/checkmyip/%sssh.log" % \
|
||||||
time.strftime("%Y-%m-%d_") # SSH log file path
|
time.strftime("%Y-%m-%d_") # SSH log file path
|
||||||
paramiko.util.log_to_file(self.paramikolog)
|
paramiko.util.log_to_file(self.paramikolog)
|
||||||
|
|
||||||
|
@ -148,14 +149,14 @@ def j2format(j2tmp, valdict):
|
||||||
|
|
||||||
##### Cleans IP addresses coming from socket library #####
|
##### Cleans IP addresses coming from socket library #####
|
||||||
def cleanip(addr):
|
def cleanip(addr):
|
||||||
ip = addr[0]
|
ip, port = addr[:2]
|
||||||
port = addr[1]
|
family = "ipv6" # Default to IPv6
|
||||||
family = "ipv6"
|
if ip.startswith("::ffff:"): # Check if this is a prefixed IPv4 address
|
||||||
if len(ip) > 6: # If this IP is not a super short v6 address
|
ip = ip.replace("::ffff:", "") # Clean the IP
|
||||||
if ip[:7] == "::ffff:": # If this is a prefixed IPv4 address
|
family = "ipv4"
|
||||||
ip = ip.replace("::ffff:", "") # Return the cleaned IP
|
elif ":" not in ip: # Simple check to recognize IPv4
|
||||||
family = "ipv4"
|
family = "ipv4"
|
||||||
return (ip, port, family) # Return the uncleaned IP if not matched
|
return ip, port, family # Return cleaned IP and family
|
||||||
|
|
||||||
|
|
||||||
##### TCP listener methods. Gets used once for each listening port #####
|
##### TCP listener methods. Gets used once for each listening port #####
|
||||||
|
@ -164,16 +165,18 @@ def listener(port, talker):
|
||||||
listen_port = port
|
listen_port = port
|
||||||
buffer_size = 1024
|
buffer_size = 1024
|
||||||
while True:
|
while True:
|
||||||
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) # v6 family
|
# Use AF_INET6 but also handle IPv4 connections
|
||||||
|
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
||||||
|
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) # Allow IPv4-mapped IPv6 addresses
|
||||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
sock.bind((listen_ip, listen_port))
|
sock.bind((listen_ip, listen_port))
|
||||||
sock.listen(buffer_size)
|
sock.listen(buffer_size)
|
||||||
client, addr = sock.accept()
|
while True:
|
||||||
ip, port, family = cleanip(addr) # Get all cleaned IP info
|
client, addr = sock.accept()
|
||||||
valdict = {"ip": ip, "port": port, "family": family} # Put in dict
|
ip, port, family = cleanip(addr) # Get cleaned IP info including family
|
||||||
thread = threading.Thread(target=talker, args=(client, valdict))
|
valdict = {"ip": ip, "port": port, "family": family, "proto": ""}
|
||||||
thread.start() # Start talker thread to listen to port
|
thread = threading.Thread(target=talker, args=(client, valdict))
|
||||||
|
thread.start() # Start talker thread to listen to port
|
||||||
|
|
||||||
##### Telnet responder method. Is run in own thread for each telnet query #####
|
##### Telnet responder method. Is run in own thread for each telnet query #####
|
||||||
def telnet_talker(client, valdict, proto="telnet"):
|
def telnet_talker(client, valdict, proto="telnet"):
|
||||||
|
@ -209,35 +212,47 @@ def ssh_talker(client, valdict, proto="ssh"):
|
||||||
|
|
||||||
##### HTTP responder method. Gets run in own thread for each HTTP query #####
|
##### HTTP responder method. Gets run in own thread for each HTTP query #####
|
||||||
##### Automatically detects if client is a browser or a telnet client #####
|
##### Automatically detects if client is a browser or a telnet client #####
|
||||||
|
##### HTTP responder method. Gets run in own thread for each HTTP query #####
|
||||||
def http_talker(client, valdict, proto="http"):
|
def http_talker(client, valdict, proto="http"):
|
||||||
time.sleep(.1) # Sleep to allow the client to send some data
|
time.sleep(.1) # Sleep to allow the client to send some data
|
||||||
client.setblocking(0) # Set the socket recv as non-blocking
|
client.setblocking(0) # Set the socket recv as non-blocking
|
||||||
browser = False # Is the client using a browser?
|
browser = False # Is the client using a browser?
|
||||||
try: # client.recv() will raise an error if the buffer is empty
|
headers = {}
|
||||||
data = client.recv(2048) # Recieve data from the buffer (if any)
|
try:
|
||||||
print(data) # Print to stdout
|
data = client.recv(2048) # Receive data from the buffer (if any)
|
||||||
browser = True # Set client browser to True
|
request_lines = data.decode().split('\r\n')
|
||||||
except: # If buffer was empty, then like a telnet client on TCP80
|
for line in request_lines:
|
||||||
browser = False # Set client browser to False
|
if ": " in line:
|
||||||
if not browser: # If the client is not a browser
|
key, value = line.split(": ", 1)
|
||||||
telnet_talker(client, valdict, "http-telnet") # Hand to telnet_talker
|
headers[key] = value
|
||||||
else: # If client is a browser
|
# Extract real IP and adjust family based on headers if present
|
||||||
# Proceed with standard HTTP response (with headers)
|
if 'X-Real-IP' in headers or 'X-Forwarded-For' in headers:
|
||||||
valdict.update({"proto": proto})
|
real_ip = headers.get('X-Real-IP', headers.get('X-Forwarded-For').split(',')[0])
|
||||||
log(j2format(j2log, valdict))
|
ip, port, family = cleanip((real_ip, valdict['port']))
|
||||||
response_body_raw = j2format(j2send, valdict)+"\n"
|
valdict.update({"ip": ip, "family": family})
|
||||||
response_headers_raw = """HTTP/1.1 200 OK
|
browser = True # Set client browser to True
|
||||||
|
except socket.error: # If buffer was empty, then like a telnet client on TCP80
|
||||||
|
browser = False # Set client browser to False
|
||||||
|
if not browser: # If the client is not a browser
|
||||||
|
telnet_talker(client, valdict, "http-telnet") # Hand to telnet_talker
|
||||||
|
else: # If client is a browser
|
||||||
|
# Proceed with standard HTTP response (with headers)
|
||||||
|
valdict.update({"proto": proto})
|
||||||
|
log(j2format(j2log, valdict))
|
||||||
|
response_body_raw = j2format(j2send, valdict)+"\n"
|
||||||
|
response_headers_raw = """HTTP/1.1 200 OK
|
||||||
Content-Length: %s
|
Content-Length: %s
|
||||||
Content-Type: application/json; encoding=utf8
|
Content-Type: application/json; encoding=utf8
|
||||||
Connection: close""" % str(len(response_body_raw)) # Response with headers
|
Connection: close""" % str(len(response_body_raw)) # Response with headers
|
||||||
client.send(f'{response_headers_raw}\n\n{response_body_raw}'.encode())
|
client.send(f'{response_headers_raw}\n\n{response_body_raw}'.encode())
|
||||||
client.close()
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
##### Server startup method. Starts a listener thread for each TCP port #####
|
##### Server startup method. Starts a listener thread for each TCP port #####
|
||||||
def start():
|
def start():
|
||||||
talkers = {22: ssh_talker, 23: telnet_talker,
|
talkers = {2222: ssh_talker, 2223: telnet_talker,
|
||||||
80: http_talker} # Three listeners on different ports
|
2280: http_talker} # Three listeners on different ports
|
||||||
for talker in talkers:
|
for talker in talkers:
|
||||||
# Launch a thread for each listener
|
# Launch a thread for each listener
|
||||||
thread = threading.Thread(target=listener,
|
thread = threading.Thread(target=listener,
|
||||||
|
|
Loading…
Reference in a new issue