Skip to content

Commit

Permalink
net: introduce net.BlockList
Browse files Browse the repository at this point in the history
`net.BlockList` provides an object intended to be used by net APIs to
specify rules for disallowing network activity with specific IP
addresses. This commit adds the basic mechanism but does not add the
specific uses.

PR-URL: #34625
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Bradley Farias <bradley.meck@gmail.com>
  • Loading branch information
jasnell authored and MylesBorins committed Aug 31, 2021
1 parent 1008c80 commit 87c7106
Show file tree
Hide file tree
Showing 10 changed files with 1,189 additions and 2 deletions.
80 changes: 80 additions & 0 deletions doc/api/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,86 @@ net.createServer().listen(
path.join('\\\\?\\pipe', process.cwd(), 'myctl'));
```

## Class: `net.BlockList`
<!-- YAML
added: REPLACEME
-->

The `BlockList` object can be used with some network APIs to specify rules for
disabling inbound or outbound access to specific IP addresses, IP ranges, or
IP subnets.

### `blockList.addAddress(address[, type])`
<!-- YAML
added: REPLACEME
-->

* `address` {string} An IPv4 or IPv6 address.
* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`.

Adds a rule to block the given IP address.

### `blockList.addRange(start, end[, type])`
<!-- YAML
added: REPLACEME
-->

* `start` {string} The starting IPv4 or IPv6 address in the range.
* `end` {string} The ending IPv4 or IPv6 address in the range.
* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`.

Adds a rule to block a range of IP addresses from `start` (inclusive) to
`end` (inclusive).

### `blockList.addSubnet(net, prefix[, type])`
<!-- YAML
added: REPLACEME
-->

* `net` {string} The network IPv4 or IPv6 address.
* `prefix` {number} The number of CIDR prefix bits. For IPv4, this
must be a value between `0` and `32`. For IPv6, this must be between
`0` and `128`.
* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`.

Adds a rule to block a range of IP addresses specified as a subnet mask.

### `blockList.check(address[, type])`
<!-- YAML
added: REPLACEME
-->

* `address` {string} The IP address to check
* `type` {string} Either `'ipv4'` or `'ipv6'`. **Default**: `'ipv4'`.
* Returns: {boolean}

Returns `true` if the given IP address matches any of the rules added to the
`BlockList`.

```js
const blockList = new net.BlockList();
blockList.addAddress('123.123.123.123');
blockList.addRange('10.0.0.1', '10.0.0.10');
blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6');

console.log(blockList.check('123.123.123.123')); // Prints: true
console.log(blockList.check('10.0.0.3')); // Prints: true
console.log(blockList.check('222.111.111.222')); // Prints: false

// IPv6 notation for IPv4 addresses works:
console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true
```

### `blockList.rules`
<!-- YAML
added: REPLACEME
-->

* Type: {string[]}

The list of rules added to the blocklist.

## Class: `net.Server`
<!-- YAML
added: v0.1.90
Expand Down
115 changes: 115 additions & 0 deletions lib/internal/blocklist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
'use strict';

const {
Boolean,
Symbol
} = primordials;

const {
BlockList: BlockListHandle,
AF_INET,
AF_INET6,
} = internalBinding('block_list');

const {
customInspectSymbol: kInspect,
} = require('internal/util');
const { inspect } = require('internal/util/inspect');

const kHandle = Symbol('kHandle');
const { owner_symbol } = internalBinding('symbols');

const {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_OUT_OF_RANGE,
} = require('internal/errors').codes;

class BlockList {
constructor() {
this[kHandle] = new BlockListHandle();
this[kHandle][owner_symbol] = this;
}

[kInspect](depth, options) {
if (depth < 0)
return this;

const opts = {
...options,
depth: options.depth == null ? null : options.depth - 1
};

return `BlockList ${inspect({
rules: this.rules
}, opts)}`;
}

addAddress(address, family = 'ipv4') {
if (typeof address !== 'string')
throw new ERR_INVALID_ARG_TYPE('address', 'string', address);
if (typeof family !== 'string')
throw new ERR_INVALID_ARG_TYPE('family', 'string', family);
if (family !== 'ipv4' && family !== 'ipv6')
throw new ERR_INVALID_ARG_VALUE('family', family);
const type = family === 'ipv4' ? AF_INET : AF_INET6;
this[kHandle].addAddress(address, type);
}

addRange(start, end, family = 'ipv4') {
if (typeof start !== 'string')
throw new ERR_INVALID_ARG_TYPE('start', 'string', start);
if (typeof end !== 'string')
throw new ERR_INVALID_ARG_TYPE('end', 'string', end);
if (typeof family !== 'string')
throw new ERR_INVALID_ARG_TYPE('family', 'string', family);
if (family !== 'ipv4' && family !== 'ipv6')
throw new ERR_INVALID_ARG_VALUE('family', family);
const type = family === 'ipv4' ? AF_INET : AF_INET6;
const ret = this[kHandle].addRange(start, end, type);
if (ret === false)
throw new ERR_INVALID_ARG_VALUE('start', start, 'must come before end');
}

addSubnet(network, prefix, family = 'ipv4') {
if (typeof network !== 'string')
throw new ERR_INVALID_ARG_TYPE('network', 'string', network);
if (typeof prefix !== 'number')
throw new ERR_INVALID_ARG_TYPE('prefix', 'number', prefix);
if (typeof family !== 'string')
throw new ERR_INVALID_ARG_TYPE('family', 'string', family);
let type;
switch (family) {
case 'ipv4':
type = AF_INET;
if (prefix < 0 || prefix > 32)
throw new ERR_OUT_OF_RANGE(prefix, '>= 0 and <= 32', prefix);
break;
case 'ipv6':
type = AF_INET6;
if (prefix < 0 || prefix > 128)
throw new ERR_OUT_OF_RANGE(prefix, '>= 0 and <= 128', prefix);
break;
default:
throw new ERR_INVALID_ARG_VALUE('family', family);
}
this[kHandle].addSubnet(network, type, prefix);
}

check(address, family = 'ipv4') {
if (typeof address !== 'string')
throw new ERR_INVALID_ARG_TYPE('address', 'string', address);
if (typeof family !== 'string')
throw new ERR_INVALID_ARG_TYPE('family', 'string', family);
if (family !== 'ipv4' && family !== 'ipv6')
throw new ERR_INVALID_ARG_VALUE('family', family);
const type = family === 'ipv4' ? AF_INET : AF_INET6;
return Boolean(this[kHandle].check(address, type));
}

get rules() {
return this[kHandle].getRules();
}
}

module.exports = BlockList;
6 changes: 6 additions & 0 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ const {
// Lazy loaded to improve startup performance.
let cluster;
let dns;
let BlockList;

const { clearTimeout } = require('timers');
const { kTimeout } = require('internal/timers');
Expand Down Expand Up @@ -1755,6 +1756,11 @@ module.exports = {
_createServerHandle: createServerHandle,
_normalizeArgs: normalizeArgs,
_setSimultaneousAccepts,
get BlockList() {
if (BlockList === undefined)
BlockList = require('internal/blocklist');
return BlockList;
},
connect,
createConnection: connect,
createServer,
Expand Down
1 change: 1 addition & 0 deletions node.gyp
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
'lib/internal/assert/assertion_error.js',
'lib/internal/assert/calltracker.js',
'lib/internal/async_hooks.js',
'lib/internal/blocklist.js',
'lib/internal/buffer.js',
'lib/internal/cli_table.js',
'lib/internal/child_process.js',
Expand Down
1 change: 1 addition & 0 deletions src/node_binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
// __attribute__((constructor)) like mechanism in GCC.
#define NODE_BUILTIN_STANDARD_MODULES(V) \
V(async_wrap) \
V(block_list) \
V(buffer) \
V(cares_wrap) \
V(config) \
Expand Down
28 changes: 26 additions & 2 deletions src/node_sockaddr-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

#include "node.h"
#include "env-inl.h"
#include "node_internals.h"
#include "node_sockaddr.h"
#include "util-inl.h"
Expand Down Expand Up @@ -88,11 +89,11 @@ SocketAddress& SocketAddress::operator=(const SocketAddress& addr) {
}

const sockaddr& SocketAddress::operator*() const {
return *this->data();
return *data();
}

const sockaddr* SocketAddress::operator->() const {
return this->data();
return data();
}

size_t SocketAddress::length() const {
Expand Down Expand Up @@ -166,6 +167,24 @@ bool SocketAddress::operator!=(const SocketAddress& other) const {
return !(*this == other);
}

bool SocketAddress::operator<(const SocketAddress& other) const {
return compare(other) == CompareResult::LESS_THAN;
}

bool SocketAddress::operator>(const SocketAddress& other) const {
return compare(other) == CompareResult::GREATER_THAN;
}

bool SocketAddress::operator<=(const SocketAddress& other) const {
CompareResult c = compare(other);
return c == CompareResult::NOT_COMPARABLE ? false :
c <= CompareResult::SAME;
}

bool SocketAddress::operator>=(const SocketAddress& other) const {
return compare(other) >= CompareResult::SAME;
}

template <typename T>
SocketAddressLRU<T>::SocketAddressLRU(
size_t max_size)
Expand Down Expand Up @@ -231,6 +250,11 @@ typename T::Type* SocketAddressLRU<T>::Upsert(
return &map_[address]->second;
}

v8::MaybeLocal<v8::Value> SocketAddressBlockList::Rule::ToV8String(
Environment* env) {
std::string str = ToString();
return ToV8Value(env->context(), str);
}
} // namespace node

#endif // NODE_WANT_INTERNALS
Expand Down
Loading

0 comments on commit 87c7106

Please sign in to comment.