Created
February 5, 2011 15:05
-
-
Save joneskoo/812505 to your computer and use it in GitHub Desktop.
ident-lookup.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Ident lookup for incoming connections | |
# RFC 1413 - Identification Protocol | |
import socket | |
def lookup_ident(host, server_port, client_port): | |
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) | |
s.settimeout(1) | |
try: | |
s.connect((host, 113)) | |
query = "%d,%d" % (server_port, client_port) | |
s.send(query + "\r\n") | |
data = "" | |
while not "\r\n" in data: | |
data_new = s.recv(1024) | |
if not len(data_new) > 0: | |
break | |
data += data_new | |
print data | |
rows = data.split("\r\n") | |
parts = rows[0].split(":") | |
parts = map(lambda x: x.strip(), parts) | |
if len(parts) < 4 or parts[0].replace(' ', '') != query: | |
return None # Invalid reply format | |
if not parts[1].upper() == 'USERID': | |
return None # Error response | |
opsys = parts[2].split(",") | |
if len(opsys) > 1: | |
charset = opsys[1] | |
else: | |
charset = 'US-ASCII' | |
user_id = parts[3].decode(charset) | |
return user_id | |
except socket.error: | |
return None | |
def receive_connections(host, port): | |
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) | |
s.bind((host, port)) | |
s.listen(1) | |
try: | |
while True: | |
(conn, addr) = s.accept() | |
print "Received connection from", addr | |
yield (conn, addr) | |
finally: | |
s.close() | |
def main(): | |
PORT = 1235 | |
for (conn,addr) in receive_connections("", PORT): | |
user = lookup_ident(addr[0], addr[1], PORT) | |
conn.send("%s\r\n" % user) | |
conn.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
query = "%d,%d" % (server_port, client_port)
in line 11 (https://gist.github.com/joneskoo/812505#file-gistfile1-py-L11) has the arguments reversed. A valid identd query needs to be "remote_port, local_port\r\n" which would translate toquery = "%d,%d" % (client_port, server_port)