Skip to content
Permalink
Browse files Browse the repository at this point in the history
limit total IPs in range to avoid DoS
  • Loading branch information
JoeScho committed Feb 10, 2021
1 parent d1377be commit 98ca22b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions index.test.ts
Expand Up @@ -91,4 +91,16 @@ describe('for two IP addresses', () => {
it('should support hyphenated range in IPv5', () => {
expect(getIPRange('::ffff:102:304-::ffff:102:307')).toEqual(successResponsev6);
});

it('should throw if the range is greater than 10000 default', () => {
const throwFn = () => getIPRange('128.0.0.0/1');
expect(throwFn).toThrow('Too many IPs in range. Total number: 2147483647. Max count is 10000, to increase, set the limit with the MAX_RANGE environment variable');
});

it('should throw if the range is greater than process.env.MAX_RANGE', () => {
process.env.MAX_RANGE = '5000';

const throwFn = () => getIPRange('128.0.0.0/1');
expect(throwFn).toThrow('Too many IPs in range. Total number: 2147483647. Max count is 5000, to increase, set the limit with the MAX_RANGE environment variable');
});
});
12 changes: 12 additions & 0 deletions index.ts
Expand Up @@ -2,6 +2,9 @@ import { toLong, fromLong } from 'ip';
// @ts-ignore
import { Address4, Address6 } from 'ip-address';

// Set default max range
let maxRange = 10000;

const getIPv4 = (ip: string): Address4 | null => {
try {
return new Address4(ip);
Expand All @@ -24,6 +27,13 @@ const getRangev4 = (ip1: string, ip2: string) => {
let firstAddressLong = toLong(ip1);
const lastAddressLong = toLong(ip2);

const totalIPs = lastAddressLong - firstAddressLong;

// Prevent DoS
if (totalIPs > maxRange) {
throw new Error(`Too many IPs in range. Total number: ${totalIPs}. Max count is ${maxRange}, to increase, set the limit with the MAX_RANGE environment variable`)
}

for (firstAddressLong; firstAddressLong <= lastAddressLong; firstAddressLong++)
ips.push(fromLong(firstAddressLong));

Expand All @@ -48,6 +58,8 @@ const isCIDR = (ipCIDR: Address4 | Address6): boolean => Boolean(ipCIDR.parsedSu
const isRange = (ipRange: string): boolean => ipRange.indexOf('-') !== -1;

const getIPRange = (ip1: string, ip2?: string): Array<string> => {
maxRange = parseInt(process.env.MAX_RANGE || '10000');

const ip1v4 = getIPv4(ip1);
const ip1v6 = getIPv6(ip1);

Expand Down

0 comments on commit 98ca22b

Please sign in to comment.