2 ###############################################################################
4 # libloc - A library to determine the location of someone on the Internet #
6 # Copyright (C) 2020 IPFire Development Team <info@ipfire.org> #
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. #
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. #
18 ###############################################################################
28 # Load our location module
30 import location
.database
31 import location
.importer
32 from location
.i18n
import _
35 log
= logging
.getLogger("location.importer")
40 parser
= argparse
.ArgumentParser(
41 description
=_("Location Importer Command Line Interface"),
43 subparsers
= parser
.add_subparsers()
45 # Global configuration flags
46 parser
.add_argument("--debug", action
="store_true",
47 help=_("Enable debug output"))
50 parser
.add_argument("--version", action
="version",
51 version
="%(prog)s @VERSION@")
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"))
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"))
73 update_whois
= subparsers
.add_parser("update-whois", help=_("Update WHOIS Information"))
74 update_whois
.set_defaults(func
=self
.handle_update_whois
)
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"))
84 update_overrides
= subparsers
.add_parser("update-overrides",
85 help=_("Update overrides"),
87 update_overrides
.add_argument(
88 "files", nargs
="+", help=_("Files to import"),
90 update_overrides
.set_defaults(func
=self
.handle_update_overrides
)
92 args
= parser
.parse_args()
94 # Enable debug logging
96 log
.setLevel(logging
.DEBUG
)
98 # Print usage if no action was given
99 if not "func" in args
:
106 # Parse command line arguments
107 args
= self
.parse_cli()
109 # Initialise database
110 self
.db
= self
._setup
_database
(args
)
113 ret
= args
.func(args
)
115 # Return with exit code
119 # Otherwise just exit
122 def _setup_database(self
, ns
):
124 Initialise the database
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
,
132 with db
.transaction():
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));
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);
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);
151 CREATE TABLE IF NOT EXISTS autnum_overrides(
152 number bigint NOT NULL,
154 is_anonymous_proxy boolean DEFAULT FALSE,
155 is_satellite_provider boolean DEFAULT FALSE,
156 is_anycast boolean DEFAULT FALSE
158 CREATE UNIQUE INDEX IF NOT EXISTS autnum_overrides_number
159 ON autnum_overrides(number);
161 CREATE TABLE IF NOT EXISTS network_overrides(
162 network inet NOT NULL,
164 is_anonymous_proxy boolean DEFAULT FALSE,
165 is_satellite_provider boolean DEFAULT FALSE,
166 is_anycast boolean DEFAULT FALSE
168 CREATE UNIQUE INDEX IF NOT EXISTS network_overrides_network
169 ON network_overrides(network);
174 def handle_write(self
, ns
):
176 Compiles a database in libloc format out of what is in the database
181 writer
= location
.Writer(ns
.signing_key
)
185 writer
.vendor
= ns
.vendor
188 writer
.description
= ns
.description
191 writer
.license
= ns
.license
193 # Add all Autonomous Systems
194 log
.info("Writing Autonomous Systems...")
196 # Select all ASes with a name
197 rows
= self
.db
.query("""
199 autnums.number AS number,
201 (SELECT overrides.name FROM autnum_overrides overrides
202 WHERE overrides.number = autnums.number),
206 WHERE name <> %s ORDER BY number
210 a
= writer
.add_as(row
.number
)
214 log
.info("Writing networks...")
216 # Select all known networks
217 rows
= self
.db
.query("""
219 announcements.network AS network,
220 announcements.autnum AS autnum,
222 SELECT networks.country FROM networks
223 WHERE announcements.network <<= networks.network
224 ORDER BY masklen(networks.network) DESC
231 SELECT is_anonymous_proxy FROM network_overrides overrides
232 WHERE announcements.network <<= overrides.network
233 ORDER BY masklen(overrides.network) DESC
237 SELECT is_anonymous_proxy FROM autnum_overrides overrides
238 WHERE announcements.autnum = overrides.number
240 ) AS is_anonymous_proxy,
243 SELECT is_satellite_provider FROM network_overrides overrides
244 WHERE announcements.network <<= overrides.network
245 ORDER BY masklen(overrides.network) DESC
249 SELECT is_satellite_provider FROM autnum_overrides overrides
250 WHERE announcements.autnum = overrides.number
252 ) AS is_satellite_provider,
255 SELECT is_anycast FROM network_overrides overrides
256 WHERE announcements.network <<= overrides.network
257 ORDER BY masklen(overrides.network) DESC
261 SELECT is_anycast FROM autnum_overrides overrides
262 WHERE announcements.autnum = overrides.number
269 network
= writer
.add_network(row
.network
)
272 network
.asn
, network
.country_code
= row
.autnum
, row
.country
275 if row
.is_anonymous_proxy
:
276 network
.set_flag(location
.NETWORK_FLAG_ANONYMOUS_PROXY
)
278 if row
.is_satellite_provider
:
279 network
.set_flag(location
.NETWORK_FLAG_SATELLITE_PROVIDER
)
282 network
.set_flag(location
.NETWORK_FLAG_ANYCAST
)
284 # Write everything to file
285 log
.info("Writing database to file...")
289 def handle_update_whois(self
, ns
):
290 downloader
= location
.importer
.Downloader()
292 # Download all sources
293 with self
.db
.transaction():
294 # Create some temporary tables to store parsed data
296 CREATE TEMPORARY TABLE _autnums(number integer, organization text)
298 CREATE UNIQUE INDEX _autnums_number ON _autnums(number);
300 CREATE TEMPORARY TABLE _organizations(handle text, name text)
302 CREATE UNIQUE INDEX _organizations_handle ON _organizations(handle);
305 for source
in location
.importer
.WHOIS_SOURCES
:
306 with downloader
.request(source
, return_blocks
=True) as f
:
308 self
._parse
_block
(block
)
311 INSERT INTO autnums(number, name)
312 SELECT _autnums.number, _organizations.name FROM _autnums
313 LEFT JOIN _organizations ON _autnums.organization = _organizations.handle
314 ON CONFLICT (number) DO UPDATE SET name = excluded.name;
317 # Download all extended sources
318 for source
in location
.importer
.EXTENDED_SOURCES
:
319 with self
.db
.transaction():
321 with downloader
.request(source
) as f
:
323 self
._parse
_line
(line
)
325 def _parse_block(self
, block
):
326 # Get first line to find out what type of block this is
330 if line
.startswith("aut-num:"):
331 return self
._parse
_autnum
_block
(block
)
334 elif line
.startswith("organisation:"):
335 return self
._parse
_org
_block
(block
)
337 def _parse_autnum_block(self
, block
):
341 key
, val
= split_line(line
)
344 m
= re
.match(r
"^(AS|as)(\d+)", val
)
346 autnum
["asn"] = m
.group(2)
355 # Insert into database
356 self
.db
.execute("INSERT INTO _autnums(number, organization) \
357 VALUES(%s, %s) ON CONFLICT (number) DO UPDATE SET \
358 organization = excluded.organization",
359 autnum
.get("asn"), autnum
.get("org"),
362 def _parse_org_block(self
, block
):
366 key
, val
= split_line(line
)
368 if key
in ("organisation", "org-name"):
375 self
.db
.execute("INSERT INTO _organizations(handle, name) \
376 VALUES(%s, %s) ON CONFLICT (handle) DO \
377 UPDATE SET name = excluded.name",
378 org
.get("organisation"), org
.get("org-name"),
381 def _parse_line(self
, line
):
383 if line
.startswith("2"):
387 if line
.startswith("#"):
391 registry
, country_code
, type, line
= line
.split("|", 3)
393 log
.warning("Could not parse line: %s" % line
)
396 # Skip any lines that are for stats only
397 if country_code
== "*":
400 if type in ("ipv6", "ipv4"):
401 return self
._parse
_ip
_line
(country_code
, type, line
)
403 def _parse_ip_line(self
, country
, type, line
):
405 address
, prefix
, date
, status
, organization
= line
.split("|")
409 # Try parsing the line without organization
411 address
, prefix
, date
, status
= line
.split("|")
413 log
.warning("Unhandled line format: %s" % line
)
416 # Skip anything that isn't properly assigned
417 if not status
in ("assigned", "allocated"):
420 # Cast prefix into an integer
424 log
.warning("Invalid prefix: %s" % prefix
)
426 # Fix prefix length for IPv4
428 prefix
= 32 - int(math
.log(prefix
, 2))
430 # Try to parse the address
432 network
= ipaddress
.ip_network("%s/%s" % (address
, prefix
), strict
=False)
434 log
.warning("Invalid IP address: %s" % address
)
437 self
.db
.execute("INSERT INTO networks(network, country) \
438 VALUES(%s, %s) ON CONFLICT (network) DO \
439 UPDATE SET country = excluded.country",
440 "%s" % network
, country
,
443 def handle_update_announcements(self
, ns
):
444 server
= ns
.server
[0]
446 # Pre-compile regular expression for routes
447 #route = re.compile(b"^\*>?\s[\si]?([^\s]+)[.\s]*?(\d+)\si$", re.MULTILINE)
448 route
= re
.compile(b
"^\*[\s\>]i([^\s]+).+?(\d+)\si\r\n", re
.MULTILINE|re
.DOTALL
)
450 with telnetlib
.Telnet(server
) as t
:
453 # t.set_debuglevel(10)
455 # Wait for console greeting
456 greeting
= t
.read_until(b
"> ")
457 log
.debug(greeting
.decode())
460 t
.write(b
"terminal length 0\n")
462 # Wait for the prompt to return
465 # Fetch the routing tables
466 with self
.db
.transaction():
467 for protocol
in ("ipv6", "ipv4"):
468 log
.info("Requesting %s routing table" % protocol
)
470 # Request the full unicast routing table
471 t
.write(b
"show bgp %s unicast\n" % protocol
.encode())
473 # Read entire header which ends with "Path"
474 t
.read_until(b
"Path\r\n")
477 # Try reading a full entry
478 # Those might be broken across multiple lines but ends with i
479 line
= t
.read_until(b
"i\r\n", timeout
=5)
483 # Show line for debugging
484 #log.debug(repr(line))
486 # Try finding a route in here
487 m
= route
.match(line
)
489 network
, autnum
= m
.groups()
491 # Convert network to string
492 network
= network
.decode()
494 # Append /24 for IPv4 addresses
495 if not "/" in network
and not ":" in network
:
496 network
= "%s/24" % network
498 # Convert AS number to integer
501 log
.info("Found announcement for %s by %s" % (network
, autnum
))
503 self
.db
.execute("INSERT INTO announcements(network, autnum) \
504 VALUES(%s, %s) ON CONFLICT (network) DO \
505 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
509 log
.info("Finished reading the %s routing table" % protocol
)
511 # Purge anything we never want here
513 -- Delete default routes
514 DELETE FROM announcements WHERE network = '::/0' OR network = '0.0.0.0/0';
516 -- Delete anything that is not global unicast address space
517 DELETE FROM announcements WHERE family(network) = 6 AND NOT network <<= '2000::/3';
519 -- DELETE "current network" address space
520 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '0.0.0.0/8';
522 -- DELETE local loopback address space
523 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '127.0.0.0/8';
525 -- DELETE RFC 1918 address space
526 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '10.0.0.0/8';
527 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '172.16.0.0/12';
528 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.168.0.0/16';
530 -- DELETE test, benchmark and documentation address space
531 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.0.0/24';
532 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.2.0/24';
533 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.18.0.0/15';
534 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.51.100.0/24';
535 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '203.0.113.0/24';
537 -- DELETE CGNAT address space (RFC 6598)
538 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '100.64.0.0/10';
540 -- DELETE link local address space
541 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '169.254.0.0/16';
543 -- DELETE IPv6 to IPv4 (6to4) address space
544 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.88.99.0/24';
546 -- Delete networks that are too small to be in the global routing table
547 DELETE FROM announcements WHERE family(network) = 6 AND masklen(network) > 48;
548 DELETE FROM announcements WHERE family(network) = 4 AND masklen(network) > 24;
550 -- Delete any non-public or reserved ASNs
551 DELETE FROM announcements WHERE NOT (
552 (autnum >= 1 AND autnum <= 23455)
554 (autnum >= 23457 AND autnum <= 64495)
556 (autnum >= 131072 AND autnum <= 4199999999)
559 -- Delete everything that we have not seen for 14 days
560 DELETE FROM announcements WHERE last_seen_at <= CURRENT_TIMESTAMP - INTERVAL '14 days';
563 def handle_update_overrides(self
, ns
):
564 with self
.db
.transaction():
565 # Drop all data that we have
567 TRUNCATE TABLE autnum_overrides;
568 TRUNCATE TABLE network_overrides;
571 for file in ns
.files
:
572 log
.info("Reading %s..." % file)
574 with
open(file, "rb") as f
:
575 for type, block
in location
.importer
.read_blocks(f
):
577 network
= block
.get("net")
578 # Try to parse and normalise the network
580 network
= ipaddress
.ip_network(network
, strict
=False)
581 except ValueError as e
:
582 log
.warning("Invalid IP network: %s: %s" % (network
, e
))
586 INSERT INTO network_overrides(
590 is_satellite_provider,
592 ) VALUES (%s, %s, %s, %s)
593 ON CONFLICT (network) DO NOTHING""",
595 block
.get("country"),
596 block
.get("is-anonymous-proxy") == "yes",
597 block
.get("is-satellite-provider") == "yes",
598 block
.get("is-anycast") == "yes",
601 elif type == "autnum":
602 autnum
= block
.get("autnum")
604 # Check if AS number begins with "AS"
605 if not autnum
.startswith("AS"):
606 log
.warning("Invalid AS number: %s" % autnum
)
613 INSERT INTO autnum_overrides(
617 is_satellite_provider,
619 ) VALUES(%s, %s, %s, %s, %s)
620 ON CONFLICT DO NOTHING""",
621 autnum
, block
.get("name"),
622 block
.get("is-anonymous-proxy") == "yes",
623 block
.get("is-satellite-provider") == "yes",
624 block
.get("is-anycast") == "yes",
628 log
.warning("Unsupport type: %s" % type)
631 def split_line(line
):
632 key
, colon
, val
= line
.partition(":")
634 # Strip any excess space
641 # Run the command line interface