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 ###############################################################################
27 # Load our location module
29 from location
.i18n
import _
33 class OutputFormatter(object):
34 def __init__(self
, ns
):
43 def __exit__(self
, type, value
, tb
):
49 if "country_code" in self
.ns
:
50 return "networks_country_%s" % self
.ns
.country_code
[0]
52 elif "asn" in self
.ns
:
53 return "networks_AS%s" % self
.ns
.asn
[0]
61 def network(self
, network
):
65 class IpsetOutputFormatter(OutputFormatter
):
70 print("create %s hash:net family inet hashsize 1024 maxelem 65536" % self
.name
)
72 def network(self
, network
):
73 print("add %s %s" % (self
.name
, network
))
76 class NftablesOutputFormatter(OutputFormatter
):
81 print("define %s = {" % self
.name
)
86 def network(self
, network
):
87 print(" %s," % network
)
90 class XTGeoIPOutputFormatter(OutputFormatter
):
92 Formats the output in that way, that it can be loaded by
93 the xt_geoip kernel module from xtables-addons.
95 def network(self
, network
):
96 n
= ipaddress
.ip_network("%s" % network
)
98 for address
in (n
.network_address
, n
.broadcast_address
):
99 bytes
= socket
.inet_pton(
100 socket
.AF_INET6
if address
.version
== 6 else socket
.AF_INET
,
109 "ipset" : IpsetOutputFormatter
,
110 "list" : OutputFormatter
,
111 "nftables" : NftablesOutputFormatter
,
112 "xt_geoip" : XTGeoIPOutputFormatter
,
116 parser
= argparse
.ArgumentParser(
117 description
=_("Location Database Command Line Interface"),
119 subparsers
= parser
.add_subparsers()
121 # Global configuration flags
122 parser
.add_argument("--debug", action
="store_true",
123 help=_("Enable debug output"))
124 parser
.add_argument("--quiet", action
="store_true",
125 help=_("Enable quiet mode"))
128 parser
.add_argument("--version", action
="version",
129 version
="%(prog)s @VERSION@")
132 parser
.add_argument("--database", "-d",
133 default
="@databasedir@/database.db", help=_("Path to database"),
137 parser
.add_argument("--public-key", "-k",
138 default
="@databasedir@/signing-key.pem", help=_("Public Signing Key"),
141 # Show the database version
142 version
= subparsers
.add_parser("version",
143 help=_("Show database version"))
144 version
.set_defaults(func
=self
.handle_version
)
146 # lookup an IP address
147 lookup
= subparsers
.add_parser("lookup",
148 help=_("Lookup one or multiple IP addresses"),
150 lookup
.add_argument("address", nargs
="+")
151 lookup
.set_defaults(func
=self
.handle_lookup
)
153 # Dump the whole database
154 dump
= subparsers
.add_parser("dump",
155 help=_("Dump the entire database"),
157 dump
.add_argument("output", nargs
="?", type=argparse
.FileType("w"))
158 dump
.set_defaults(func
=self
.handle_dump
)
161 get_as
= subparsers
.add_parser("get-as",
162 help=_("Get information about one or multiple Autonomous Systems"),
164 get_as
.add_argument("asn", nargs
="+")
165 get_as
.set_defaults(func
=self
.handle_get_as
)
168 search_as
= subparsers
.add_parser("search-as",
169 help=_("Search for Autonomous Systems that match the string"),
171 search_as
.add_argument("query", nargs
=1)
172 search_as
.set_defaults(func
=self
.handle_search_as
)
174 # List all networks in an AS
175 list_networks_by_as
= subparsers
.add_parser("list-networks-by-as",
176 help=_("Lists all networks in an AS"),
178 list_networks_by_as
.add_argument("asn", nargs
=1, type=int)
179 list_networks_by_as
.add_argument("--family", choices
=("ipv6", "ipv4"))
180 list_networks_by_as
.add_argument("--output-format",
181 choices
=self
.output_formats
.keys(), default
="list")
182 list_networks_by_as
.set_defaults(func
=self
.handle_list_networks_by_as
)
184 # List all networks in a country
185 list_networks_by_cc
= subparsers
.add_parser("list-networks-by-cc",
186 help=_("Lists all networks in a country"),
188 list_networks_by_cc
.add_argument("country_code", nargs
=1)
189 list_networks_by_cc
.add_argument("--family", choices
=("ipv6", "ipv4"))
190 list_networks_by_cc
.add_argument("--output-format",
191 choices
=self
.output_formats
.keys(), default
="list")
192 list_networks_by_cc
.set_defaults(func
=self
.handle_list_networks_by_cc
)
194 # List all networks with flags
195 list_networks_by_flags
= subparsers
.add_parser("list-networks-by-flags",
196 help=_("Lists all networks with flags"),
198 list_networks_by_flags
.add_argument("--anonymous-proxy",
199 action
="store_true", help=_("Anonymous Proxies"),
201 list_networks_by_flags
.add_argument("--satellite-provider",
202 action
="store_true", help=_("Satellite Providers"),
204 list_networks_by_flags
.add_argument("--anycast",
205 action
="store_true", help=_("Anycasts"),
207 list_networks_by_flags
.add_argument("--family", choices
=("ipv6", "ipv4"))
208 list_networks_by_flags
.add_argument("--output-format",
209 choices
=self
.output_formats
.keys(), default
="list")
210 list_networks_by_flags
.set_defaults(func
=self
.handle_list_networks_by_flags
)
212 args
= parser
.parse_args()
216 location
.logger
.set_level(logging
.DEBUG
)
218 location
.logger
.set_level(logging
.WARNING
)
220 # Print usage if no action was given
221 if not "func" in args
:
228 # Parse command line arguments
229 args
= self
.parse_cli()
233 db
= location
.Database(args
.database
)
234 except FileNotFoundError
as e
:
235 sys
.stderr
.write("location-query: Could not open database %s: %s\n" \
236 % (args
.database
, e
))
239 # Translate family (if present)
241 if args
.family
== "ipv6":
242 args
.family
= socket
.AF_INET6
243 elif args
.family
== "ipv4":
244 args
.family
= socket
.AF_INET
250 ret
= args
.func(db
, args
)
252 # Catch invalid inputs
253 except ValueError as e
:
254 sys
.stderr
.write("%s\n" % e
)
257 # Return with exit code
261 # Otherwise just exit
264 def handle_version(self
, db
, ns
):
266 Print the version of the database
269 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
274 def handle_lookup(self
, db
, ns
):
277 format
= " %-24s: %s"
279 for address
in ns
.address
:
281 network
= db
.lookup(address
)
283 print(_("Invalid IP address: %s") % address
, file=sys
.stderr
)
292 print(_("Nothing found for %(address)s") % args
, file=sys
.stderr
)
296 print("%s:" % address
)
297 print(format
% (_("Network"), network
))
300 if network
.country_code
:
301 country
= db
.get_country(network
.country_code
)
305 country
.name
if country
else network
.country_code
),
308 # Print AS information
310 autonomous_system
= db
.get_as(network
.asn
)
313 _("Autonomous System"),
314 autonomous_system
or "AS%s" % network
.asn
),
318 if network
.has_flag(location
.NETWORK_FLAG_ANONYMOUS_PROXY
):
320 _("Anonymous Proxy"), _("yes"),
324 if network
.has_flag(location
.NETWORK_FLAG_SATELLITE_PROVIDER
):
326 _("Satellite Provider"), _("yes"),
330 if network
.has_flag(location
.NETWORK_FLAG_ANYCAST
):
332 _("Anycast"), _("yes"),
337 def handle_dump(self
, db
, ns
):
338 # Use output file or write to stdout
339 f
= ns
.output
or sys
.stdout
341 # Format everything like this
342 format
= "%-24s %s\n"
345 f
.write("#\n# Location Database Export\n#\n")
347 f
.write("# Generated: %s\n" % time
.strftime(
348 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
352 f
.write("# Vendor: %s\n" % db
.vendor
)
355 f
.write("# License: %s\n" % db
.license
)
360 for line
in db
.description
.splitlines():
361 f
.write("# %s\n" % line
)
365 # Iterate over all ASes
368 f
.write(format
% ("aut-num:", "AS%s" % a
.number
))
369 f
.write(format
% ("name:", a
.name
))
372 location
.NETWORK_FLAG_ANONYMOUS_PROXY
: "is-anonymous-proxy:",
373 location
.NETWORK_FLAG_SATELLITE_PROVIDER
: "is-satellite-provider:",
374 location
.NETWORK_FLAG_ANYCAST
: "is-anycast:",
377 # Iterate over all networks
378 for n
in db
.networks
:
380 f
.write(format
% ("net:", n
))
383 f
.write(format
% ("country:", n
.country_code
))
386 f
.write(format
% ("aut-num:", n
.asn
))
391 f
.write(format
% (flags
[flag
], "yes"))
393 def handle_get_as(self
, db
, ns
):
395 Gets information about Autonomous Systems
403 print(_("Invalid ASN: %s") % asn
, file=sys
.stderr
)
407 # Fetch AS from database
412 print(_("Could not find AS%s") % asn
, file=sys
.stderr
)
416 print(_("AS%(asn)s belongs to %(name)s") % { "asn" : a
.number
, "name" : a
.name
})
420 def handle_search_as(self
, db
, ns
):
421 for query
in ns
.query
:
422 # Print all matches ASes
423 for a
in db
.search_as(query
):
426 def __get_output_formatter(self
, ns
):
428 cls
= self
.output_formats
[ns
.output_format
]
430 cls
= OutputFormatter
434 def handle_list_networks_by_as(self
, db
, ns
):
435 with self
.__get
_output
_formatter
(ns
) as f
:
437 # Print all matching networks
438 for n
in db
.search_networks(asn
=asn
, family
=ns
.family
):
441 def handle_list_networks_by_cc(self
, db
, ns
):
442 with self
.__get
_output
_formatter
(ns
) as f
:
443 for country_code
in ns
.country_code
:
444 # Print all matching networks
445 for n
in db
.search_networks(country_code
=country_code
, family
=ns
.family
):
448 def handle_list_networks_by_flags(self
, db
, ns
):
451 if ns
.anonymous_proxy
:
452 flags |
= location
.NETWORK_FLAG_ANONYMOUS_PROXY
454 if ns
.satellite_provider
:
455 flags |
= location
.NETWORK_FLAG_SATELLITE_PROVIDER
458 flags |
= location
.NETWORK_FLAG_ANYCAST
461 raise ValueError(_("You must at least pass one flag"))
463 with self
.__get
_output
_formatter
(ns
) as f
:
464 for n
in db
.search_networks(flags
=flags
, family
=ns
.family
):
469 # Run the command line interface