]> git.ipfire.org Git - people/ms/libloc.git/blob - src/python/location-importer.in
python: Implement writing database content to file
[people/ms/libloc.git] / src / python / location-importer.in
1 #!/usr/bin/python3
2 ###############################################################################
3 # #
4 # libloc - A library to determine the location of someone on the Internet #
5 # #
6 # Copyright (C) 2020 IPFire Development Team <info@ipfire.org> #
7 # #
8 # This library is free software; you can redistribute it and/or #
9 # modify it under the terms of the GNU Lesser General Public #
10 # License as published by the Free Software Foundation; either #
11 # version 2.1 of the License, or (at your option) any later version. #
12 # #
13 # This library is distributed in the hope that it will be useful, #
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU #
16 # Lesser General Public License for more details. #
17 # #
18 ###############################################################################
19
20 import argparse
21 import ipaddress
22 import logging
23 import math
24 import re
25 import sys
26 import telnetlib
27
28 # Load our location module
29 import location
30 import location.database
31 import location.importer
32 from location.i18n import _
33
34 # Initialise logging
35 log = logging.getLogger("location.importer")
36 log.propagate = 1
37
38 class CLI(object):
39 def parse_cli(self):
40 parser = argparse.ArgumentParser(
41 description=_("Location Importer Command Line Interface"),
42 )
43 subparsers = parser.add_subparsers()
44
45 # Global configuration flags
46 parser.add_argument("--debug", action="store_true",
47 help=_("Enable debug output"))
48
49 # version
50 parser.add_argument("--version", action="version",
51 version="%(prog)s @VERSION@")
52
53 # Database
54 parser.add_argument("--database-host", required=True,
55 help=_("Database Hostname"), metavar=_("HOST"))
56 parser.add_argument("--database-name", required=True,
57 help=_("Database Name"), metavar=_("NAME"))
58 parser.add_argument("--database-username", required=True,
59 help=_("Database Username"), metavar=_("USERNAME"))
60 parser.add_argument("--database-password", required=True,
61 help=_("Database Password"), metavar=_("PASSWORD"))
62
63 # Write Database
64 write = subparsers.add_parser("write", help=_("Write database to file"))
65 write.set_defaults(func=self.handle_write)
66 write.add_argument("file", nargs=1, help=_("Database File"))
67 write.add_argument("--signing-key", nargs="?", type=open, help=_("Signing Key"))
68 write.add_argument("--vendor", nargs="?", help=_("Sets the vendor"))
69 write.add_argument("--description", nargs="?", help=_("Sets a description"))
70 write.add_argument("--license", nargs="?", help=_("Sets the license"))
71
72 # Update WHOIS
73 update_whois = subparsers.add_parser("update-whois", help=_("Update WHOIS Information"))
74 update_whois.set_defaults(func=self.handle_update_whois)
75
76 # Update announcements
77 update_announcements = subparsers.add_parser("update-announcements",
78 help=_("Update BGP Annoucements"))
79 update_announcements.set_defaults(func=self.handle_update_announcements)
80 update_announcements.add_argument("server", nargs=1,
81 help=_("Route Server to connect to"), metavar=_("SERVER"))
82
83 # Update overrides
84 update_overrides = subparsers.add_parser("update-overrides",
85 help=_("Update overrides"),
86 )
87 update_overrides.add_argument(
88 "files", nargs="+", help=_("Files to import"),
89 )
90 update_overrides.set_defaults(func=self.handle_update_overrides)
91
92 args = parser.parse_args()
93
94 # Enable debug logging
95 if args.debug:
96 log.setLevel(logging.DEBUG)
97
98 # Print usage if no action was given
99 if not "func" in args:
100 parser.print_usage()
101 sys.exit(2)
102
103 return args
104
105 def run(self):
106 # Parse command line arguments
107 args = self.parse_cli()
108
109 # Initialise database
110 self.db = self._setup_database(args)
111
112 # Call function
113 ret = args.func(args)
114
115 # Return with exit code
116 if ret:
117 sys.exit(ret)
118
119 # Otherwise just exit
120 sys.exit(0)
121
122 def _setup_database(self, ns):
123 """
124 Initialise the database
125 """
126 # Connect to database
127 db = location.database.Connection(
128 host=ns.database_host, database=ns.database_name,
129 user=ns.database_username, password=ns.database_password,
130 )
131
132 with db.transaction():
133 db.execute("""
134 -- announcements
135 CREATE TABLE IF NOT EXISTS announcements(network inet, autnum bigint,
136 first_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
137 last_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP);
138 CREATE UNIQUE INDEX IF NOT EXISTS announcements_networks ON announcements(network);
139 CREATE INDEX IF NOT EXISTS announcements_family ON announcements(family(network));
140
141 -- autnums
142 CREATE TABLE IF NOT EXISTS autnums(number bigint, name text NOT NULL);
143 CREATE UNIQUE INDEX IF NOT EXISTS autnums_number ON autnums(number);
144
145 -- networks
146 CREATE TABLE IF NOT EXISTS networks(network inet, country text);
147 CREATE UNIQUE INDEX IF NOT EXISTS networks_network ON networks(network);
148 CREATE INDEX IF NOT EXISTS networks_search ON networks USING GIST(network inet_ops);
149
150 -- overrides
151 CREATE TABLE IF NOT EXISTS autnum_overrides(
152 number bigint NOT NULL,
153 name text,
154 is_anonymous_proxy boolean DEFAULT FALSE,
155 is_satellite_provider boolean DEFAULT FALSE,
156 is_anycast boolean DEFAULT FALSE
157 );
158 CREATE UNIQUE INDEX IF NOT EXISTS autnum_overrides_number
159 ON autnum_overrides(number);
160
161 CREATE TABLE IF NOT EXISTS network_overrides(
162 network inet NOT NULL,
163 country text,
164 is_anonymous_proxy boolean DEFAULT FALSE,
165 is_satellite_provider boolean DEFAULT FALSE,
166 is_anycast boolean DEFAULT FALSE
167 );
168 CREATE UNIQUE INDEX IF NOT EXISTS network_overrides_network
169 ON network_overrides(network);
170 """)
171
172 return db
173
174 def handle_write(self, ns):
175 """
176 Compiles a database in libloc format out of what is in the database
177 """
178 print(ns)
179
180 # Allocate a writer
181 writer = location.Writer(ns.signing_key)
182
183 # Set all metadata
184 if ns.vendor:
185 writer.vendor = ns.vendor
186
187 if ns.description:
188 writer.description = ns.description
189
190 if ns.license:
191 writer.license = ns.license
192
193 # Add all Autonomous Systems
194 log.info("Writing Autonomous Systems...")
195
196 # Select all ASes with a name
197 rows = self.db.query("SELECT * FROM autnums \
198 WHERE name <> %s ORDER BY number", "")
199
200 for row in rows:
201 a = writer.add_as(row.number)
202 a.name = row.name
203
204 # Add all networks
205 log.info("Writing networks...")
206
207 # Select all known networks
208 rows = self.db.query("""
209 SELECT
210 announcements.network AS network,
211 announcements.autnum AS autnum,
212 (
213 SELECT networks.country FROM networks
214 WHERE announcements.network <<= networks.network
215 ) AS country,
216
217 -- Flags
218 FALSE AS is_anonymous_proxy,
219 FALSE AS is_satellite_provider,
220 FALSE AS is_anycast
221 FROM announcements
222 """)
223
224 for row in rows:
225 network = writer.add_network(row.network)
226
227 # Save AS & country
228 network.asn, network.country_code = row.autnum, row.country
229
230 # Set flags
231 if row.is_anonymous_proxy:
232 network.set_flag(location.NETWORK_FLAG_ANONYMOUS_PROXY)
233
234 if row.is_satellite_provider:
235 network.set_flag(location.NETWORK_FLAG_SATELLITE_PROVIDER)
236
237 if row.is_anycast:
238 network.set_flag(location.NETWORK_FLAG_ANYCAST)
239
240 # Write everything to file
241 log.info("Writing database to file...")
242 for file in ns.file:
243 writer.write(file)
244
245 def handle_update_whois(self, ns):
246 downloader = location.importer.Downloader()
247
248 # Download all sources
249 with self.db.transaction():
250 # Create some temporary tables to store parsed data
251 self.db.execute("""
252 CREATE TEMPORARY TABLE _autnums(number integer, organization text)
253 ON COMMIT DROP;
254 CREATE UNIQUE INDEX _autnums_number ON _autnums(number);
255
256 CREATE TEMPORARY TABLE _organizations(handle text, name text)
257 ON COMMIT DROP;
258 CREATE UNIQUE INDEX _organizations_handle ON _organizations(handle);
259 """)
260
261 for source in location.importer.WHOIS_SOURCES:
262 with downloader.request(source, return_blocks=True) as f:
263 for block in f:
264 self._parse_block(block)
265
266 self.db.execute("""
267 INSERT INTO autnums(number, name)
268 SELECT _autnums.number, _organizations.name FROM _autnums
269 LEFT JOIN _organizations ON _autnums.organization = _organizations.handle
270 ON CONFLICT (number) DO UPDATE SET name = excluded.name;
271 """)
272
273 # Download all extended sources
274 for source in location.importer.EXTENDED_SOURCES:
275 with self.db.transaction():
276 # Download data
277 with downloader.request(source) as f:
278 for line in f:
279 self._parse_line(line)
280
281 def _parse_block(self, block):
282 # Get first line to find out what type of block this is
283 line = block[0]
284
285 # aut-num
286 if line.startswith("aut-num:"):
287 return self._parse_autnum_block(block)
288
289 # organisation
290 elif line.startswith("organisation:"):
291 return self._parse_org_block(block)
292
293 def _parse_autnum_block(self, block):
294 autnum = {}
295 for line in block:
296 # Split line
297 key, val = split_line(line)
298
299 if key == "aut-num":
300 m = re.match(r"^(AS|as)(\d+)", val)
301 if m:
302 autnum["asn"] = m.group(2)
303
304 elif key == "org":
305 autnum[key] = val
306
307 # Skip empty objects
308 if not autnum:
309 return
310
311 # Insert into database
312 self.db.execute("INSERT INTO _autnums(number, organization) \
313 VALUES(%s, %s) ON CONFLICT (number) DO UPDATE SET \
314 organization = excluded.organization",
315 autnum.get("asn"), autnum.get("org"),
316 )
317
318 def _parse_org_block(self, block):
319 org = {}
320 for line in block:
321 # Split line
322 key, val = split_line(line)
323
324 if key in ("organisation", "org-name"):
325 org[key] = val
326
327 # Skip empty objects
328 if not org:
329 return
330
331 self.db.execute("INSERT INTO _organizations(handle, name) \
332 VALUES(%s, %s) ON CONFLICT (handle) DO \
333 UPDATE SET name = excluded.name",
334 org.get("organisation"), org.get("org-name"),
335 )
336
337 def _parse_line(self, line):
338 # Skip version line
339 if line.startswith("2"):
340 return
341
342 # Skip comments
343 if line.startswith("#"):
344 return
345
346 try:
347 registry, country_code, type, line = line.split("|", 3)
348 except:
349 log.warning("Could not parse line: %s" % line)
350 return
351
352 # Skip any lines that are for stats only
353 if country_code == "*":
354 return
355
356 if type in ("ipv6", "ipv4"):
357 return self._parse_ip_line(country_code, type, line)
358
359 def _parse_ip_line(self, country, type, line):
360 try:
361 address, prefix, date, status, organization = line.split("|")
362 except ValueError:
363 organization = None
364
365 # Try parsing the line without organization
366 try:
367 address, prefix, date, status = line.split("|")
368 except ValueError:
369 log.warning("Unhandled line format: %s" % line)
370 return
371
372 # Skip anything that isn't properly assigned
373 if not status in ("assigned", "allocated"):
374 return
375
376 # Cast prefix into an integer
377 try:
378 prefix = int(prefix)
379 except:
380 log.warning("Invalid prefix: %s" % prefix)
381
382 # Fix prefix length for IPv4
383 if type == "ipv4":
384 prefix = 32 - int(math.log(prefix, 2))
385
386 # Try to parse the address
387 try:
388 network = ipaddress.ip_network("%s/%s" % (address, prefix), strict=False)
389 except ValueError:
390 log.warning("Invalid IP address: %s" % address)
391 return
392
393 self.db.execute("INSERT INTO networks(network, country) \
394 VALUES(%s, %s) ON CONFLICT (network) DO \
395 UPDATE SET country = excluded.country",
396 "%s" % network, country,
397 )
398
399 def handle_update_announcements(self, ns):
400 server = ns.server[0]
401
402 # Pre-compile regular expression for routes
403 #route = re.compile(b"^\*>?\s[\si]?([^\s]+)[.\s]*?(\d+)\si$", re.MULTILINE)
404 route = re.compile(b"^\*[\s\>]i([^\s]+).+?(\d+)\si\r\n", re.MULTILINE|re.DOTALL)
405
406 with telnetlib.Telnet(server) as t:
407 # Enable debug mode
408 #if ns.debug:
409 # t.set_debuglevel(10)
410
411 # Wait for console greeting
412 greeting = t.read_until(b"> ")
413 log.debug(greeting.decode())
414
415 # Disable pagination
416 t.write(b"terminal length 0\n")
417
418 # Wait for the prompt to return
419 t.read_until(b"> ")
420
421 # Fetch the routing tables
422 with self.db.transaction():
423 for protocol in ("ipv6", "ipv4"):
424 log.info("Requesting %s routing table" % protocol)
425
426 # Request the full unicast routing table
427 t.write(b"show bgp %s unicast\n" % protocol.encode())
428
429 # Read entire header which ends with "Path"
430 t.read_until(b"Path\r\n")
431
432 while True:
433 # Try reading a full entry
434 # Those might be broken across multiple lines but ends with i
435 line = t.read_until(b"i\r\n", timeout=5)
436 if not line:
437 break
438
439 # Show line for debugging
440 #log.debug(repr(line))
441
442 # Try finding a route in here
443 m = route.match(line)
444 if m:
445 network, autnum = m.groups()
446
447 # Convert network to string
448 network = network.decode()
449
450 # Convert AS number to integer
451 autnum = int(autnum)
452
453 log.info("Found announcement for %s by %s" % (network, autnum))
454
455 self.db.execute("INSERT INTO announcements(network, autnum) \
456 VALUES(%s, %s) ON CONFLICT (network) DO \
457 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
458 network, autnum,
459 )
460
461 log.info("Finished reading the %s routing table" % protocol)
462
463 # Purge anything we never want here
464 self.db.execute("""
465 -- Delete default routes
466 DELETE FROM announcements WHERE network = '::/0' OR network = '0.0.0.0/0';
467
468 -- Delete anything that is not global unicast address space
469 DELETE FROM announcements WHERE family(network) = 6 AND NOT network <<= '2000::/3';
470
471 -- DELETE RFC1918 address space
472 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '10.0.0.0/8';
473 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '172.16.0.0/12';
474 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.168.0.0/16';
475
476 -- Delete networks that are too small to be in the global routing table
477 DELETE FROM announcements WHERE family(network) = 6 AND masklen(network) > 48;
478 DELETE FROM announcements WHERE family(network) = 4 AND masklen(network) > 24;
479
480 -- Delete any non-public or reserved ASNs
481 DELETE FROM announcements WHERE NOT (
482 (autnum >= 1 AND autnum <= 23455)
483 OR
484 (autnum >= 23457 AND autnum <= 64495)
485 OR
486 (autnum >= 131072 AND autnum <= 4199999999)
487 );
488
489 -- Delete everything that we have not seen for 14 days
490 DELETE FROM announcements WHERE last_seen_at <= CURRENT_TIMESTAMP - INTERVAL '14 days';
491 """)
492
493 def handle_update_overrides(self, ns):
494 with self.db.transaction():
495 # Drop all data that we have
496 self.db.execute("""
497 TRUNCATE TABLE autnum_overrides;
498 TRUNCATE TABLE network_overrides;
499 """)
500
501 for file in ns.files:
502 log.info("Reading %s..." % file)
503
504 with open(file, "rb") as f:
505 for type, block in location.importer.read_blocks(f):
506 if type == "net":
507 network = block.get("net")
508 # Try to parse and normalise the network
509 try:
510 network = ipaddress.ip_network(network, strict=False)
511 except ValueError as e:
512 log.warning("Invalid IP network: %s: %s" % (network, e))
513 continue
514
515 self.db.execute("""
516 INSERT INTO network_overrides(
517 network,
518 country,
519 is_anonymous_proxy,
520 is_satellite_provider,
521 is_anycast
522 ) VALUES (%s, %s, %s, %s)
523 ON CONFLICT (network) DO NOTHING""",
524 "%s" % network,
525 block.get("country"),
526 block.get("is-anonymous-proxy") == "yes",
527 block.get("is-satellite-provider") == "yes",
528 block.get("is-anycast") == "yes",
529 )
530
531 elif type == "autnum":
532 autnum = block.get("autnum")
533
534 # Check if AS number begins with "AS"
535 if not autnum.startswith("AS"):
536 log.warning("Invalid AS number: %s" % autnum)
537 continue
538
539 # Strip "AS"
540 autnum = autnum[2:]
541
542 self.db.execute("""
543 INSERT INTO autnum_overrides(
544 number,
545 name,
546 is_anonymous_proxy,
547 is_satellite_provider,
548 is_anycast
549 ) VALUES(%s, %s, %s, %s, %s)
550 ON CONFLICT DO NOTHING""",
551 autnum, block.get("name"),
552 block.get("is-anonymous-proxy") == "yes",
553 block.get("is-satellite-provider") == "yes",
554 block.get("is-anycast") == "yes",
555 )
556
557 else:
558 log.warning("Unsupport type: %s" % type)
559
560
561 def split_line(line):
562 key, colon, val = line.partition(":")
563
564 # Strip any excess space
565 key = key.strip()
566 val = val.strip()
567
568 return key, val
569
570 def main():
571 # Run the command line interface
572 c = CLI()
573 c.run()
574
575 main()