aboutsummaryrefslogtreecommitdiffstats
path: root/dtube/dtube.py
blob: ca1be1c515da010cae3d5341e4a023e96bb85423 (plain) (blame)
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
#!/usr/bin/env python
#
# dtube - Tube Definer, detube the intertubes to look into the right tube
# 2013 Laurent Ghigonis <laurent@p1sec.com>
#
# TODO
# * ip dns country
# * -t

import sys
import os
import requests
import requests_cache # pip install requests_cache
import pprint
import time
import random
import unittest
import re
from lxml import etree
from optparse import OptionParser

import conf_dtube

def usage():
  # [-t ranges|A|PTR|ip] [-f filter] 
  return """usage: %s [-h] [-v] AS | range-cidr | IP | DNS | country

Examples:
%s AS23118
%s 91.220.156.0/24
%s 8.8.8.8
%s ovh.net
%s US""" % (sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0])

# XXX already exists in python libs ?
def merge_table(left, right):
	content = ""
	w = 0
	while True:
		line = ''
		if w < len(left): line += left[w].strip()
		if w < len(right): line += "\t" + right[w].strip()
		if line == '':
			break
		content += line + '\n'
		w += 1
	return content

class He:
  url_headers = {'User-Agent': conf_dtube.url_useragent}

  @classmethod
  def initTarget(cls, target, verbose=False):
    match = re.search(r'^AS([0-9]*)$', target)
    if match:
      print "Target identified as AS %s" % match.group(1)
      return HeAS(match.group(1), verbose=verbose)
    match = re.search(r'^([0-9]+(?:\.[0-9]+){3}/[0-9]+)$', target)
    if match:
      print "Target identified as IPrange %s" % match.group(1)
      return HeIPrange(match.group(1), verbose=verbose)
    match = re.search(r'^([0-9]+(?:\.[0-9]+){3})$', target)
    if match:
      print "Target identified as IP %s" % match.group(1)
      return HeIP(match.group(1), verbose=verbose)
    match = re.search(r'(.*\..*)', target)
    if match:
      print "Target identified as DNS %s" % match.group(1)
      return HeDNS(match.group(1), verbose=verbose)
    match = re.search(r'^([^\.0-9]*)$', target)
    if match:
      print "Target identified as Country %s" % match.group(1)
      return HeCountry(match.group(1), verbose=verbose)
    raise Exception("Unable to identify target as AS / IPrange / IP / DNS / Country")

  def __init__(self, url, fromfile=None, verbose=False):
    self.url = url
    self.verbose = verbose
    if fromfile:
      f = open(fromfile)
      self.tree = etree.parse(f, etree.HTMLParser())
    else:
      if self.verbose: print url
      self.html = requests.get(url, headers=He.url_headers)
      if self.verbose: print self.html.status_code
      if not self.html.ok:
        if self.html.status_code == 404:
          raise Exception("Target not found")
        self.html.raise_for_status()
      self.tree = etree.HTML(self.html.content)
      if not getattr(self.html, 'from_cache', False):
        time.sleep(random.random() * 3) # Forced to be kind

class HeAS(He):
  url_prefix = '/AS'
  
  def __init__(self, AS, fromfile=None, verbose=False):
    self.AS = str(AS)
    He.__init__(self, conf_dtube.url_root + HeAS.url_prefix + self.AS, fromfile, verbose=verbose)
    self.parse()
  
  def parse(self):
    # AS Info
    info_it = self.tree.xpath('//div[@class="asinfotext"]')[0]
    left_it = info_it.xpath('//div[@class="asleft"]/child::text()')
    right_it = info_it.xpath('//div[@class="asright"]/a/child::text()')
    self.info = merge_table(left_it, right_it)
    # XXX Route propagation
    # Prefixes
    self.prefixes = dict()
    prefixes_l = self.tree.xpath('//table[@id="table_prefixes4"]')
    if prefixes_l:
      prefixes_it = prefixes_l[0]
      for p in prefixes_it.xpath('tbody/tr'):
        self.prefixes[p.xpath('td/a/child::text()')[0]] = {
          "href": p.xpath('td/a')[0].get('href'),
          "description": p.xpath('td[position()=2]/child::text()')[0].strip(),
          "country": p.xpath('td/div/img')[0].get('title'),
        }
    self.prefixes_txt = ""
    for p in self.prefixes.keys():
      self.prefixes_txt += p \
          + '\t' + self.prefixes[p]["description"] \
          + '\t(' + self.prefixes[p]["country"] + ')' + '\n'
    # XXX Peers
    # XXX Whois
    # XXX IRR

  def show(self):
    print "====== INFO ======"
    print self.info
    print "====== PREFIXES ======"
    print "Range\t\tDescription\t(Country)"
    print self.prefixes_txt

class HeIPrange(He):
  url_prefix = '/net/'

  def __init__(self, IPRange_cidr, fromfile=None, verbose=False):
    self.IPRange_cidr = str(IPRange_cidr)
    He.__init__(self, conf_dtube.url_root + HeIPrange.url_prefix + self.IPRange_cidr,
                fromfile, verbose=verbose)
    self.parse()

  def parse(self):
    # Network Info
    info_it = self.tree.xpath('//div[@id="netinfo"]')[0]
    self.info = [e.text for e in info_it.getiterator()] # XXX ugly
    # XXX Whois
    # DNS
    dns_l = self.tree.xpath('//div[@id="dns"]')
    self.dns = dict()
    if dns_l:
      dns_it = dns_l[0]
      for i in dns_it.xpath('table/tbody/tr'):
        self.dns[i.xpath('td[position()=1]/a/child::text()')[0]] = {
          "href": i.xpath('td[position()=1]/a')[0].get('href'),
          "PTR": i.xpath('td[position()=2]/a/child::text()')[0],
          "PTR_href": i.xpath('td[position()=2]/a')[0].get('href'),
          "A_list": i.xpath('td[position()=3]/a/child::text()'),
          "A_href_list": [it.get('href') for it in i.xpath('td[position()=3]/a')],
        }
    self.dns_txt = ""
    for d in self.dns.keys():
      self.dns_txt += d + '\t' + self.dns[d]["PTR"]
      if len(self.dns[d]["A_list"]) > 0:
        self.dns_txt += ' | ' + ' '.join(self.dns[d]["A_list"])
      self.dns_txt += '\n'
    # XXX IRR

  def show(self):
    print "====== INFO ======"
    print self.info
    print "======  DNS  ======"
    print "IP\tPTR [| A]"
    print self.dns_txt

class HeIP(He):
  url_prefix = '/ip/'

  def __init__(self, IP, fromfile=None, verbose=False):
    raise Exception("IP Not supported yet")

class HeDNS(He):
  url_prefix = '/ip/'

  def __init__(self, dns, fromfile=None, verbose=False):
    raise Exception("DNS Not supported yet")

class HeCountry(He):
  url_prefix = '/ip/'

  def __init__(self, country, fromfile=None, verbose=False):
    raise Exception("Country Not supported yet")

class HeAS_unittest(unittest.TestCase):
  def test_parse(self):
    print "HeAS_unittest.test_parse()"
    for t in os.listdir('tests/AS'):
      tname = t[:-5]
      h = HeAS(tname, fromfile="tests/AS/%s" % t)
      self.assertTrue(h is not None)

class HeIPRange_unittest(unittest.TestCase):
  def test_parse(self):
    print "HeIPRange_unittest.test_parse()"
    for t in os.listdir('tests/IPRange'):
      tname = t[:-5]
      h = HeIPrange(tname, fromfile="tests/IPRange/%s" % t)
      self.assertTrue(h is not None)

if __name__ == '__main__':
  if os.environ.has_key("UNITTEST"):
    if len(sys.argv) > 1:
      raise Exception("No arguments accepted in UNITTEST mode")
    unittest.main()
    sys.exit(0)

  parser = OptionParser(usage=usage())
  #parser.add_option('-t', action="store", dest="query_type", default=0, type=str,
  #                        help='Query type: range, A, PTR, ip, country')
  #parser.add_option('-f', action="store", dest="filter", default=None, type=str,
  #                        help='Filter regex for company name')
  parser.add_option('-n', action="store_true", dest="url_nocache", default=False,
                          help='Do not cache answers')
  parser.add_option('-v', action="store_true", dest="verbose", default=False,
                          help='Verbose')
  (options, args) = parser.parse_args()
  if (len(args) != 1):
    print usage()
    sys.exit(1)
  target = args[0]

  if options.url_nocache is False:
    requests_cache.install_cache('cache_dtube')

  he = He.initTarget(target, verbose=options.verbose)
  he.show()