Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/source/api/msticpy.context.tiproviders.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ Submodules
msticpy.context.tiproviders.ti_provider_base
msticpy.context.tiproviders.tor_exit_nodes
msticpy.context.tiproviders.virustotal
msticpy.context.tiproviders.vpndetection
7 changes: 7 additions & 0 deletions docs/source/api/msticpy.context.tiproviders.vpndetection.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
msticpy.context.tiproviders.vpndetection module
===============================================

.. automodule:: msticpy.context.tiproviders.vpndetection
:members:
:show-inheritance:
:undoc-members:
7 changes: 6 additions & 1 deletion docs/source/data_acquisition/TIProviders.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Features
- **CrowdSec**
- **AbuseIPDB**
- **ScanMalware**
- **VPNDetection**

- Other pseudo-TI providers are also included:

Expand Down Expand Up @@ -286,6 +287,9 @@ fictitious - the format of the keys may differ from what is shown
ScanMalware:
Primary: True
Provider: "ScanMalware"
VPNDetection:
Primary: True
Provider: "VPNDetection"

You need to tell `TILookup` to refresh its configuration.

Expand All @@ -307,7 +311,8 @@ of providers loaded.
'AzSTI - Microsoft Sentinel TI provider class. (primary)',
'CrowdSec - CrowdSec CTI Smoke Lookup. (primary)',
'AbuseIPDB - AbuseIPDB Lookup. (primary)',
'ScanMalware - ScanMalware Lookup. (primary)']
'ScanMalware - ScanMalware Lookup. (primary)',
'VPNDetection - VPNDetection Lookup. (primary)']

.. warning:: Depending on the type of account that you
have with a provider, they will typically impose a limit
Expand Down
4 changes: 4 additions & 0 deletions docs/source/getting_started/msticpyconfig.rst
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ Currently supported provider names are:
- CrowdSec
- AbuseIPDB
- ScanMalware
- VPNDetection

.. code:: yaml

Expand Down Expand Up @@ -152,6 +153,9 @@ Currently supported provider names are:
ScanMalware:
Primary: True
Provider: "ScanMalware"
VPNDetection:
Primary: True
Provider: "VPNDetection"

.. note:: You store values in the ``Args`` section as simple strings,
as names of environment variables containing the value, or
Expand Down
1 change: 1 addition & 0 deletions msticpy/context/tiproviders/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@
"BinaryEdge": ("binaryedge", "BinaryEdge"),
"Cyberint": ("cyberint", "Cyberint"),
"ScanMalware": ("scanmalware", "ScanMalware"),
"VPNDetection": ("vpndetection", "VPNDetection"),
}
113 changes: 113 additions & 0 deletions msticpy/context/tiproviders/vpndetection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
VPNDetection Provider.

Flags whether an IP address is a VPN, Tor exit or relay (iCloud Private Relay and
similar), with its country and ASN. The API answers without a key; a key adds the
proxy and hosting flags and the VPN's provider on paid plans.
https://vpndetection.io/
"""

from __future__ import annotations

from typing import Any, ClassVar

from typing_extensions import Self

from ..._version import VERSION
from ..http_provider import APILookupParams
from .ti_http_provider import HttpTIProvider
from .ti_provider_base import ResultSeverity

__version__ = VERSION
__author__ = "Uman Shahzad"

_ANONYMIZER_FLAGS = (
"is_vpn",
"is_tor",
"is_relay",
"is_resproxy",
"is_dcproxy",
"is_mobproxy",
"is_pubproxy",
)


class VPNDetection(HttpTIProvider):
"""VPNDetection Lookup."""

_BASE_URL: ClassVar[str] = "https://api.vpndetection.io"

_QUERIES: ClassVar[dict[str, APILookupParams]] = {
"ipv4": APILookupParams(
path="/{observable}",
headers={"Authorization": "Bearer {AuthKey}"},
),
"ipv6": APILookupParams(
path="/{observable}",
headers={"Authorization": "Bearer {AuthKey}"},
),
}

def _substitute_parms(
self: Self,
value: str,
value_type: str,
query_type: str | None = None,
) -> tuple[str, dict[str, Any]]:
"""Drop the Authorization header when no AuthKey is configured."""
verb, req_dict = super()._substitute_parms(value, value_type, query_type)
if not self._request_params.get("AuthKey"):
req_dict["headers"].pop("Authorization", None)
return verb, req_dict

def parse_results(self: Self, response: dict) -> tuple[bool, ResultSeverity, Any]:
"""
Return the details of the response.

Parameters
----------
response : Dict
The returned data response

Returns
-------
Tuple[bool, ResultSeverity, Any]
bool = positive or negative hit
ResultSeverity = enumeration of severity
Object with match details

"""
if self._failed_response(response) or not isinstance(
response["RawResult"],
dict,
):
return False, ResultSeverity.information, "Not found."
raw: dict[str, Any] = response["RawResult"]
vpn: dict[str, Any] = raw.get("vpn") or {}
location: dict[str, Any] = raw.get("location") or {}
asn: dict[str, Any] = raw.get("asn") or {}
result_dict: dict[str, Any] = {
"IsVPN": raw.get("is_vpn"),
"VPNProvider": vpn.get("provider_name") or vpn.get("provider"),
"IsTor": raw.get("is_tor"),
"IsRelay": raw.get("is_relay"),
"IsHosting": raw.get("is_hosting"),
"IsResidentialProxy": raw.get("is_resproxy"),
"IsDatacenterProxy": raw.get("is_dcproxy"),
"IsMobileProxy": raw.get("is_mobproxy"),
"IsPublicProxy": raw.get("is_pubproxy"),
"IsBogon": raw.get("is_bogon"),
"CountryOrRegion": location.get("country"),
"ASN": asn.get("asn"),
"ASNName": asn.get("name"),
"ASNType": asn.get("type"),
}
severity = ResultSeverity.information
if any(raw.get(flag) for flag in _ANONYMIZER_FLAGS):
severity = ResultSeverity.warning
return True, severity, result_dict
6 changes: 6 additions & 0 deletions msticpy/resources/mpconfig_defaults.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ TIProviders:
ScanMalware:
Primary: bool(default=True)
Provider: "ScanMalware"
VPNDetection:
Args:
# Leave AuthKey empty to use the API without a key, or set one for the proxy and hosting flags.
AuthKey: *cred_key
Primary: bool(default=False)
Provider: "VPNDetection"
RiskIQ:
Primary: bool(default=True)
Provider: "RiskIQ"
Expand Down
53 changes: 53 additions & 0 deletions tests/context/test_tiproviders.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ class TiTestCase:
TiTestCase("IPQualityScore", exp_responses=20),
TiTestCase("BinaryEdge"),
TiTestCase("ScanMalware"),
TiTestCase("VPNDetection"),
]


Expand Down Expand Up @@ -257,6 +258,7 @@ def verify_result(result, ti_lookup):
"IPQualityScore",
"BinaryEdge",
"ScanMalware",
"VPNDetection",
],
)
check.is_not_none(lu_result["Ioc"])
Expand All @@ -279,6 +281,37 @@ def verify_result(result, ti_lookup):
check.is_instance(result_df, pd.DataFrame)


def test_vpndetection_auth_header(ti_lookup):
"""Test VPNDetection sends a key only when one is configured."""
ti_provider = ti_lookup.loaded_providers["VPNDetection"]
_, req = ti_provider._substitute_parms("146.70.116.130", "ipv4")
check.equal(req["url"], "https://api.vpndetection.io/146.70.116.130")
check.is_not_in("Authorization", req["headers"])

ti_provider._request_params["AuthKey"] = "test-key"
try:
_, req = ti_provider._substitute_parms("2001:db8::1", "ipv6")
finally:
ti_provider._request_params["AuthKey"] = None
check.equal(req["headers"]["Authorization"], "Bearer test-key")


def test_vpndetection_parse_results(ti_lookup):
"""Test VPNDetection flags an anonymizer as a warning."""
ti_provider = ti_lookup.loaded_providers["VPNDetection"]
raw = _PROVIDER_RESPONSES["https://api.vpndetection.io"]["response"]
result, severity, details = ti_provider.parse_results({"Status": 200, "RawResult": raw})
check.is_true(result)
check.equal(severity, ResultSeverity.warning)
check.is_true(details["IsVPN"])
check.equal(details["ASN"], 9009)
check.equal(details["CountryOrRegion"], "AT")

clean = {**raw, "is_vpn": False}
_, severity, _ = ti_provider.parse_results({"Status": 200, "RawResult": clean})
check.equal(severity, ResultSeverity.information)


@pytest.mark.filterwarnings("ignore::UserWarning")
def test_ti_config_and_load(ti_lookup):
"""Test loading TI providers."""
Expand Down Expand Up @@ -776,6 +809,26 @@ def _scanmalware_scans(**kwargs):
"message": "Success",
},
},
"https://api.vpndetection.io": {
"ioc_param": "url",
"response": {
"ip": "146.70.116.130",
"is_bogon": False,
"is_vpn": True,
"is_relay": False,
"is_tor": False,
"relay": {},
"tor": {},
"location": {"country": "AT", "country_name": "Austria"},
"asn": {
"asn": 9009,
"name": "M247 Europe SRL",
"domain": "m247global.com",
"type": "hosting",
"prefix": "146.70.116.0/24",
},
},
},
"https://www.ipqualityscore.com": {
"ioc_param": "ipv4",
"response": {
Expand Down
3 changes: 3 additions & 0 deletions tests/msticpyconfig-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ TIProviders:
ScanMalware:
Primary: True
Provider: "ScanMalware"
VPNDetection:
Primary: True
Provider: "VPNDetection"
OpenPageRank:
Args:
AuthKey:
Expand Down
3 changes: 3 additions & 0 deletions tests/testdata/msticpyconfig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ TIProviders:
ScanMalware:
Primary: True
Provider: "ScanMalware"
VPNDetection:
Primary: True
Provider: "VPNDetection"
AzureSentinel:
Args:
WorkspaceID: "a927809c-8142-43e1-96b3-4ad87cfe95a3"
Expand Down