0

Whenever my client connect to my server via telnet

telnet myip 43

When the client hits ctrl+c on his own machine continuously it causes the telnet server to crash... how can this be stopped ? Also are there any chances by which my server can be attacked by a buffer overflow?

This is my script(very basic script it is)

#!/usr/bin/env python
import sys
import socket
import urllib2
def main():
    s = socket.socket()         # Create a socket object
    host = '' 
    BUFFER_SIZE = 2048
    port = 43                   # Reserve a port for your service.
    s.bind((host, port))        # Bind to the port
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.listen(120)               # Now wait for client connection.
    while True:
        data = ''
        print 'waiting for connection...'
        c, addr = s.accept()     # Establish connection with client.
        print 'Got connection from', addr
        data = c.recv(BUFFER_SIZE)
        print 'requested website: '+data
        print x
        c.send(x)
        c.close()                # Close the connection
if __name__ == '__main__':
    main()
Karl-Henrik
  • 1,087
  • 1
  • 11
  • 17
Harsh Daftary
  • 2,275
  • 1
  • 11
  • 12
  • Do you get an error message and traceback when your server crashes? – Wooble Apr 04 '14 at 11:34
  • I think you cut out the interesting part. I bet you try to open the file without checking if it exists or is a same filename. That's why Python crashes. – Mathias Apr 04 '14 at 11:36
  • before print x there is x = urllib2.urlopen('http://localhost:2020/?id='+data ).read() but is there any way to strip out bad char from a string ? like in php there is htmlspecialchar() or something @Mathias – Harsh Daftary Apr 04 '14 at 11:41

1 Answers1

1

try this:

import string
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)

[...]

        data = c.recv(BUFFER_SIZE)
        data=''.join(c for c in data if c in valid_chars)
        print 'requested website: '+data
        if len(data)>0:
            try:
                urllib2.urlopen('localhost:2020/?id='+data ).read()
                print x
                c.send(x)
            except:
                pass
        c.close()                # Close the connection

Edit valid_chars to only allow characters allowed for your id argument.

Community
  • 1
  • 1
Mathias
  • 1,410
  • 9
  • 19