#!/usr/bin/env python

# I started with this simple server
# http://www.binarytides.com/python-socket-server-code-example/
# and added the hello and password prompt from here
# https://github.com/robertdavidgraham/telnetlogger/blob/master/telnetlogger.c


'''
    Simple socket server using threads
'''
 
import socket, sys, datetime
from thread import *
 
HOST = ''   # Symbolic name meaning all available interfaces
PORT = 23   # TELNET
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print 'Socket created'
 
#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()
     
# print 'Socket bind complete'
 
#Start listening on socket
s.listen(10)
# print 'Socket now listening'


def underline(text):
    # underline unprintable characters
    l = len(text)
    clean = ''
    for i in range(l):
      c = ord(text[i])
      if (c < 32) or (c >127):
        clean += "_"
      else:
        clean += chr(c)
    return clean

 
#Function for handling connections. This will be used to create threads
def clientthread(conn,addr):

    hello = "\xff\xfb\x03" 	# 		/* Will Suppress Go Ahead */
    hello += "\xff\xfb\x01" #		/* Will Echo */
    hello += "\xff\xfd\x1f" #		/* Do Negotiate Window Size */
    hello += "\xff\xfd\x18" #		/* Do Negotiate Terminal Type */
    hello += "\r\nlogin: "

    #Sending message to connected client
    conn.send(hello) 
    r = conn.recv(1024) # first answer is junk, discard it
    
    reply = "\r\nPassword: "
    conn.send(reply)
    r = conn.recv(1024).rstrip('\n')
    username = underline(r)
    username_hex = r.encode('hex')
    l = len(username)
    if l > 20:
      username = username[18:l-1]
    username = username.replace('<', '<');	# anti-XSS
    username = username.replace('>', '>');
    
    reply = "\r\nPassword: "
    conn.send(reply)
    r = conn.recv(1024).rstrip('\n')
    password = underline(r)
    password_hex = r.encode('hex')
    l = len(password)
    if l > 0:
      password = password[:l-1]
    password = password.replace('<', '<');	# anti-XSS
    password = password.replace('>', '>');
    
    print '', datetime.datetime.now(), '', addr[0], ':', str(addr[1]), '', username, ':', password, '', username_hex, '\t',  password_hex, ''
    sys.stdout.flush()
    conn.close()
 
#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    # print 'Connected with ' + addr[0] + ':' + str(addr[1])
     
    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,addr))
 
s.close()