Added logging

This commit is contained in:
John W Kerns 2017-09-01 17:34:46 -07:00
parent b5298d7ada
commit 5f085c5eb1

View file

@ -1,120 +1,184 @@
import os
import sys import sys
import time
import socket import socket
import jinja2 import jinja2
import paramiko import paramiko
import threading import threading
j2log = "Connection from: {{ ip }} ({{ port }})" j2log = "Connection from: {{ ip }} ({{ port }}) ({{ proto }})"
j2send = "\n\n\nYour IP Address is {{ ip }} ({{ port }})\n\n\n\n" #j2send = "\n\n\nYour IP Address is {{ ip }} ({{ port }})\n\n\n\n"
paramiko.util.log_to_file('demo_server.log') j2send = """{
"comment": "## Your IP Address is {{ ip }} ({{ port }}) ##",
"family": "{{ family }}",
"ip": "{{ ip }}",
"port": "{{ port }}"
}"""
class log_management:
def __init__(self):
self.logpath = "/etc/checkmyip/"
self.logfile = "/etc/checkmyip/checkmyip.log"
self._publish_methods()
self.can_log = True
paramiko.util.log_to_file('/etc/checkmyip/ssh.log')
def _logger(self, data):
logdata = time.strftime("%Y-%m-%d %H:%M:%S") + ": " + data + "\n"
if self.can_log:
try:
f = open(self.logfile, 'a')
f.write(logdata)
f.close()
except IOError:
self._console("Unable to log to logfile %s. Creating log directory" % self.logfile)
self.can_log = False
self._create_log_dir()
self._console(logdata)
def _console(self, data, timestamp=False):
if timestamp:
logdata = time.strftime("%Y-%m-%d %H:%M:%S") + ": " + data + "\n"
else:
logdata = data
print(logdata)
def _publish_methods(self):
global log
global console
log = self._logger
console = self._console
def _create_log_dir(self):
os.system('mkdir -p ' + self.logpath)
self._console("Logpath (%s) created" % self.logpath)
self.can_log = True
class rsa_key: class rsa_key:
data = """-----BEGIN RSA PRIVATE KEY----- data = """-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz MIICWgIBAAKBgQDTj1bqB4WmayWNPB+8jVSYpZYk80Ujvj680pOTh2bORBjbIAyz
oWGW+GUjzKxTiiPvVmxFgx5wdsFvF03v34lEVV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YSgbddOT6miqRskOQF3DZVkJT3kyuBgU2zKygz52ukQZMqxCb1fAkASvuTv
qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV qfpH87Qq5kQhNKdbbwbmd2NxlNabazPijWuphGTdW0VfJdWfklyS2Kr+iqrs/5wV
HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc HhathJt636Eg7oIjAkA8ht3MQ+XSl9yIJIS8gVpbPxSw5OMfw0PjVE7tBdQruiSc
nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7 nvuQES5C9BMHjF39LZiGH1iLQy7FgdHyoP+eodI7
-----END RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----
""" """
def open(self): def open(self):
pass pass
def close(self): def close(self):
pass pass
def readlines(self): def readlines(self):
return self.data.split("\n") return self.data.split("\n")
def __call__(self): def __call__(self):
return paramiko.RSAKey.from_private_key(self) return paramiko.RSAKey.from_private_key(self)
class ssh_server (paramiko.ServerInterface): class ssh_server (paramiko.ServerInterface):
def __init__(self): def __init__(self):
self.event = threading.Event() self.event = threading.Event()
def check_channel_request(self, kind, chanid): def check_channel_request(self, kind, chanid):
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):
return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_SUCCESSFUL
def get_allowed_auths(self, username): def get_allowed_auths(self, username):
return 'none' return 'none'
def check_channel_shell_request(self, channel): def check_channel_shell_request(self, channel):
self.event.set() self.event.set()
return True return True
def check_channel_pty_request(self, channel, term, width, height, def check_channel_pty_request(self, channel, term, width, height,
pixelwidth, pixelheight, modes): pixelwidth, pixelheight, modes):
return True return True
def j2format(j2tmp, valdict): def j2format(j2tmp, valdict):
template = jinja2.Template(j2tmp) template = jinja2.Template(j2tmp)
return template.render(valdict) return template.render(valdict)
def cleanip(ip): def cleanip(addr):
if len(ip) > 6: # If this IP is not a super short v6 address ip = addr[0]
if ip[:7] == "::ffff:": # If this is a prefixed IPv4 address port = addr[1]
return ip.replace("::ffff:", "") # Return the cleaned IP family = "ipv6"
return ip # Return the uncleaned IP if not matched if len(ip) > 6: # If this IP is not a super short v6 address
if ip[:7] == "::ffff:": # If this is a prefixed IPv4 address
ip = ip.replace("::ffff:", "") # Return the cleaned IP
family = "ipv4"
return (ip, port, family) # Return the uncleaned IP if not matched
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 = 100 # Normally 1024, but we want fast response
while True: while True:
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
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()
thread = threading.Thread(target=talker, args=(client, addr)) ip, port, family = cleanip(addr)
thread.start() valdict = {"ip": ip, "port": port, "family": family}
thread = threading.Thread(target=talker, args=(client, valdict))
thread.start()
def telnet_talker(client, addr): def telnet_talker(client, valdict):
valdict = {"ip": cleanip(addr[0]), "port": addr[1]} valdict.update({"proto": "telnet"})
print(j2format(j2log, valdict)) log(j2format(j2log, valdict))
client.send(j2format(j2send, valdict)) # echo client.send(j2format(j2send, valdict)) # echo
client.close() client.close()
#quit()
def ssh_talker(client, addr): def ssh_talker(client, valdict):
t = paramiko.Transport(client, gss_kex=True) valdict.update({"proto": "ssh"})
t.set_gss_host(socket.getfqdn("")) t = paramiko.Transport(client, gss_kex=True)
t.load_server_moduli() t.set_gss_host(socket.getfqdn(""))
t.add_server_key(rsa_key()()) t.load_server_moduli()
server = ssh_server() t.add_server_key(rsa_key()())
t.start_server(server=server) server = ssh_server()
chan = t.accept(20) t.start_server(server=server)
server.event.wait(10) chan = t.accept(20)
valdict = {"ip": cleanip(addr[0]), "port": addr[1]} if chan:
#chan.send(j2format(j2log, valdict)) server.event.wait(10)
chan.send('%s' % j2format(j2send, valdict)) #chan.send(j2format(j2log, valdict))
chan.makefile('rU').readline().strip('\r\n') log(j2format(j2log, valdict))
chan.close() chan.send('%s' % j2format(j2send, valdict))
chan.makefile('rU').readline().strip('\r\n')
chan.close()
#quit()
def start(): def start():
talkers = {2200: ssh_talker, 23: telnet_talker} talkers = {22: ssh_talker, 23: telnet_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 = False thread.daemon = True
thread.start() thread.start()
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
quit()
if __name__ == "__main__": if __name__ == "__main__":
start() logging = log_management()
start()