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 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_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: print(traceback.format_exc()) pass try: print("-- TELNET TRANSPORT CLOSED --") socket.close() except: pass
def check_auth_password(self, username, password): print("Password-based authentication: user={} pass={}".format( username, password)) log_append('tcp_ssh_passwords', username, password, *self.socket_peername) #self.username = username #return paramiko.AUTH_SUCCESSFUL return paramiko.AUTH_FAILED
def process_incoming_udp(data, srcaddr, srcport, dstport): timestr = datetime.datetime.now().strftime("%a %Y/%m/%d %H:%M:%S%z") origcountry = geoip.country_name_by_addr(srcaddr) log_append('intruders', 'UDP', dstport, srcaddr, srcport, origcountry) print colored( "[{}]: Intruder {}:{} ({}) connected to fake port {}/udp".format( timestr, srcaddr, srcport, origcountry, dstport), 'magenta', attrs=['bold']) handle_udp(UDP_socketobject_proxy(dstport), data, (srcaddr, srcport), dstport)
def handle(self): # self.request is the socket try: srcaddr, srcport = self.request.getpeername() except: # This may happen if the connection gets closed by the # peer while we are still spawning the thread to handle it return dstaddr, dstport = self.getoriginaldest() timestr = datetime.datetime.now().strftime("%a %Y/%m/%d %H:%M:%S%z") origcountry = geoip.country_name_by_addr(srcaddr) print colored("[{}]: Intruder {}:{} ({}) connected to fake port {}/tcp".format(timestr, srcaddr, srcport, origcountry, dstport), 'magenta', attrs=['bold']) log_append('intruders', 'TCP', dstport, srcaddr, srcport, origcountry) handle_tcp(self.request, dstport)
def handle(self): # self.request is the socket try: srcaddr, srcport = self.request.getpeername() except: # This may happen if the connection gets closed by the # peer while we are still spawning the thread to handle it return dstaddr, dstport = self.getoriginaldest() timestr = datetime.datetime.now().strftime("%a %Y/%m/%d %H:%M:%S%z") origcountry = geoip.country_name_by_addr(srcaddr) print("[{}]: Intruder {}:{} ({}) connected to fake port {}/tcp".format(timestr, srcaddr, srcport, dstport)) log_append('intruders', 'TCP', dstport, srcaddr, srcport, origcountry) handle_tcp(self.request, dstport)
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_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_auth_password(self, username, password): print("Password-based authentication: user={} pass={}".format(username, password)) log_append('tcp_ssh_passwords', username, password, *self.socket_peername) self.username = username return paramiko.AUTH_SUCCESSFUL
def process_incoming_udp(data, srcaddr, srcport, dstport): timestr = datetime.datetime.now().strftime("%a %Y/%m/%d %H:%M:%S%z") origcountry = geoip.country_name_by_addr(srcaddr) log_append('intruders', 'UDP', dstport, srcaddr, srcport, origcountry) print colored("[{}]: Intruder {}:{} ({}) connected to fake port {}/udp".format(timestr, srcaddr, srcport, origcountry, dstport), 'magenta', attrs=['bold']) handle_udp(UDP_socketobject_proxy(dstport), data, (srcaddr, srcport), dstport)
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_udp_sip(socket, data, srcpeername, dstport): input_stream = StringIO.StringIO(tee_received_text(data)) firstline = input_stream.readline().strip() rematch = re.match("([A-Z]+) ([^ ]+) ?.*", firstline) if not rematch: raise Exception('Unexpected request') method = rematch.group(1) url = rematch.group(2) # Parse headers headers = {} while True: header = input_stream.readline().strip() if header == '': break else: rematch = re.match("([^:]+): ?(.*)", header) if not rematch: raise Exception('Unexpected header') else: headers[rematch.group(1)] = rematch.group(2) svtool = detect_sipvicious(headers['From'], dstport) # Send reply if (method == 'OPTIONS' or method == 'INVITE') and svtool == SIPVICIOUS_SVMAP: print("It looks like we are being scanned by svmap") resp = 'SIP/2.0 200 OK\n' rheaders = dict(headers) rheaders['To'] += ';tag=' + uuid.uuid4().hex rheaders['Allow'] = 'INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, SUBSCRIBE, NOTIFY, INFO' rheaders['User-Agent'] = USER_AGENT elif (method == 'REGISTER' or method == 'INVITE') and svtool == SIPVICIOUS_SVWAR: print("It looks like we are being scanned by svwar") if is_bad_user(srcpeername[0], headers['To']): print("Pretending {} is a bad user".format(headers['To'])) resp = 'SIP/2.0 404 Not Found\n' else: print("Pretending {} is a good user".format(headers['To'])) resp = 'SIP/2.0 200 OK\n' # http://kb.smartvox.co.uk/asterisk/friendlyscanner-gets-aggressive/ rheaders = { 'From': headers['From'], 'To': headers['To'], 'Call-ID': headers['Call-ID'], 'CSeq': headers['CSeq'] } rheaders['Via'] = '{};received={}'.format(headers['Via'].replace(';rport', ''), srcpeername[0]) rheaders['User-Agent'] = USER_AGENT elif method == 'INVITE': print("The intruder is trying to make a call") # Pretend we don't understand to stop further interactions resp = 'SIP/2.0 501 Not Implemented\n' rheaders = {} to_hdr = headers.get('To', '') from_hdr = headers.get('From', '') ua_hdr = headers.get('User-Agent', '') log_append('udp_sip_invites', srcpeername[0], to_hdr, from_hdr, ua_hdr) elif (method == 'ACK' or method == 'BYE'): resp = 'SIP/2.0 200 OK\n' rheaders = dict(headers) rheaders['User-Agent'] = USER_AGENT else: resp = 'SIP/2.0 501 Not Implemented\n' rheaders = {} # Assemble response for k in rheaders: resp += '{}: {}\n'.format(k, rheaders[k]) socket.sendto(tee_sent_text('{}\n'.format(resp)), srcpeername)