Skip to content

Commit

Permalink
Add ipv6 cidr support
Browse files Browse the repository at this point in the history
  • Loading branch information
ArtemBaskal committed May 27, 2020
1 parent 7db0a2f commit 3d38f21
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 21 deletions.
3 changes: 1 addition & 2 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"date-fns": "^1.29.0",
"i18next": "^19.4.4",
"i18next-browser-languagedetector": "^4.2.0",
"ipaddr.js": "^1.9.1",
"lodash": "^4.17.15",
"nanoid": "^3.1.9",
"prop-types": "^15.7.2",
Expand Down
48 changes: 29 additions & 19 deletions client/src/helpers/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import round from 'lodash/round';
import axios from 'axios';
import i18n from 'i18next';
import uniqBy from 'lodash/uniqBy';
import ipaddr from 'ipaddr.js';
import versionCompare from './versionCompare';

import {
Expand Down Expand Up @@ -494,22 +495,27 @@ export const normalizeMultiline = (multiline) => `${normalizeTextarea(multiline)
.map((line) => line.trim())
.join('\n')}\n`;

/**
* @param ip {string}
* @returns {number}
*/
export const ipToInt = (ip) => ip.split('.')
.reduce((int, oct) => (int << 8) + parseInt(oct, 10), 0) >>> 0;

/**
* @param cidr {string}
* @param ip {string}
* @param cidr {string}
* @returns {boolean}
*/
export const isIpInCidr = (cidr, ip) => {
const [range, bits = 32] = cidr.split('/');
const mask = ~((2 ** (32 - bits)) - 1);
return (ipToInt(ip) & mask) === (ipToInt(range) & mask);
export const isIpInCidr = (ip, cidr) => {
try {
const [cidrIp] = cidr.split('/');
const cidrIpVersion = ipaddr.parse(cidrIp)
.kind();

const parsedIp = ipaddr.parse(ip);
const ipVersion = parsedIp.kind();

const parsedCidr = ipaddr.parseCIDR(cidr);

return ipVersion === cidrIpVersion && parsedIp.match(parsedCidr);
} catch (e) {
return false;
}
};

/**
Expand All @@ -518,15 +524,19 @@ export const isIpInCidr = (cidr, ip) => {
* @returns {boolean | 'CIDR' | 'IP'}
*/
export const isClientInIpsOrCidrs = (rawClients, currentClient) => rawClients.split('\n')
.reduce((acc, curr) => {
if (acc) {
return acc;
}
if (curr.includes('/') && isIpInCidr(curr, currentClient)) {
return BLOCKED_CLIENT.CIDR;
.reduce((isClientInList, rawClient) => {
if (isClientInList) {
return isClientInList;
}
if (curr === currentClient) {

if (rawClient === currentClient) {
return BLOCKED_CLIENT.IP;
}

if (rawClient.includes('/') && isIpInCidr(currentClient, rawClient)) {
return BLOCKED_CLIENT.CIDR;
}

return false;
}, false);
},
false);

0 comments on commit 3d38f21

Please sign in to comment.