Skip to content
Myr

Merge commit from fork

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(ip-restriction): match static IP rules numerically * fix: throw TypeError for invalid IP addresses in ipaddr utils * fix(ip-restriction): validate CIDR prefixes

authored by Taku Amano · committed by GitHub · parent 905aedb · Browse files · 4 files+395 added−39 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+395 added−39 removed

  • tests:+116 added−5 removed
  • other:+279 added−34 removed

4 files+395 added−39 removed

modified:src/middleware/ip-restriction/index.test.ts+76 added-3 removed
modified:src/middleware/ip-restriction/index.ts+60 added-24 removed
4 unmodified lines
56import type { Context, MiddlewareHandler } from '../..'7import type { AddressType, GetConnInfo } from '../../helper/conninfo'8import { HTTPException } from '../../http-exception'9import type { InvalidIPAddressError } from '../../utils/ipaddr'10import {11 convertIPv4MappedIPv6ToIPv4,12 convertIPv4ToBinary,13 convertIPv6BinaryToString,14 convertIPv6ToBinary,15 distinctRemoteAddr,16 isIPv4MappedIPv6,17 INVALID_IP_ADDRESS_ERROR_CODE,18} from '../../utils/ipaddr'1920/**21 * Function to get IP Address
14 unmodified lines
36 */37type IPRestrictionRuleFunction = (addr: { addr: string; type: AddressType }) => boolean38export type IPRestrictionRule = string | ((addr: { addr: string; type: AddressType }) => boolean)3938const IS_CIDR_NOTATION_REGEX = /\/[0-9]{0,3}$/40const IS_CIDR_NOTATION_REGEX = /\/[^/]*$/41const parseCidrPrefix = (rule: string, prefix: string, max: number): number => {42 if (!/^[0-9]{1,3}$/.test(prefix)) {43 throw new TypeError(`Invalid rule: ${rule}`)44 }45 const parsedPrefix = parseInt(prefix)46 if (parsedPrefix > max) {47 throw new TypeError(`Invalid rule: ${rule}`)48 }49 return parsedPrefix50}51const buildMatcher = (52 rules: IPRestrictionRule[]53): ((addr: { addr: string; type: AddressType; isIPv4: boolean }) => boolean) => {54 const functionRules: IPRestrictionRuleFunction[] = []55 const staticRules: Set<string> = new Set()56 const staticIPv4Rules: Set<bigint> = new Set()57 const staticIPv6Rules: Set<bigint> = new Set()58 const cidrRules: [boolean, bigint, bigint][] = []59 const registerStaticRule = (rule: string): void => {60 const type = distinctRemoteAddr(rule)61 if (type === undefined) {62 throw new TypeError(`Invalid rule: ${rule}`)63 }64 if (type === 'IPv4') {65 const ipv4binary = convertIPv4ToBinary(rule)66 staticRules.add(rule)67 staticRules.add(`::ffff:${rule}`)68 staticIPv4Rules.add(ipv4binary)69 staticIPv6Rules.add((0xffffn << 32n) | ipv4binary)70 } else {71 const ipv6binary = convertIPv6ToBinary(rule)72 const ipv6Addr = convertIPv6BinaryToString(ipv6binary)73 staticRules.add(ipv6Addr)74 staticIPv6Rules.add(ipv6binary)75 if (isIPv4MappedIPv6(ipv6binary)) {76 staticRules.add(ipv6Addr.substring(7)) // remove ::ffff: prefix77 staticIPv4Rules.add(convertIPv4MappedIPv6ToIPv4(ipv6binary))78 }79 }80 }8182 for (let rule of rules) {83 if (rule === '*') {84 return () => true
9 unmodified lines
94 throw new TypeError(`Invalid rule: ${rule}`)95 }9697 let isIPv4 = type === 'IPv4'62 let prefix = parseInt(separatedRule[1])98 let prefix = parseCidrPrefix(rule, separatedRule[1], isIPv4 ? 32 : 128)99100 if (isIPv4 ? prefix === 32 : prefix === 128) {101 // this rule is a static rule102 rule = addrStr
11 unmodified lines
114 continue115 }116 }11782 const type = distinctRemoteAddr(rule)83 if (type === undefined) {84 throw new TypeError(`Invalid rule: ${rule}`)85 }86 if (type === 'IPv4') {87 staticRules.add(rule)88 staticRules.add(`::ffff:${rule}`)89 } else {90 const ipv6binary = convertIPv6ToBinary(rule)91 const ipv6Addr = convertIPv6BinaryToString(ipv6binary)92 staticRules.add(ipv6Addr)93 if (isIPv4MappedIPv6(ipv6binary)) {94 staticRules.add(ipv6Addr.substring(7)) // remove ::ffff: prefix95 }96 }118 registerStaticRule(rule)119 }120 }121122 return (remote: {
13 unmodified lines
136 ? remote.isIPv4137 ? remoteAddr138 : convertIPv4MappedIPv6ToIPv4(remoteAddr)139 : undefined140 if ((remote.isIPv4 ? staticIPv4Rules : staticIPv6Rules).has(remoteAddr)) {141 return true142 }143 for (const [isIPv4, addr, mask] of cidrRules) {144 if (isIPv4) {145 if (remoteIPv4Addr === undefined) {146 continue
98 unmodified lines
245 (typeof connInfo !== 'string' && connInfo.remote.addressType) || distinctRemoteAddr(addr)246247 const remoteData = { addr, type, isIPv4: type === 'IPv4' }248249 try {224 if (denyMatcher(remoteData)) {225 if (onError) {226 return onError({ addr, type }, c)250 if (denyMatcher(remoteData)) {251 if (onError) {252 return onError({ addr, type }, c)253 }254 throw blockError(c)255 }256 if (allowMatcher(remoteData)) {257 return await next()258 }259 } catch (e) {260 if (261 e instanceof TypeError &&262 (e as InvalidIPAddressError).code === INVALID_IP_ADDRESS_ERROR_CODE263 ) {264 // If an invalid IP address is specified, treat it as if no IP address was specified228 throw blockError(c)265 throw blockError(c)266 }267 throw e268 }230 if (allowMatcher(remoteData)) {231 return await next()232 }269270 if (allowLength === 0) {271 return await next()272 } else {
7 unmodified lines
modified:src/utils/ipaddr.test.ts+40 added-2 removed
3 unmodified lines
4 convertIPv6BinaryToString,5 convertIPv6ToBinary,6 distinctRemoteAddr,7 expandIPv6,8 INVALID_IP_ADDRESS_ERROR_CODE,9} from './ipaddr'1011const expectInvalidIPAddressError = (fn: () => unknown) => {12 try {13 fn()14 } catch (error) {15 expect(error).toBeInstanceOf(TypeError)16 expect(error).toHaveProperty('code', INVALID_IP_ADDRESS_ERROR_CODE)17 return18 }19 throw new Error('Expected invalid IP address error')20}2122describe('expandIPv6', () => {23 it('Should result be valid', () => {24 expect(expandIPv6('1::1')).toBe('0001:0000:0000:0000:0000:0000:0000:0001')25 expect(expandIPv6('::1')).toBe('0000:0000:0000:0000:0000:0000:0000:0001')
36 unmodified lines
62 expect(convertIPv4ToBinary('0.0.0.1')).toBe(1n)6364 expect(convertIPv4ToBinary('0.0.1.0')).toBe(1n << 8n)65 })6667 test.each(['1.2.3.256', '1.2.3', '1.2.3.4.5', '1..3.4', '01.2.3.4', 'a.b.c.d'])(68 'Should throw for invalid IPv4: %s',69 (input) => {70 expectInvalidIPAddressError(() => convertIPv4ToBinary(input))71 }72 )73})7475describe('convertIPv4ToString', () => {76 // add tons of test cases here
12 unmodified lines
89 expect(convertIPv6ToBinary('::0')).toBe(0n)90 expect(convertIPv6ToBinary('::1')).toBe(1n)9192 expect(convertIPv6ToBinary('::f')).toBe(15n)74 expect(convertIPv6ToBinary('1234:::5678')).toBe(24196103360772296748952112894165669496n)93 expect(convertIPv6ToBinary('1234::5678')).toBe(24196103360772296748952112894165669496n)94 expect(convertIPv6ToBinary('::ffff:127.0.0.1')).toBe(281472812449793n)95 expect(convertIPv6ToBinary('fe80::1%eth0')).toBe(convertIPv6ToBinary('fe80::1'))96 })9798 test.each([99 '1::2::3',100 '1:2:3:4:5:6:7:8:9',101 '1:2:3:4:5:6:7',102 '12345::',103 'gggg::',104 '::ffff:127.0.0.256',105 '1234:::5678',106 '2001:db8::1%eth0',107 '::ffff:127.0.0.1%eth0',108 '1:2:3%eth0',109 'gggg%eth0',110 'fe80::1%',111 ])('Should throw for invalid IPv6: %s', (input) => {112 expectInvalidIPAddressError(() => convertIPv6ToBinary(input))113 })114})115116describe('convertIPv6ToString', () => {117 // add tons of test cases here118 test.each`119 input | expected120 ${'::1'} | ${'::1'}121 ${'1::'} | ${'1::'}85 ${'1234:::5678'} | ${'1234::5678'}122 ${'1234::5678'} | ${'1234::5678'}123 ${'2001:2::'} | ${'2001:2::'}124 ${'2001::db8:0:0:0:0:1'} | ${'2001:0:db8::1'}125 ${'1234:5678:9abc:def0:1234:5678:9abc:def0'} | ${'1234:5678:9abc:def0:1234:5678:9abc:def0'}126 ${'::ffff:127.0.0.1'} | ${'::ffff:127.0.0.1'}127 ${'fe80::1%eth0'} | ${'fe80::1'}128 `('convertIPv6ToString($input) === $expected', ({ input, expected }) => {129 expect(convertIPv6BinaryToString(convertIPv6ToBinary(input))).toBe(expected)130 })131})
modified:src/utils/ipaddr.ts+219 added-10 removed
33 unmodified lines
34}3536const IPV4_OCTET_PART = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])'37const IPV4_REGEX = new RegExp(`^(?:${IPV4_OCTET_PART}\\.){3}${IPV4_OCTET_PART}$`)38export const INVALID_IP_ADDRESS_ERROR_CODE = 'ERR_INVALID_IP_ADDRESS'39export type InvalidIPAddressError = TypeError & {40 code: typeof INVALID_IP_ADDRESS_ERROR_CODE41}42const CHAR_CODE_0 = 4843const CHAR_CODE_9 = 5744const CHAR_CODE_A = 6545const CHAR_CODE_F = 7046const CHAR_CODE_a = 9747const CHAR_CODE_f = 10248const CHAR_CODE_DOT = 4649const CHAR_CODE_COLON = 5850const CHAR_CODE_PERCENT = 375152/**53 * Distinct Remote Addr54 * @param remoteAddr Remote Addr
7 unmodified lines
62 return 'IPv6'63 }64}6566const createInvalidIPAddressError = (message: string): InvalidIPAddressError => {67 const error = new TypeError(message) as InvalidIPAddressError68 error.code = INVALID_IP_ADDRESS_ERROR_CODE69 return error70}7172const throwInvalidIPv4Address = (ipv4: string): never => {73 throw createInvalidIPAddressError(`Invalid IPv4 address: ${ipv4}`)74}7576const throwInvalidIPv6Address = (ipv6: string): never => {77 throw createInvalidIPAddressError(`Invalid IPv6 address: ${ipv6}`)78}7980const parseIPv4ToBinary = (81 ipv4: string,82 start: number,83 end: number,84 onInvalid: () => never85): bigint => {86 let result = 0n87 let octets = 088 let octet = 089 let digits = 090 let firstDigit = 09192 for (let i = start; i <= end; i++) {93 const code = i < end ? ipv4.charCodeAt(i) : CHAR_CODE_DOT94 if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) {95 if (digits === 0) {96 firstDigit = code97 } else if (firstDigit === CHAR_CODE_0) {98 onInvalid()99 }100 octet = octet * 10 + code - CHAR_CODE_0101 if (octet > 255) {102 onInvalid()103 }104 digits++105 continue106 }107108 if (code !== CHAR_CODE_DOT || digits === 0 || octets === 4) {109 onInvalid()110 }111112 result = (result << 8n) + BigInt(octet)113 octets++114 octet = 0115 digits = 0116 }117118 if (octets !== 4) {119 onInvalid()120 }121122 return result123}124125const parseIPv6HexCode = (code: number): number => {126 if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) {127 return code - CHAR_CODE_0128 }129 if (code >= CHAR_CODE_A && code <= CHAR_CODE_F) {130 return code - CHAR_CODE_A + 10131 }132 if (code >= CHAR_CODE_a && code <= CHAR_CODE_f) {133 return code - CHAR_CODE_a + 10134 }135 return -1136}137138const isIPv6LinkLocal = (ipv6binary: bigint): boolean => ipv6binary >> 118n === 0x3fan139140/**141 * Convert IPv4 to Uint8Array142 * @param ipv4 IPv4 Address143 * @returns BigInt144 */145export const convertIPv4ToBinary = (ipv4: string): bigint => {59 const parts = ipv4.split('.')60 let result = 0n61 for (let i = 0; i < 4; i++) {62 result <<= 8n63 result += BigInt(parts[i])64 }65 return result146 return parseIPv4ToBinary(ipv4, 0, ipv4.length, () => throwInvalidIPv4Address(ipv4))147}148149/**150 * Convert IPv6 to Uint8Array151 * @param ipv6 IPv6 Address152 * @returns BigInt153 */154export const convertIPv6ToBinary = (ipv6: string): bigint => {74 const sections = expandIPv6(ipv6).split(':')155 const length = ipv6.length156 const sections: number[] = []157 let hasZoneId = false158 let compressAt = -1159 let index = 0160161 if (length === 0) {162 throwInvalidIPv6Address(ipv6)163 }164165 while (index < length) {166 if (sections.length > 8) {167 throwInvalidIPv6Address(ipv6)168 }169170 let code = ipv6.charCodeAt(index)171172 if (code === CHAR_CODE_PERCENT) {173 if (index + 1 === length) {174 throwInvalidIPv6Address(ipv6)175 }176 hasZoneId = true177 break178 }179180 if (code === CHAR_CODE_COLON) {181 if (index + 1 < length && ipv6.charCodeAt(index + 1) === CHAR_CODE_COLON) {182 if (compressAt !== -1) {183 throwInvalidIPv6Address(ipv6)184 }185 compressAt = sections.length186 index += 2187 continue188 }189 throwInvalidIPv6Address(ipv6)190 }191192 let value = 0193 let digits = 0194 const sectionStart = index195196 while (index < length) {197 code = ipv6.charCodeAt(index)198 const hex = parseIPv6HexCode(code)199 if (hex === -1) {200 break201 }202 if (digits === 4) {203 throwInvalidIPv6Address(ipv6)204 }205 value = (value << 4) | hex206 digits++207 index++208 }209210 if (index < length && ipv6.charCodeAt(index) === CHAR_CODE_DOT) {211 let ipv4End = length212 for (let i = index; i < length; i++) {213 if (ipv6.charCodeAt(i) === CHAR_CODE_PERCENT) {214 if (i + 1 === length) {215 throwInvalidIPv6Address(ipv6)216 }217 hasZoneId = true218 ipv4End = i219 break220 }221 }222 const ipv4 = parseIPv4ToBinary(ipv6, sectionStart, ipv4End, () =>223 throwInvalidIPv6Address(ipv6)224 )225 sections.push(Number((ipv4 >> 16n) & 0xffffn), Number(ipv4 & 0xffffn))226 index = length227 break228 }229230 if (digits === 0) {231 throwInvalidIPv6Address(ipv6)232 }233234 sections.push(value)235236 if (index === length) {237 break238 }239240 code = ipv6.charCodeAt(index)241 if (code === CHAR_CODE_PERCENT) {242 if (index + 1 === length) {243 throwInvalidIPv6Address(ipv6)244 }245 hasZoneId = true246 break247 }248249 if (code !== CHAR_CODE_COLON) {250 throwInvalidIPv6Address(ipv6)251 }252253 if (index + 1 < length && ipv6.charCodeAt(index + 1) === CHAR_CODE_COLON) {254 if (compressAt !== -1) {255 throwInvalidIPv6Address(ipv6)256 }257 compressAt = sections.length258 index += 2259 continue260 }261262 index++263 if (index === length) {264 throwInvalidIPv6Address(ipv6)265 }266 }267268 if (compressAt === -1 ? sections.length !== 8 : sections.length >= 8) {269 throwInvalidIPv6Address(ipv6)270 }271272 let result = 0n273 const zeros = compressAt === -1 ? 0 : 8 - sections.length274 const firstSectionEnd = compressAt === -1 ? sections.length : compressAt76 for (let i = 0; i < 8; i++) {275 for (let i = 0; i < firstSectionEnd; i++) {276 result <<= 16n78 result += BigInt(parseInt(sections[i], 16))277 result += BigInt(sections[i])278 }279 for (let i = 0; i < zeros; i++) {280 result <<= 16n281 }282 for (let i = firstSectionEnd; i < sections.length; i++) {283 result <<= 16n284 result += BigInt(sections[i])285 }286 if (hasZoneId && !isIPv6LinkLocal(result)) {287 throwInvalidIPv6Address(ipv6)288 }289 return result290}291292/**
71 unmodified lines