]> git.ipfire.org Git - location/libloc.git/blame - src/python/location-query.in
location-downloader: Verify the database after download
[location/libloc.git] / src / python / location-query.in
CommitLineData
5118a4b8
MT
1#!/usr/bin/python3
2###############################################################################
3# #
4# libloc - A library to determine the location of someone on the Internet #
5# #
6# Copyright (C) 2017 IPFire Development Team <info@ipfire.org> #
7# #
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. #
12# #
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. #
17# #
18###############################################################################
19
20import argparse
2bb7d64e 21import gettext
4439e317
MT
22import ipaddress
23import os
24import socket
5118a4b8
MT
25import sys
26import syslog
27
28# Load our location module
29import location
30
31# i18n
2bb7d64e
MT
32def _(singular, plural=None, n=None):
33 if plural:
34 return gettext.dngettext("libloc", singular, plural, n)
35
36 return gettext.dgettext("libloc", singular)
5118a4b8 37
4439e317
MT
38# Output formatters
39
40class OutputFormatter(object):
71e0ad0b
MT
41 def __init__(self, ns):
42 self.ns = ns
43
4439e317
MT
44 def __enter__(self):
45 # Open the output
46 self.open()
47
48 return self
49
50 def __exit__(self, type, value, tb):
51 if tb is None:
52 self.close()
53
71e0ad0b
MT
54 @property
55 def name(self):
56 if "country_code" in self.ns:
57 return "networks_country_%s" % self.ns.country_code[0]
58
59 elif "asn" in self.ns:
60 return "networks_AS%s" % self.ns.asn[0]
61
4439e317
MT
62 def open(self):
63 pass
64
65 def close(self):
66 pass
67
68 def network(self, network):
69 print(network)
70
71
6da14cc1
MT
72class IpsetOutputFormatter(OutputFormatter):
73 """
74 For nftables
75 """
76 def open(self):
77 print("create %s hash:net family inet hashsize 1024 maxelem 65536" % self.name)
78
79 def network(self, network):
80 print("add %s %s" % (self.name, network))
81
82
71e0ad0b
MT
83class NftablesOutputFormatter(OutputFormatter):
84 """
85 For nftables
86 """
87 def open(self):
88 print("define %s = {" % self.name)
89
90 def close(self):
91 print("}")
92
93 def network(self, network):
94 print(" %s," % network)
95
96
4439e317
MT
97class XTGeoIPOutputFormatter(OutputFormatter):
98 """
99 Formats the output in that way, that it can be loaded by
100 the xt_geoip kernel module from xtables-addons.
101 """
102 def network(self, network):
103 n = ipaddress.ip_network("%s" % network)
104
105 for address in (n.network_address, n.broadcast_address):
106 bytes = socket.inet_pton(
107 socket.AF_INET6 if address.version == 6 else socket.AF_INET,
108 "%s" % address,
109 )
110
111 os.write(1, bytes)
112
113
5118a4b8 114class CLI(object):
4439e317 115 output_formats = {
6da14cc1 116 "ipset" : IpsetOutputFormatter,
4439e317 117 "list" : OutputFormatter,
71e0ad0b 118 "nftables" : NftablesOutputFormatter,
4439e317
MT
119 "xt_geoip" : XTGeoIPOutputFormatter,
120 }
121
5118a4b8
MT
122 def parse_cli(self):
123 parser = argparse.ArgumentParser(
124 description=_("Location Database Command Line Interface"),
125 )
126 subparsers = parser.add_subparsers()
127
128 # Global configuration flags
129 parser.add_argument("--debug", action="store_true",
130 help=_("Enable debug output"))
131
ddb184be
MT
132 # version
133 parser.add_argument("--version", action="version",
134 version="%%(prog)s %s" % location.__version__)
135
2538ed9a
MT
136 # database
137 parser.add_argument("--database", "-d",
138 default="@databasedir@/database.db", help=_("Path to database"),
139 )
140
726f9984
MT
141 # public key
142 parser.add_argument("--public-key", "-k",
143 default="@databasedir@/signing-key.pem", help=_("Public Signing Key"),
144 )
145
5118a4b8
MT
146 # lookup an IP address
147 lookup = subparsers.add_parser("lookup",
148 help=_("Lookup one or multiple IP addresses"),
149 )
150 lookup.add_argument("address", nargs="+")
151 lookup.set_defaults(func=self.handle_lookup)
152
fadc1af0
MT
153 # Get AS
154 get_as = subparsers.add_parser("get-as",
155 help=_("Get information about one or multiple Autonomous Systems"),
156 )
157 get_as.add_argument("asn", nargs="+")
158 get_as.set_defaults(func=self.handle_get_as)
159
da3e360e
MT
160 # Search for AS
161 search_as = subparsers.add_parser("search-as",
162 help=_("Search for Autonomous Systems that match the string"),
163 )
164 search_as.add_argument("query", nargs=1)
165 search_as.set_defaults(func=self.handle_search_as)
166
43154ed7
MT
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"),
170 )
171 list_networks_by_as.add_argument("asn", nargs=1, type=int)
4439e317
MT
172 list_networks_by_as.add_argument("--output-format",
173 choices=self.output_formats.keys(), default="list")
43154ed7
MT
174 list_networks_by_as.set_defaults(func=self.handle_list_networks_by_as)
175
ccc7ab4e 176 # List all networks in a country
b5cdfad7 177 list_networks_by_cc = subparsers.add_parser("list-networks-by-cc",
ccc7ab4e
MT
178 help=_("Lists all networks in a country"),
179 )
b5cdfad7 180 list_networks_by_cc.add_argument("country_code", nargs=1)
4439e317
MT
181 list_networks_by_cc.add_argument("--output-format",
182 choices=self.output_formats.keys(), default="list")
b5cdfad7 183 list_networks_by_cc.set_defaults(func=self.handle_list_networks_by_cc)
ccc7ab4e 184
bbdb2e0a
MT
185 # List all networks with flags
186 list_networks_by_flags = subparsers.add_parser("list-networks-by-flags",
187 help=_("Lists all networks with flags"),
188 )
189 list_networks_by_flags.add_argument("--anonymous-proxy",
190 action="store_true", help=_("Anonymous Proxies"),
191 )
192 list_networks_by_flags.add_argument("--satellite-provider",
193 action="store_true", help=_("Satellite Providers"),
194 )
195 list_networks_by_flags.add_argument("--anycast",
196 action="store_true", help=_("Anycasts"),
197 )
198 list_networks_by_flags.add_argument("--output-format",
199 choices=self.output_formats.keys(), default="list")
200 list_networks_by_flags.set_defaults(func=self.handle_list_networks_by_flags)
201
78f37815
MT
202 args = parser.parse_args()
203
204 # Print usage if no action was given
205 if not "func" in args:
206 parser.print_usage()
207 sys.exit(2)
208
209 return args
5118a4b8
MT
210
211 def run(self):
212 # Parse command line arguments
213 args = self.parse_cli()
214
2538ed9a
MT
215 # Open database
216 try:
217 db = location.Database(args.database)
218 except FileNotFoundError as e:
219 sys.stderr.write("location-query: Could not open database %s: %s\n" \
220 % (args.database, e))
221 sys.exit(1)
222
b1720435 223 # Verify the database
726f9984
MT
224 try:
225 with open(args.public_key, "r") as f:
226 if not db.verify(f):
227 sys.stderr.write("location-query: Could not verify the database\n")
228 sys.exit(1)
229
230 # Catch any errors when loading the public key
231 except (FileNotFoundError, OSError) as e:
232 sys.stderr.write("Could not read the public key: %s\n" % e)
b1720435
MT
233 sys.exit(1)
234
5118a4b8 235 # Call function
2538ed9a 236 ret = args.func(db, args)
5118a4b8
MT
237
238 # Return with exit code
239 if ret:
240 sys.exit(ret)
241
242 # Otherwise just exit
243 sys.exit(0)
244
2538ed9a 245 def handle_lookup(self, db, ns):
5118a4b8
MT
246 ret = 0
247
248 for address in ns.address:
249 try:
2538ed9a 250 n = db.lookup(address)
5118a4b8 251 except ValueError:
9f2f5d13 252 print(_("Invalid IP address: %s") % address, file=sys.stderr)
5118a4b8
MT
253
254 args = {
255 "address" : address,
256 "network" : n,
257 }
258
259 # Nothing found?
260 if not n:
9f2f5d13 261 print(_("Nothing found for %(address)s") % args, file=sys.stderr)
5118a4b8
MT
262 ret = 1
263 continue
264
265 # Try to retrieve the AS if we have an AS number
266 if n.asn:
2538ed9a 267 a = db.get_as(n.asn)
5118a4b8
MT
268
269 # If we have found an AS we will print it in the message
270 if a:
271 args.update({
272 "as" : a,
273 })
274
275 print(_("%(address)s belongs to %(network)s which is a part of %(as)s") % args)
276 continue
277
278 print(_("%(address)s belongs to %(network)s") % args)
279
280 return ret
281
2538ed9a 282 def handle_get_as(self, db, ns):
fadc1af0
MT
283 """
284 Gets information about Autonomous Systems
285 """
286 ret = 0
287
288 for asn in ns.asn:
289 try:
290 asn = int(asn)
291 except ValueError:
9f2f5d13 292 print(_("Invalid ASN: %s") % asn, file=sys.stderr)
fadc1af0
MT
293 ret = 1
294 continue
295
296 # Fetch AS from database
2538ed9a 297 a = db.get_as(asn)
fadc1af0
MT
298
299 # Nothing found
300 if not a:
9f2f5d13 301 print(_("Could not find AS%s") % asn, file=sys.stderr)
fadc1af0
MT
302 ret = 1
303 continue
304
305 print(_("AS%(asn)s belongs to %(name)s") % { "asn" : a.number, "name" : a.name })
306
307 return ret
5118a4b8 308
2538ed9a 309 def handle_search_as(self, db, ns):
da3e360e
MT
310 for query in ns.query:
311 # Print all matches ASes
2538ed9a 312 for a in db.search_as(query):
da3e360e
MT
313 print(a)
314
4439e317
MT
315 def __get_output_formatter(self, ns):
316 try:
317 cls = self.output_formats[ns.output_format]
318 except KeyError:
319 cls = OutputFormatter
320
71e0ad0b 321 return cls(ns)
4439e317 322
43154ed7 323 def handle_list_networks_by_as(self, db, ns):
4439e317
MT
324 with self.__get_output_formatter(ns) as f:
325 for asn in ns.asn:
326 # Print all matching networks
327 for n in db.search_networks(asn=asn):
328 f.network(n)
43154ed7 329
ccc7ab4e 330 def handle_list_networks_by_cc(self, db, ns):
4439e317
MT
331 with self.__get_output_formatter(ns) as f:
332 for country_code in ns.country_code:
333 # Print all matching networks
334 for n in db.search_networks(country_code=country_code):
335 f.network(n)
336
bbdb2e0a
MT
337 def handle_list_networks_by_flags(self, db, ns):
338 flags = 0
339
340 if ns.anonymous_proxy:
341 flags |= location.NETWORK_FLAG_ANONYMOUS_PROXY
342
343 if ns.satellite_provider:
344 flags |= location.NETWORK_FLAG_SATELLITE_PROVIDER
345
346 if ns.anycast:
347 flags |= location.NETWORK_FLAG_ANYCAST
348
349 with self.__get_output_formatter(ns) as f:
350 for n in db.search_networks(flags=flags):
351 f.network(n)
352
ccc7ab4e 353
5118a4b8
MT
354def main():
355 # Run the command line interface
356 c = CLI()
357 c.run()
358
359main()