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"))
126 parser
.add_argument("--version", action
="version",
127 version
="%(prog)s @VERSION@")
130 parser
.add_argument("--database", "-d",
131 default
="@databasedir@/database.db", help=_("Path to database"),
135 parser
.add_argument("--public-key", "-k",
136 default
="@databasedir@/signing-key.pem", help=_("Public Signing Key"),
139 # lookup an IP address
140 lookup
= subparsers
.add_parser("lookup",
141 help=_("Lookup one or multiple IP addresses"),
143 lookup
.add_argument("address", nargs
="+")
144 lookup
.set_defaults(func
=self
.handle_lookup
)
146 # Dump the whole database
147 dump
= subparsers
.add_parser("dump",
148 help=_("Dump the entire database"),
150 dump
.add_argument("output", nargs
="?", type=argparse
.FileType("w"))
151 dump
.set_defaults(func
=self
.handle_dump
)
154 get_as
= subparsers
.add_parser("get-as",
155 help=_("Get information about one or multiple Autonomous Systems"),
157 get_as
.add_argument("asn", nargs
="+")
158 get_as
.set_defaults(func
=self
.handle_get_as
)
161 search_as
= subparsers
.add_parser("search-as",
162 help=_("Search for Autonomous Systems that match the string"),
164 search_as
.add_argument("query", nargs
=1)
165 search_as
.set_defaults(func
=self
.handle_search_as
)
167 # List all networks in an AS
168 list_networks_by_as
= subparsers
.add_parser("list-networks-by-as",
169 help=_("Lists all networks in an AS"),
171 list_networks_by_as
.add_argument("asn", nargs
=1, type=int)
172 list_networks_by_as
.add_argument("--family", choices
=("ipv6", "ipv4"))
173 list_networks_by_as
.add_argument("--output-format",
174 choices
=self
.output_formats
.keys(), default
="list")
175 list_networks_by_as
.set_defaults(func
=self
.handle_list_networks_by_as
)
177 # List all networks in a country
178 list_networks_by_cc
= subparsers
.add_parser("list-networks-by-cc",
179 help=_("Lists all networks in a country"),
181 list_networks_by_cc
.add_argument("country_code", nargs
=1)
182 list_networks_by_cc
.add_argument("--family", choices
=("ipv6", "ipv4"))
183 list_networks_by_cc
.add_argument("--output-format",
184 choices
=self
.output_formats
.keys(), default
="list")
185 list_networks_by_cc
.set_defaults(func
=self
.handle_list_networks_by_cc
)
187 # List all networks with flags
188 list_networks_by_flags
= subparsers
.add_parser("list-networks-by-flags",
189 help=_("Lists all networks with flags"),
191 list_networks_by_flags
.add_argument("--anonymous-proxy",
192 action
="store_true", help=_("Anonymous Proxies"),
194 list_networks_by_flags
.add_argument("--satellite-provider",
195 action
="store_true", help=_("Satellite Providers"),
197 list_networks_by_flags
.add_argument("--anycast",
198 action
="store_true", help=_("Anycasts"),
200 list_networks_by_flags
.add_argument("--family", choices
=("ipv6", "ipv4"))
201 list_networks_by_flags
.add_argument("--output-format",
202 choices
=self
.output_formats
.keys(), default
="list")
203 list_networks_by_flags
.set_defaults(func
=self
.handle_list_networks_by_flags
)
205 args
= parser
.parse_args()
207 # Print usage if no action was given
208 if not "func" in args
:
215 # Parse command line arguments
216 args
= self
.parse_cli()
220 db
= location
.Database(args
.database
)
221 except FileNotFoundError
as e
:
222 sys
.stderr
.write("location-query: Could not open database %s: %s\n" \
223 % (args
.database
, e
))
226 # Translate family (if present)
228 if args
.family
== "ipv6":
229 args
.family
= socket
.AF_INET6
230 elif args
.family
== "ipv4":
231 args
.family
= socket
.AF_INET
236 ret
= args
.func(db
, args
)
238 # Return with exit code
242 # Otherwise just exit
245 def handle_lookup(self
, db
, ns
):
248 for address
in ns
.address
:
250 n
= db
.lookup(address
)
252 print(_("Invalid IP address: %s") % address
, file=sys
.stderr
)
261 print(_("Nothing found for %(address)s") % args
, file=sys
.stderr
)
265 # Try to retrieve the AS if we have an AS number
269 # If we have found an AS we will print it in the message
275 print(_("%(address)s belongs to %(network)s which is a part of %(as)s") % args
)
278 print(_("%(address)s belongs to %(network)s") % args
)
282 def handle_dump(self
, db
, ns
):
283 # Use output file or write to stdout
284 f
= ns
.output
or sys
.stdout
287 f
.write("#\n# Location Database Export\n#\n")
289 f
.write("# Generated: %s\n" % time
.strftime(
290 "%a, %d %b %Y %H:%M:%S GMT", time
.gmtime(db
.created_at
),
294 f
.write("# Vendor: %s\n" % db
.vendor
)
297 f
.write("# License: %s\n" % db
.license
)
302 for line
in db
.description
.splitlines():
303 f
.write("# %s\n" % line
)
307 # Iterate over all ASes
310 f
.write("aut-num: AS%s\n" % a
.number
)
311 f
.write("name: %s\n" % a
.name
)
313 # Iterate over all networks
314 for n
in db
.networks
:
316 f
.write("net: %s\n" % n
)
319 f
.write("country: %s\n" % n
.country_code
)
322 f
.write("autnum: %s\n" % n
.asn
)
324 def handle_get_as(self
, db
, ns
):
326 Gets information about Autonomous Systems
334 print(_("Invalid ASN: %s") % asn
, file=sys
.stderr
)
338 # Fetch AS from database
343 print(_("Could not find AS%s") % asn
, file=sys
.stderr
)
347 print(_("AS%(asn)s belongs to %(name)s") % { "asn" : a
.number
, "name" : a
.name
})
351 def handle_search_as(self
, db
, ns
):
352 for query
in ns
.query
:
353 # Print all matches ASes
354 for a
in db
.search_as(query
):
357 def __get_output_formatter(self
, ns
):
359 cls
= self
.output_formats
[ns
.output_format
]
361 cls
= OutputFormatter
365 def handle_list_networks_by_as(self
, db
, ns
):
366 with self
.__get
_output
_formatter
(ns
) as f
:
368 # Print all matching networks
369 for n
in db
.search_networks(asn
=asn
, family
=ns
.family
):
372 def handle_list_networks_by_cc(self
, db
, ns
):
373 with self
.__get
_output
_formatter
(ns
) as f
:
374 for country_code
in ns
.country_code
:
375 # Print all matching networks
376 for n
in db
.search_networks(country_code
=country_code
, family
=ns
.family
):
379 def handle_list_networks_by_flags(self
, db
, ns
):
382 if ns
.anonymous_proxy
:
383 flags |
= location
.NETWORK_FLAG_ANONYMOUS_PROXY
385 if ns
.satellite_provider
:
386 flags |
= location
.NETWORK_FLAG_SATELLITE_PROVIDER
389 flags |
= location
.NETWORK_FLAG_ANYCAST
391 with self
.__get
_output
_formatter
(ns
) as f
:
392 for n
in db
.search_networks(flags
=flags
, family
=ns
.family
):
397 # Run the command line interface