forked from BSDCafe/checkmyip
HTTP Completed
This commit is contained in:
parent
b28c6cfbf3
commit
ebc7e94aea
1 changed files with 61 additions and 42 deletions
103
checkmyip.py
103
checkmyip.py
|
@ -11,6 +11,7 @@
|
||||||
version = "v1.0.0"
|
version = "v1.0.0"
|
||||||
|
|
||||||
|
|
||||||
|
##### Import python2 native modules #####
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
@ -20,10 +21,11 @@ import paramiko
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
|
|
||||||
|
##### Jinja formatting for logging queries #####
|
||||||
j2log = "Connection from: {{ ip }} ({{ port }}) ({{ proto }})"
|
j2log = "Connection from: {{ ip }} ({{ port }}) ({{ proto }})"
|
||||||
#j2send = "\n\n\nYour IP Address is {{ ip }} ({{ port }})\n\n\n\n"
|
|
||||||
|
|
||||||
|
|
||||||
|
##### Jinja formatting for response queries #####
|
||||||
j2send = """{
|
j2send = """{
|
||||||
|
|
||||||
|
|
||||||
|
@ -32,24 +34,28 @@ j2send = """{
|
||||||
|
|
||||||
"family": "{{ family }}",
|
"family": "{{ family }}",
|
||||||
"ip": "{{ ip }}",
|
"ip": "{{ ip }}",
|
||||||
"port": "{{ port }}"
|
"port": "{{ port }}",
|
||||||
}"""
|
"protocol": "{{ proto }}",
|
||||||
|
"version": "%s",
|
||||||
|
"website": "https://github.com/packetsar/checkmyip"
|
||||||
|
}""" % version
|
||||||
|
|
||||||
|
|
||||||
|
##### 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/"
|
self.logpath = "/etc/checkmyip/" # Log file directory path
|
||||||
self.logfile = "/etc/checkmyip/checkmyip.log"
|
self.logfile = "/etc/checkmyip/checkmyip.log" # Log file full path
|
||||||
self._publish_methods()
|
self._publish_methods() # Publish the console and log methods to glob
|
||||||
self.can_log = True
|
self.can_log = True # Variable used to check if we can log
|
||||||
try:
|
try: # Try to configure the SSH log file, create dir if fail
|
||||||
paramiko.util.log_to_file('/etc/checkmyip/ssh.log')
|
paramiko.util.log_to_file('/etc/checkmyip/ssh.log')
|
||||||
except IOError:
|
except IOError:
|
||||||
self._create_log_dir()
|
self._create_log_dir()
|
||||||
def _logger(self, data):
|
def _logger(self, data): # Logging method published to global as 'log'
|
||||||
logdata = time.strftime("%Y-%m-%d %H:%M:%S") + ": " + data + "\n"
|
logdata = time.strftime("%Y-%m-%d %H:%M:%S") + ": " + data + "\n"
|
||||||
if self.can_log:
|
if self.can_log:
|
||||||
try:
|
try: # Try to write to log, create log dir if fail
|
||||||
f = open(self.logfile, 'a')
|
f = open(self.logfile, 'a')
|
||||||
f.write(logdata)
|
f.write(logdata)
|
||||||
f.close()
|
f.close()
|
||||||
|
@ -67,14 +73,15 @@ class log_management:
|
||||||
def _publish_methods(self):
|
def _publish_methods(self):
|
||||||
global log
|
global log
|
||||||
global console
|
global console
|
||||||
log = self._logger
|
log = self._logger # Global method used to write to the log file
|
||||||
console = self._console
|
console = self._console # Global method used to write to the console
|
||||||
def _create_log_dir(self):
|
def _create_log_dir(self): # Create the directory for logging
|
||||||
os.system('mkdir -p ' + self.logpath)
|
os.system('mkdir -p ' + self.logpath)
|
||||||
self._console("Logpath (%s) created" % self.logpath)
|
self._console("Logpath (%s) created" % self.logpath)
|
||||||
self.can_log = True
|
self.can_log = True
|
||||||
|
|
||||||
|
|
||||||
|
##### Creates a RSA key for use by paramiko #####
|
||||||
class rsa_key:
|
class rsa_key:
|
||||||
data = """-----BEGIN RSA PRIVATE KEY-----
|
data = """-----BEGIN RSA PRIVATE KEY-----
|
||||||
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
|
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
|
||||||
|
@ -92,16 +99,13 @@ class rsa_key:
|
||||||
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
|
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
|
||||||
-----END RSA PRIVATE KEY-----
|
-----END RSA PRIVATE KEY-----
|
||||||
"""
|
"""
|
||||||
def open(self):
|
def readlines(self): # For use by paramiko.RSAKey.from_private_key mthd
|
||||||
pass
|
|
||||||
def close(self):
|
|
||||||
pass
|
|
||||||
def readlines(self):
|
|
||||||
return self.data.split("\n")
|
return self.data.split("\n")
|
||||||
def __call__(self):
|
def __call__(self): # Recursive method uses own object as arg when called
|
||||||
return paramiko.RSAKey.from_private_key(self)
|
return paramiko.RSAKey.from_private_key(self)
|
||||||
|
|
||||||
|
|
||||||
|
##### Imports and modifies the ServerInterface module for use by paramiko #####
|
||||||
class ssh_server (paramiko.ServerInterface):
|
class ssh_server (paramiko.ServerInterface):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.event = threading.Event()
|
self.event = threading.Event()
|
||||||
|
@ -109,9 +113,9 @@ class ssh_server (paramiko.ServerInterface):
|
||||||
if kind == 'session':
|
if kind == 'session':
|
||||||
return paramiko.OPEN_SUCCEEDED
|
return paramiko.OPEN_SUCCEEDED
|
||||||
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
|
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
|
||||||
def check_auth_none(self, username):
|
def check_auth_none(self, username): # Auth none method left wide open
|
||||||
return paramiko.AUTH_SUCCESSFUL
|
return paramiko.AUTH_SUCCESSFUL
|
||||||
def get_allowed_auths(self, username):
|
def get_allowed_auths(self, username): # Give no auth options
|
||||||
return 'none'
|
return 'none'
|
||||||
def check_channel_shell_request(self, channel):
|
def check_channel_shell_request(self, channel):
|
||||||
self.event.set()
|
self.event.set()
|
||||||
|
@ -121,11 +125,13 @@ class ssh_server (paramiko.ServerInterface):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
##### Method to merge Jinja templates #####
|
||||||
def j2format(j2tmp, valdict):
|
def j2format(j2tmp, valdict):
|
||||||
template = jinja2.Template(j2tmp)
|
template = jinja2.Template(j2tmp)
|
||||||
return template.render(valdict)
|
return template.render(valdict)
|
||||||
|
|
||||||
|
|
||||||
|
##### Cleans IP addresses coming from socket library #####
|
||||||
def cleanip(addr):
|
def cleanip(addr):
|
||||||
ip = addr[0]
|
ip = addr[0]
|
||||||
port = addr[1]
|
port = addr[1]
|
||||||
|
@ -137,47 +143,55 @@ def cleanip(addr):
|
||||||
return (ip, port, family) # Return the uncleaned IP if not matched
|
return (ip, port, family) # Return the uncleaned IP if not matched
|
||||||
|
|
||||||
|
|
||||||
|
##### TCP listener methods. Gets used once for each listening port #####
|
||||||
def listener(port, talker):
|
def listener(port, talker):
|
||||||
listen_ip = ''
|
listen_ip = ''
|
||||||
listen_port = port
|
listen_port = port
|
||||||
buffer_size = 100 # Normally 1024, but we want fast response
|
buffer_size = 1024
|
||||||
while True:
|
while True:
|
||||||
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
|
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) # v6 family
|
||||||
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()
|
client, addr = sock.accept()
|
||||||
ip, port, family = cleanip(addr)
|
ip, port, family = cleanip(addr) # Get all cleaned IP info
|
||||||
valdict = {"ip": ip, "port": port, "family": family}
|
valdict = {"ip": ip, "port": port, "family": family} # Put in dict
|
||||||
thread = threading.Thread(target=talker, args=(client, valdict))
|
thread = threading.Thread(target=talker, args=(client, valdict))
|
||||||
thread.start()
|
thread.start() # Start talker thread to listen to port
|
||||||
|
|
||||||
|
|
||||||
|
##### Telnet responder method. Is run in own thread for each telnet query #####
|
||||||
def telnet_talker(client, valdict):
|
def telnet_talker(client, valdict):
|
||||||
valdict.update({"proto": "telnet"})
|
valdict.update({"proto": "telnet"}) # Add the protocol to the value dict
|
||||||
log(j2format(j2log, valdict))
|
log(j2format(j2log, valdict)) # Log the query to the console and logfile
|
||||||
client.send(j2format(j2send, valdict)) # echo
|
client.send(j2format(j2send, valdict)) # Send the query response
|
||||||
client.close()
|
client.close() # Close the channel
|
||||||
|
|
||||||
|
|
||||||
|
##### SSH responder method. Gets run in own thread for each SSH query #####
|
||||||
def ssh_talker(client, valdict):
|
def ssh_talker(client, valdict):
|
||||||
|
def makefile(): # A hack to make Cisco SSH sessions work properly
|
||||||
|
chan.makefile('rU').readline().strip('\r\n')
|
||||||
valdict.update({"proto": "ssh"})
|
valdict.update({"proto": "ssh"})
|
||||||
log(j2format(j2log, valdict))
|
log(j2format(j2log, valdict))
|
||||||
t = paramiko.Transport(client, gss_kex=True)
|
t = paramiko.Transport(client, gss_kex=True)
|
||||||
t.set_gss_host(socket.getfqdn(""))
|
t.set_gss_host(socket.getfqdn(""))
|
||||||
t.load_server_moduli()
|
t.load_server_moduli()
|
||||||
t.add_server_key(rsa_key()())
|
t.add_server_key(rsa_key()()) # RSA key object nested call
|
||||||
server = ssh_server()
|
server = ssh_server()
|
||||||
t.start_server(server=server)
|
t.start_server(server=server)
|
||||||
chan = t.accept(20)
|
chan = t.accept(20)
|
||||||
if chan:
|
if chan:
|
||||||
server.event.wait(10)
|
server.event.wait(10)
|
||||||
chan.send('%s' % j2format(j2send, valdict))
|
chan.send('%s' % j2format(j2send, valdict)) # Send the response
|
||||||
chan.makefile('rU').readline().strip('\r\n')
|
thread = threading.Thread(target=makefile)
|
||||||
chan.close()
|
thread.start() # Start hack in thread since it hangs indefinately
|
||||||
client.close()
|
time.sleep(1) # Wait a second
|
||||||
|
chan.close() # And kill the SSH channel
|
||||||
|
client.close() # And kill the session
|
||||||
|
|
||||||
|
|
||||||
|
##### HTTP responder method. Gets run in own thread for each HTTP query #####
|
||||||
def http_talker(client, valdict):
|
def http_talker(client, valdict):
|
||||||
valdict.update({"proto": "http"})
|
valdict.update({"proto": "http"})
|
||||||
log(j2format(j2log, valdict))
|
log(j2format(j2log, valdict))
|
||||||
|
@ -185,15 +199,17 @@ def http_talker(client, valdict):
|
||||||
response_headers_raw = """HTTP/1.1 200 OK
|
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))
|
Connection: close""" % str(len(response_body_raw)) # Response with headers
|
||||||
client.send(response_headers_raw + "\n\n" + response_body_raw)
|
client.send(response_headers_raw + "\n\n" + response_body_raw)
|
||||||
client.close()
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
##### Server startup method. Starts a listener thread for each TCP port #####
|
||||||
def start():
|
def start():
|
||||||
talkers = {22: ssh_talker, 23: telnet_talker, 80: http_talker}
|
talkers = {22: ssh_talker, 23: telnet_talker, 80: http_talker}
|
||||||
for talker in talkers:
|
for talker in talkers:
|
||||||
thread = threading.Thread(target=listener, args=(talker, talkers[talker]))
|
thread = threading.Thread(target=listener,
|
||||||
|
args=(talker, talkers[talker]))
|
||||||
thread.daemon = True
|
thread.daemon = True
|
||||||
thread.start()
|
thread.start()
|
||||||
while True:
|
while True:
|
||||||
|
@ -203,10 +219,12 @@ def start():
|
||||||
quit()
|
quit()
|
||||||
|
|
||||||
|
|
||||||
|
##### Client class to be used to make API calls to CheckMyIP server #####
|
||||||
class CheckMyIP_Client:
|
class CheckMyIP_Client:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._json = __import__('json') # Import the JSON library
|
self._json = __import__('json') # Import the JSON library
|
||||||
self._socket = __import__('socket') # Import the socket library
|
self._socket = __import__('socket') # Import the socket library
|
||||||
|
self._raw_data = None # Initialize the _raw_data variable
|
||||||
self._data = None # Initialize the _data variable
|
self._data = None # Initialize the _data variable
|
||||||
self._af = "auto" # Set the IP address family type to "auto"
|
self._af = "auto" # Set the IP address family type to "auto"
|
||||||
self.server = "telnetmyip.com" # Set the default CheckMyIP server
|
self.server = "telnetmyip.com" # Set the default CheckMyIP server
|
||||||
|
@ -228,9 +246,10 @@ class CheckMyIP_Client:
|
||||||
sock = self._socket.socket(self._socket.AF_INET,
|
sock = self._socket.socket(self._socket.AF_INET,
|
||||||
self._socket.SOCK_STREAM)
|
self._socket.SOCK_STREAM)
|
||||||
sock.connect((self.server, 23))
|
sock.connect((self.server, 23))
|
||||||
self._data = sock.recv(1024) # Recieve data from the buffer
|
self._raw_data = sock.recv(1024).decode()
|
||||||
|
self._data = self._json.loads(self._raw_data) # Recieve data from the buffer
|
||||||
sock.close() # Close the socket
|
sock.close() # Close the socket
|
||||||
return self._json.loads(self._data) # Return the JSON data
|
return self._data # Return the JSON data
|
||||||
def set_family(self, family): # Method to set the IP address family
|
def set_family(self, family): # Method to set the IP address family
|
||||||
allowed = ["auto", "ipv4", "ipv6"] # Allowed input values
|
allowed = ["auto", "ipv4", "ipv6"] # Allowed input values
|
||||||
if family in allowed:
|
if family in allowed:
|
||||||
|
@ -240,5 +259,5 @@ class CheckMyIP_Client:
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
logging = log_management()
|
logging = log_management() # Instantiate log class
|
||||||
start()
|
start() # Start the server
|
Loading…
Reference in a new issue