1use std::{fs, net::IpAddr, path::PathBuf, sync::Arc, time::SystemTime};
8
9use maxminddb::{
10 Reader,
11 geoip2::{AnonymousIp, City, ConnectionType, Isp, Names},
12};
13use ordered_float::NotNan;
14use serde::Deserialize;
15use vector_lib::{
16 configurable::configurable_component,
17 enrichment::{Case, Condition, Error, IndexHandle, Table},
18};
19use vrl::value::{ObjectMap, Value};
20
21use crate::config::{EnrichmentTableConfig, GenerateConfig};
22
23#[derive(Copy, Clone, Debug)]
26#[allow(missing_docs)]
27pub enum DatabaseKind {
28 Asn,
29 Isp,
30 ConnectionType,
31 City,
32 AnonymousIp,
33}
34
35impl TryFrom<&str> for DatabaseKind {
36 type Error = ();
37
38 fn try_from(value: &str) -> Result<Self, Self::Error> {
39 match value {
40 "GeoLite2-ASN" => Ok(Self::Asn),
41 "GeoIP2-ISP" => Ok(Self::Isp),
42 "GeoIP2-Connection-Type" => Ok(Self::ConnectionType),
43 "GeoIP2-City" | "GeoLite2-City" => Ok(Self::City),
44 "GeoIP2-Anonymous-IP" => Ok(Self::AnonymousIp),
45 _ => Err(()),
46 }
47 }
48}
49
50#[derive(Clone, Debug, Eq, PartialEq)]
52#[configurable_component(enrichment_table("geoip"))]
53pub struct GeoipConfig {
54 pub path: PathBuf,
63
64 #[serde(default = "default_locale")]
75 pub locale: String,
76}
77
78fn default_locale() -> String {
79 "en".to_string()
88}
89
90impl GenerateConfig for GeoipConfig {
91 fn generate_config() -> toml::Value {
92 toml::Value::try_from(Self {
93 path: "/path/to/GeoLite2-City.mmdb".into(),
94 locale: default_locale(),
95 })
96 .unwrap()
97 }
98}
99
100impl EnrichmentTableConfig for GeoipConfig {
101 async fn build(
102 &self,
103 _: &crate::config::GlobalOptions,
104 ) -> crate::Result<Box<dyn Table + Send + Sync>> {
105 Ok(Box::new(Geoip::new(self.clone())?))
106 }
107}
108
109#[derive(Clone)]
110pub struct Geoip {
112 config: GeoipConfig,
113 dbreader: Arc<maxminddb::Reader<Vec<u8>>>,
114 dbkind: DatabaseKind,
115 last_modified: SystemTime,
116}
117
118fn lookup_value<'de, A: Deserialize<'de>>(
119 dbreader: &'de Reader<Vec<u8>>,
120 address: IpAddr,
121) -> crate::Result<Option<(A, String)>> {
122 let result = dbreader.lookup(address)?;
123 match result.decode::<A>()? {
124 Some(data) => {
125 let network = result.network()?.to_string();
126 Ok(Some((data, network)))
127 }
128 None => Ok(None),
129 }
130}
131
132impl Geoip {
133 pub fn new(config: GeoipConfig) -> crate::Result<Self> {
135 let dbreader = Arc::new(Reader::open_readfile(&config.path)?);
136 let dbkind =
137 DatabaseKind::try_from(dbreader.metadata.database_type.as_str()).map_err(|_| {
138 format!(
139 "Unsupported MMDB database type ({}). Use `mmdb` enrichment table instead.",
140 dbreader.metadata.database_type
141 )
142 })?;
143
144 let ip = IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED);
146 match dbkind {
147 DatabaseKind::Asn | DatabaseKind::Isp => lookup_value::<Isp>(&dbreader, ip).map(|_| ()),
149 DatabaseKind::ConnectionType => {
150 lookup_value::<ConnectionType>(&dbreader, ip).map(|_| ())
151 }
152 DatabaseKind::City => lookup_value::<City>(&dbreader, ip).map(|_| ()),
153 DatabaseKind::AnonymousIp => lookup_value::<AnonymousIp>(&dbreader, ip).map(|_| ()),
154 }?;
155
156 Ok(Geoip {
157 last_modified: fs::metadata(&config.path)?.modified()?,
158 dbreader,
159 dbkind,
160 config,
161 })
162 }
163
164 fn lookup(&self, ip: IpAddr, select: Option<&[String]>) -> Option<ObjectMap> {
165 let mut map = ObjectMap::new();
166 let mut add_field = |key: &str, value: Option<Value>| {
167 if select
168 .map(|fields| fields.iter().any(|field| field == key))
169 .unwrap_or(true)
170 {
171 map.insert(key.into(), value.unwrap_or(Value::Null));
172 }
173 };
174
175 macro_rules! add_field {
176 ($k:expr_2021, $v:expr_2021) => {
177 add_field($k, $v.map(Into::into))
178 };
179 }
180
181 match self.dbkind {
182 DatabaseKind::Asn | DatabaseKind::Isp => {
183 let (data, network) = lookup_value::<Isp>(&self.dbreader, ip).ok()??;
184
185 add_field!("autonomous_system_number", data.autonomous_system_number);
186 add_field!(
187 "autonomous_system_organization",
188 data.autonomous_system_organization
189 );
190 add_field!("isp", data.isp);
191 add_field!("organization", data.organization);
192 add_field!("network", Some(network));
193 }
194 DatabaseKind::City => {
195 let (data, network): (City, String) =
196 lookup_value::<City>(&self.dbreader, ip).ok()??;
197
198 add_field!("city_name", self.take_translation(&data.city.names));
199
200 add_field!("continent_code", data.continent.code);
201
202 let country = data.country;
203 add_field!("country_code", country.iso_code);
204 add_field!("country_name", self.take_translation(&country.names));
205
206 let location = data.location;
207 add_field!("timezone", location.time_zone);
208 add_field!(
209 "latitude",
210 location.latitude.map(|latitude| Value::Float(
211 NotNan::new(latitude).expect("latitude cannot be Nan")
212 ))
213 );
214 add_field!(
215 "longitude",
216 location
217 .longitude
218 .map(|longitude| NotNan::new(longitude).expect("longitude cannot be Nan"))
219 );
220 add_field!("metro_code", location.metro_code);
221
222 let subdivision = data.subdivisions.last();
224 add_field!(
225 "region_name",
226 subdivision.map(|s| self.take_translation(&s.names))
227 );
228
229 add_field!(
230 "region_code",
231 subdivision.and_then(|subdivision| subdivision.iso_code)
232 );
233 add_field!("postal_code", data.postal.code);
234 add_field!("network", Some(network));
235 }
236 DatabaseKind::ConnectionType => {
237 let (data, network) = lookup_value::<ConnectionType>(&self.dbreader, ip).ok()??;
238
239 add_field!("connection_type", data.connection_type);
240 add_field!("network", Some(network));
241 }
242 DatabaseKind::AnonymousIp => {
243 let (data, network) = lookup_value::<AnonymousIp>(&self.dbreader, ip).ok()??;
244
245 add_field!("is_anonymous", data.is_anonymous);
246 add_field!("is_anonymous_vpn", data.is_anonymous_vpn);
247 add_field!("is_hosting_provider", data.is_hosting_provider);
248 add_field!("is_public_proxy", data.is_public_proxy);
249 add_field!("is_residential_proxy", data.is_residential_proxy);
250 add_field!("is_tor_exit_node", data.is_tor_exit_node);
251 add_field!("network", Some(network));
252 }
253 }
254
255 Some(map)
256 }
257
258 fn take_translation<'a>(&self, translations: &'a Names<'a>) -> Option<&'a str> {
259 match self.config.locale.as_ref() {
260 "en" => translations.english,
261 "de" => translations.german,
262 "es" => translations.spanish,
263 "fr" => translations.french,
264 "ja" => translations.japanese,
265 "pt-BR" => translations.brazilian_portuguese,
266 "ru" => translations.russian,
267 "zh-CN" => translations.simplified_chinese,
268 _ => None,
269 }
270 }
271}
272
273impl Table for Geoip {
274 fn find_table_row<'a>(
280 &self,
281 case: Case,
282 condition: &'a [Condition<'a>],
283 select: Option<&[String]>,
284 wildcard: Option<&Value>,
285 index: Option<IndexHandle>,
286 ) -> Result<ObjectMap, Error> {
287 let mut rows = self.find_table_rows(case, condition, select, wildcard, index)?;
288
289 match rows.pop() {
290 Some(row) if rows.is_empty() => Ok(row),
291 Some(_) => Err(Error::MoreThanOneRowFound),
292 None => Err(Error::NoRowsFound),
293 }
294 }
295
296 fn find_table_rows<'a>(
300 &self,
301 _: Case,
302 condition: &'a [Condition<'a>],
303 select: Option<&[String]>,
304 _wildcard: Option<&Value>,
305 _: Option<IndexHandle>,
306 ) -> Result<Vec<ObjectMap>, Error> {
307 match condition.first() {
308 Some(_) if condition.len() > 1 => Err(Error::OnlyOneConditionAllowed),
309 Some(Condition::Equals { value, .. }) => {
310 let ip = value
311 .to_string_lossy()
312 .parse::<IpAddr>()
313 .map_err(|source| Error::InvalidAddress { source })?;
314 Ok(self
315 .lookup(ip, select)
316 .map(|values| vec![values])
317 .unwrap_or_default())
318 }
319 Some(_) => Err(Error::OnlyEqualityConditionAllowed),
320 None => Err(Error::MissingCondition { kind: "IP" }),
321 }
322 }
323
324 fn add_index(&mut self, _: Case, fields: &[&str]) -> Result<IndexHandle, Error> {
330 match fields.len() {
331 0 => Err(Error::MissingRequiredField { field: "IP" }),
332 1 => Ok(IndexHandle(0)),
333 _ => Err(Error::OnlyOneFieldAllowed),
334 }
335 }
336
337 fn index_fields(&self) -> Vec<(Case, Vec<String>)> {
339 Vec::new()
340 }
341
342 fn needs_reload(&self) -> bool {
344 matches!(fs::metadata(&self.config.path)
345 .and_then(|metadata| metadata.modified()),
346 Ok(modified) if modified > self.last_modified)
347 }
348}
349
350impl std::fmt::Debug for Geoip {
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 write!(
353 f,
354 "Geoip {} database {})",
355 self.config.locale,
356 self.config.path.display()
357 )
358 }
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 #[test]
366 fn city_lookup() {
367 let values = find("2.125.160.216", "tests/data/GeoIP2-City-Test.mmdb").unwrap();
368
369 let mut expected = ObjectMap::new();
370 expected.insert("city_name".into(), "Boxford".into());
371 expected.insert("country_code".into(), "GB".into());
372 expected.insert("continent_code".into(), "EU".into());
373 expected.insert("country_name".into(), "United Kingdom".into());
374 expected.insert("region_code".into(), "WBK".into());
375 expected.insert("region_name".into(), "West Berkshire".into());
376 expected.insert("timezone".into(), "Europe/London".into());
377 expected.insert("latitude".into(), Value::from(51.75));
378 expected.insert("longitude".into(), Value::from(-1.25));
379 expected.insert("postal_code".into(), "OX1".into());
380 expected.insert("metro_code".into(), Value::Null);
381 expected.insert("network".into(), "2.125.160.216/29".into());
382
383 assert_eq!(values, expected);
384 }
385
386 #[test]
387 fn city_partial_lookup() {
388 let values = find_select(
389 "2.125.160.216",
390 "tests/data/GeoIP2-City-Test.mmdb",
391 Some(&["latitude".to_string(), "longitude".to_string()]),
392 )
393 .unwrap();
394
395 let mut expected = ObjectMap::new();
396 expected.insert("latitude".into(), Value::from(51.75));
397 expected.insert("longitude".into(), Value::from(-1.25));
398
399 assert_eq!(values, expected);
400 }
401
402 #[test]
403 fn city_lookup_partial_results() {
404 let values = find("67.43.156.9", "tests/data/GeoIP2-City-Test.mmdb").unwrap();
405
406 let mut expected = ObjectMap::new();
407 expected.insert("city_name".into(), Value::Null);
408 expected.insert("country_code".into(), "BT".into());
409 expected.insert("country_name".into(), "Bhutan".into());
410 expected.insert("continent_code".into(), "AS".into());
411 expected.insert("region_code".into(), Value::Null);
412 expected.insert("region_name".into(), Value::Null);
413 expected.insert("timezone".into(), "Asia/Thimphu".into());
414 expected.insert("latitude".into(), Value::from(27.5));
415 expected.insert("longitude".into(), Value::from(90.5));
416 expected.insert("postal_code".into(), Value::Null);
417 expected.insert("metro_code".into(), Value::Null);
418 expected.insert("network".into(), "67.43.156.0/24".into());
419
420 assert_eq!(values, expected);
421 }
422
423 #[test]
424 fn city_lookup_no_results() {
425 let values = find("10.1.12.1", "tests/data/GeoIP2-City-Test.mmdb");
426
427 assert!(values.is_none());
428 }
429
430 #[test]
431 fn isp_lookup() {
432 let values = find("208.192.1.2", "tests/data/GeoIP2-ISP-Test.mmdb").unwrap();
433
434 let mut expected = ObjectMap::new();
435 expected.insert("autonomous_system_number".into(), 701i64.into());
436 expected.insert(
437 "autonomous_system_organization".into(),
438 "MCI Communications Services, Inc. d/b/a Verizon Business".into(),
439 );
440 expected.insert("isp".into(), "Verizon Business".into());
441 expected.insert("organization".into(), "Verizon Business".into());
442 expected.insert("network".into(), "208.192.0.0/10".into());
443
444 assert_eq!(values, expected);
445 }
446
447 #[test]
448 fn isp_lookup_partial_results() {
449 let values = find("2600:7000::1", "tests/data/GeoLite2-ASN-Test.mmdb").unwrap();
450
451 let mut expected = ObjectMap::new();
452 expected.insert("autonomous_system_number".into(), 6939i64.into());
453 expected.insert(
454 "autonomous_system_organization".into(),
455 "Hurricane Electric, Inc.".into(),
456 );
457 expected.insert("isp".into(), Value::Null);
458 expected.insert("organization".into(), Value::Null);
459 expected.insert("network".into(), "2600:7000::/24".into());
460
461 assert_eq!(values, expected);
462 }
463
464 #[test]
465 fn isp_lookup_no_results() {
466 let values = find("10.1.12.1", "tests/data/GeoLite2-ASN-Test.mmdb");
467
468 assert!(values.is_none());
469 }
470
471 #[test]
472 fn connection_type_lookup_success() {
473 let values = find(
474 "201.243.200.1",
475 "tests/data/GeoIP2-Connection-Type-Test.mmdb",
476 )
477 .unwrap();
478
479 let mut expected = ObjectMap::new();
480 expected.insert("connection_type".into(), "Corporate".into());
481 expected.insert("network".into(), "201.243.200.0/24".into());
482
483 assert_eq!(values, expected);
484 }
485
486 #[test]
487 fn connection_type_lookup_missing() {
488 let values = find("10.1.12.1", "tests/data/GeoIP2-Connection-Type-Test.mmdb");
489
490 assert!(values.is_none());
491 }
492
493 #[test]
494 fn custom_mmdb_type_error() {
495 let result = Geoip::new(GeoipConfig {
496 path: "tests/data/custom-type.mmdb".into(),
497 locale: default_locale(),
498 });
499
500 assert!(result.is_err());
501 }
502 #[test]
503 fn anonymous_ip_lookup() {
504 let values = find("101.99.92.179", "tests/data/GeoIP2-Anonymous-IP-Test.mmdb").unwrap();
505
506 let mut expected = ObjectMap::new();
507 expected.insert("is_anonymous".into(), true.into());
508 expected.insert("is_anonymous_vpn".into(), true.into());
509 expected.insert("is_hosting_provider".into(), true.into());
510 expected.insert("is_tor_exit_node".into(), true.into());
511 expected.insert("is_public_proxy".into(), Value::Null);
512 expected.insert("is_residential_proxy".into(), Value::Null);
513 expected.insert("network".into(), "101.99.92.179/32".into());
514
515 assert_eq!(values, expected);
516 }
517
518 #[test]
519 fn anonymous_ip_lookup_no_results() {
520 let values = find("10.1.12.1", "tests/data/GeoIP2-Anonymous-IP-Test.mmdb");
521
522 assert!(values.is_none());
523 }
524
525 fn find(ip: &str, database: &str) -> Option<ObjectMap> {
526 find_select(ip, database, None)
527 }
528
529 fn find_select(ip: &str, database: &str, select: Option<&[String]>) -> Option<ObjectMap> {
530 Geoip::new(GeoipConfig {
531 path: database.into(),
532 locale: default_locale(),
533 })
534 .unwrap()
535 .find_table_rows(
536 Case::Insensitive,
537 &[Condition::Equals {
538 field: "ip",
539 value: ip.into(),
540 }],
541 select,
542 None,
543 None,
544 )
545 .unwrap()
546 .pop()
547 }
548}