#identd.py
Language:
PythonWritten by
doug on 2008-01-31 23:12:10
import socket, sys, re, pwd
EOL = "\r\n";
OPSYS = "UNIX";
def gettcpuid(localp, remotep, localh, remoteh):
lph = "%X" % localp
rph = "%X" % remotep
for i in range(4-len(lph)):
lph = "0" + lph
for i in range(4-len(rph)):
rph = "0" + rph
fp = open("/proc/net/tcp", "r")
d = fp.read()
lines = re.split("[\r\n]", d)
for line in lines:
r = re.findall("([^ ]+)", line)
if r:
remoteaddr = r[2]
localaddr = r[1]
uid = r[7]
rs = remoteaddr.split(":")
ls = localaddr.split(":")
if len(ls) > 1 and len(rs) > 1:
print "comparing ", rs, rph, "and", ls, lph
if rph == rs[1] and lph == ls[1]:
print "remote =", remoteaddr, "local =", localaddr, "uid =", uid
return uid
return -1
if (len(sys.argv) > 1):
USERNAME = sys.argv[1];
if (len(sys.argv) > 2):
OPSYS = sys.argv[2];
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
listener.bind((socket.gethostname(), 113));
listener.listen(5);
while 1:
print "=[listening on " + socket.gethostname() + ":113]=";
(clientsocket, address) = listener.accept();
print "=[accepted connection from " + address[0] + ":" + str(address[1]) + "]=";
last2chrs = ['',''];
data = "";
while 1:
buf = clientsocket.recv(1);
last2chrs[0] = last2chrs[1];
last2chrs[1] = buf;
if last2chrs[0] == '\r' and last2chrs[1] == '\n':
break;
data = data + buf;
print "<<" + data;
p = re.compile( '\s');
data = p.sub('', data);
ports = re.split(",",data);
localp = int(ports[0]);
remotep = int(ports[1]);
portpair = str(localp) + "," + str(remotep);
uid = gettcpuid(localp, remotep, socket.gethostname(), address[0])
if (localp > 0 and localp < 65535) and (remotep > 0 and remotep < 65535):
if uid >= 0:
ud = pwd.getpwuid(int(uid))
if len(ud) >= 1:
username = ud[0]
outdata = portpair + ":USERID:" + OPSYS + ":" + username;
else:
outdata = portpair + ":ERROR:UNKNOWN-ERROR";
else:
outdata = portpair + ":ERROR:NO-USER"
else:
outdata = portpair + ":ERROR:INVALID-PORT";
clientsocket.send(outdata + EOL);
print ">>" + outdata;
print "=[request fullfilled]=";
clientsocket.close()
print "=[closing]=";
listener.close();