def handle_tcp_httpproxy(origsocket, dstport): socket = TextChannel(origsocket) try: target = readline(socket).strip() rematch = re.match("CONNECT [^:]+(:[0-9]+)? ?.*", target) if not rematch: raise Exception('Unexpected request') port_num = int(rematch.groups(":80")[0][1:]) # Skip headers while readline(socket).strip() != '': pass log_append('tcp_httpproxy_connections', target, *origsocket.getpeername()) if port_num not in HTTP_CONNECT_FORBIDDEN_PORTS: socket.send("HTTP/1.0 200 Connection established\nProxy-agent: Netscape-Proxy/1.1\n\n") else: socket.send("HTTP/1.0 407 Proxy authentication required\nProxy-agent: Netscape-Proxy/1.1\n\n") port_num = None except Exception as err: #print(traceback.format_exc()) port_num = None if port_num: print("Forwarding intruder to fake port {}/tcp".format(port_num)) tcp_handler(origsocket, port_num) else: socket.close() print("-- HTTP TRANSPORT CLOSED --")
def check_channel_shell_request(self, channel): print("Shell requested") if 'root' in self.username: ps1 = '[root@localhost ~]# ' else: ps1 = '[{}@localhost ~]$ '.format(self.username) threading.Thread(target=noexceptwrap(interactive_shell), args=[TextChannel(channel, fix_incoming_endl=True), ps1]).start() return True
def handle_tcp_http(socket, dstport): socket = TextChannel(socket) try: keep_alive = True while keep_alive: firstline = readline(socket).strip() rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline) if not rematch: raise Exception('Unexpected request') verb = rematch.group(1) url = rematch.group(2) # Skip headers keep_alive = False user_agent = '' while True: header = readline(socket).strip() if header == '': break elif header.upper() == 'CONNECTION: KEEP-ALIVE': keep_alive = True elif header.upper().startswith('USER-AGENT: '): user_agent = header[len('USER-AGENT: '):] session_token = uuid.uuid4().hex log_append('tcp_http_requests', socket.getpeername()[0], dstport, verb, url, user_agent, session_token) socket.send( "HTTP/1.0 200 OK\nServer: microhttpd (MontaVista/2.4, i386-uClibc)\nSet-Cookie: sessionToken={}; Expires={}\nContent-Type: text/html\nContent-Length: 38\nConnection: {}\n\nmicrohttpd on Linux 2.4, it works!\n\n" .format(session_token, __getexpdate(5 * 365 * 24 * 60 * 60), "keep-alive" if keep_alive else "close")) except ssl.SSLError as err: print("SSL error: {}".format(err.reason)) pass except Exception as err: #print(traceback.format_exc()) pass try: print("-- HTTP TRANSPORT CLOSED --") socket.close() except: pass
def handle_tcp_httpproxy(origsocket, dstport): socket = TextChannel(origsocket) try: target = readline(socket).strip() rematch = re.match("CONNECT [^:]+(:[0-9]+)? ?.*", target) if not rematch: raise Exception('Unexpected request') port_num = int(rematch.groups(":80")[0][1:]) # Skip headers while readline(socket).strip() != '': pass log_append('tcp_httpproxy_connections', target, *origsocket.getpeername()) if port_num not in HTTP_CONNECT_FORBIDDEN_PORTS: socket.send( "HTTP/1.0 200 Connection established\nProxy-agent: Netscape-Proxy/1.1\n\n" ) else: socket.send( "HTTP/1.0 407 Proxy authentication required\nProxy-agent: Netscape-Proxy/1.1\n\n" ) port_num = None except Exception as err: #print(traceback.format_exc()) port_num = None if port_num: print("Forwarding intruder to fake port {}/tcp".format(port_num)) tcp_handler(origsocket, port_num) else: socket.close() print("-- HTTP TRANSPORT CLOSED --")
def check_channel_exec_request(self, channel, command): print("EXEC requested: {}".format(command)) threading.Thread(target=noexceptwrap(process_commandline), args=[TextChannel(channel, fix_incoming_endl=True), command]).start() return True
def handle_tcp_telnet(socket, dstport): socket = TextChannel(socket) try: socket.send("Linux-x86/2.4\nSamsung Smart TV\n\nlocalhost login: "******"Password: "******"\n\nSuccessfully logged in. Log in successful.\n") socket.send("Busybox v1.01 (2014.08.14-10:49+0000) Built-in shell (ash)\n") socket.send("Enter 'help' for a list of built-in commands.\n\n{}".format(ps1a)) process_commandline(socket, readline(socket, True, 10).strip()) interactive_shell(socket, ps1b, 10) except Exception as err: #print(traceback.format_exc()) pass try: print("-- TELNET TRANSPORT CLOSED --") socket.close() except: pass
def handle_tcp_smtp(plaintext_socket, dstport): socket = TextChannel(plaintext_socket) tls_started = False ctr = 0.5 msg_from = '' msg_to = [] try: socket.send("220 localhost ESMTP server ready\n") while True: cmd = readline(socket) cmdupper = cmd.upper() if cmd else None time.sleep(ctr) # Rate limit ctr *= 1.1 if not cmd or not cmd.endswith('\n'): raise Exception('Invalid request') elif cmdupper.startswith('HELO'): socket.send("250 localhost\n") elif cmdupper.startswith('EHLO'): socket.send( "250-localhost offers TWO extensions:\n250-8BITMIME\n250 STARTTLS\n" ) elif cmdupper.startswith('STARTTLS'): if tls_started: socket.send( "454 TLS not available due to temporary reason\n") else: tls_started = True socket.send("220 Go ahead\n") socket = TextChannel(switchtossl(plaintext_socket)) elif cmdupper.startswith('QUIT'): socket.send("221 localhost ESMTP server closing connection\n") break elif cmdupper.startswith('NOOP'): socket.send("250 No-op Ok\n") elif cmdupper.startswith('RSET'): msg_from = '' msg_to = [] socket.send("250 Reset Ok\n") elif cmdupper.startswith('DATA'): socket.send("354 Ok Send data ending with <CRLF>.<CRLF>\n") msg_contents = receive_data(socket) msg_id = uuid.uuid4().hex store_email(plaintext_socket.getpeername()[0], msg_id, msg_contents, msg_from, msg_to) socket.send( "250 Message received: {}@localhost\n".format(msg_id)) elif cmdupper.startswith('MAIL FROM:') or cmdupper.startswith( 'SEND FROM:') or cmdupper.startswith( 'SOML FROM:') or cmdupper.startswith('SAML FROM:'): msg_from = cmd[len('MAIL FROM:'):].strip() socket.send("250 Sender: {} Ok\n".format(msg_from)) elif cmdupper.startswith('RCPT TO:'): recipient = cmd[len('RCPT TO:'):].strip() msg_to.append(recipient) socket.send("250 Recipient: {} Ok\n".format(recipient)) else: socket.send("502 Command not implemented\n") except Exception as err: #print(traceback.format_exc()) pass try: print("-- SMTP TRANSPORT CLOSED --") socket.close() except: pass
def handle_tcp_telnet(socket, dstport): socket = TextChannel(socket) try: socket.send("Linux-x86/2.4\nSamsung Smart TV\n\nlocalhost login: "******"Password: "******"\n\nSuccessfully logged in. Log in successful.\n") socket.send( "Busybox v1.01 (2014.08.14-10:49+0000) Built-in shell (ash)\n") socket.send( "Enter 'help' for a list of built-in commands.\n\n{}".format(ps1a)) process_commandline(socket, readline(socket, True, 10).strip()) interactive_shell(socket, ps1b, 10) except Exception as err: #print(traceback.format_exc()) pass try: print("-- TELNET TRANSPORT CLOSED --") socket.close() except: pass
def dummy_tcp_handler(socket, dstport): TextChannel(socket).send("Request for port {}/tcp\n".format(dstport)) socket.close()
def handle_tcp_http(socket, dsthost, dstport, persona): # load body index_file = persona.get('index') if (os.path.exists(index_file) and os.path.isfile(index_file)): with open(index_file) as body_file: body = body_file.read() else: body = "<h1>It's Alive!</h1>" socket = TextChannel(socket) try: keep_alive = True while keep_alive: firstline = readline(socket).strip() if firstline == "": continue rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline) if not rematch: raise Exception('Unexpected request: "{}"'.format(firstline)) verb = rematch.group(1) url = rematch.group(2) # Skip headers keep_alive = False user_agent = '' while True: header = readline(socket).strip() if header == '': break elif header.upper() == 'CONNECTION: KEEP-ALIVE': keep_alive = True elif header.upper().startswith('USER-AGENT: '): user_agent = header[len('USER-AGENT: '):] session_token = uuid.uuid4().hex log_append('tcp_http_requests', socket.getpeername()[0], dstport, verb, url, user_agent, session_token) #HEADERS['Server'] = persona.get('headers').get('Server') HEADERS.update(persona.get('headers')) HEADERS['Set-Cookie'] = 'sessionToken={}; Expires={}'.format( session_token, __getexpdate(5 * 365 * 24 * 60 * 60)) HEADERS['Connection'] = "keep-alive" if keep_alive else "close" HEADERS['Content-Length'] = str(len(body)) header = 'HTTP/1.1 200 OK\n' for header_title in HEADERS: header += header_title + ': ' + HEADERS[header_title] + '\n' socket.send(header + '\n' + body) except ssl.SSLError as err: print("SSL error: {}".format(err.reason)) pass except ConnectionResetError: print("Connection reset by peer") pass except Exception: print(traceback.format_exc()) pass try: socket.close except: pass
def handle_tcp_smtp(plaintext_socket, dstport): socket = TextChannel(plaintext_socket) tls_started = False ctr = 0.5 msg_from = '' msg_to = [] try: socket.send("220 localhost ESMTP server ready\n") while True: cmd = readline(socket) cmdupper = cmd.upper() if cmd else None time.sleep(ctr) # Rate limit ctr *= 1.1 if not cmd or not cmd.endswith('\n'): raise Exception('Invalid request') elif cmdupper.startswith('HELO'): socket.send("250 localhost\n") elif cmdupper.startswith('EHLO'): socket.send("250-localhost offers TWO extensions:\n250-8BITMIME\n250 STARTTLS\n") elif cmdupper.startswith('STARTTLS'): if tls_started: socket.send("454 TLS not available due to temporary reason\n") else: tls_started = True socket.send("220 Go ahead\n") socket = TextChannel(switchtossl(plaintext_socket)) elif cmdupper.startswith('QUIT'): socket.send("221 localhost ESMTP server closing connection\n") break elif cmdupper.startswith('NOOP'): socket.send("250 No-op Ok\n") elif cmdupper.startswith('RSET'): msg_from = '' msg_to = [] socket.send("250 Reset Ok\n") elif cmdupper.startswith('DATA'): socket.send("354 Ok Send data ending with <CRLF>.<CRLF>\n") msg_contents = receive_data(socket) msg_id = uuid.uuid4().hex store_email(plaintext_socket.getpeername()[0], msg_id, msg_contents, msg_from, msg_to) socket.send("250 Message received: {}@localhost\n".format(msg_id)) elif cmdupper.startswith('MAIL FROM:') or cmdupper.startswith('SEND FROM:') or cmdupper.startswith('SOML FROM:') or cmdupper.startswith('SAML FROM:'): msg_from = cmd[len('MAIL FROM:'):].strip() socket.send("250 Sender: {} Ok\n".format(msg_from)) elif cmdupper.startswith('RCPT TO:'): recipient = cmd[len('RCPT TO:'):].strip() msg_to.append(recipient) socket.send("250 Recipient: {} Ok\n".format(recipient)) else: socket.send("502 Command not implemented\n") except Exception as err: #print(traceback.format_exc()) pass try: print("-- SMTP TRANSPORT CLOSED --") socket.close() except: pass