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);
192 CREATE INDEX IF NOT EXISTS network_overrides_search
193 ON network_overrides USING GIST(network inet_ops);
198 def handle_write(self
, ns
):
200 Compiles a database in libloc format out of what is in the database
203 writer
= location
.Writer(ns
.signing_key
, ns
.backup_signing_key
)
207 writer
.vendor
= ns
.vendor
210 writer
.description
= ns
.description
213 writer
.license
= ns
.license
215 # Add all Autonomous Systems
216 log
.info("Writing Autonomous Systems...")
218 # Select all ASes with a name
219 rows
= self
.db
.query("""
221 autnums.number AS number,
223 (SELECT overrides.name FROM autnum_overrides overrides
224 WHERE overrides.number = autnums.number),
228 WHERE name <> %s ORDER BY number
232 a
= writer
.add_as(row
.number
)
236 log
.info("Writing networks...")
238 # Select all known networks
239 rows
= self
.db
.query("""
240 -- Return a list of those networks enriched with all
241 -- other information that we store in the database
243 DISTINCT ON (network)
250 SELECT country FROM network_overrides overrides
251 WHERE networks.network <<= overrides.network
252 ORDER BY masklen(overrides.network) DESC
256 SELECT country FROM autnum_overrides overrides
257 WHERE networks.autnum = overrides.number
265 SELECT is_anonymous_proxy FROM network_overrides overrides
266 WHERE networks.network <<= overrides.network
267 ORDER BY masklen(overrides.network) DESC
271 SELECT is_anonymous_proxy FROM autnum_overrides overrides
272 WHERE networks.autnum = overrides.number
275 ) AS is_anonymous_proxy,
278 SELECT is_satellite_provider FROM network_overrides overrides
279 WHERE networks.network <<= overrides.network
280 ORDER BY masklen(overrides.network) DESC
284 SELECT is_satellite_provider FROM autnum_overrides overrides
285 WHERE networks.autnum = overrides.number
288 ) AS is_satellite_provider,
291 SELECT is_anycast FROM network_overrides overrides
292 WHERE networks.network <<= overrides.network
293 ORDER BY masklen(overrides.network) DESC
297 SELECT is_anycast FROM autnum_overrides overrides
298 WHERE networks.autnum = overrides.number
304 known_networks.network AS network,
305 announcements.autnum AS autnum,
306 networks.country AS country,
308 -- Must be part of returned values for ORDER BY clause
309 masklen(announcements.network) AS sort_a,
310 masklen(networks.network) AS sort_b
312 SELECT network FROM announcements
314 SELECT network FROM networks
316 SELECT network FROM network_overrides
319 announcements ON known_networks.network <<= announcements.network
321 networks ON known_networks.network <<= networks.network
323 known_networks.network,
330 network
= writer
.add_network(row
.network
)
334 network
.country_code
= row
.country
338 network
.asn
= row
.autnum
341 if row
.is_anonymous_proxy
:
342 network
.set_flag(location
.NETWORK_FLAG_ANONYMOUS_PROXY
)
344 if row
.is_satellite_provider
:
345 network
.set_flag(location
.NETWORK_FLAG_SATELLITE_PROVIDER
)
348 network
.set_flag(location
.NETWORK_FLAG_ANYCAST
)
351 log
.info("Writing countries...")
352 rows
= self
.db
.query("SELECT * FROM countries ORDER BY country_code")
355 c
= writer
.add_country(row
.country_code
)
356 c
.continent_code
= row
.continent_code
359 # Write everything to file
360 log
.info("Writing database to file...")
364 def handle_update_whois(self
, ns
):
365 downloader
= location
.importer
.Downloader()
367 # Download all sources
368 with self
.db
.transaction():
369 # Create some temporary tables to store parsed data
371 CREATE TEMPORARY TABLE _autnums(number integer, organization text)
373 CREATE UNIQUE INDEX _autnums_number ON _autnums(number);
375 CREATE TEMPORARY TABLE _organizations(handle text, name text NOT NULL)
377 CREATE UNIQUE INDEX _organizations_handle ON _organizations(handle);
380 for source
in location
.importer
.WHOIS_SOURCES
:
381 with downloader
.request(source
, return_blocks
=True) as f
:
383 self
._parse
_block
(block
)
386 INSERT INTO autnums(number, name)
387 SELECT _autnums.number, _organizations.name FROM _autnums
388 JOIN _organizations ON _autnums.organization = _organizations.handle
389 ON CONFLICT (number) DO UPDATE SET name = excluded.name;
392 # Download all extended sources
393 for source
in location
.importer
.EXTENDED_SOURCES
:
394 with self
.db
.transaction():
396 with downloader
.request(source
) as f
:
398 self
._parse
_line
(line
)
400 def _parse_block(self
, block
):
401 # Get first line to find out what type of block this is
405 if line
.startswith("aut-num:"):
406 return self
._parse
_autnum
_block
(block
)
409 if line
.startswith("inet6num:") or line
.startswith("inetnum:"):
410 return self
._parse
_inetnum
_block
(block
)
413 elif line
.startswith("organisation:"):
414 return self
._parse
_org
_block
(block
)
416 def _parse_autnum_block(self
, block
):
420 key
, val
= split_line(line
)
423 m
= re
.match(r
"^(AS|as)(\d+)", val
)
425 autnum
["asn"] = m
.group(2)
434 # Insert into database
435 self
.db
.execute("INSERT INTO _autnums(number, organization) \
436 VALUES(%s, %s) ON CONFLICT (number) DO UPDATE SET \
437 organization = excluded.organization",
438 autnum
.get("asn"), autnum
.get("org"),
441 def _parse_inetnum_block(self
, block
):
442 logging
.debug("Parsing inetnum block:")
449 key
, val
= split_line(line
)
452 start_address
, delim
, end_address
= val
.partition("-")
454 # Strip any excess space
455 start_address
, end_address
= start_address
.rstrip(), end_address
.strip()
457 # Convert to IP address
459 start_address
= ipaddress
.ip_address(start_address
)
460 end_address
= ipaddress
.ip_address(end_address
)
462 logging
.warning("Could not parse line: %s" % line
)
465 # Set prefix to default
468 # Count number of addresses in this subnet
469 num_addresses
= int(end_address
) - int(start_address
)
471 prefix
-= math
.log(num_addresses
, 2)
473 inetnum
["inetnum"] = "%s/%.0f" % (start_address
, prefix
)
475 elif key
== "inet6num":
478 elif key
== "country":
479 if val
== "UNITED STATES":
482 inetnum
[key
] = val
.upper()
488 network
= ipaddress
.ip_network(inetnum
.get("inet6num") or inetnum
.get("inetnum"), strict
=False)
490 # Bail out in case we have processed a non-public IP network
491 if network
.is_private
:
492 logging
.warning("Skipping non-globally routable network: %s" % network
)
495 self
.db
.execute("INSERT INTO networks(network, country) \
496 VALUES(%s, %s) ON CONFLICT (network) DO UPDATE SET country = excluded.country",
497 "%s" % network
, inetnum
.get("country"),
500 def _parse_org_block(self
, block
):
504 key
, val
= split_line(line
)
506 if key
in ("organisation", "org-name"):
513 self
.db
.execute("INSERT INTO _organizations(handle, name) \
514 VALUES(%s, %s) ON CONFLICT (handle) DO \
515 UPDATE SET name = excluded.name",
516 org
.get("organisation"), org
.get("org-name"),
519 def _parse_line(self
, line
):
521 if line
.startswith("2"):
525 if line
.startswith("#"):
529 registry
, country_code
, type, line
= line
.split("|", 3)
531 log
.warning("Could not parse line: %s" % line
)
534 # Skip any lines that are for stats only
535 if country_code
== "*":
538 if type in ("ipv6", "ipv4"):
539 return self
._parse
_ip
_line
(country_code
, type, line
)
541 def _parse_ip_line(self
, country
, type, line
):
543 address
, prefix
, date
, status
, organization
= line
.split("|")
547 # Try parsing the line without organization
549 address
, prefix
, date
, status
= line
.split("|")
551 log
.warning("Unhandled line format: %s" % line
)
554 # Skip anything that isn't properly assigned
555 if not status
in ("assigned", "allocated"):
558 # Cast prefix into an integer
562 log
.warning("Invalid prefix: %s" % prefix
)
565 # Fix prefix length for IPv4
567 prefix
= 32 - int(math
.log(prefix
, 2))
569 # Try to parse the address
571 network
= ipaddress
.ip_network("%s/%s" % (address
, prefix
), strict
=False)
573 log
.warning("Invalid IP address: %s" % address
)
576 self
.db
.execute("INSERT INTO networks(network, country) \
577 VALUES(%s, %s) ON CONFLICT (network) DO \
578 UPDATE SET country = excluded.country",
579 "%s" % network
, country
,
582 def handle_update_announcements(self
, ns
):
583 server
= ns
.server
[0]
585 with self
.db
.transaction():
586 if server
.startswith("/"):
587 self
._handle
_update
_announcements
_from
_bird
(server
)
589 self
._handle
_update
_announcements
_from
_telnet
(server
)
591 # Purge anything we never want here
593 -- Delete default routes
594 DELETE FROM announcements WHERE network = '::/0' OR network = '0.0.0.0/0';
596 -- Delete anything that is not global unicast address space
597 DELETE FROM announcements WHERE family(network) = 6 AND NOT network <<= '2000::/3';
599 -- DELETE "current network" address space
600 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '0.0.0.0/8';
602 -- DELETE local loopback address space
603 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '127.0.0.0/8';
605 -- DELETE RFC 1918 address space
606 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '10.0.0.0/8';
607 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '172.16.0.0/12';
608 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.168.0.0/16';
610 -- DELETE test, benchmark and documentation address space
611 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.0.0/24';
612 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.2.0/24';
613 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.18.0.0/15';
614 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.51.100.0/24';
615 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '203.0.113.0/24';
617 -- DELETE CGNAT address space (RFC 6598)
618 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '100.64.0.0/10';
620 -- DELETE link local address space
621 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '169.254.0.0/16';
623 -- DELETE IPv6 to IPv4 (6to4) address space
624 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.88.99.0/24';
626 -- DELETE multicast and reserved address space
627 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '224.0.0.0/4';
628 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '240.0.0.0/4';
630 -- Delete networks that are too small to be in the global routing table
631 DELETE FROM announcements WHERE family(network) = 6 AND masklen(network) > 48;
632 DELETE FROM announcements WHERE family(network) = 4 AND masklen(network) > 24;
634 -- Delete any non-public or reserved ASNs
635 DELETE FROM announcements WHERE NOT (
636 (autnum >= 1 AND autnum <= 23455)
638 (autnum >= 23457 AND autnum <= 64495)
640 (autnum >= 131072 AND autnum <= 4199999999)
643 -- Delete everything that we have not seen for 14 days
644 DELETE FROM announcements WHERE last_seen_at <= CURRENT_TIMESTAMP - INTERVAL '14 days';
647 def _handle_update_announcements_from_bird(self
, server
):
648 # Pre-compile the regular expression for faster searching
649 route
= re
.compile(b
"^\s(.+?)\s+.+?\[AS(.*?).\]$")
651 log
.info("Requesting routing table from Bird (%s)" % server
)
653 # Send command to list all routes
654 for line
in self
._bird
_cmd
(server
, "show route"):
655 m
= route
.match(line
)
657 log
.debug("Could not parse line: %s" % line
.decode())
660 # Fetch the extracted network and ASN
661 network
, autnum
= m
.groups()
663 # Insert it into the database
664 self
.db
.execute("INSERT INTO announcements(network, autnum) \
665 VALUES(%s, %s) ON CONFLICT (network) DO \
666 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
667 network
.decode(), autnum
.decode(),
670 def _handle_update_announcements_from_telnet(self
, server
):
671 # Pre-compile regular expression for routes
672 route
= re
.compile(b
"^\*[\s\>]i([^\s]+).+?(\d+)\si\r\n", re
.MULTILINE|re
.DOTALL
)
674 with telnetlib
.Telnet(server
) as t
:
677 # t.set_debuglevel(10)
679 # Wait for console greeting
680 greeting
= t
.read_until(b
"> ", timeout
=30)
682 log
.error("Could not get a console prompt")
686 t
.write(b
"terminal length 0\n")
688 # Wait for the prompt to return
691 # Fetch the routing tables
692 for protocol
in ("ipv6", "ipv4"):
693 log
.info("Requesting %s routing table" % protocol
)
695 # Request the full unicast routing table
696 t
.write(b
"show bgp %s unicast\n" % protocol
.encode())
698 # Read entire header which ends with "Path"
699 t
.read_until(b
"Path\r\n")
702 # Try reading a full entry
703 # Those might be broken across multiple lines but ends with i
704 line
= t
.read_until(b
"i\r\n", timeout
=5)
708 # Show line for debugging
709 #log.debug(repr(line))
711 # Try finding a route in here
712 m
= route
.match(line
)
714 network
, autnum
= m
.groups()
716 # Convert network to string
717 network
= network
.decode()
719 # Append /24 for IPv4 addresses
720 if not "/" in network
and not ":" in network
:
721 network
= "%s/24" % network
723 # Convert AS number to integer
726 log
.info("Found announcement for %s by %s" % (network
, autnum
))
728 self
.db
.execute("INSERT INTO announcements(network, autnum) \
729 VALUES(%s, %s) ON CONFLICT (network) DO \
730 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
734 log
.info("Finished reading the %s routing table" % protocol
)
736 def _bird_cmd(self
, socket_path
, command
):
737 # Connect to the socket
738 s
= socket
.socket(socket
.AF_UNIX
, socket
.SOCK_STREAM
)
739 s
.connect(socket_path
)
741 # Allocate some buffer
745 s
.send(b
"%s\n" % command
.encode())
749 buffer += s
.recv(4096)
752 # Search for the next newline
753 pos
= buffer.find(b
"\n")
755 # If we cannot find one, we go back and read more data
759 # Cut after the newline character
762 # Split the line we want and keep the rest in buffer
763 line
, buffer = buffer[:pos
], buffer[pos
:]
765 # Look for the end-of-output indicator
766 if line
== b
"0000 \n":
769 # Otherwise return the line
772 def handle_update_overrides(self
, ns
):
773 with self
.db
.transaction():
774 # Drop all data that we have
776 TRUNCATE TABLE autnum_overrides;
777 TRUNCATE TABLE network_overrides;
780 for file in ns
.files
:
781 log
.info("Reading %s..." % file)
783 with
open(file, "rb") as f
:
784 for type, block
in location
.importer
.read_blocks(f
):
786 network
= block
.get("net")
787 # Try to parse and normalise the network
789 network
= ipaddress
.ip_network(network
, strict
=False)
790 except ValueError as e
:
791 log
.warning("Invalid IP network: %s: %s" % (network
, e
))
794 # Prevent that we overwrite all networks
795 if network
.prefixlen
== 0:
796 log
.warning("Skipping %s: You cannot overwrite default" % network
)
800 INSERT INTO network_overrides(
804 is_satellite_provider,
806 ) VALUES (%s, %s, %s, %s, %s)
807 ON CONFLICT (network) DO NOTHING""",
809 block
.get("country"),
810 self
._parse
_bool
(block
, "is-anonymous-proxy"),
811 self
._parse
_bool
(block
, "is-satellite-provider"),
812 self
._parse
_bool
(block
, "is-anycast"),
815 elif type == "aut-num":
816 autnum
= block
.get("aut-num")
818 # Check if AS number begins with "AS"
819 if not autnum
.startswith("AS"):
820 log
.warning("Invalid AS number: %s" % autnum
)
827 INSERT INTO autnum_overrides(
832 is_satellite_provider,
834 ) VALUES(%s, %s, %s, %s, %s, %s)
835 ON CONFLICT DO NOTHING""",
838 block
.get("country"),
839 self
._parse
_bool
(block
, "is-anonymous-proxy"),
840 self
._parse
_bool
(block
, "is-satellite-provider"),
841 self
._parse
_bool
(block
, "is-anycast"),
845 log
.warning("Unsupport type: %s" % type)
848 def _parse_bool(block
, key
):
851 # There is no point to proceed when we got None
855 # Convert to lowercase
859 if val
in ("yes", "1"):
863 if val
in ("no", "0"):
869 def handle_import_countries(self
, ns
):
870 with self
.db
.transaction():
871 # Drop all data that we have
872 self
.db
.execute("TRUNCATE TABLE countries")
878 # Ignore any comments
879 if line
.startswith("#"):
883 country_code
, continent_code
, name
= line
.split(maxsplit
=2)
885 log
.warning("Could not parse line: %s" % line
)
888 self
.db
.execute("INSERT INTO countries(country_code, name, continent_code) \
889 VALUES(%s, %s, %s) ON CONFLICT DO NOTHING", country_code
, name
, continent_code
)
892 def split_line(line
):
893 key
, colon
, val
= line
.partition(":")
895 # Strip any excess space
902 # Run the command line interface