2 ###############################################################################
4 # libloc - A library to determine the location of someone on the Internet #
6 # Copyright (C) 2017 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 ###############################################################################
31 # Load our location module
33 import location
.downloader
34 import location
.export
36 from location
.i18n
import _
39 log
= logging
.getLogger("location")
45 parser
= argparse
.ArgumentParser(
46 description
=_("Location Database Command Line Interface"),
48 subparsers
= parser
.add_subparsers()
50 # Global configuration flags
51 parser
.add_argument("--debug", action
="store_true",
52 help=_("Enable debug output"))
53 parser
.add_argument("--quiet", action
="store_true",
54 help=_("Enable quiet mode"))
57 parser
.add_argument("--version", action
="version",
58 version
="%(prog)s @VERSION@")
61 parser
.add_argument("--database", "-d",
62 default
="@databasedir@/database.db", help=_("Path to database"),
66 parser
.add_argument("--public-key", "-k",
67 default
="@databasedir@/signing-key.pem", help=_("Public Signing Key"),
70 # Show the database version
71 version
= subparsers
.add_parser("version",
72 help=_("Show database version"))
73 version
.set_defaults(func
=self
.handle_version
)
75 # lookup an IP address
76 lookup
= subparsers
.add_parser("lookup",
77 help=_("Lookup one or multiple IP addresses"),
79 lookup
.add_argument("address", nargs
="+")
80 lookup
.set_defaults(func
=self
.handle_lookup
)
82 # Dump the whole database
83 dump
= subparsers
.add_parser("dump",
84 help=_("Dump the entire database"),
86 dump
.add_argument("output", nargs
="?", type=argparse
.FileType("w"))
87 dump
.set_defaults(func
=self
.handle_dump
)
90 update
= subparsers
.add_parser("update", help=_("Update database"))
91 update
.set_defaults(func
=self
.handle_update
)
94 verify
= subparsers
.add_parser("verify",
95 help=_("Verify the downloaded database"))
96 verify
.set_defaults(func
=self
.handle_verify
)
99 get_as
= subparsers
.add_parser("get-as",
100 help=_("Get information about one or multiple Autonomous Systems"),
102 get_as
.add_argument("asn", nargs
="+")
103 get_as
.set_defaults(func
=self
.handle_get_as
)
106 search_as
= subparsers
.add_parser("search-as",
107 help=_("Search for Autonomous Systems that match the string"),
109 search_as
.add_argument("query", nargs
=1)
110 search_as
.set_defaults(func
=self
.handle_search_as
)
112 # List all networks in an AS
113 list_networks_by_as
= subparsers
.add_parser("list-networks-by-as",
114 help=_("Lists all networks in an AS"),
116 list_networks_by_as
.add_argument("asn", nargs
=1, type=int)
117 list_networks_by_as
.add_argument("--family", choices
=("ipv6", "ipv4"))
118 list_networks_by_as
.add_argument("--format",
119 choices
=location
.export
.formats
.keys(), default
="list")
120 list_networks_by_as
.set_defaults(func
=self
.handle_list_networks_by_as
)
122 # List all networks in a country
123 list_networks_by_cc
= subparsers
.add_parser("list-networks-by-cc",
124 help=_("Lists all networks in a country"),
126 list_networks_by_cc
.add_argument("country_code", nargs
=1)
127 list_networks_by_cc
.add_argument("--family", choices
=("ipv6", "ipv4"))
128 list_networks_by_cc
.add_argument("--format",
129 choices
=location
.export
.formats
.keys(), default
="list")
130 list_networks_by_cc
.set_defaults(func
=self
.handle_list_networks_by_cc
)
132 # List all networks with flags
133 list_networks_by_flags
= subparsers
.add_parser("list-networks-by-flags",
134 help=_("Lists all networks with flags"),
136 list_networks_by_flags
.add_argument("--anonymous-proxy",
137 action
="store_true", help=_("Anonymous Proxies"),
139 list_networks_by_flags
.add_argument("--satellite-provider",
140 action
="store_true", help=_("Satellite Providers"),
142 list_networks_by_flags
.add_argument("--anycast",
143 action
="store_true", help=_("Anycasts"),
145 list_networks_by_flags
.add_argument("--family", choices
=("ipv6", "ipv4"))
146 list_networks_by_flags
.add_argument("--format",
147 choices
=location
.export
.formats
.keys(), default
="list")
148 list_networks_by_flags
.set_defaults(func
=self
.handle_list_networks_by_flags
)
151 list_countries
= subparsers
.add_parser("list-countries",
152 help=_("Lists all countries"),
154 list_countries
.add_argument("--show-name",
155 action
="store_true", help=_("Show the name of the country"),
157 list_countries
.add_argument("--show-continent",
158 action
="store_true", help=_("Show the continent"),
160 list_countries
.set_defaults(func
=self
.handle_list_countries
)
163 export
= subparsers
.add_parser("export",
164 help=_("Exports data in many formats to load it into packet filters"),
166 export
.add_argument("--format", help=_("Output format"),
167 choices
=location
.export
.formats
.keys(), default
="list")
168 export
.add_argument("--directory", help=_("Output directory"), required
=True)
169 export
.add_argument("--family",
170 help=_("Specify address family"), choices
=("ipv6", "ipv4"),
172 export
.add_argument("objects", nargs
="*", help=_("List country codes or ASNs to export"))
173 export
.set_defaults(func
=self
.handle_export
)
175 args
= parser
.parse_args()
179 location
.logger
.set_level(logging
.DEBUG
)
181 location
.logger
.set_level(logging
.WARNING
)
183 # Print usage if no action was given
184 if not "func" in args
:
191 # Parse command line arguments
192 args
= self
.parse_cli()
196 db
= location
.Database(args
.database
)
197 except FileNotFoundError
as e
:
198 sys
.stderr
.write("location: Could not open database %s: %s\n" \
199 % (args
.database
, e
))
202 # Translate family (if present)
204 if args
.family
== "ipv6":
205 args
.family
= socket
.AF_INET6
206 elif args
.family
== "ipv4":
207 args
.family
= socket
.AF_INET
213 ret
= args
.func(db
, args
)
215 # Catch invalid inputs
216 except ValueError as e
:
217 sys
.stderr
.write("%s\n" % e
)
220 # Return with exit code
224 # Otherwise just exit
227 def handle_version(self
, db
, ns
):
229 Print the version of the database
232 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
237 def handle_lookup(self
, db
, ns
):
240 format
= " %-24s: %s"
242 for address
in ns
.address
:
244 network
= db
.lookup(address
)
246 print(_("Invalid IP address: %s") % address
, file=sys
.stderr
)
255 print(_("Nothing found for %(address)s") % args
, file=sys
.stderr
)
259 print("%s:" % address
)
260 print(format
% (_("Network"), network
))
263 if network
.country_code
:
264 country
= db
.get_country(network
.country_code
)
268 country
.name
if country
else network
.country_code
),
271 # Print AS information
273 autonomous_system
= db
.get_as(network
.asn
)
276 _("Autonomous System"),
277 autonomous_system
or "AS%s" % network
.asn
),
281 if network
.has_flag(location
.NETWORK_FLAG_ANONYMOUS_PROXY
):
283 _("Anonymous Proxy"), _("yes"),
287 if network
.has_flag(location
.NETWORK_FLAG_SATELLITE_PROVIDER
):
289 _("Satellite Provider"), _("yes"),
293 if network
.has_flag(location
.NETWORK_FLAG_ANYCAST
):
295 _("Anycast"), _("yes"),
300 def handle_dump(self
, db
, ns
):
301 # Use output file or write to stdout
302 f
= ns
.output
or sys
.stdout
304 # Format everything like this
305 format
= "%-24s %s\n"
308 f
.write("#\n# Location Database Export\n#\n")
310 f
.write("# Generated: %s\n" % time
.strftime(
311 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
315 f
.write("# Vendor: %s\n" % db
.vendor
)
318 f
.write("# License: %s\n" % db
.license
)
323 for line
in db
.description
.splitlines():
324 f
.write("# %s\n" % line
)
328 # Iterate over all ASes
331 f
.write(format
% ("aut-num:", "AS%s" % a
.number
))
332 f
.write(format
% ("name:", a
.name
))
335 location
.NETWORK_FLAG_ANONYMOUS_PROXY
: "is-anonymous-proxy:",
336 location
.NETWORK_FLAG_SATELLITE_PROVIDER
: "is-satellite-provider:",
337 location
.NETWORK_FLAG_ANYCAST
: "is-anycast:",
340 # Iterate over all networks
341 for n
in db
.networks
:
343 f
.write(format
% ("net:", n
))
346 f
.write(format
% ("country:", n
.country_code
))
349 f
.write(format
% ("aut-num:", n
.asn
))
354 f
.write(format
% (flags
[flag
], "yes"))
356 def handle_get_as(self
, db
, ns
):
358 Gets information about Autonomous Systems
366 print(_("Invalid ASN: %s") % asn
, file=sys
.stderr
)
370 # Fetch AS from database
375 print(_("Could not find AS%s") % asn
, file=sys
.stderr
)
379 print(_("AS%(asn)s belongs to %(name)s") % { "asn" : a
.number
, "name" : a
.name
})
383 def handle_search_as(self
, db
, ns
):
384 for query
in ns
.query
:
385 # Print all matches ASes
386 for a
in db
.search_as(query
):
389 def handle_update(self
, db
, ns
):
390 # Fetch the timestamp we need from DNS
391 t
= location
.discover_latest_version()
393 # Parse timestamp into datetime format
394 timestamp
= datetime
.datetime
.fromtimestamp(t
) if t
else None
396 # Check the version of the local database
397 if db
and timestamp
and db
.created_at
>= timestamp
.timestamp():
398 log
.info("Already on the latest version")
401 # Download the database into the correct directory
402 tmpdir
= os
.path
.dirname(ns
.database
)
404 # Create a downloader
405 d
= location
.downloader
.Downloader()
407 # Try downloading a new database
409 t
= d
.download(public_key
=ns
.public_key
, timestamp
=timestamp
, tmpdir
=tmpdir
)
411 # If no file could be downloaded, log a message
412 except FileNotFoundError
as e
:
413 log
.error("Could not download a new database")
416 # If we have not received a new file, there is nothing to do
420 # Move temporary file to destination
421 shutil
.move(t
.name
, ns
.database
)
425 def handle_verify(self
, ns
):
427 db
= location
.Database(ns
.database
)
428 except FileNotFoundError
as e
:
429 log
.error("%s: %s" % (ns
.database
, e
))
432 # Verify the database
433 with
open(ns
.public_key
, "r") as f
:
435 log
.error("Could not verify database")
439 log
.debug("Database successfully verified")
442 def __get_output_formatter(self
, ns
):
444 cls
= location
.export
.formats
[ns
.format
]
446 cls
= location
.export
.OutputFormatter
450 def handle_list_countries(self
, db
, ns
):
451 for country
in db
.countries
:
456 if ns
.show_continent
:
457 line
.append(country
.continent_code
)
460 line
.append(country
.name
)
463 line
= " ".join(line
)
468 def handle_list_networks_by_as(self
, db
, ns
):
469 writer
= self
.__get
_output
_formatter
(ns
)
472 f
= writer(sys
.stdout
, prefix
="AS%s" % asn
)
474 # Print all matching networks
475 for n
in db
.search_networks(asn
=asn
, family
=ns
.family
):
480 def handle_list_networks_by_cc(self
, db
, ns
):
481 writer
= self
.__get
_output
_formatter
(ns
)
483 for country_code
in ns
.country_code
:
484 # Open standard output
485 f
= writer(sys
.stdout
, prefix
=country_code
)
487 # Print all matching networks
488 for n
in db
.search_networks(country_code
=country_code
, family
=ns
.family
):
493 def handle_list_networks_by_flags(self
, db
, ns
):
496 if ns
.anonymous_proxy
:
497 flags |
= location
.NETWORK_FLAG_ANONYMOUS_PROXY
499 if ns
.satellite_provider
:
500 flags |
= location
.NETWORK_FLAG_SATELLITE_PROVIDER
503 flags |
= location
.NETWORK_FLAG_ANYCAST
506 raise ValueError(_("You must at least pass one flag"))
508 writer
= self
.__get
_output
_formatter
(ns
)
509 f
= writer(sys
.stdout
, prefix
="custom")
511 for n
in db
.search_networks(flags
=flags
, family
=ns
.family
):
516 def handle_export(self
, db
, ns
):
517 countries
, asns
= [], []
521 families
= [ ns
.family
]
523 families
= [ socket
.AF_INET6
, socket
.AF_INET
]
525 for object in ns
.objects
:
526 m
= re
.match("^AS(\d+)$", object)
528 object = int(m
.group(1))
532 elif location
.country_code_is_valid(object) \
533 or object in ("A1", "A2", "A3"):
534 countries
.append(object)
537 log
.warning("Invalid argument: %s" % object)
540 # Default to exporting all countries
541 if not countries
and not asns
:
542 countries
= ["A1", "A2", "A3"] + [country
.code
for country
in db
.countries
]
544 # Select the output format
545 writer
= self
.__get
_output
_formatter
(ns
)
547 e
= location
.export
.Exporter(db
, writer
)
548 e
.export(ns
.directory
, countries
=countries
, asns
=asns
, families
=families
)
552 # Run the command line interface