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 ###############################################################################
29 # Load our location module
31 import location
.database
32 import location
.importer
33 from location
.i18n
import _
36 log
= logging
.getLogger("location.importer")
41 parser
= argparse
.ArgumentParser(
42 description
=_("Location Importer Command Line Interface"),
44 subparsers
= parser
.add_subparsers()
46 # Global configuration flags
47 parser
.add_argument("--debug", action
="store_true",
48 help=_("Enable debug output"))
49 parser
.add_argument("--quiet", action
="store_true",
50 help=_("Enable quiet mode"))
53 parser
.add_argument("--version", action
="version",
54 version
="%(prog)s @VERSION@")
57 parser
.add_argument("--database-host", required
=True,
58 help=_("Database Hostname"), metavar
=_("HOST"))
59 parser
.add_argument("--database-name", required
=True,
60 help=_("Database Name"), metavar
=_("NAME"))
61 parser
.add_argument("--database-username", required
=True,
62 help=_("Database Username"), metavar
=_("USERNAME"))
63 parser
.add_argument("--database-password", required
=True,
64 help=_("Database Password"), metavar
=_("PASSWORD"))
67 write
= subparsers
.add_parser("write", help=_("Write database to file"))
68 write
.set_defaults(func
=self
.handle_write
)
69 write
.add_argument("file", nargs
=1, help=_("Database File"))
70 write
.add_argument("--signing-key", nargs
="?", type=open, help=_("Signing Key"))
71 write
.add_argument("--backup-signing-key", nargs
="?", type=open, help=_("Backup Signing Key"))
72 write
.add_argument("--vendor", nargs
="?", help=_("Sets the vendor"))
73 write
.add_argument("--description", nargs
="?", help=_("Sets a description"))
74 write
.add_argument("--license", nargs
="?", help=_("Sets the license"))
75 write
.add_argument("--version", type=int, help=_("Database Format Version"))
78 update_whois
= subparsers
.add_parser("update-whois", help=_("Update WHOIS Information"))
79 update_whois
.set_defaults(func
=self
.handle_update_whois
)
81 # Update announcements
82 update_announcements
= subparsers
.add_parser("update-announcements",
83 help=_("Update BGP Annoucements"))
84 update_announcements
.set_defaults(func
=self
.handle_update_announcements
)
85 update_announcements
.add_argument("server", nargs
=1,
86 help=_("Route Server to connect to"), metavar
=_("SERVER"))
89 update_overrides
= subparsers
.add_parser("update-overrides",
90 help=_("Update overrides"),
92 update_overrides
.add_argument(
93 "files", nargs
="+", help=_("Files to import"),
95 update_overrides
.set_defaults(func
=self
.handle_update_overrides
)
98 import_countries
= subparsers
.add_parser("import-countries",
99 help=_("Import countries"),
101 import_countries
.add_argument("file", nargs
=1, type=argparse
.FileType("r"),
102 help=_("File to import"))
103 import_countries
.set_defaults(func
=self
.handle_import_countries
)
105 args
= parser
.parse_args()
109 location
.logger
.set_level(logging
.DEBUG
)
111 location
.logger
.set_level(logging
.WARNING
)
113 # Print usage if no action was given
114 if not "func" in args
:
121 # Parse command line arguments
122 args
= self
.parse_cli()
124 # Initialise database
125 self
.db
= self
._setup
_database
(args
)
128 ret
= args
.func(args
)
130 # Return with exit code
134 # Otherwise just exit
137 def _setup_database(self
, ns
):
139 Initialise the database
141 # Connect to database
142 db
= location
.database
.Connection(
143 host
=ns
.database_host
, database
=ns
.database_name
,
144 user
=ns
.database_username
, password
=ns
.database_password
,
147 with db
.transaction():
150 CREATE TABLE IF NOT EXISTS announcements(network inet, autnum bigint,
151 first_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
152 last_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP);
153 CREATE UNIQUE INDEX IF NOT EXISTS announcements_networks ON announcements(network);
154 CREATE INDEX IF NOT EXISTS announcements_family ON announcements(family(network));
155 CREATE INDEX IF NOT EXISTS announcements_search ON announcements USING GIST(network inet_ops);
158 CREATE TABLE IF NOT EXISTS autnums(number bigint, name text NOT NULL);
159 CREATE UNIQUE INDEX IF NOT EXISTS autnums_number ON autnums(number);
162 CREATE TABLE IF NOT EXISTS countries(
163 country_code text NOT NULL, name text NOT NULL, continent_code text NOT NULL);
164 CREATE UNIQUE INDEX IF NOT EXISTS countries_country_code ON countries(country_code);
167 CREATE TABLE IF NOT EXISTS networks(network inet, country text);
168 CREATE UNIQUE INDEX IF NOT EXISTS networks_network ON networks(network);
169 CREATE INDEX IF NOT EXISTS networks_search ON networks USING GIST(network inet_ops);
172 CREATE TABLE IF NOT EXISTS autnum_overrides(
173 number bigint NOT NULL,
176 is_anonymous_proxy boolean,
177 is_satellite_provider boolean,
180 CREATE UNIQUE INDEX IF NOT EXISTS autnum_overrides_number
181 ON autnum_overrides(number);
183 CREATE TABLE IF NOT EXISTS network_overrides(
184 network inet NOT NULL,
186 is_anonymous_proxy boolean,
187 is_satellite_provider boolean,
190 CREATE UNIQUE INDEX IF NOT EXISTS network_overrides_network
191 ON network_overrides(network);
196 def handle_write(self
, ns
):
198 Compiles a database in libloc format out of what is in the database
201 writer
= location
.Writer(ns
.signing_key
, ns
.backup_signing_key
)
205 writer
.vendor
= ns
.vendor
208 writer
.description
= ns
.description
211 writer
.license
= ns
.license
213 # Add all Autonomous Systems
214 log
.info("Writing Autonomous Systems...")
216 # Select all ASes with a name
217 rows
= self
.db
.query("""
219 autnums.number AS number,
221 (SELECT overrides.name FROM autnum_overrides overrides
222 WHERE overrides.number = autnums.number),
226 WHERE name <> %s ORDER BY number
230 a
= writer
.add_as(row
.number
)
234 log
.info("Writing networks...")
236 # Select all known networks
237 rows
= self
.db
.query("""
238 -- Get a (sorted) list of all known networks
239 WITH known_networks AS (
240 SELECT network FROM announcements
242 SELECT network FROM networks
244 SELECT network FROM network_overrides
248 -- Return a list of those networks enriched with all
249 -- other information that we store in the database
251 DISTINCT ON (known_networks.network)
252 known_networks.network AS network,
253 announcements.autnum AS autnum,
258 SELECT country FROM network_overrides overrides
259 WHERE announcements.network <<= overrides.network
260 ORDER BY masklen(overrides.network) DESC
264 SELECT country FROM autnum_overrides overrides
265 WHERE announcements.autnum = overrides.number
273 SELECT is_anonymous_proxy FROM network_overrides overrides
274 WHERE announcements.network <<= overrides.network
275 ORDER BY masklen(overrides.network) DESC
279 SELECT is_anonymous_proxy FROM autnum_overrides overrides
280 WHERE announcements.autnum = overrides.number
283 ) AS is_anonymous_proxy,
286 SELECT is_satellite_provider FROM network_overrides overrides
287 WHERE announcements.network <<= overrides.network
288 ORDER BY masklen(overrides.network) DESC
292 SELECT is_satellite_provider FROM autnum_overrides overrides
293 WHERE announcements.autnum = overrides.number
296 ) AS is_satellite_provider,
299 SELECT is_anycast FROM network_overrides overrides
300 WHERE announcements.network <<= overrides.network
301 ORDER BY masklen(overrides.network) DESC
305 SELECT is_anycast FROM autnum_overrides overrides
306 WHERE announcements.autnum = overrides.number
311 -- Must be part of returned values for ORDER BY clause
312 masklen(announcements.network) AS sort_a,
313 masklen(networks.network) AS sort_b
315 LEFT JOIN announcements ON known_networks.network <<= announcements.network
316 LEFT JOIN networks ON known_networks.network <<= networks.network
317 ORDER BY known_networks.network, sort_a DESC, sort_b DESC
321 network
= writer
.add_network(row
.network
)
325 network
.country_code
= row
.country
329 network
.asn
= row
.autnum
332 if row
.is_anonymous_proxy
:
333 network
.set_flag(location
.NETWORK_FLAG_ANONYMOUS_PROXY
)
335 if row
.is_satellite_provider
:
336 network
.set_flag(location
.NETWORK_FLAG_SATELLITE_PROVIDER
)
339 network
.set_flag(location
.NETWORK_FLAG_ANYCAST
)
342 log
.info("Writing countries...")
343 rows
= self
.db
.query("SELECT * FROM countries ORDER BY country_code")
346 c
= writer
.add_country(row
.country_code
)
347 c
.continent_code
= row
.continent_code
350 # Write everything to file
351 log
.info("Writing database to file...")
355 def handle_update_whois(self
, ns
):
356 downloader
= location
.importer
.Downloader()
358 # Download all sources
359 with self
.db
.transaction():
360 # Create some temporary tables to store parsed data
362 CREATE TEMPORARY TABLE _autnums(number integer, organization text)
364 CREATE UNIQUE INDEX _autnums_number ON _autnums(number);
366 CREATE TEMPORARY TABLE _organizations(handle text, name text NOT NULL)
368 CREATE UNIQUE INDEX _organizations_handle ON _organizations(handle);
371 for source
in location
.importer
.WHOIS_SOURCES
:
372 with downloader
.request(source
, return_blocks
=True) as f
:
374 self
._parse
_block
(block
)
377 INSERT INTO autnums(number, name)
378 SELECT _autnums.number, _organizations.name FROM _autnums
379 JOIN _organizations ON _autnums.organization = _organizations.handle
380 ON CONFLICT (number) DO UPDATE SET name = excluded.name;
383 # Download all extended sources
384 for source
in location
.importer
.EXTENDED_SOURCES
:
385 with self
.db
.transaction():
387 with downloader
.request(source
) as f
:
389 self
._parse
_line
(line
)
391 def _parse_block(self
, block
):
392 # Get first line to find out what type of block this is
396 if line
.startswith("aut-num:"):
397 return self
._parse
_autnum
_block
(block
)
400 elif line
.startswith("organisation:"):
401 return self
._parse
_org
_block
(block
)
403 def _parse_autnum_block(self
, block
):
407 key
, val
= split_line(line
)
410 m
= re
.match(r
"^(AS|as)(\d+)", val
)
412 autnum
["asn"] = m
.group(2)
421 # Insert into database
422 self
.db
.execute("INSERT INTO _autnums(number, organization) \
423 VALUES(%s, %s) ON CONFLICT (number) DO UPDATE SET \
424 organization = excluded.organization",
425 autnum
.get("asn"), autnum
.get("org"),
428 def _parse_org_block(self
, block
):
432 key
, val
= split_line(line
)
434 if key
in ("organisation", "org-name"):
441 self
.db
.execute("INSERT INTO _organizations(handle, name) \
442 VALUES(%s, %s) ON CONFLICT (handle) DO \
443 UPDATE SET name = excluded.name",
444 org
.get("organisation"), org
.get("org-name"),
447 def _parse_line(self
, line
):
449 if line
.startswith("2"):
453 if line
.startswith("#"):
457 registry
, country_code
, type, line
= line
.split("|", 3)
459 log
.warning("Could not parse line: %s" % line
)
462 # Skip any lines that are for stats only
463 if country_code
== "*":
466 if type in ("ipv6", "ipv4"):
467 return self
._parse
_ip
_line
(country_code
, type, line
)
469 def _parse_ip_line(self
, country
, type, line
):
471 address
, prefix
, date
, status
, organization
= line
.split("|")
475 # Try parsing the line without organization
477 address
, prefix
, date
, status
= line
.split("|")
479 log
.warning("Unhandled line format: %s" % line
)
482 # Skip anything that isn't properly assigned
483 if not status
in ("assigned", "allocated"):
486 # Cast prefix into an integer
490 log
.warning("Invalid prefix: %s" % prefix
)
493 # Fix prefix length for IPv4
495 prefix
= 32 - int(math
.log(prefix
, 2))
497 # Try to parse the address
499 network
= ipaddress
.ip_network("%s/%s" % (address
, prefix
), strict
=False)
501 log
.warning("Invalid IP address: %s" % address
)
504 self
.db
.execute("INSERT INTO networks(network, country) \
505 VALUES(%s, %s) ON CONFLICT (network) DO \
506 UPDATE SET country = excluded.country",
507 "%s" % network
, country
,
510 def handle_update_announcements(self
, ns
):
511 server
= ns
.server
[0]
513 with self
.db
.transaction():
514 if server
.startswith("/"):
515 self
._handle
_update
_announcements
_from
_bird
(server
)
517 self
._handle
_update
_announcements
_from
_telnet
(server
)
519 # Purge anything we never want here
521 -- Delete default routes
522 DELETE FROM announcements WHERE network = '::/0' OR network = '0.0.0.0/0';
524 -- Delete anything that is not global unicast address space
525 DELETE FROM announcements WHERE family(network) = 6 AND NOT network <<= '2000::/3';
527 -- DELETE "current network" address space
528 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '0.0.0.0/8';
530 -- DELETE local loopback address space
531 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '127.0.0.0/8';
533 -- DELETE RFC 1918 address space
534 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '10.0.0.0/8';
535 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '172.16.0.0/12';
536 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.168.0.0/16';
538 -- DELETE test, benchmark and documentation address space
539 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.0.0/24';
540 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.2.0/24';
541 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.18.0.0/15';
542 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.51.100.0/24';
543 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '203.0.113.0/24';
545 -- DELETE CGNAT address space (RFC 6598)
546 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '100.64.0.0/10';
548 -- DELETE link local address space
549 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '169.254.0.0/16';
551 -- DELETE IPv6 to IPv4 (6to4) address space
552 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.88.99.0/24';
554 -- DELETE multicast and reserved address space
555 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '224.0.0.0/4';
556 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '240.0.0.0/4';
558 -- Delete networks that are too small to be in the global routing table
559 DELETE FROM announcements WHERE family(network) = 6 AND masklen(network) > 48;
560 DELETE FROM announcements WHERE family(network) = 4 AND masklen(network) > 24;
562 -- Delete any non-public or reserved ASNs
563 DELETE FROM announcements WHERE NOT (
564 (autnum >= 1 AND autnum <= 23455)
566 (autnum >= 23457 AND autnum <= 64495)
568 (autnum >= 131072 AND autnum <= 4199999999)
571 -- Delete everything that we have not seen for 14 days
572 DELETE FROM announcements WHERE last_seen_at <= CURRENT_TIMESTAMP - INTERVAL '14 days';
575 def _handle_update_announcements_from_bird(self
, server
):
576 # Pre-compile the regular expression for faster searching
577 route
= re
.compile(b
"^\s(.+?)\s+.+?\[AS(.*?).\]$")
579 log
.info("Requesting routing table from Bird (%s)" % server
)
581 # Send command to list all routes
582 for line
in self
._bird
_cmd
(server
, "show route"):
583 m
= route
.match(line
)
585 log
.debug("Could not parse line: %s" % line
.decode())
588 # Fetch the extracted network and ASN
589 network
, autnum
= m
.groups()
591 # Insert it into the database
592 self
.db
.execute("INSERT INTO announcements(network, autnum) \
593 VALUES(%s, %s) ON CONFLICT (network) DO \
594 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
595 network
.decode(), autnum
.decode(),
598 def _handle_update_announcements_from_telnet(self
, server
):
599 # Pre-compile regular expression for routes
600 route
= re
.compile(b
"^\*[\s\>]i([^\s]+).+?(\d+)\si\r\n", re
.MULTILINE|re
.DOTALL
)
602 with telnetlib
.Telnet(server
) as t
:
605 # t.set_debuglevel(10)
607 # Wait for console greeting
608 greeting
= t
.read_until(b
"> ", timeout
=30)
610 log
.error("Could not get a console prompt")
614 t
.write(b
"terminal length 0\n")
616 # Wait for the prompt to return
619 # Fetch the routing tables
620 for protocol
in ("ipv6", "ipv4"):
621 log
.info("Requesting %s routing table" % protocol
)
623 # Request the full unicast routing table
624 t
.write(b
"show bgp %s unicast\n" % protocol
.encode())
626 # Read entire header which ends with "Path"
627 t
.read_until(b
"Path\r\n")
630 # Try reading a full entry
631 # Those might be broken across multiple lines but ends with i
632 line
= t
.read_until(b
"i\r\n", timeout
=5)
636 # Show line for debugging
637 #log.debug(repr(line))
639 # Try finding a route in here
640 m
= route
.match(line
)
642 network
, autnum
= m
.groups()
644 # Convert network to string
645 network
= network
.decode()
647 # Append /24 for IPv4 addresses
648 if not "/" in network
and not ":" in network
:
649 network
= "%s/24" % network
651 # Convert AS number to integer
654 log
.info("Found announcement for %s by %s" % (network
, autnum
))
656 self
.db
.execute("INSERT INTO announcements(network, autnum) \
657 VALUES(%s, %s) ON CONFLICT (network) DO \
658 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
662 log
.info("Finished reading the %s routing table" % protocol
)
664 def _bird_cmd(self
, socket_path
, command
):
665 # Connect to the socket
666 s
= socket
.socket(socket
.AF_UNIX
, socket
.SOCK_STREAM
)
667 s
.connect(socket_path
)
669 # Allocate some buffer
673 s
.send(b
"%s\n" % command
.encode())
677 buffer += s
.recv(4096)
680 # Search for the next newline
681 pos
= buffer.find(b
"\n")
683 # If we cannot find one, we go back and read more data
687 # Cut after the newline character
690 # Split the line we want and keep the rest in buffer
691 line
, buffer = buffer[:pos
], buffer[pos
:]
693 # Look for the end-of-output indicator
694 if line
== b
"0000 \n":
697 # Otherwise return the line
700 def handle_update_overrides(self
, ns
):
701 with self
.db
.transaction():
702 # Drop all data that we have
704 TRUNCATE TABLE autnum_overrides;
705 TRUNCATE TABLE network_overrides;
708 for file in ns
.files
:
709 log
.info("Reading %s..." % file)
711 with
open(file, "rb") as f
:
712 for type, block
in location
.importer
.read_blocks(f
):
714 network
= block
.get("net")
715 # Try to parse and normalise the network
717 network
= ipaddress
.ip_network(network
, strict
=False)
718 except ValueError as e
:
719 log
.warning("Invalid IP network: %s: %s" % (network
, e
))
722 # Prevent that we overwrite all networks
723 if network
.prefixlen
== 0:
724 log
.warning("Skipping %s: You cannot overwrite default" % network
)
728 INSERT INTO network_overrides(
732 is_satellite_provider,
734 ) VALUES (%s, %s, %s, %s, %s)
735 ON CONFLICT (network) DO NOTHING""",
737 block
.get("country"),
738 self
._parse
_bool
(block
, "is-anonymous-proxy"),
739 self
._parse
_bool
(block
, "is-satellite-provider"),
740 self
._parse
_bool
(block
, "is-anycast"),
743 elif type == "aut-num":
744 autnum
= block
.get("aut-num")
746 # Check if AS number begins with "AS"
747 if not autnum
.startswith("AS"):
748 log
.warning("Invalid AS number: %s" % autnum
)
755 INSERT INTO autnum_overrides(
760 is_satellite_provider,
762 ) VALUES(%s, %s, %s, %s, %s, %s)
763 ON CONFLICT DO NOTHING""",
766 block
.get("country"),
767 self
._parse
_bool
(block
, "is-anonymous-proxy"),
768 self
._parse
_bool
(block
, "is-satellite-provider"),
769 self
._parse
_bool
(block
, "is-anycast"),
773 log
.warning("Unsupport type: %s" % type)
776 def _parse_bool(block
, key
):
779 # There is no point to proceed when we got None
783 # Convert to lowercase
787 if val
in ("yes", "1"):
791 if val
in ("no", "0"):
797 def handle_import_countries(self
, ns
):
798 with self
.db
.transaction():
799 # Drop all data that we have
800 self
.db
.execute("TRUNCATE TABLE countries")
806 # Ignore any comments
807 if line
.startswith("#"):
811 country_code
, continent_code
, name
= line
.split(maxsplit
=2)
813 log
.warning("Could not parse line: %s" % line
)
816 self
.db
.execute("INSERT INTO countries(country_code, name, continent_code) \
817 VALUES(%s, %s, %s) ON CONFLICT DO NOTHING", country_code
, name
, continent_code
)
820 def split_line(line
):
821 key
, colon
, val
= line
.partition(":")
823 # Strip any excess space
830 # Run the command line interface