[Twisted-Python] Aborting a connection attempt when HTTPS client detected on HTTP only server?

Michael Schlenker msc at contact.de
Thu Feb 28 09:49:06 EST 2013


Am 11.02.2013 15:51, schrieb Itamar Turner-Trauring:
> 
> 
> On Mon, Feb 11, 2013 at 9:24 AM, Michael Schlenker <msc at contact.de
> <mailto:msc at contact.de>> wrote:
> 
>     Is there some pre-made solution, or would i have to hook into the
>     connection setup of twisted.web and check the first few bytes for the
>     signs of an SSL Handshake signature?
> 
> 
> Subclassing the HTTP protocol class and just adding a check in
> dataReceived is probably the easiest thing to do, yes. Might be worth
> filing a ticket for this as well. My guess is the logic would be
> something like "in dataReceived, if you've not hit first line, and any
> byte is non-ASCII, close connection", which has the nice property of
> being more general than just SSL. Or perhaps check what Apache does exactly.
> 
Okay, solved it like this:

from twisted.web import server, http

class HTTPChannel(http.HTTPChannel):
    """
    HTTP Channel that recognizes connection attempts via non-HTTP
    and closes the connection in such cases.
    """

    def __init__(self):
        http.HTTPChannel.__init__(self)
        self.__request_line_received = False

    def lineReceived(self, line):
        self.__request_line_received = True
        http.HTTPChannel.lineReceived(self, line)

    def dataReceived(self, data):
        if not self.__request_line_received:
            # check for any binary garbage, e.g. not ASCII
            # e.g. ssl connection attempt
            try:
                data.decode('ascii')
            except UnicodeDecodeError:
                return self.transport.loseConnection()
        http.HTTPChannel.dataReceived(self, data)


class Site(server.Site):
    protocol = HTTPChannel


Works fine. Thx for the suggestion to check for ASCII.

Michael

-- 
Michael Schlenker
Software Architect

CONTACT Software GmbH           Tel.:   +49 (421) 20153-80
Wiener Straße 1-3               Fax:    +49 (421) 20153-41
28359 Bremen
http://www.contact.de/          E-Mail: msc at contact.de

Sitz der Gesellschaft: Bremen
Geschäftsführer: Karl Heinz Zachries, Ralf Holtgrefe
Eingetragen im Handelsregister des Amtsgerichts Bremen unter HRB 13215



More information about the Twisted-Python mailing list