✨ New util API command: address

Allows to test a provided or the client's address whether it is a LAN
address, and if so returns the subnet address in CIDR notation.
This commit is contained in:
Gina Häußge committed 2020-11-16 17:55:49 +01:00
1 parent c44e90302d
commit 89f3edcb27
4 files changed
+206 -59

No files matched your search

+90 -2
View File
@@ -6,8 +6,8 @@ Util
.. _sec-api-util-test:
Test paths or URLs
==================
Various tests
=============
.. http:post:: /api/util/test
@@ -107,6 +107,15 @@ Test paths or URLs
The ``resolution`` command returns :http:statuscode:`200` with a :ref:`Resolution test result <sec-api-util-datamodel-resolutiontestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
address
Tests whether a provided address (or, if none is provided, the client's remote address) is
a LAN address and if so returns the subnet specifier in CIDR format.
* ``address``: the address to test. If not set, the client's remote address will be used
The ``address`` command return :http:statuscode:`200` with a :ref:`Address test result <sec-api-util-datamodel-addresstestresult>`
when the test could be performed. The status code of the response does NOT reflect the test result!
Requires the ``ADMIN`` permission.
**Example 1**
@@ -320,6 +329,58 @@ Test paths or URLs
"result": true
}
**Example 8**
Test whether the client's address is a LAN address.
.. sourcecode:: http
POST /api/util/test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"command": "address"
}
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"address": "192.168.1.3",
"is_lan_address": true,
"subnet": "192.168.0.0/16"
}
**Example 9**
Test whether ``8.8.8.8`` is a LAN address.
.. sourcecode:: http
POST /api/util/test HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
Content-Type: application/json
{
"command": "address",
"address": "8.8.8.8"
}
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"address": "8.8.8.8",
"is_lan_address": false
}
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
@@ -337,6 +398,7 @@ Test paths or URLs
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:json name: ``resolution`` command only: the host name to test
:json address: ``address`` command only: the address to test
:statuscode 200: No error occurred
.. _sec-api-util-datamodel:
@@ -466,3 +528,29 @@ Resolution test result
- 1
- bool
- ``true`` if the check passed.
.. _sec-api-util-datamodel-addresstestresult:
Address test result
-------------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``address``
- 1
- string
- The address that was tested.
* - ``is_lan_address``
- 1
- bool
- ``true`` if the address is a LAN address, false otherwise.
* - ``subnet``
- 0..1
- string
- The detected subnet, if address is a LAN address.
+34
View File
@@ -398,6 +398,7 @@ def utilTest():
"url": ["url"],
"server": ["host", "port"],
"resolution": ["name"],
"address": [],
}
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -412,6 +413,8 @@ def utilTest():
return _test_server(data)
elif command == "resolution":
return _test_resolution(data)
elif command == "address":
return _test_address(data)
def _test_path(data):
@@ -743,3 +746,34 @@ def _test_resolution(data):
result = {"name": name, "result": resolvable}
return jsonify(**result)
def _test_address(data):
import netaddr
from octoprint.util.net import get_lan_ranges, sanitize_address
remote_addr = data.get("address")
if not remote_addr:
remote_addr = get_remote_address(request)
remote_addr = sanitize_address(remote_addr)
ip = netaddr.IPAddress(remote_addr)
lan_subnets = get_lan_ranges()
detected_subnet = None
for subnet in lan_subnets:
if ip in subnet:
detected_subnet = subnet
break
result = {
"is_lan_address": detected_subnet is not None,
"address": remote_addr,
}
if detected_subnet is not None:
result["subnet"] = str(detected_subnet)
return jsonify(**result)
@@ -64,6 +64,15 @@
return this.test("resolution", data, opts);
};
OctoPrintUtilClient.prototype.testAddress = function (address, additional, opts) {
additional = additional || {};
var data = $.extend({}, additional);
data.address = address;
return this.test("address", data, opts);
};
OctoPrintClient.registerComponent("util", OctoPrintUtilClient);
return OctoPrintUtilClient;
});
+73 -57
View File
@@ -53,71 +53,81 @@ else:
HAS_V6 = False
def get_lan_ranges(additional_private=None):
logger = logging.getLogger(__name__)
if additional_private is None or not isinstance(additional_private, (list, tuple)):
additional_private = []
subnets = list(netaddr.ip.IPV4_PRIVATE) + [
netaddr.ip.IPV4_LOOPBACK,
netaddr.ip.IPV4_LINK_LOCAL,
]
if HAS_V6:
subnets += list(netaddr.ip.IPV6_PRIVATE) + [
netaddr.IPNetwork(netaddr.ip.IPV6_LOOPBACK),
netaddr.ip.IPV6_LINK_LOCAL,
]
for additional in additional_private:
try:
subnets.append(netaddr.IPNetwork(additional))
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception(
"Error while trying to add additional private network to local subnets: {}".format(
additional
)
)
def to_ipnetwork(address):
prefix = address["netmask"]
if "/" in prefix:
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
_, prefix = prefix.split("/")
addr = strip_interface_tag(address["addr"])
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for v4 in addrs.get(socket.AF_INET, ()):
try:
subnets.append(to_ipnetwork(v4))
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception(
"Error while trying to add v4 network to local subnets: {!r}".format(
v4
)
)
if HAS_V6:
for v6 in addrs.get(socket.AF_INET6, ()):
try:
subnets.append(to_ipnetwork(v6))
except Exception:
if logger.isEnabledFor(logging.DEBUG):
logger.exception(
"Error while trying to add v6 network to local subnets: {!r}".format(
v6
)
)
return subnets
def is_lan_address(address, additional_private=None):
if not address:
# no address is LAN address
return True
try:
address = unmap_v4_as_v6(address)
address = strip_interface_tag(address)
address = sanitize_address(address)
ip = netaddr.IPAddress(address)
if ip.is_private() or ip.is_loopback():
return True
subnets = get_lan_ranges(additional_private=additional_private)
if additional_private is None or not isinstance(
additional_private, (list, tuple)
):
additional_private = []
subnets = netaddr.IPSet()
for additional in additional_private:
try:
subnets.add(netaddr.IPNetwork(additional))
except Exception:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception(
"Error while trying to add additional private network to local subnets: {}".format(
additional
)
)
def to_ipnetwork(address):
prefix = address["netmask"]
if "/" in prefix:
# v6 notation in netifaces output, e.g. "ffff:ffff:ffff:ffff::/64"
_, prefix = prefix.split("/")
addr = strip_interface_tag(address["addr"])
return netaddr.IPNetwork("{}/{}".format(addr, prefix))
for interface in netifaces.interfaces():
addrs = netifaces.ifaddresses(interface)
for v4 in addrs.get(socket.AF_INET, ()):
try:
subnets.add(to_ipnetwork(v4))
except Exception:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception(
"Error while trying to add v4 network to local subnets: {!r}".format(
v4
)
)
if HAS_V6:
for v6 in addrs.get(socket.AF_INET6, ()):
try:
subnets.add(to_ipnetwork(v6))
except Exception:
if logging.getLogger(__name__).isEnabledFor(logging.DEBUG):
logging.getLogger(__name__).exception(
"Error while trying to add v6 network to local subnets: {!r}".format(
v6
)
)
if ip in subnets:
if any(map(lambda subnet: ip in subnet, subnets)):
return True
return False
@@ -132,6 +142,12 @@ def is_lan_address(address, additional_private=None):
return True
def sanitize_address(address):
address = unmap_v4_as_v6(address)
address = strip_interface_tag(address)
return address
def strip_interface_tag(address):
if "%" in address:
# interface comment, e.g. "fe80::457f:bbee:d579:1063%wlan0"