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"))
48 parser
.add_argument("--quiet", action
="store_true",
49 help=_("Enable quiet mode"))
52 parser
.add_argument("--version", action
="version",
53 version
="%(prog)s @VERSION@")
56 parser
.add_argument("--database-host", required
=True,
57 help=_("Database Hostname"), metavar
=_("HOST"))
58 parser
.add_argument("--database-name", required
=True,
59 help=_("Database Name"), metavar
=_("NAME"))
60 parser
.add_argument("--database-username", required
=True,
61 help=_("Database Username"), metavar
=_("USERNAME"))
62 parser
.add_argument("--database-password", required
=True,
63 help=_("Database Password"), metavar
=_("PASSWORD"))
66 write
= subparsers
.add_parser("write", help=_("Write database to file"))
67 write
.set_defaults(func
=self
.handle_write
)
68 write
.add_argument("file", nargs
=1, help=_("Database File"))
69 write
.add_argument("--signing-key", nargs
="?", type=open, help=_("Signing Key"))
70 write
.add_argument("--vendor", nargs
="?", help=_("Sets the vendor"))
71 write
.add_argument("--description", nargs
="?", help=_("Sets a description"))
72 write
.add_argument("--license", nargs
="?", help=_("Sets the license"))
75 update_whois
= subparsers
.add_parser("update-whois", help=_("Update WHOIS Information"))
76 update_whois
.set_defaults(func
=self
.handle_update_whois
)
78 # Update announcements
79 update_announcements
= subparsers
.add_parser("update-announcements",
80 help=_("Update BGP Annoucements"))
81 update_announcements
.set_defaults(func
=self
.handle_update_announcements
)
82 update_announcements
.add_argument("server", nargs
=1,
83 help=_("Route Server to connect to"), metavar
=_("SERVER"))
86 update_overrides
= subparsers
.add_parser("update-overrides",
87 help=_("Update overrides"),
89 update_overrides
.add_argument(
90 "files", nargs
="+", help=_("Files to import"),
92 update_overrides
.set_defaults(func
=self
.handle_update_overrides
)
94 args
= parser
.parse_args()
98 location
.logger
.set_level(logging
.DEBUG
)
100 location
.logger
.set_level(logging
.WARNING
)
102 # Print usage if no action was given
103 if not "func" in args
:
110 # Parse command line arguments
111 args
= self
.parse_cli()
113 # Initialise database
114 self
.db
= self
._setup
_database
(args
)
117 ret
= args
.func(args
)
119 # Return with exit code
123 # Otherwise just exit
126 def _setup_database(self
, ns
):
128 Initialise the database
130 # Connect to database
131 db
= location
.database
.Connection(
132 host
=ns
.database_host
, database
=ns
.database_name
,
133 user
=ns
.database_username
, password
=ns
.database_password
,
136 with db
.transaction():
139 CREATE TABLE IF NOT EXISTS announcements(network inet, autnum bigint,
140 first_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP,
141 last_seen_at timestamp without time zone DEFAULT CURRENT_TIMESTAMP);
142 CREATE UNIQUE INDEX IF NOT EXISTS announcements_networks ON announcements(network);
143 CREATE INDEX IF NOT EXISTS announcements_family ON announcements(family(network));
146 CREATE TABLE IF NOT EXISTS autnums(number bigint, name text NOT NULL);
147 CREATE UNIQUE INDEX IF NOT EXISTS autnums_number ON autnums(number);
150 CREATE TABLE IF NOT EXISTS networks(network inet, country text);
151 CREATE UNIQUE INDEX IF NOT EXISTS networks_network ON networks(network);
152 CREATE INDEX IF NOT EXISTS networks_search ON networks USING GIST(network inet_ops);
155 CREATE TABLE IF NOT EXISTS autnum_overrides(
156 number bigint NOT NULL,
158 is_anonymous_proxy boolean DEFAULT FALSE,
159 is_satellite_provider boolean DEFAULT FALSE,
160 is_anycast boolean DEFAULT FALSE
162 CREATE UNIQUE INDEX IF NOT EXISTS autnum_overrides_number
163 ON autnum_overrides(number);
165 CREATE TABLE IF NOT EXISTS network_overrides(
166 network inet NOT NULL,
168 is_anonymous_proxy boolean DEFAULT FALSE,
169 is_satellite_provider boolean DEFAULT FALSE,
170 is_anycast boolean DEFAULT FALSE
172 CREATE UNIQUE INDEX IF NOT EXISTS network_overrides_network
173 ON network_overrides(network);
178 def handle_write(self
, ns
):
180 Compiles a database in libloc format out of what is in the database
183 writer
= location
.Writer(ns
.signing_key
)
187 writer
.vendor
= ns
.vendor
190 writer
.description
= ns
.description
193 writer
.license
= ns
.license
195 # Add all Autonomous Systems
196 log
.info("Writing Autonomous Systems...")
198 # Select all ASes with a name
199 rows
= self
.db
.query("""
201 autnums.number AS number,
203 (SELECT overrides.name FROM autnum_overrides overrides
204 WHERE overrides.number = autnums.number),
208 WHERE name <> %s ORDER BY number
212 a
= writer
.add_as(row
.number
)
216 log
.info("Writing networks...")
218 # Select all known networks
219 rows
= self
.db
.query("""
221 DISTINCT ON (announcements.network)
222 announcements.network AS network,
223 announcements.autnum AS autnum,
224 networks.country AS country,
226 -- Must be part of returned values for ORDER BY clause
227 masklen(networks.network) AS sort,
232 SELECT is_anonymous_proxy FROM network_overrides overrides
233 WHERE announcements.network <<= overrides.network
234 ORDER BY masklen(overrides.network) DESC
238 SELECT is_anonymous_proxy FROM autnum_overrides overrides
239 WHERE announcements.autnum = overrides.number
241 ) AS is_anonymous_proxy,
244 SELECT is_satellite_provider FROM network_overrides overrides
245 WHERE announcements.network <<= overrides.network
246 ORDER BY masklen(overrides.network) DESC
250 SELECT is_satellite_provider FROM autnum_overrides overrides
251 WHERE announcements.autnum = overrides.number
253 ) AS is_satellite_provider,
256 SELECT is_anycast FROM network_overrides overrides
257 WHERE announcements.network <<= overrides.network
258 ORDER BY masklen(overrides.network) DESC
262 SELECT is_anycast FROM autnum_overrides overrides
263 WHERE announcements.autnum = overrides.number
267 LEFT JOIN networks ON announcements.network <<= networks.network
268 ORDER BY announcements.network, sort DESC
272 network
= writer
.add_network(row
.network
)
275 network
.asn
, network
.country_code
= row
.autnum
, row
.country
278 if row
.is_anonymous_proxy
:
279 network
.set_flag(location
.NETWORK_FLAG_ANONYMOUS_PROXY
)
281 if row
.is_satellite_provider
:
282 network
.set_flag(location
.NETWORK_FLAG_SATELLITE_PROVIDER
)
285 network
.set_flag(location
.NETWORK_FLAG_ANYCAST
)
287 # Write everything to file
288 log
.info("Writing database to file...")
292 def handle_update_whois(self
, ns
):
293 downloader
= location
.importer
.Downloader()
295 # Download all sources
296 with self
.db
.transaction():
297 # Create some temporary tables to store parsed data
299 CREATE TEMPORARY TABLE _autnums(number integer, organization text)
301 CREATE UNIQUE INDEX _autnums_number ON _autnums(number);
303 CREATE TEMPORARY TABLE _organizations(handle text, name text)
305 CREATE UNIQUE INDEX _organizations_handle ON _organizations(handle);
308 for source
in location
.importer
.WHOIS_SOURCES
:
309 with downloader
.request(source
, return_blocks
=True) as f
:
311 self
._parse
_block
(block
)
314 INSERT INTO autnums(number, name)
315 SELECT _autnums.number, _organizations.name FROM _autnums
316 LEFT JOIN _organizations ON _autnums.organization = _organizations.handle
317 ON CONFLICT (number) DO UPDATE SET name = excluded.name;
320 # Download all extended sources
321 for source
in location
.importer
.EXTENDED_SOURCES
:
322 with self
.db
.transaction():
324 with downloader
.request(source
) as f
:
326 self
._parse
_line
(line
)
328 def _parse_block(self
, block
):
329 # Get first line to find out what type of block this is
333 if line
.startswith("aut-num:"):
334 return self
._parse
_autnum
_block
(block
)
337 elif line
.startswith("organisation:"):
338 return self
._parse
_org
_block
(block
)
340 def _parse_autnum_block(self
, block
):
344 key
, val
= split_line(line
)
347 m
= re
.match(r
"^(AS|as)(\d+)", val
)
349 autnum
["asn"] = m
.group(2)
358 # Insert into database
359 self
.db
.execute("INSERT INTO _autnums(number, organization) \
360 VALUES(%s, %s) ON CONFLICT (number) DO UPDATE SET \
361 organization = excluded.organization",
362 autnum
.get("asn"), autnum
.get("org"),
365 def _parse_org_block(self
, block
):
369 key
, val
= split_line(line
)
371 if key
in ("organisation", "org-name"):
378 self
.db
.execute("INSERT INTO _organizations(handle, name) \
379 VALUES(%s, %s) ON CONFLICT (handle) DO \
380 UPDATE SET name = excluded.name",
381 org
.get("organisation"), org
.get("org-name"),
384 def _parse_line(self
, line
):
386 if line
.startswith("2"):
390 if line
.startswith("#"):
394 registry
, country_code
, type, line
= line
.split("|", 3)
396 log
.warning("Could not parse line: %s" % line
)
399 # Skip any lines that are for stats only
400 if country_code
== "*":
403 if type in ("ipv6", "ipv4"):
404 return self
._parse
_ip
_line
(country_code
, type, line
)
406 def _parse_ip_line(self
, country
, type, line
):
408 address
, prefix
, date
, status
, organization
= line
.split("|")
412 # Try parsing the line without organization
414 address
, prefix
, date
, status
= line
.split("|")
416 log
.warning("Unhandled line format: %s" % line
)
419 # Skip anything that isn't properly assigned
420 if not status
in ("assigned", "allocated"):
423 # Cast prefix into an integer
427 log
.warning("Invalid prefix: %s" % prefix
)
430 # Fix prefix length for IPv4
432 prefix
= 32 - int(math
.log(prefix
, 2))
434 # Try to parse the address
436 network
= ipaddress
.ip_network("%s/%s" % (address
, prefix
), strict
=False)
438 log
.warning("Invalid IP address: %s" % address
)
441 self
.db
.execute("INSERT INTO networks(network, country) \
442 VALUES(%s, %s) ON CONFLICT (network) DO \
443 UPDATE SET country = excluded.country",
444 "%s" % network
, country
,
447 def handle_update_announcements(self
, ns
):
448 server
= ns
.server
[0]
450 # Pre-compile regular expression for routes
451 #route = re.compile(b"^\*>?\s[\si]?([^\s]+)[.\s]*?(\d+)\si$", re.MULTILINE)
452 route
= re
.compile(b
"^\*[\s\>]i([^\s]+).+?(\d+)\si\r\n", re
.MULTILINE|re
.DOTALL
)
454 with telnetlib
.Telnet(server
) as t
:
457 # t.set_debuglevel(10)
459 # Wait for console greeting
460 greeting
= t
.read_until(b
"> ")
461 log
.debug(greeting
.decode())
464 t
.write(b
"terminal length 0\n")
466 # Wait for the prompt to return
469 # Fetch the routing tables
470 with self
.db
.transaction():
471 for protocol
in ("ipv6", "ipv4"):
472 log
.info("Requesting %s routing table" % protocol
)
474 # Request the full unicast routing table
475 t
.write(b
"show bgp %s unicast\n" % protocol
.encode())
477 # Read entire header which ends with "Path"
478 t
.read_until(b
"Path\r\n")
481 # Try reading a full entry
482 # Those might be broken across multiple lines but ends with i
483 line
= t
.read_until(b
"i\r\n", timeout
=5)
487 # Show line for debugging
488 #log.debug(repr(line))
490 # Try finding a route in here
491 m
= route
.match(line
)
493 network
, autnum
= m
.groups()
495 # Convert network to string
496 network
= network
.decode()
498 # Append /24 for IPv4 addresses
499 if not "/" in network
and not ":" in network
:
500 network
= "%s/24" % network
502 # Convert AS number to integer
505 log
.info("Found announcement for %s by %s" % (network
, autnum
))
507 self
.db
.execute("INSERT INTO announcements(network, autnum) \
508 VALUES(%s, %s) ON CONFLICT (network) DO \
509 UPDATE SET autnum = excluded.autnum, last_seen_at = CURRENT_TIMESTAMP",
513 log
.info("Finished reading the %s routing table" % protocol
)
515 # Purge anything we never want here
517 -- Delete default routes
518 DELETE FROM announcements WHERE network = '::/0' OR network = '0.0.0.0/0';
520 -- Delete anything that is not global unicast address space
521 DELETE FROM announcements WHERE family(network) = 6 AND NOT network <<= '2000::/3';
523 -- DELETE "current network" address space
524 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '0.0.0.0/8';
526 -- DELETE local loopback address space
527 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '127.0.0.0/8';
529 -- DELETE RFC 1918 address space
530 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '10.0.0.0/8';
531 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '172.16.0.0/12';
532 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.168.0.0/16';
534 -- DELETE test, benchmark and documentation address space
535 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.0.0/24';
536 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.0.2.0/24';
537 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.18.0.0/15';
538 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '198.51.100.0/24';
539 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '203.0.113.0/24';
541 -- DELETE CGNAT address space (RFC 6598)
542 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '100.64.0.0/10';
544 -- DELETE link local address space
545 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '169.254.0.0/16';
547 -- DELETE IPv6 to IPv4 (6to4) address space
548 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '192.88.99.0/24';
550 -- DELETE multicast and reserved address space
551 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '224.0.0.0/4';
552 DELETE FROM announcements WHERE family(network) = 4 AND network <<= '240.0.0.0/4';
554 -- Delete networks that are too small to be in the global routing table
555 DELETE FROM announcements WHERE family(network) = 6 AND masklen(network) > 48;
556 DELETE FROM announcements WHERE family(network) = 4 AND masklen(network) > 24;
558 -- Delete any non-public or reserved ASNs
559 DELETE FROM announcements WHERE NOT (
560 (autnum >= 1 AND autnum <= 23455)
562 (autnum >= 23457 AND autnum <= 64495)
564 (autnum >= 131072 AND autnum <= 4199999999)
567 -- Delete everything that we have not seen for 14 days
568 DELETE FROM announcements WHERE last_seen_at <= CURRENT_TIMESTAMP - INTERVAL '14 days';
571 def handle_update_overrides(self
, ns
):
572 with self
.db
.transaction():
573 # Drop all data that we have
575 TRUNCATE TABLE autnum_overrides;
576 TRUNCATE TABLE network_overrides;
579 for file in ns
.files
:
580 log
.info("Reading %s..." % file)
582 with
open(file, "rb") as f
:
583 for type, block
in location
.importer
.read_blocks(f
):
585 network
= block
.get("net")
586 # Try to parse and normalise the network
588 network
= ipaddress
.ip_network(network
, strict
=False)
589 except ValueError as e
:
590 log
.warning("Invalid IP network: %s: %s" % (network
, e
))
594 INSERT INTO network_overrides(
598 is_satellite_provider,
600 ) VALUES (%s, %s, %s, %s, %s)
601 ON CONFLICT (network) DO NOTHING""",
603 block
.get("country"),
604 block
.get("is-anonymous-proxy") == "yes",
605 block
.get("is-satellite-provider") == "yes",
606 block
.get("is-anycast") == "yes",
609 elif type == "autnum":
610 autnum
= block
.get("autnum")
612 # Check if AS number begins with "AS"
613 if not autnum
.startswith("AS"):
614 log
.warning("Invalid AS number: %s" % autnum
)
621 INSERT INTO autnum_overrides(
625 is_satellite_provider,
627 ) VALUES(%s, %s, %s, %s, %s)
628 ON CONFLICT DO NOTHING""",
629 autnum
, block
.get("name"),
630 block
.get("is-anonymous-proxy") == "yes",
631 block
.get("is-satellite-provider") == "yes",
632 block
.get("is-anycast") == "yes",
636 log
.warning("Unsupport type: %s" % type)
639 def split_line(line
):
640 key
, colon
, val
= line
.partition(":")
642 # Strip any excess space
649 # Run the command line interface