├── .eslintrc.yml
├── .github
└── workflows
│ ├── ci.yml
│ ├── codeql-analysis.yml
│ └── ossar-analysis.yml
├── .gitignore
├── .husky
├── .gitignore
├── post-merge
├── pre-commit
└── pre-push
├── .lintstagedrc.yml
├── .npmrc
├── .nvmrc
├── .prettierrc.yml
├── LICENSE
├── README.md
├── __mocks__
└── dns.ts
├── index.test.ts
├── index.ts
├── package-lock.json
├── package.json
├── renovate.json
├── tsconfig.build.json
├── tsconfig.json
└── vite.config.ts
/.eslintrc.yml:
--------------------------------------------------------------------------------
1 | extends:
2 | - '@janejeon/typescript'
3 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Node CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | pull_request:
8 | branches:
9 | - master
10 |
11 | jobs:
12 | lint:
13 | runs-on: ubuntu-latest
14 | steps:
15 | - uses: actions/checkout@v4
16 | - uses: actions/setup-node@v3
17 | with:
18 | node-version-file: .nvmrc
19 | cache: npm
20 | - run: npm ci
21 | - run: npm run typecheck
22 | - run: npm run lint
23 |
24 | test:
25 | needs: lint
26 | runs-on: ubuntu-latest
27 | steps:
28 | - uses: actions/checkout@v4
29 | - uses: actions/setup-node@v3
30 | with:
31 | node-version: 20
32 | - run: npm ci
33 | - name: Run test with coverage
34 | run: npm run test:cov
35 | - uses: codecov/codecov-action@v4
36 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: 'CodeQL'
13 |
14 | on:
15 | push:
16 | branches: [master]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [master]
20 | schedule:
21 | - cron: '34 11 * * 0'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: ['javascript']
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
37 | # Learn more:
38 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
39 |
40 | steps:
41 | - name: Checkout repository
42 | uses: actions/checkout@v4
43 |
44 | # Initializes the CodeQL tools for scanning.
45 | - name: Initialize CodeQL
46 | uses: github/codeql-action/init@v2
47 | with:
48 | languages: ${{ matrix.language }}
49 | # If you wish to specify custom queries, you can do so here or in a config file.
50 | # By default, queries listed here will override any specified in a config file.
51 | # Prefix the list here with "+" to use these queries and those in the config file.
52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main
53 |
54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
55 | # If this step fails, then you should remove it and run the build manually (see below)
56 | - name: Autobuild
57 | uses: github/codeql-action/autobuild@v2
58 |
59 | # ℹ️ Command-line programs to run using the OS shell.
60 | # 📚 https://git.io/JvXDl
61 |
62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
63 | # and modify them (or add more) to build your code if your project
64 | # uses a compiled language
65 |
66 | #- run: |
67 | # make bootstrap
68 | # make release
69 |
70 | - name: Perform CodeQL Analysis
71 | uses: github/codeql-action/analyze@v2
72 |
--------------------------------------------------------------------------------
/.github/workflows/ossar-analysis.yml:
--------------------------------------------------------------------------------
1 | # This workflow integrates a collection of open source static analysis tools
2 | # with GitHub code scanning. For documentation, or to provide feedback, visit
3 | # https://github.com/github/ossar-action
4 | name: OSSAR
5 |
6 | on:
7 | push:
8 | branches: [master]
9 | pull_request:
10 | # The branches below must be a subset of the branches above
11 | branches: [master]
12 | schedule:
13 | - cron: '31 11 * * 1'
14 |
15 | jobs:
16 | OSSAR-Scan:
17 | # OSSAR runs on windows-latest.
18 | # ubuntu-latest and macos-latest support coming soon
19 | runs-on: windows-latest
20 |
21 | steps:
22 | - name: Checkout repository
23 | uses: actions/checkout@v4
24 |
25 | # Ensure a compatible version of dotnet is installed.
26 | # The [Microsoft Security Code Analysis CLI](https://aka.ms/mscadocs) is built with dotnet v3.1.201.
27 | # A version greater than or equal to v3.1.201 of dotnet must be installed on the agent in order to run this action.
28 | # GitHub hosted runners already have a compatible version of dotnet installed and this step may be skipped.
29 | # For self-hosted runners, ensure dotnet version 3.1.201 or later is installed by including this action:
30 | # - name: Install .NET
31 | # uses: actions/setup-dotnet@v1
32 | # with:
33 | # dotnet-version: '3.1.x'
34 | # Run open source static analysis tools
35 | - name: Run OSSAR
36 | uses: github/ossar-action@v1
37 | id: ossar
38 |
39 | # Upload results to the Security tab
40 | - name: Upload OSSAR results
41 | uses: github/codeql-action/upload-sarif@v2
42 | with:
43 | sarif_file: ${{ steps.ossar.outputs.sarifFile }}
44 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 | lerna-debug.log*
8 |
9 | # Diagnostic reports (https://nodejs.org/api/report.html)
10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
11 |
12 | # Runtime data
13 | pids
14 | *.pid
15 | *.seed
16 | *.pid.lock
17 |
18 | # Directory for instrumented libs generated by jscoverage/JSCover
19 | lib-cov
20 |
21 | # Coverage directory used by tools like istanbul
22 | coverage
23 | *.lcov
24 |
25 | # nyc test coverage
26 | .nyc_output
27 |
28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
29 | .grunt
30 |
31 | # Bower dependency directory (https://bower.io/)
32 | bower_components
33 |
34 | # node-waf configuration
35 | .lock-wscript
36 |
37 | # Compiled binary addons (https://nodejs.org/api/addons.html)
38 | build/Release
39 |
40 | # Dependency directories
41 | node_modules/
42 | jspm_packages/
43 |
44 | # TypeScript v1 declaration files
45 | typings/
46 |
47 | # TypeScript cache
48 | *.tsbuildinfo
49 |
50 | # Optional npm cache directory
51 | .npm
52 |
53 | # Optional eslint cache
54 | .eslintcache
55 |
56 | # Microbundle cache
57 | .rpt2_cache/
58 | .rts2_cache_cjs/
59 | .rts2_cache_es/
60 | .rts2_cache_umd/
61 |
62 | # Optional REPL history
63 | .node_repl_history
64 |
65 | # Output of 'npm pack'
66 | *.tgz
67 |
68 | # Yarn Integrity file
69 | .yarn-integrity
70 |
71 | # dotenv environment variables file
72 | .env
73 | .env.test
74 |
75 | # parcel-bundler cache (https://parceljs.org/)
76 | .cache
77 |
78 | # Next.js build output
79 | .next
80 |
81 | # Nuxt.js build / generate output
82 | .nuxt
83 | dist
84 |
85 | # Gatsby files
86 | .cache/
87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js
88 | # https://nextjs.org/blog/next-9-1#public-directory-support
89 | # public
90 |
91 | # vuepress build output
92 | .vuepress/dist
93 |
94 | # Serverless directories
95 | .serverless/
96 |
97 | # FuseBox cache
98 | .fusebox/
99 |
100 | # DynamoDB Local files
101 | .dynamodb/
102 |
103 | # TernJS port file
104 | .tern-port
105 |
106 | index.cjs.js
107 | index.esm.js
108 |
109 | reports/
110 |
111 | .DS_Store
112 |
--------------------------------------------------------------------------------
/.husky/.gitignore:
--------------------------------------------------------------------------------
1 | _
2 |
--------------------------------------------------------------------------------
/.husky/post-merge:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npm i
5 |
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npx lint-staged
5 |
--------------------------------------------------------------------------------
/.husky/pre-push:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 | . "$(dirname -- "$0")/_/husky.sh"
3 |
4 | npx skip-ci && echo "Skipping test..." || CI=1 npm test
5 |
--------------------------------------------------------------------------------
/.lintstagedrc.yml:
--------------------------------------------------------------------------------
1 | '*':
2 | - prettier --write --ignore-unknown
3 |
4 | '*.js':
5 | - eslint --fix
6 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | audit=false
2 | fund=false
3 | engine-strict=true
4 |
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | 20
2 |
--------------------------------------------------------------------------------
/.prettierrc.yml:
--------------------------------------------------------------------------------
1 | '@janejeon/prettier-config'
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
Welcome to got-ssrf 👋
2 |
3 | [](https://github.com/hanover-computing/got-ssrf/actions/workflows/ci.yml)
4 | [](https://codecov.io/gh/hanover-computing/got-ssrf)
5 | [](https://www.npmjs.com/package/got-ssrf)
6 | [](https://www.npmjs.com/package/got-ssrf)
7 |
8 | > Protect Got requests from SSRF
9 |
10 | ### 🏠 [Homepage](https://github.com/hanover-computing/got-ssrf)
11 |
12 | ## Why does this matter?
13 |
14 | SSRF is the evil sibling to CSRF that essentially allows RCE against your backends: https://portswigger.net/web-security/ssrf.
15 |
16 | This module automatically rejects all such requests so you can safely use got without even thinking about it.
17 |
18 | ## Install
19 |
20 | ```sh
21 | npm i got-ssrf
22 | ```
23 |
24 | ## Usage
25 |
26 | > Note that this package is ESM-only; see https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c for what to do if you're using CJS (i.e. `require()`).
27 |
28 | ```js
29 | import { gotSsrf } from 'got-ssrf'
30 |
31 | await gotSsrf(url) // automatically filters requests for safety
32 | ```
33 |
34 | If you have any other plugins you want to "mix" got-ssrf with, see https://github.com/sindresorhus/got/blob/main/documentation/examples/advanced-creation.js for how to do so. Example:
35 |
36 | ```js
37 | import got from 'got'
38 | import { gotSsrf } from 'got-ssrf'
39 | import { gotInstance } from 'some-other-got-plugin'
40 |
41 | const merged = got.extend(gotSsrf, gotInstance)
42 | ```
43 |
44 | ### Security
45 |
46 | This library is tested against a whole host of weird edge cases (a URL is not as straightforward as it seems). To see what behaviours are expected, please see the test suite.
47 |
48 | As this library doesn't parse the URLs itself (but rather relies on got, which relies on the node `URL` module), a good rule of thumb is that whatever you'd expect from the node `URL` module, you can expect of this library as well.
49 |
50 | If you want to disallow "weird" URLs (and trust me, there are _many_), as people may try to 'smuggle' hostnames in them (and cause SSRF that may not be caught by the `URL` module), you'll need to do an input validation of the URL (and reject the "weird" ones) _before_ passing it into got/got-ssrf.
51 |
52 | ## Run tests
53 |
54 | ```sh
55 | npm test
56 | ```
57 |
58 | ## Author
59 |
60 | 👤 **Jane Jeon **
61 |
62 | - Website: janejeon.dev
63 | - Github: [@JaneJeon](https://github.com/JaneJeon)
64 |
65 | ## 🤝 Contributing
66 |
67 | Contributions, issues and feature requests are welcome!
Feel free to check [issues page](https://github.com/JaneJeon/got-csrf/issues).
68 |
69 | ## Show your support
70 |
71 | Give a ⭐️ if this project helped you!
72 |
73 | ## 📝 License
74 |
75 | Copyright © 2023 [Jane Jeon ](https://github.com/JaneJeon).
76 | This project is [LGPL-3.0](https://github.com/JaneJeon/got-csrf/blob/master/LICENSE) licensed.
77 |
78 | TL;DR: you are free to import and use this library "as-is" in your code, without needing to make your code source-available or to license it under the same license as this library; however, if you do change this library and you distribute it (directly or as part of your code consuming this library), please do contribute back any improvements for this library and this library alone.
79 |
--------------------------------------------------------------------------------
/__mocks__/dns.ts:
--------------------------------------------------------------------------------
1 | import type { LookupOneOptions } from 'dns'
2 |
3 | type LookupCallback = (
4 | err: NodeJS.ErrnoException | null,
5 | // In the real dns module, the callback signature is (err, address, family).
6 | // However, because this needs to get promisify'd (just like the real dns.lookup),
7 | // I'm choosing to return an object so the promisify'd function returns the object.
8 | result?: { address: string; family: number }
9 | ) => void
10 |
11 | // We use the hostname lookups to define how got should behave when visiting a URL.
12 | // For URLs that are supposed to be public, we return a public IP address.
13 | // For URLs that are supposed to be private, we return a private IP address.
14 | // This, *in conjunction with* the HTTP request mocking (the `nock` module),
15 | // defines the entire behaviour of what a request looks like.
16 | export function lookup(
17 | hostname: string,
18 | options: LookupOneOptions | LookupCallback,
19 | callback?: LookupCallback
20 | ) {
21 | if (callback === undefined) {
22 | callback = options as LookupCallback
23 | }
24 |
25 | if (hostname === 'public-url.com') {
26 | // The callback return format has to be in form of object as util.promisify doesn't know
27 | // that it's supposed to translate callback(error, address, family) into return value of {address, family}
28 | callback(null, { address: '1.1.1.1', family: 4 }) // something I know is public
29 | }
30 |
31 | if (
32 | hostname === 'private-url.com' ||
33 | hostname === 'public-url.com.' ||
34 | hostname === 'private'
35 | ) {
36 | callback(null, { address: '192.168.0.1', family: 4 }) // should be caught by SSRF protection
37 | }
38 |
39 | if (
40 | hostname ===
41 | 'public-url-that-redirects-to-private-url-that-redirects-to-public-url.com'
42 | ) {
43 | callback(null, { address: '1.1.1.1', family: 4 })
44 | }
45 |
46 | // Really make sure that all test cases - at least, the ones that resolve an actual hostname -
47 | // have a corresponding DNS mock as well (on top of the HTTP mock).
48 | callback(new Error('DNS lookup was not mocked'))
49 | }
50 |
--------------------------------------------------------------------------------
/index.test.ts:
--------------------------------------------------------------------------------
1 | import { promisify } from 'util'
2 | import nock from 'nock'
3 | import CacheableLookup from 'cacheable-lookup'
4 |
5 | // We can directly mock the "import { lookup } from 'dns'" call in index.js with vitest.
6 | import * as mockDns from './__mocks__/dns.js'
7 | vi.mock('dns', () => mockDns)
8 |
9 | // However, it does mean that we need to do a dynamic import to make sure we load the mocked import.
10 | // See: https://jestjs.io/docs/ecmascript-modules#module-mocking-in-esm
11 | const { gotSsrf } = await import('./index.js')
12 |
13 | nock.disableNetConnect()
14 |
15 | // Whether you pass in dnsCache: true, or an *instance* of CacheableLookup,
16 | // the dnsCache.lookupAsync being used is from an instance of the CacheableLookup class,
17 | // so we don't have to separately test the { dnsCache: true } case.
18 | // We just need to ensure that this library works correctly with a dnsCache.lookupAsync.
19 | const dnsCache = new CacheableLookup()
20 |
21 | // Also, for some reason trying to pass a mocked resolver with a resolve4() and a resolve6()
22 | // that always throws ENOTFOUND doesn't work (i.e. it doesn't use the `lookup` we pass to the options).
23 | // So we just directly mock lookupAsync.
24 | vi.spyOn(dnsCache, 'lookupAsync').mockImplementation(
25 | promisify(mockDns.lookup) as CacheableLookup['lookupAsync']
26 | )
27 |
28 | const setups = [
29 | {
30 | title: 'dnsCache',
31 | options: {
32 | dnsCache
33 | }
34 | },
35 | {
36 | title: 'dnsLookup',
37 | options: {
38 | dnsLookup: mockDns.lookup as unknown as CacheableLookup['lookup']
39 | }
40 | },
41 | {
42 | title: 'native dns',
43 | options: {}
44 | }
45 | ]
46 |
47 | describe('got-ssrf', () => {
48 | describe.each(setups)('w/ $title', ({ options }) => {
49 | const got = gotSsrf.extend(options)
50 |
51 | it('rejects non-http(s) protocols', async () => {
52 | await expect(got('ftp://example.com')).rejects.toThrow(
53 | 'Unsupported protocol: ftp'
54 | )
55 |
56 | await expect(got('http2://example.com')).rejects.toThrow(
57 | 'Unsupported protocol: http2'
58 | )
59 |
60 | await expect(got('file:///etc/passwd')).rejects.toThrow(
61 | 'Unsupported protocol: file'
62 | )
63 |
64 | // You *need* to specify the protocol
65 | await expect(got('example.com')).rejects.toThrow('Invalid URL')
66 | })
67 |
68 | it('works for public address', async () => {
69 | nock('http://public-url.com').get('/').reply(200)
70 | await got('http://public-url.com/')
71 | })
72 |
73 | it('throws for reserved addresses', async () => {
74 | nock('http://private-url.com').get('/').reply(200)
75 | await expect(got('http://private-url.com/')).rejects.toThrow(
76 | 'The IP of the domain is reserved!'
77 | )
78 | })
79 |
80 | it('checks every redirect', async () => {
81 | // Basically, we prevent "smuggling" internal endpoints from a public hostname
82 | // by checking the URL before every redirect.
83 | // In this example, the seemingly public URL redirects to private-url.com,
84 | // so even though the private-url.com ultimately redirects the URL to a public one,
85 | // we must still reject this request!
86 | nock(
87 | 'http://public-url-that-redirects-to-private-url-that-redirects-to-public-url.com'
88 | )
89 | .get('/')
90 | .reply(301, 'Moved', { Location: 'http://private-url.com/' })
91 | nock('http://private-url.com')
92 | .get('/')
93 | .reply(301, 'Moved', { Location: 'http://public-url.com/' })
94 | nock('http://public-url.com').get('/').reply(200)
95 | await expect(
96 | got(
97 | 'http://public-url-that-redirects-to-private-url-that-redirects-to-public-url.com'
98 | )
99 | ).rejects.toThrow('The IP of the domain is reserved!')
100 | })
101 |
102 | it('handles weird URLs/edge cases', async () => {
103 | await expect(got('http://public-url.com.')).rejects.toThrow(
104 | 'The IP of the domain is reserved!'
105 | )
106 |
107 | await expect(got('http://example.com:foo')).rejects.toThrow('Invalid URL')
108 |
109 | // Below are trick cases from https://azeemba.com/posts/what-is-a-url.html#query-or-username
110 |
111 | // Based on the http://http://http://@http://http://?http://#http:// example.
112 | await expect(
113 | got('http://private://part2://@part3://part4://?part5://#part6://')
114 | ).rejects.toThrow('The IP of the domain is reserved!')
115 |
116 | // Query or Username?
117 | await expect(got('http://1.1.1.1 &@ 2.2.2.2# @3.3.3.3/')).rejects.toThrow(
118 | 'Invalid URL'
119 | )
120 |
121 | await expect(got('http://1.1.1.1&@127.0.0.1#@3.3.3.3/')).rejects.toThrow(
122 | 'The IP of the domain is reserved!'
123 | )
124 |
125 | // Port or Path?
126 | await expect(got('http://127.0.0.1:5000:80/')).rejects.toThrow(
127 | 'Invalid URL'
128 | )
129 |
130 | // Host confusion (see: https://daniel.haxx.se/blog/2021/04/19/curl-those-funny-ipv4-addresses/)
131 | await expect(got('http://127.0.1')).rejects.toThrow(
132 | 'The IP of the domain is reserved!' // the first number assumed to be 8 bits, the next 8, then 16
133 | )
134 | await expect(got('http://127.1')).rejects.toThrow(
135 | 'The IP of the domain is reserved!' // the first number assumed to be 8 bits, the next one 24
136 | )
137 | await expect(got('http://2130706433')).rejects.toThrow(
138 | 'The IP of the domain is reserved!' // 32-bit number converted as IPv4 addresses
139 | )
140 | await expect(got('http://0300.0250.0.01')).rejects.toThrow(
141 | 'The IP of the domain is reserved!' // zero-prefix = octal number -> converted to 192.168.0.1
142 | )
143 | await expect(got('http://0xc0.0xa8.0x00.0x01')).rejects.toThrow(
144 | 'The IP of the domain is reserved!' // same deal, but octal
145 | )
146 |
147 | // Other weird hostnames
148 | await expect(got('http://example.com%2F10.0.0.1/')).rejects.toThrow(
149 | 'Invalid URL'
150 | )
151 | })
152 |
153 | // NOTE: for IP address tests, any valid IP address will be processed directly in the code,
154 | // without the need for a DNS lookup (after all, you do a DNS lookup to get the IP address).
155 | // Therefore, we do not need DNS mocks (__mocks__/dns.js) for the tests below.
156 |
157 | it('handles IPv4 addresses', async () => {
158 | // A private IPv4 address
159 | await expect(got('http://192.168.0.1')).rejects.toThrow(
160 | 'The IP of the domain is reserved!'
161 | )
162 |
163 | // Commonly used for metadata services in cloud environments
164 | await expect(got('http://169.254.169.254')).rejects.toThrow(
165 | 'The IP of the domain is reserved!'
166 | )
167 |
168 | // A public IPv4 address
169 | nock('http://1.1.1.1').get('/').reply(200)
170 | await got('http://1.1.1.1')
171 | })
172 |
173 | it('handles IPv6 addresses', async () => {
174 | // This is 127.0.0.1 mapped to IPv6
175 | await expect(got('http://[::ffff:7f00:1]:1338/hello')).rejects.toThrow(
176 | 'The IP of the domain is reserved!'
177 | )
178 |
179 | // A public IPv4 address (1.1.1.1) mapped to IPv6
180 | nock('http://[::ffff:101:101]').get('/').reply(200)
181 | await got('http://[::ffff:101:101]')
182 |
183 | // A public IPv6 address
184 | nock('http://[2606:2800:220:1:248:1893:25c8:1946]').get('/').reply(200)
185 | await got('http://[2606:2800:220:1:248:1893:25c8:1946]')
186 |
187 | // A private IPv6 address
188 | await expect(got('http://[::1]')).rejects.toThrow(
189 | 'The IP of the domain is reserved!'
190 | )
191 | })
192 |
193 | it('handles hostnames with brackets in it', async () => {
194 | await expect(got('http://[hostname1.com')).rejects.toThrow('Invalid URL')
195 |
196 | await expect(got('http://[hostnam]e2.com')).rejects.toThrow('Invalid URL')
197 |
198 | await expect(
199 | got('http://[2606:2800:220:1:248:1893:25c8:g]')
200 | ).rejects.toThrow('Invalid URL')
201 | })
202 | })
203 | })
204 |
--------------------------------------------------------------------------------
/index.ts:
--------------------------------------------------------------------------------
1 | import { lookup as nativeCallbackLookup } from 'dns'
2 | import { promisify } from 'util'
3 | import got, { Options } from 'got'
4 | import ip from 'ipaddr.js'
5 | import debugGen from 'debug'
6 |
7 | import type CacheableLookup from 'cacheable-lookup'
8 |
9 | const debug = debugGen('got-ssrf')
10 | const nativeLookup = promisify(nativeCallbackLookup) // importing straight from dns/promises limits node.js version to 15 or higher
11 |
12 | type LookupFn = (hostname: string) => Promise<{ address: string }>
13 |
14 | // Assume all URLs are properly formed by the time it hits the hooks
15 | const protect = async (options: Options) => {
16 | let lookup: LookupFn
17 | if (options.dnsCache) {
18 | debug('Using user-provided dnsCache.lookupAsync')
19 | lookup = (options.dnsCache as CacheableLookup).lookupAsync
20 | } else if (options.dnsLookup) {
21 | debug('Promisifying user-provided dnsLookup')
22 | lookup = promisify(
23 | options.dnsLookup
24 | ) as unknown as CacheableLookup['lookupAsync'] // yay wildly incorrect types
25 | } else {
26 | debug('Falling back to native dns/promises lookup')
27 | lookup = nativeLookup
28 | }
29 |
30 | // To prevent Server Side Request Forgery, we need to check the protocol.
31 | // Otherwise, you could end up making requests to internal services (e.g. the database)
32 | // that are within the same network but is not intended to be reached by the user.
33 | // This is done automatically by got, so we don't need to do anything here:
34 | // https://github.com/sindresorhus/got/blob/8f77e8d07d8684cde95d351feafaa308b466dff4/source/core/options.ts#L1411
35 |
36 | // Check if the hostname is an IP address - we don't need to "lookup" IP addresses!
37 | let IP: string
38 |
39 | // Even the got author himself casts this incorrect type: https://github.com/sindresorhus/got/blob/b1d61c173a681755ac23afb2f155f08801c1e7e4/source/core/index.ts#L1121
40 | const { hostname } = options.url as URL
41 |
42 | if (ip.IPv4.isIPv4(hostname)) {
43 | IP = hostname
44 | } else if (
45 | // Per https://url.spec.whatwg.org/#host-parsing,
46 | // if the hostname starts with a [, we need to check if it ends with a ], and is an IPv6.
47 | hostname.startsWith('[') &&
48 | hostname.endsWith(']') &&
49 | ip.IPv6.isIPv6(hostname.slice(1, -1)) // strip the first and last characters - the brackets
50 | ) {
51 | IP = hostname.slice(1, -1)
52 | } else {
53 | // A regular hostname - we need to do a DNS lookup to get the IP address
54 | const { address } = await lookup(hostname)
55 | IP = address
56 | }
57 |
58 | // Another layer of protection against SSRF - ensure we're not hitting internal services.
59 | // Try to match "reserved" IP ranges: https://en.wikipedia.org/wiki/Reserved_IP_addresses
60 | // https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html#case-2-application-can-send-requests-to-any-external-ip-address-or-domain-name
61 | // The function returns 'unicast' or the name of the reserved IP range, should it match any.
62 | // This in effect blocks all private IP Range: https://git.io/JWy3u, https://git.io/JWy3b
63 | // We use ip.process() here to deal with potentially IPv4-mapped IPv6 addresses (which will show up as "ipv4mapped"
64 | // and not the whatever range the actual IPv4 address actually belongs to).
65 | if (ip.process(IP).range() !== 'unicast')
66 | throw new Error('The IP of the domain is reserved!')
67 | }
68 |
69 | export const gotSsrf = got.extend({
70 | hooks: {
71 | beforeRequest: [protect],
72 | beforeRedirect: [protect]
73 | }
74 | })
75 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "got-ssrf",
3 | "version": "3.0.0",
4 | "description": "Protect Got requests from SSRF",
5 | "type": "module",
6 | "repository": "hanover-computing/got-ssrf",
7 | "author": "Jane Jeon ",
8 | "license": "LGPL-3.0",
9 | "engines": {
10 | "node": ">=16"
11 | },
12 | "files": [
13 | "dist"
14 | ],
15 | "main": "dist/index.js",
16 | "types": "dist/index.d.ts",
17 | "scripts": {
18 | "typecheck": "tsc -p tsconfig.build.json --noEmit",
19 | "build": "tsc -p tsconfig.build.json",
20 | "test": "vitest",
21 | "test:cov": "vitest run --coverage",
22 | "test:ui": "vitest --ui",
23 | "lint": "run-s lint:*",
24 | "lint:prettier": "prettier --check . --ignore-path .gitignore",
25 | "lint:eslint": "eslint . --ignore-path .gitignore",
26 | "prepare": "husky install",
27 | "prepublishOnly": "npm run build"
28 | },
29 | "dependencies": {
30 | "debug": "^4.3.2",
31 | "ipaddr.js": "^2.0.1"
32 | },
33 | "devDependencies": {
34 | "@janejeon/eslint-config-typescript": "^0.1.0",
35 | "@janejeon/prettier-config": "^2.0.0",
36 | "@janejeon/tsconfig": "^0.3.1",
37 | "@types/debug": "^4.1.8",
38 | "@types/node": "^20.5.1",
39 | "@vitest/coverage-istanbul": "^1.0.0",
40 | "@vitest/ui": "^1.0.0",
41 | "cacheable-lookup": "^7.0.0",
42 | "husky": "^8.0.1",
43 | "lint-staged": "^15.0.0",
44 | "nock": "^13.1.3",
45 | "npm-run-all2": "^6.0.0",
46 | "skip-ci": "^1.0.4",
47 | "typescript": "^5.1.6",
48 | "vitest": "^1.0.0"
49 | },
50 | "peerDependencies": {
51 | "got": "^14"
52 | },
53 | "keywords": [
54 | "http",
55 | "https",
56 | "http2",
57 | "get",
58 | "got",
59 | "url",
60 | "uri",
61 | "request",
62 | "simple",
63 | "curl",
64 | "wget",
65 | "fetch",
66 | "net",
67 | "network",
68 | "gzip",
69 | "brotli",
70 | "requests",
71 | "human-friendly",
72 | "axios",
73 | "superagent",
74 | "node-fetch",
75 | "ky",
76 | "ssrf",
77 | "csrf",
78 | "security",
79 | "plugin"
80 | ]
81 | }
82 |
--------------------------------------------------------------------------------
/renovate.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 | "extends": ["github>JaneJeon/dev//packages/renovate-config/default.json"]
4 | }
5 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "include": ["index.ts"],
4 | "compilerOptions": {
5 | "outDir": "dist",
6 | "declaration": true,
7 | "skipLibCheck": true
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "@janejeon/tsconfig",
3 | "compilerOptions": {
4 | "types": ["vitest/globals"]
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/vite.config.ts:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vitest/config'
2 |
3 | export default defineConfig({
4 | test: {
5 | globals: true,
6 | coverage: {
7 | provider: 'istanbul',
8 | include: ['index.ts']
9 | }
10 | }
11 | })
12 |
--------------------------------------------------------------------------------