This repository has been archived by the owner on Apr 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathproxywhois.py
264 lines (232 loc) · 8.75 KB
/
proxywhois.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python
"""
Taken from pywhois project: https://code.google.com/p/pywhois/
with some modifications for proxy support
"""
import socks
import config
debug = False
class WhoisNoServerException(Exception):
def __init__(self, server):
self.server = server
def __str__(self):
return "Invalid Server: "+repr(self.server)
class ServerTroubleException(Exception):
def __init__(self, server, error):
self.server = server
self.error = error
def __str__(self):
return repr(self.server) + repr(self.error)
def enforce_ascii(a):
if isinstance(a, str) or isinstance(a, unicode):
# return a.encode('ascii', 'replace')
r = ""
for i in a:
if ord(i) >= 128:
r += "?"
else:
r += i
return r
else:
return a
class NICClient(object) :
ABUSEHOST = "whois.abuse.net"
NICHOST = "whois.crsnic.net"
INICHOST = "whois.networksolutions.com"
DNICHOST = "whois.nic.mil"
GNICHOST = "whois.nic.gov"
ANICHOST = "whois.arin.net"
LNICHOST = "whois.lacnic.net"
RNICHOST = "whois.ripe.net"
PNICHOST = "whois.apnic.net"
MNICHOST = "whois.ra.net"
QNICHOST_TAIL = ".whois-servers.net"
SNICHOST = "whois.6bone.net"
BNICHOST = "whois.registro.br"
NORIDHOST = "whois.norid.no"
IANAHOST = "whois.iana.org"
DENICHOST = "de.whois-servers.net"
DEFAULT_PORT = "nicname"
WHOIS_SERVER_ID = "Whois Server:"
WHOIS_ORG_SERVER_ID = "Registrant Street1:Whois Server:"
WHOIS_RECURSE = 0x01
WHOIS_QUICK = 0x02
ip_whois = [ LNICHOST, RNICHOST, PNICHOST, BNICHOST ]
def __init__(self) :
self.use_qnichost = False
self.use_proxy = False
self.proxy_type = None
self.proxy_server = None
self.proxy_port = None
def set_proxy(self, proxy_type, server,port):
"""Enables the use of the specified proxy for lookups"""
self.use_proxy = True
self.proxy_type = proxy_type
self.proxy_server = server
self.proxy_port = port
def findwhois_server(self, buf, hostname):
"""Search the initial TLD lookup results for the regional-specifc
whois server for getting contact details.
"""
#print 'finding whois server'
#print 'parameters:', buf, 'hostname', hostname
nhost = None
parts_index = 1
start = buf.rfind(NICClient.WHOIS_SERVER_ID)
#print 'start', start
if (start == -1):
start = buf.rfind(NICClient.WHOIS_ORG_SERVER_ID)
parts_index = 2
if (start > -1):
end = buf[start:].find('\n')
#print 'end:', end
whois_line = buf[start:end+start]
#print 'whois_line', whois_line
nhost = whois_line.split(NICClient.WHOIS_SERVER_ID+' ').pop()
nhost = nhost.split('http://').pop()
#if the whois address is domain.tld/something then
#s.connect((hostname, 43)) does not work
if nhost.count('/') > 0:
nhost = None
#print 'nhost:',nhost
elif (hostname == NICClient.ANICHOST):
for nichost in NICClient.ip_whois:
if (buf.find(nichost) != -1):
nhost = nichost
break
return nhost
def TLDSpecificQuery(self,tld,query,server):
tld = tld.lower()
if tld in ['com','net'] and server.endswith(NICClient.QNICHOST_TAIL):
query = "="+query
return query
def whois(self, query, hostname, flags):
"""Perform initial lookup with TLD whois server
then, if the quick flag is false, search that result
for the region-specifc whois server and do a lookup
there for contact details
"""
if debug:
print 'parameters given:', query, hostname, flags
#pdb.set_trace()
s = socks.socksocket(socks.socket.AF_INET, socks.socket.SOCK_STREAM)
s.settimeout(config.WHOIS_TIMEOUT_SECONDS)
#added code for proxy
if (self.use_proxy):
s.setproxy(self.proxy_type,self.proxy_server,self.proxy_port)
#convert hostname to ascii
hostname = hostname.encode('ascii','ignore')
if debug:
print "==DEBUG: Attempting to connect to: "+hostname
try:
s.connect((hostname, 43))
"""send takes bytes as an input
"""
queryBytes = None
tld = self.getTLD(query)
if tld:
query = self.TLDSpecificQuery(tld,query,hostname)
if (hostname == NICClient.DENICHOST):
#print 'the domain is in NIC DENIC'
queryBytes = ("-T dn,ace -C UTF-8 " + query + "\r\n").encode()
#print 'queryBytes:', queryBytes
else:
queryBytes = (query + "\r\n").encode()
s.send(queryBytes)
"""recv returns bytes
"""
#print s
response = b''
while True:
d = s.recv(4096)
response += d
if not d:
break
#pdb.set_trace()
nhost = None
if debug:
print '===========response=============='
print response
print "================================="
response = enforce_ascii(response)
if (flags & NICClient.WHOIS_RECURSE and nhost == None):
nhost = self.findwhois_server(response.decode(), hostname)
if (nhost != None):
r = self.whois(query, nhost, 0)
if not r:
return
response += r
#print 'returning whois response'
return response.decode()
except socks.socket.gaierror as e:
#bad hostname
if debug:
print "This TLD has no whois server."
return
else:
raise WhoisNoServerException(hostname)
except (socks.socket.error, socks.socket.timeout) as e:
error = ServerTroubleException(hostname,repr(e))
if debug:
print error
return
raise error
finally:
s.close()
def getTLD(self, domain):
if (domain.endswith("-NORID")):
return NICClient.NORIDHOST
pos = domain.rfind('.')
if (pos == -1):
return None
tld = domain[pos+1:]
if (tld[0].isdigit()):
return None
return tld
def choose_server(self, domain):
"""Choose initial lookup NIC host"""
tld = self.getTLD(domain)
if tld:
return tld + NICClient.QNICHOST_TAIL
return NICClient.ANICHOST
def whois_lookup(self, options, query_arg, flags):
"""Main entry point: Perform initial lookup on TLD whois server,
or other server to get region-specific whois server, then if quick
flag is false, perform a second lookup on the region-specific
server for contact records"""
#print 'whois_lookup'
nichost = None
#pdb.set_trace()
# this would be the case when this function is called by other than main
if (options == None):
options = {}
if ( (not 'whoishost' in options or options['whoishost'] == None)
and (not 'country' in options or options['country'] == None)):
self.use_qnichost = True
options['whoishost'] = NICClient.NICHOST
if ( not (flags & NICClient.WHOIS_QUICK)):
flags |= NICClient.WHOIS_RECURSE
if ('country' in options and options['country'] != None):
result = self.whois(query_arg, options['country'] + NICClient.QNICHOST_TAIL, flags)
elif (self.use_qnichost):
nichost = self.choose_server(query_arg)
if (nichost != None):
result = self.whois(query_arg, nichost, flags)
else:
result = self.whois(query_arg, options['whoishost'], flags)
#print 'whois_lookup finished'
return result
#---- END OF NICClient class def ---------------------
if __name__ == "__main__":
import sys #for args
import traceback
debug = True
flags = 0
nic_client = NICClient()
#(options, args) = parse_command_line(sys.argv)
#if (options.b_quicklookup is True):
# flags = flags|NICClient.WHOIS_QUICK
#print(nic_client.whois_lookup(options.__dict__, args[1], flags))
data = nic_client.whois_lookup(None, sys.argv[1], flags)
if data:
print data