├── .github
└── workflows
│ ├── build.yaml
│ └── lint.yaml
├── .gitignore
├── .golangci.yml
├── LICENSE
├── README.md
├── auth.go
├── config.go
├── context.go
├── examples
├── auth
│ ├── README.md
│ └── main.go
├── mitm
│ ├── README.md
│ ├── demo.crt
│ ├── demo.key
│ └── main.go
└── simple
│ └── main.go
├── go.mod
├── go.sum
├── helper.go
├── hopbyhop.go
├── mitm
├── mitm.go
└── mitm_test.go
├── proxy.go
└── proxyutil
└── util.go
/.github/workflows/build.yaml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | 'env':
4 | 'GO_VERSION': '1.20'
5 |
6 | 'on':
7 | 'push':
8 | 'tags':
9 | - 'v*'
10 | 'branches':
11 | - '*'
12 | 'pull_request':
13 |
14 | jobs:
15 | tests:
16 | runs-on: ${{ matrix.os }}
17 | strategy:
18 | matrix:
19 | os:
20 | - windows-latest
21 | - macos-latest
22 | - ubuntu-latest
23 | steps:
24 | - uses: actions/checkout@v3
25 | - uses: actions/setup-go@v3
26 | with:
27 | go-version: '${{ env.GO_VERSION }}'
28 | - name: Run tests
29 | env:
30 | CI: "1"
31 | run: |-
32 | go test -race -v -bench="." -coverprofile="coverage.txt" -covermode=atomic ./...
33 | - name: Upload coverage
34 | uses: codecov/codecov-action@v1
35 | if: "success() && matrix.os == 'ubuntu-latest'"
36 | with:
37 | token: ${{ secrets.CODECOV_TOKEN }}
38 | file: ./coverage.txt
39 |
40 | notify:
41 | needs:
42 | - tests
43 | if:
44 | ${{ always() &&
45 | (
46 | github.event_name == 'push' ||
47 | github.event.pull_request.head.repo.full_name == github.repository
48 | )
49 | }}
50 | runs-on: ubuntu-latest
51 | steps:
52 | - name: Conclusion
53 | uses: technote-space/workflow-conclusion-action@v1
54 | - name: Send Slack notif
55 | uses: 8398a7/action-slack@v3
56 | with:
57 | status: ${{ env.WORKFLOW_CONCLUSION }}
58 | fields: workflow, repo, message, commit, author, eventName,ref
59 | env:
60 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
61 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
62 |
63 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yaml:
--------------------------------------------------------------------------------
1 | name: golangci-lint
2 |
3 | 'env':
4 | 'GO_VERSION': '1.19'
5 |
6 | 'on':
7 | 'push':
8 | 'tags':
9 | - 'v*'
10 | 'branches':
11 | - '*'
12 | 'pull_request':
13 |
14 | jobs:
15 | golangci:
16 | runs-on:
17 | ${{ matrix.os }}
18 | strategy:
19 | matrix:
20 | os:
21 | - ubuntu-latest
22 | - macos-latest
23 | steps:
24 | - uses: actions/checkout@v3
25 | - uses: actions/setup-go@v3
26 | with:
27 | go-version: '${{ env.GO_VERSION }}'
28 |
29 | - name: golangci-lint
30 | uses: golangci/golangci-lint-action@v3
31 | with:
32 | # This field is required. Dont set the patch version to always use
33 | # the latest patch version.
34 | version: v1.52.2
35 | notify:
36 | needs:
37 | - golangci
38 | # Secrets are not passed to workflows that are triggered by a pull request
39 | # from a fork.
40 | #
41 | # Use always() to signal to the runner that this job must run even if the
42 | # previous ones failed.
43 | if:
44 | ${{ always() &&
45 | (
46 | github.event_name == 'push' ||
47 | github.event.pull_request.head.repo.full_name == github.repository
48 | )
49 | }}
50 | runs-on: ubuntu-latest
51 | steps:
52 | - name: Conclusion
53 | uses: technote-space/workflow-conclusion-action@v1
54 | - name: Send Slack notif
55 | uses: 8398a7/action-slack@v3
56 | with:
57 | status: ${{ env.WORKFLOW_CONCLUSION }}
58 | fields: workflow, repo, message, commit, author, eventName, ref
59 | env:
60 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
61 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
62 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | .idea
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | # options for analysis running
2 | run:
3 | # default concurrency is a available CPU number
4 | concurrency: 4
5 |
6 | # timeout for analysis, e.g. 30s, 5m, default is 1m
7 | deadline: 2m
8 |
9 | # which files to skip: they will be analyzed, but issues from them
10 | # won't be reported. Default value is empty list, but there is
11 | # no need to include all autogenerated files, we confidently recognize
12 | # autogenerated files. If it's not please let us know.
13 | skip-files:
14 | - ".*generated.*"
15 |
16 | # all available settings of specific linters
17 | linters-settings:
18 | gocyclo:
19 | min-complexity: 20
20 | lll:
21 | line-length: 120
22 |
23 | linters:
24 | enable:
25 | - errcheck
26 | - govet
27 | - ineffassign
28 | - staticcheck
29 | - unused
30 | - depguard
31 | - dupl
32 | - gocyclo
33 | - goimports
34 | - revive
35 | - gosec
36 | - misspell
37 | - stylecheck
38 | - unconvert
39 | disable-all: true
40 | fast: true
41 |
42 | issues:
43 | exclude-use-default: false
44 |
45 | # List of regexps of issue texts to exclude, empty list by default.
46 | # But independently from this option we use default exclude patterns,
47 | # it can be disabled by `exclude-use-default: false`. To list all
48 | # excluded by default patterns execute `golangci-lint run --help`
49 | exclude:
50 | # gosec: False positive is triggered by 'src, err := os.ReadFile(filename)'
51 | - Potential file inclusion via variable
52 | # gosec: TLS InsecureSkipVerify may be true
53 | # We have a configuration option that allows to do this
54 | - G402
55 | # gosec: Use of weak random number generator
56 | - G404
57 | # gosec: Use of weak cryptographic primitive
58 | - G401
59 | # gosec: Blocklisted import crypto/sha1: weak cryptographic primitive
60 | - G505
61 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | ### GNU GENERAL PUBLIC LICENSE
2 |
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 |
7 |
8 | Everyone is permitted to copy and distribute verbatim copies of this
9 | license document, but changing it is not allowed.
10 |
11 | ### Preamble
12 |
13 | The GNU General Public License is a free, copyleft license for
14 | software and other kinds of works.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | the GNU General Public License is intended to guarantee your freedom
19 | to share and change all versions of a program--to make sure it remains
20 | free software for all its users. We, the Free Software Foundation, use
21 | the GNU General Public License for most of our software; it applies
22 | also to any other work released this way by its authors. You can apply
23 | it to your programs, too.
24 |
25 | When we speak of free software, we are referring to freedom, not
26 | price. Our General Public Licenses are designed to make sure that you
27 | have the freedom to distribute copies of free software (and charge for
28 | them if you wish), that you receive source code or can get it if you
29 | want it, that you can change the software or use pieces of it in new
30 | free programs, and that you know you can do these things.
31 |
32 | To protect your rights, we need to prevent others from denying you
33 | these rights or asking you to surrender the rights. Therefore, you
34 | have certain responsibilities if you distribute copies of the
35 | software, or if you modify it: responsibilities to respect the freedom
36 | of others.
37 |
38 | For example, if you distribute copies of such a program, whether
39 | gratis or for a fee, you must pass on to the recipients the same
40 | freedoms that you received. You must make sure that they, too, receive
41 | or can get the source code. And you must show them these terms so they
42 | know their rights.
43 |
44 | Developers that use the GNU GPL protect your rights with two steps:
45 | (1) assert copyright on the software, and (2) offer you this License
46 | giving you legal permission to copy, distribute and/or modify it.
47 |
48 | For the developers' and authors' protection, the GPL clearly explains
49 | that there is no warranty for this free software. For both users' and
50 | authors' sake, the GPL requires that modified versions be marked as
51 | changed, so that their problems will not be attributed erroneously to
52 | authors of previous versions.
53 |
54 | Some devices are designed to deny users access to install or run
55 | modified versions of the software inside them, although the
56 | manufacturer can do so. This is fundamentally incompatible with the
57 | aim of protecting users' freedom to change the software. The
58 | systematic pattern of such abuse occurs in the area of products for
59 | individuals to use, which is precisely where it is most unacceptable.
60 | Therefore, we have designed this version of the GPL to prohibit the
61 | practice for those products. If such problems arise substantially in
62 | other domains, we stand ready to extend this provision to those
63 | domains in future versions of the GPL, as needed to protect the
64 | freedom of users.
65 |
66 | Finally, every program is threatened constantly by software patents.
67 | States should not allow patents to restrict development and use of
68 | software on general-purpose computers, but in those that do, we wish
69 | to avoid the special danger that patents applied to a free program
70 | could make it effectively proprietary. To prevent this, the GPL
71 | assures that patents cannot be used to render the program non-free.
72 |
73 | The precise terms and conditions for copying, distribution and
74 | modification follow.
75 |
76 | ### TERMS AND CONDITIONS
77 |
78 | #### 0. Definitions.
79 |
80 | "This License" refers to version 3 of the GNU General Public License.
81 |
82 | "Copyright" also means copyright-like laws that apply to other kinds
83 | of works, such as semiconductor masks.
84 |
85 | "The Program" refers to any copyrightable work licensed under this
86 | License. Each licensee is addressed as "you". "Licensees" and
87 | "recipients" may be individuals or organizations.
88 |
89 | To "modify" a work means to copy from or adapt all or part of the work
90 | in a fashion requiring copyright permission, other than the making of
91 | an exact copy. The resulting work is called a "modified version" of
92 | the earlier work or a work "based on" the earlier work.
93 |
94 | A "covered work" means either the unmodified Program or a work based
95 | on the Program.
96 |
97 | To "propagate" a work means to do anything with it that, without
98 | permission, would make you directly or secondarily liable for
99 | infringement under applicable copyright law, except executing it on a
100 | computer or modifying a private copy. Propagation includes copying,
101 | distribution (with or without modification), making available to the
102 | public, and in some countries other activities as well.
103 |
104 | To "convey" a work means any kind of propagation that enables other
105 | parties to make or receive copies. Mere interaction with a user
106 | through a computer network, with no transfer of a copy, is not
107 | conveying.
108 |
109 | An interactive user interface displays "Appropriate Legal Notices" to
110 | the extent that it includes a convenient and prominently visible
111 | feature that (1) displays an appropriate copyright notice, and (2)
112 | tells the user that there is no warranty for the work (except to the
113 | extent that warranties are provided), that licensees may convey the
114 | work under this License, and how to view a copy of this License. If
115 | the interface presents a list of user commands or options, such as a
116 | menu, a prominent item in the list meets this criterion.
117 |
118 | #### 1. Source Code.
119 |
120 | The "source code" for a work means the preferred form of the work for
121 | making modifications to it. "Object code" means any non-source form of
122 | a work.
123 |
124 | A "Standard Interface" means an interface that either is an official
125 | standard defined by a recognized standards body, or, in the case of
126 | interfaces specified for a particular programming language, one that
127 | is widely used among developers working in that language.
128 |
129 | The "System Libraries" of an executable work include anything, other
130 | than the work as a whole, that (a) is included in the normal form of
131 | packaging a Major Component, but which is not part of that Major
132 | Component, and (b) serves only to enable use of the work with that
133 | Major Component, or to implement a Standard Interface for which an
134 | implementation is available to the public in source code form. A
135 | "Major Component", in this context, means a major essential component
136 | (kernel, window system, and so on) of the specific operating system
137 | (if any) on which the executable work runs, or a compiler used to
138 | produce the work, or an object code interpreter used to run it.
139 |
140 | The "Corresponding Source" for a work in object code form means all
141 | the source code needed to generate, install, and (for an executable
142 | work) run the object code and to modify the work, including scripts to
143 | control those activities. However, it does not include the work's
144 | System Libraries, or general-purpose tools or generally available free
145 | programs which are used unmodified in performing those activities but
146 | which are not part of the work. For example, Corresponding Source
147 | includes interface definition files associated with source files for
148 | the work, and the source code for shared libraries and dynamically
149 | linked subprograms that the work is specifically designed to require,
150 | such as by intimate data communication or control flow between those
151 | subprograms and other parts of the work.
152 |
153 | The Corresponding Source need not include anything that users can
154 | regenerate automatically from other parts of the Corresponding Source.
155 |
156 | The Corresponding Source for a work in source code form is that same
157 | work.
158 |
159 | #### 2. Basic Permissions.
160 |
161 | All rights granted under this License are granted for the term of
162 | copyright on the Program, and are irrevocable provided the stated
163 | conditions are met. This License explicitly affirms your unlimited
164 | permission to run the unmodified Program. The output from running a
165 | covered work is covered by this License only if the output, given its
166 | content, constitutes a covered work. This License acknowledges your
167 | rights of fair use or other equivalent, as provided by copyright law.
168 |
169 | You may make, run and propagate covered works that you do not convey,
170 | without conditions so long as your license otherwise remains in force.
171 | You may convey covered works to others for the sole purpose of having
172 | them make modifications exclusively for you, or provide you with
173 | facilities for running those works, provided that you comply with the
174 | terms of this License in conveying all material for which you do not
175 | control copyright. Those thus making or running the covered works for
176 | you must do so exclusively on your behalf, under your direction and
177 | control, on terms that prohibit them from making any copies of your
178 | copyrighted material outside their relationship with you.
179 |
180 | Conveying under any other circumstances is permitted solely under the
181 | conditions stated below. Sublicensing is not allowed; section 10 makes
182 | it unnecessary.
183 |
184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185 |
186 | No covered work shall be deemed part of an effective technological
187 | measure under any applicable law fulfilling obligations under article
188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 | similar laws prohibiting or restricting circumvention of such
190 | measures.
191 |
192 | When you convey a covered work, you waive any legal power to forbid
193 | circumvention of technological measures to the extent such
194 | circumvention is effected by exercising rights under this License with
195 | respect to the covered work, and you disclaim any intention to limit
196 | operation or modification of the work as a means of enforcing, against
197 | the work's users, your or third parties' legal rights to forbid
198 | circumvention of technological measures.
199 |
200 | #### 4. Conveying Verbatim Copies.
201 |
202 | You may convey verbatim copies of the Program's source code as you
203 | receive it, in any medium, provided that you conspicuously and
204 | appropriately publish on each copy an appropriate copyright notice;
205 | keep intact all notices stating that this License and any
206 | non-permissive terms added in accord with section 7 apply to the code;
207 | keep intact all notices of the absence of any warranty; and give all
208 | recipients a copy of this License along with the Program.
209 |
210 | You may charge any price or no price for each copy that you convey,
211 | and you may offer support or warranty protection for a fee.
212 |
213 | #### 5. Conveying Modified Source Versions.
214 |
215 | You may convey a work based on the Program, or the modifications to
216 | produce it from the Program, in the form of source code under the
217 | terms of section 4, provided that you also meet all of these
218 | conditions:
219 |
220 | - a) The work must carry prominent notices stating that you modified
221 | it, and giving a relevant date.
222 | - b) The work must carry prominent notices stating that it is
223 | released under this License and any conditions added under
224 | section 7. This requirement modifies the requirement in section 4
225 | to "keep intact all notices".
226 | - c) You must license the entire work, as a whole, under this
227 | License to anyone who comes into possession of a copy. This
228 | License will therefore apply, along with any applicable section 7
229 | additional terms, to the whole of the work, and all its parts,
230 | regardless of how they are packaged. This License gives no
231 | permission to license the work in any other way, but it does not
232 | invalidate such permission if you have separately received it.
233 | - d) If the work has interactive user interfaces, each must display
234 | Appropriate Legal Notices; however, if the Program has interactive
235 | interfaces that do not display Appropriate Legal Notices, your
236 | work need not make them do so.
237 |
238 | A compilation of a covered work with other separate and independent
239 | works, which are not by their nature extensions of the covered work,
240 | and which are not combined with it such as to form a larger program,
241 | in or on a volume of a storage or distribution medium, is called an
242 | "aggregate" if the compilation and its resulting copyright are not
243 | used to limit the access or legal rights of the compilation's users
244 | beyond what the individual works permit. Inclusion of a covered work
245 | in an aggregate does not cause this License to apply to the other
246 | parts of the aggregate.
247 |
248 | #### 6. Conveying Non-Source Forms.
249 |
250 | You may convey a covered work in object code form under the terms of
251 | sections 4 and 5, provided that you also convey the machine-readable
252 | Corresponding Source under the terms of this License, in one of these
253 | ways:
254 |
255 | - a) Convey the object code in, or embodied in, a physical product
256 | (including a physical distribution medium), accompanied by the
257 | Corresponding Source fixed on a durable physical medium
258 | customarily used for software interchange.
259 | - b) Convey the object code in, or embodied in, a physical product
260 | (including a physical distribution medium), accompanied by a
261 | written offer, valid for at least three years and valid for as
262 | long as you offer spare parts or customer support for that product
263 | model, to give anyone who possesses the object code either (1) a
264 | copy of the Corresponding Source for all the software in the
265 | product that is covered by this License, on a durable physical
266 | medium customarily used for software interchange, for a price no
267 | more than your reasonable cost of physically performing this
268 | conveying of source, or (2) access to copy the Corresponding
269 | Source from a network server at no charge.
270 | - c) Convey individual copies of the object code with a copy of the
271 | written offer to provide the Corresponding Source. This
272 | alternative is allowed only occasionally and noncommercially, and
273 | only if you received the object code with such an offer, in accord
274 | with subsection 6b.
275 | - d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 | - e) Convey the object code using peer-to-peer transmission,
288 | provided you inform other peers where the object code and
289 | Corresponding Source of the work are being offered to the general
290 | public at no charge under subsection 6d.
291 |
292 | A separable portion of the object code, whose source code is excluded
293 | from the Corresponding Source as a System Library, need not be
294 | included in conveying the object code work.
295 |
296 | A "User Product" is either (1) a "consumer product", which means any
297 | tangible personal property which is normally used for personal,
298 | family, or household purposes, or (2) anything designed or sold for
299 | incorporation into a dwelling. In determining whether a product is a
300 | consumer product, doubtful cases shall be resolved in favor of
301 | coverage. For a particular product received by a particular user,
302 | "normally used" refers to a typical or common use of that class of
303 | product, regardless of the status of the particular user or of the way
304 | in which the particular user actually uses, or expects or is expected
305 | to use, the product. A product is a consumer product regardless of
306 | whether the product has substantial commercial, industrial or
307 | non-consumer uses, unless such uses represent the only significant
308 | mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to
312 | install and execute modified versions of a covered work in that User
313 | Product from a modified version of its Corresponding Source. The
314 | information must suffice to ensure that the continued functioning of
315 | the modified object code is in no case prevented or interfered with
316 | solely because modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or
331 | updates for a work that has been modified or installed by the
332 | recipient, or for the User Product in which it has been modified or
333 | installed. Access to a network may be denied when the modification
334 | itself materially and adversely affects the operation of the network
335 | or violates the rules and protocols for communication across the
336 | network.
337 |
338 | Corresponding Source conveyed, and Installation Information provided,
339 | in accord with this section must be in a format that is publicly
340 | documented (and with an implementation available to the public in
341 | source code form), and must require no special password or key for
342 | unpacking, reading or copying.
343 |
344 | #### 7. Additional Terms.
345 |
346 | "Additional permissions" are terms that supplement the terms of this
347 | License by making exceptions from one or more of its conditions.
348 | Additional permissions that are applicable to the entire Program shall
349 | be treated as though they were included in this License, to the extent
350 | that they are valid under applicable law. If additional permissions
351 | apply only to part of the Program, that part may be used separately
352 | under those permissions, but the entire Program remains governed by
353 | this License without regard to the additional permissions.
354 |
355 | When you convey a copy of a covered work, you may at your option
356 | remove any additional permissions from that copy, or from any part of
357 | it. (Additional permissions may be written to require their own
358 | removal in certain cases when you modify the work.) You may place
359 | additional permissions on material, added by you to a covered work,
360 | for which you have or can give appropriate copyright permission.
361 |
362 | Notwithstanding any other provision of this License, for material you
363 | add to a covered work, you may (if authorized by the copyright holders
364 | of that material) supplement the terms of this License with terms:
365 |
366 | - a) Disclaiming warranty or limiting liability differently from the
367 | terms of sections 15 and 16 of this License; or
368 | - b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 | - c) Prohibiting misrepresentation of the origin of that material,
372 | or requiring that modified versions of such material be marked in
373 | reasonable ways as different from the original version; or
374 | - d) Limiting the use for publicity purposes of names of licensors
375 | or authors of the material; or
376 | - e) Declining to grant rights under trademark law for use of some
377 | trade names, trademarks, or service marks; or
378 | - f) Requiring indemnification of licensors and authors of that
379 | material by anyone who conveys the material (or modified versions
380 | of it) with contractual assumptions of liability to the recipient,
381 | for any liability that these contractual assumptions directly
382 | impose on those licensors and authors.
383 |
384 | All other non-permissive additional terms are considered "further
385 | restrictions" within the meaning of section 10. If the Program as you
386 | received it, or any part of it, contains a notice stating that it is
387 | governed by this License along with a term that is a further
388 | restriction, you may remove that term. If a license document contains
389 | a further restriction but permits relicensing or conveying under this
390 | License, you may add to a covered work material governed by the terms
391 | of that license document, provided that the further restriction does
392 | not survive such relicensing or conveying.
393 |
394 | If you add terms to a covered work in accord with this section, you
395 | must place, in the relevant source files, a statement of the
396 | additional terms that apply to those files, or a notice indicating
397 | where to find the applicable terms.
398 |
399 | Additional terms, permissive or non-permissive, may be stated in the
400 | form of a separately written license, or stated as exceptions; the
401 | above requirements apply either way.
402 |
403 | #### 8. Termination.
404 |
405 | You may not propagate or modify a covered work except as expressly
406 | provided under this License. Any attempt otherwise to propagate or
407 | modify it is void, and will automatically terminate your rights under
408 | this License (including any patent licenses granted under the third
409 | paragraph of section 11).
410 |
411 | However, if you cease all violation of this License, then your license
412 | from a particular copyright holder is reinstated (a) provisionally,
413 | unless and until the copyright holder explicitly and finally
414 | terminates your license, and (b) permanently, if the copyright holder
415 | fails to notify you of the violation by some reasonable means prior to
416 | 60 days after the cessation.
417 |
418 | Moreover, your license from a particular copyright holder is
419 | reinstated permanently if the copyright holder notifies you of the
420 | violation by some reasonable means, this is the first time you have
421 | received notice of violation of this License (for any work) from that
422 | copyright holder, and you cure the violation prior to 30 days after
423 | your receipt of the notice.
424 |
425 | Termination of your rights under this section does not terminate the
426 | licenses of parties who have received copies or rights from you under
427 | this License. If your rights have been terminated and not permanently
428 | reinstated, you do not qualify to receive new licenses for the same
429 | material under section 10.
430 |
431 | #### 9. Acceptance Not Required for Having Copies.
432 |
433 | You are not required to accept this License in order to receive or run
434 | a copy of the Program. Ancillary propagation of a covered work
435 | occurring solely as a consequence of using peer-to-peer transmission
436 | to receive a copy likewise does not require acceptance. However,
437 | nothing other than this License grants you permission to propagate or
438 | modify any covered work. These actions infringe copyright if you do
439 | not accept this License. Therefore, by modifying or propagating a
440 | covered work, you indicate your acceptance of this License to do so.
441 |
442 | #### 10. Automatic Licensing of Downstream Recipients.
443 |
444 | Each time you convey a covered work, the recipient automatically
445 | receives a license from the original licensors, to run, modify and
446 | propagate that work, subject to this License. You are not responsible
447 | for enforcing compliance by third parties with this License.
448 |
449 | An "entity transaction" is a transaction transferring control of an
450 | organization, or substantially all assets of one, or subdividing an
451 | organization, or merging organizations. If propagation of a covered
452 | work results from an entity transaction, each party to that
453 | transaction who receives a copy of the work also receives whatever
454 | licenses to the work the party's predecessor in interest had or could
455 | give under the previous paragraph, plus a right to possession of the
456 | Corresponding Source of the work from the predecessor in interest, if
457 | the predecessor has it or can get it with reasonable efforts.
458 |
459 | You may not impose any further restrictions on the exercise of the
460 | rights granted or affirmed under this License. For example, you may
461 | not impose a license fee, royalty, or other charge for exercise of
462 | rights granted under this License, and you may not initiate litigation
463 | (including a cross-claim or counterclaim in a lawsuit) alleging that
464 | any patent claim is infringed by making, using, selling, offering for
465 | sale, or importing the Program or any portion of it.
466 |
467 | #### 11. Patents.
468 |
469 | A "contributor" is a copyright holder who authorizes use under this
470 | License of the Program or a work on which the Program is based. The
471 | work thus licensed is called the contributor's "contributor version".
472 |
473 | A contributor's "essential patent claims" are all patent claims owned
474 | or controlled by the contributor, whether already acquired or
475 | hereafter acquired, that would be infringed by some manner, permitted
476 | by this License, of making, using, or selling its contributor version,
477 | but do not include claims that would be infringed only as a
478 | consequence of further modification of the contributor version. For
479 | purposes of this definition, "control" includes the right to grant
480 | patent sublicenses in a manner consistent with the requirements of
481 | this License.
482 |
483 | Each contributor grants you a non-exclusive, worldwide, royalty-free
484 | patent license under the contributor's essential patent claims, to
485 | make, use, sell, offer for sale, import and otherwise run, modify and
486 | propagate the contents of its contributor version.
487 |
488 | In the following three paragraphs, a "patent license" is any express
489 | agreement or commitment, however denominated, not to enforce a patent
490 | (such as an express permission to practice a patent or covenant not to
491 | sue for patent infringement). To "grant" such a patent license to a
492 | party means to make such an agreement or commitment not to enforce a
493 | patent against the party.
494 |
495 | If you convey a covered work, knowingly relying on a patent license,
496 | and the Corresponding Source of the work is not available for anyone
497 | to copy, free of charge and under the terms of this License, through a
498 | publicly available network server or other readily accessible means,
499 | then you must either (1) cause the Corresponding Source to be so
500 | available, or (2) arrange to deprive yourself of the benefit of the
501 | patent license for this particular work, or (3) arrange, in a manner
502 | consistent with the requirements of this License, to extend the patent
503 | license to downstream recipients. "Knowingly relying" means you have
504 | actual knowledge that, but for the patent license, your conveying the
505 | covered work in a country, or your recipient's use of the covered work
506 | in a country, would infringe one or more identifiable patents in that
507 | country that you have reason to believe are valid.
508 |
509 | If, pursuant to or in connection with a single transaction or
510 | arrangement, you convey, or propagate by procuring conveyance of, a
511 | covered work, and grant a patent license to some of the parties
512 | receiving the covered work authorizing them to use, propagate, modify
513 | or convey a specific copy of the covered work, then the patent license
514 | you grant is automatically extended to all recipients of the covered
515 | work and works based on it.
516 |
517 | A patent license is "discriminatory" if it does not include within the
518 | scope of its coverage, prohibits the exercise of, or is conditioned on
519 | the non-exercise of one or more of the rights that are specifically
520 | granted under this License. You may not convey a covered work if you
521 | are a party to an arrangement with a third party that is in the
522 | business of distributing software, under which you make payment to the
523 | third party based on the extent of your activity of conveying the
524 | work, and under which the third party grants, to any of the parties
525 | who would receive the covered work from you, a discriminatory patent
526 | license (a) in connection with copies of the covered work conveyed by
527 | you (or copies made from those copies), or (b) primarily for and in
528 | connection with specific products or compilations that contain the
529 | covered work, unless you entered into that arrangement, or that patent
530 | license was granted, prior to 28 March 2007.
531 |
532 | Nothing in this License shall be construed as excluding or limiting
533 | any implied license or other defenses to infringement that may
534 | otherwise be available to you under applicable patent law.
535 |
536 | #### 12. No Surrender of Others' Freedom.
537 |
538 | If conditions are imposed on you (whether by court order, agreement or
539 | otherwise) that contradict the conditions of this License, they do not
540 | excuse you from the conditions of this License. If you cannot convey a
541 | covered work so as to satisfy simultaneously your obligations under
542 | this License and any other pertinent obligations, then as a
543 | consequence you may not convey it at all. For example, if you agree to
544 | terms that obligate you to collect a royalty for further conveying
545 | from those to whom you convey the Program, the only way you could
546 | satisfy both those terms and this License would be to refrain entirely
547 | from conveying the Program.
548 |
549 | #### 13. Use with the GNU Affero General Public License.
550 |
551 | Notwithstanding any other provision of this License, you have
552 | permission to link or combine any covered work with a work licensed
553 | under version 3 of the GNU Affero General Public License into a single
554 | combined work, and to convey the resulting work. The terms of this
555 | License will continue to apply to the part which is the covered work,
556 | but the special requirements of the GNU Affero General Public License,
557 | section 13, concerning interaction through a network will apply to the
558 | combination as such.
559 |
560 | #### 14. Revised Versions of this License.
561 |
562 | The Free Software Foundation may publish revised and/or new versions
563 | of the GNU General Public License from time to time. Such new versions
564 | will be similar in spirit to the present version, but may differ in
565 | detail to address new problems or concerns.
566 |
567 | Each version is given a distinguishing version number. If the Program
568 | specifies that a certain numbered version of the GNU General Public
569 | License "or any later version" applies to it, you have the option of
570 | following the terms and conditions either of that numbered version or
571 | of any later version published by the Free Software Foundation. If the
572 | Program does not specify a version number of the GNU General Public
573 | License, you may choose any version ever published by the Free
574 | Software Foundation.
575 |
576 | If the Program specifies that a proxy can decide which future versions
577 | of the GNU General Public License can be used, that proxy's public
578 | statement of acceptance of a version permanently authorizes you to
579 | choose that version for the Program.
580 |
581 | Later license versions may give you additional or different
582 | permissions. However, no additional obligations are imposed on any
583 | author or copyright holder as a result of your choosing to follow a
584 | later version.
585 |
586 | #### 15. Disclaimer of Warranty.
587 |
588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
596 | CORRECTION.
597 |
598 | #### 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
609 |
610 | #### 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | ### How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these
626 | terms.
627 |
628 | To do so, attach the following notices to the program. It is safest to
629 | attach them to the start of each source file to most effectively state
630 | the exclusion of warranty; and each file should have at least the
631 | "copyright" line and a pointer to where the full notice is found.
632 |
633 |
634 | Copyright (C)
635 |
636 | This program is free software: you can redistribute it and/or modify
637 | it under the terms of the GNU General Public License as published by
638 | the Free Software Foundation, either version 3 of the License, or
639 | (at your option) any later version.
640 |
641 | This program is distributed in the hope that it will be useful,
642 | but WITHOUT ANY WARRANTY; without even the implied warranty of
643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 | GNU General Public License for more details.
645 |
646 | You should have received a copy of the GNU General Public License
647 | along with this program. If not, see .
648 |
649 | Also add information on how to contact you by electronic and paper
650 | mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands \`show w' and \`show c' should show the
661 | appropriate parts of the General Public License. Of course, your
662 | program's commands might be different; for a GUI interface, you would
663 | use an "about box".
664 |
665 | You should also get your employer (if you work as a programmer) or
666 | school, if any, to sign a "copyright disclaimer" for the program, if
667 | necessary. For more information on this, and how to apply and follow
668 | the GNU GPL, see .
669 |
670 | The GNU General Public License does not permit incorporating your
671 | program into proprietary programs. If your program is a subroutine
672 | library, you may consider it more useful to permit linking proprietary
673 | applications with the library. If this is what you want to do, use the
674 | GNU Lesser General Public License instead of this License. But first,
675 | please read .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://codecov.io/github/AdguardTeam/gomitmproxy?branch=master)
2 | [](https://goreportcard.com/report/AdguardTeam/gomitmproxy)
3 | [](https://golangci.com/r/github.com/AdguardTeam/gomitmproxy)
4 | [](https://godoc.org/github.com/AdguardTeam/gomitmproxy)
5 |
6 | # gomitmproxy
7 |
8 | This is a customizable HTTP proxy with TLS interception support.
9 | It was created as a part of [AdGuard Home](https://github.com/AdguardTeam/AdGuardHome).
10 | However, it can be used for different purposes so we decided to make it a separate project.
11 |
12 | ## Features
13 |
14 | * HTTP proxy
15 | * HTTP over TLS (HTTPS) proxy
16 | * Proxy authorization
17 | * TLS termination
18 |
19 | ## How to use gomitmproxy
20 |
21 | ### Simple HTTP proxy
22 |
23 | ```go
24 | package main
25 |
26 | import (
27 | "log"
28 | "net"
29 | "os"
30 | "os/signal"
31 | "syscall"
32 |
33 | "github.com/AdguardTeam/gomitmproxy"
34 | )
35 |
36 | func main() {
37 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
38 | ListenAddr: &net.TCPAddr{
39 | IP: net.IPv4(0, 0, 0, 0),
40 | Port: 8080,
41 | },
42 | })
43 | err := proxy.Start()
44 | if err != nil {
45 | log.Fatal(err)
46 | }
47 |
48 | signalChannel := make(chan os.Signal, 1)
49 | signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
50 | <-signalChannel
51 |
52 | // Clean up
53 | proxy.Close()
54 | }
55 | ```
56 |
57 | ### Modifying requests and responses
58 |
59 | You can modify requests and responses using `OnRequest` and `OnResponse` handlers.
60 |
61 | The example below will block requests to `example.net` and add a short comment to
62 | the end of every HTML response.
63 |
64 | ```go
65 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
66 | ListenAddr: &net.TCPAddr{
67 | IP: net.IPv4(0, 0, 0, 0),
68 | Port: 8080,
69 | },
70 | OnRequest: func(session *gomitmproxy.Session) (request *http.Request, response *http.Response) {
71 | req := session.Request()
72 |
73 | log.Printf("onRequest: %s %s", req.Method, req.URL.String())
74 |
75 | if req.URL.Host == "example.net" {
76 | body := strings.NewReader("Replaced response
")
77 | res := proxyutil.NewResponse(http.StatusOK, body, req)
78 | res.Header.Set("Content-Type", "text/html")
79 |
80 | // Use session props to pass the information about request being blocked
81 | session.SetProp("blocked", true)
82 | return nil, res
83 | }
84 |
85 | return nil, nil
86 | },
87 | OnResponse: func(session *gomitmproxy.Session) *http.Response {
88 | log.Printf("onResponse: %s", session.Request().URL.String())
89 |
90 | if _, ok := session.GetProp("blocked"); ok {
91 | log.Printf("onResponse: was blocked")
92 | }
93 |
94 | res := session.Response()
95 | req := session.Request()
96 |
97 | if strings.Index(res.Header.Get("Content-Type"), "text/html") != 0 {
98 | // Do nothing with non-HTML responses
99 | return nil
100 | }
101 |
102 | b, err := proxyutil.ReadDecompressedBody(res)
103 | // Close the original body
104 | _ = res.Body.Close()
105 | if err != nil {
106 | return proxyutil.NewErrorResponse(req, err)
107 | }
108 |
109 | // Use latin1 before modifying the body
110 | // Using this 1-byte encoding will let us preserve all original characters
111 | // regardless of what exactly is the encoding
112 | body, err := proxyutil.DecodeLatin1(bytes.NewReader(b))
113 | if err != nil {
114 | return proxyutil.NewErrorResponse(session.Request(), err)
115 | }
116 |
117 | // Modifying the original body
118 | modifiedBody, err := proxyutil.EncodeLatin1(body + "")
119 | if err != nil {
120 | return proxyutil.NewErrorResponse(session.Request(), err)
121 | }
122 |
123 | res.Body = ioutil.NopCloser(bytes.NewReader(modifiedBody))
124 | res.Header.Del("Content-Encoding")
125 | res.ContentLength = int64(len(modifiedBody))
126 | return res
127 | },
128 | })
129 | ```
130 |
131 | ### Proxy authorization
132 |
133 | If you want to protect your proxy with Basic authentication, set `Username` and `Password`
134 | fields in the proxy configuration.
135 |
136 | ```go
137 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
138 | ListenAddr: &net.TCPAddr{
139 | IP: net.IPv4(0, 0, 0, 0),
140 | Port: 8080,
141 | },
142 | Username: "user",
143 | Password: "pass",
144 | })
145 | ```
146 |
147 | ### HTTP over TLS (HTTPS) proxy
148 |
149 | If you want to protect yourself from eavesdropping on your traffic to proxy, you can configure
150 | it to work over a TLS tunnel. This is really simple to do, just set a `*tls.Config` instance
151 | in your proxy configuration.
152 |
153 | ```go
154 | tlsConfig := &tls.Config{
155 | Certificates: []tls.Certificate{*proxyCert},
156 | }
157 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
158 | ListenAddr: addr,
159 | TLSConfig: tlsConfig,
160 | })
161 | ```
162 |
163 | ### TLS interception
164 |
165 | If you want to do TLS termination, you first need to prepare a self-signed certificate
166 | that will be used as a certificates authority. Use the following `openssl` commands to do this.
167 |
168 | ```bash
169 | openssl genrsa -out demo.key 2048
170 | openssl req -new -x509 -key demo.key -out demo.crt -days 3650 -addext subjectAltName=DNS:,IP:
171 | ```
172 |
173 | Now you can use it to initialize `MITMConfig`:
174 | ```go
175 | tlsCert, err := tls.LoadX509KeyPair("demo.crt", "demo.key")
176 | if err != nil {
177 | log.Fatal(err)
178 | }
179 | privateKey := tlsCert.PrivateKey.(*rsa.PrivateKey)
180 |
181 | x509c, err := x509.ParseCertificate(tlsCert.Certificate[0])
182 | if err != nil {
183 | log.Fatal(err)
184 | }
185 |
186 | mitmConfig, err := mitm.NewConfig(x509c, privateKey, nil)
187 | if err != nil {
188 | log.Fatal(err)
189 | }
190 |
191 | mitmConfig.SetValidity(time.Hour * 24 * 7) // generate certs valid for 7 days
192 | mitmConfig.SetOrganization("gomitmproxy") // cert organization
193 | ```
194 |
195 | Please note that you can set `MITMExceptions` to a list of hostnames,
196 | which will be excluded from TLS interception.
197 |
198 | ```go
199 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
200 | ListenAddr: &net.TCPAddr{
201 | IP: net.IPv4(0, 0, 0, 0),
202 | Port: 3333,
203 | },
204 | MITMConfig: mitmConfig,
205 | MITMExceptions: []string{"example.com"},
206 | })
207 | ```
208 |
209 | If you configure the `APIHost`, you'll be able to download the CA certificate
210 | from `http://[APIHost]/cert.crt` when the proxy is configured.
211 |
212 | ```go
213 | // Navigate to http://gomitmproxy/cert.crt to download the CA certificate
214 | proxy.APIHost = "gomitmproxy"
215 | ```
216 |
217 | ### Custom certs storage
218 |
219 | By default, `gomitmproxy` uses an in-memory map-based storage for the certificates,
220 | generated while doing TLS interception. It is often necessary to use a different kind
221 | of certificates storage. If this is your case, you can supply your own implementation
222 | of the `CertsStorage` interface.
223 |
224 | ```go
225 | // CustomCertsStorage - an example of a custom cert storage
226 | type CustomCertsStorage struct {
227 | certsCache map[string]*tls.Certificate // cache with the generated certificates
228 | }
229 |
230 | // Get gets the certificate from the storage
231 | func (c *CustomCertsStorage) Get(key string) (*tls.Certificate, bool) {
232 | v, ok := c.certsCache[key]
233 | return v, ok
234 | }
235 |
236 | // Set saves the certificate to the storage
237 | func (c *CustomCertsStorage) Set(key string, cert *tls.Certificate) {
238 | c.certsCache[key] = cert
239 | }
240 | ```
241 |
242 | Then pass it to the `NewConfig` function.
243 |
244 | ```go
245 | mitmConfig, err := mitm.NewConfig(x509c, privateKey, &CustomCertsStorage{
246 | certsCache: map[string]*tls.Certificate{}},
247 | )
248 | ```
249 |
250 | ## Notable alternatives
251 |
252 | * [martian](https://github.com/google/martian) - an awesome debugging proxy with TLS interception support.
253 | * [goproxy](https://github.com/elazarl/goproxy) - also supports TLS interception and requests.
254 |
255 | ## TODO
256 |
257 | * [X] Basic HTTP proxy without MITM
258 | * [ ] Proxy
259 | * [X] Expose APIs for the library users
260 | * [X] How-to doc
261 | * [X] Travis configuration
262 | * [X] Proxy-Authorization
263 | * [X] WebSockets support (see [this](https://github.com/google/martian/issues/31))
264 | * [X] `certsCache` -- allow custom implementations
265 | * [X] Support HTTP CONNECT over TLS
266 | * [X] Test plain HTTP requests inside HTTP CONNECT
267 | * [X] Test memory leaks
268 | * [X] Editing response body in a callback
269 | * [X] Handle unknown content-encoding values
270 | * [X] Handle CONNECT to APIHost properly (without trying to actually connect anywhere)
271 | * [X] Allow hijacking connections (!)
272 | * [X] Multiple listeners
273 | * [ ] Unit tests
274 | * [ ] Check & fix TODOs
275 | * [ ] Allow specifying net.Dialer
276 | * [ ] Specify timeouts for http.Transport
277 | * [ ] MITM
278 | * [X] Basic MITM
279 | * [X] MITM exceptions
280 | * [X] Handle invalid server certificates properly (not just reset connections)
281 | * [X] Pass the most important tests on badssl.com/dashboard
282 | * [X] Handle certificate authentication
283 | * [ ] Allow configuring minimum supported TLS version
284 | * [ ] OCSP check (see [example](https://stackoverflow.com/questions/46626963/golang-sending-ocsp-request-returns))
285 | * [ ] (?) HPKP (see [example](https://github.com/tam7t/hpkp))
286 | * [ ] (?) CT logs (see [example](https://github.com/google/certificate-transparency-go))
287 | * [ ] (?) CRLSets (see [example](https://github.com/agl/crlset-tools))
288 |
--------------------------------------------------------------------------------
/auth.go:
--------------------------------------------------------------------------------
1 | package gomitmproxy
2 |
3 | import (
4 | "encoding/base64"
5 | "net/http"
6 | "strings"
7 |
8 | "github.com/AdguardTeam/gomitmproxy/proxyutil"
9 | )
10 |
11 | // basicAuth returns an HTTP authorization header value according to RFC2617.
12 | // See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt:
13 | // "To receive authorization, the client sends the userid and password,
14 | // separated by a single colon (":") character, within a base64 encoded string
15 | // in the credentials."
16 | // It is not meant to be urlencoded.
17 | func basicAuth(username, password string) string {
18 | auth := username + ":" + password
19 | return base64.StdEncoding.EncodeToString([]byte(auth))
20 | }
21 |
22 | // newNotAuthorizedResponse creates a new "407 (Proxy Authentication Required)"
23 | // response.
24 | func newNotAuthorizedResponse(session *Session) *http.Response {
25 | res := proxyutil.NewResponse(http.StatusProxyAuthRequired, nil, session.req)
26 |
27 | // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authenticate.
28 | res.Header.Set("Proxy-Authenticate", "Basic")
29 |
30 | return res
31 | }
32 |
33 | // authorize checks the "Proxy-Authorization" header and returns true if the
34 | // request is authorized. If it returns false, it also returns the response that
35 | // should be written to the client.
36 | func (p *Proxy) authorize(session *Session) (bool, *http.Response) {
37 | if session.ctx.parent != nil {
38 | // If we're here, it means the connection is authorized already.
39 | return true, nil
40 | }
41 |
42 | if p.Username == "" {
43 | return true, nil
44 | }
45 |
46 | // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization.
47 | proxyAuth := session.req.Header.Get("Proxy-Authorization")
48 | if strings.Index(proxyAuth, "Basic ") != 0 {
49 | return false, newNotAuthorizedResponse(session)
50 | }
51 |
52 | authHeader := proxyAuth[len("Basic "):]
53 | if authHeader != basicAuth(p.Username, p.Password) {
54 | return false, newNotAuthorizedResponse(session)
55 | }
56 |
57 | return true, nil
58 | }
59 |
--------------------------------------------------------------------------------
/config.go:
--------------------------------------------------------------------------------
1 | package gomitmproxy
2 |
3 | import (
4 | "crypto/tls"
5 | "net"
6 | "net/http"
7 |
8 | "github.com/AdguardTeam/gomitmproxy/mitm"
9 | )
10 |
11 | // OnConnectFunc is a declaration of the Config.OnConnect handler.
12 | type OnConnectFunc func(session *Session, proto string, addr string) (conn net.Conn)
13 |
14 | // OnRequestFunc is a declaration of the Config.OnRequest handler.
15 | type OnRequestFunc func(session *Session) (req *http.Request, resp *http.Response)
16 |
17 | // OnResponseFunc is a declaration of the Config.OnResponse handler.
18 | type OnResponseFunc func(session *Session) (resp *http.Response)
19 |
20 | // OnErrorFunc is a declaration of the Config.OnError handler.
21 | type OnErrorFunc func(session *Session, err error)
22 |
23 | // Config is the configuration of the Proxy.
24 | type Config struct {
25 | // ListenAddr is the TCP address the proxy should listen to.
26 | ListenAddr *net.TCPAddr
27 |
28 | // TLSConfig is a *tls.Config to use for the HTTP over TLS proxy. If not set
29 | // the proxy will work as a simple plain HTTP proxy.
30 | TLSConfig *tls.Config
31 |
32 | // Username is the username to be used in the "Proxy-Authorization" header.
33 | Username string
34 |
35 | // Password is the password to be used in the "Proxy-Authorization" header.
36 | Password string
37 |
38 | // MITMConfig defines the MITM configuration of the proxy. If it is not set
39 | // MITM won't be enabled for this proxy instance.
40 | MITMConfig *mitm.Config
41 |
42 | // MITMExceptions is a list of hostnames for which MITM will be disabled.
43 | MITMExceptions []string
44 |
45 | // APIHost is a name of the gomitmproxy API hostname. If it is not set, the
46 | // API won't be exposed via HTTP.
47 | //
48 | // Here are the methods exposed:
49 | // 1. apihost/cert.crt - serves the authority cert if MITMConfig is
50 | // configured.
51 | APIHost string
52 |
53 | // OnConnect is called when the proxy tries to open a new net.Conn. This
54 | // function allows hijacking the remote connection and replacing it with a
55 | // different one.
56 | //
57 | // 1. When the proxy handles the HTTP CONNECT.
58 | // IMPORTANT: In this case we don't actually use the remote connections.
59 | // It is only used to check if the remote endpoint is available.
60 | // 2. When the proxy bypasses data from the client to the remote endpoint.
61 | // For instance, it could happen when there's a WebSocket connection.
62 | OnConnect OnConnectFunc
63 |
64 | // OnRequest is called when the request has been just received, but has not
65 | // been sent to the remote server.
66 | //
67 | // At this stage, it is possible to do the following things:
68 | // 1. Modify or even replace the request.
69 | // 2. Supply an HTTP response to be written to the client.
70 | //
71 | // Return nil instead of *http.Request or *http.Response to keep the
72 | // original request / response.
73 | //
74 | // Note that even if you supply your own HTTP response here, the OnResponse
75 | // handler will be called anyway!
76 | OnRequest OnRequestFunc
77 |
78 | // OnResponse is called when the response has been just received, but has
79 | // not been sent to the local client. At this stage you can either keep the
80 | // original response, or you can replace it with a new one.
81 | OnResponse OnResponseFunc
82 |
83 | // OnError is called if there's an issue with retrieving the response from
84 | // the remote server.
85 | OnError OnErrorFunc
86 | }
87 |
--------------------------------------------------------------------------------
/context.go:
--------------------------------------------------------------------------------
1 | package gomitmproxy
2 |
3 | import (
4 | "bufio"
5 | "crypto/tls"
6 | "fmt"
7 | "net"
8 | "net/http"
9 | "sync/atomic"
10 | "time"
11 | )
12 |
13 | var (
14 | // currentContextID is an auto-incremented value, used for every new
15 | // Context instance.
16 | currentContextID = int64(100000)
17 | )
18 |
19 | // Context contains all the necessary information about the connection that is
20 | // currently being processed by the proxy.
21 | type Context struct {
22 | // id is the connection identifier.
23 | id int64
24 |
25 | // lastSessionID is the number of the last session processed via the
26 | // connection. This is an auto-incremented field.
27 | lastSessionID int64
28 |
29 | // parent session makes sense in the case of handling HTTP CONNECT tunnels.
30 | // Also, it may become useful in the future when HTTP/2 support is added.
31 | parent *Session
32 |
33 | // conn is the local network connection.
34 | conn net.Conn
35 |
36 | // localRW is a buffered read/writer to conn.
37 | localRW *bufio.ReadWriter
38 |
39 | // props is a map with custom properties that can be used by gomitmproxy to
40 | // store additional context properties.
41 | props map[string]interface{}
42 | }
43 |
44 | // newContext creates a new Context instance.
45 | func newContext(conn net.Conn, localRW *bufio.ReadWriter, parent *Session) (ctx *Context) {
46 | var contextID int64
47 | if parent == nil {
48 | contextID = atomic.AddInt64(¤tContextID, 1)
49 | } else {
50 | contextID = atomic.AddInt64(&parent.lastChildID, 1)
51 | }
52 |
53 | return &Context{
54 | id: contextID,
55 | parent: parent,
56 | conn: conn,
57 | localRW: localRW,
58 | props: map[string]interface{}{},
59 | }
60 | }
61 |
62 | // ID is the context's unique ID.
63 | func (c *Context) ID() (id string) {
64 | if c.parent != nil {
65 | return fmt.Sprintf("%s-%d", c.parent.ID(), c.id)
66 | }
67 |
68 | return fmt.Sprintf("%d", c.id)
69 | }
70 |
71 | // IsMITM returns true if this context is for a MITMed connection.
72 | func (c *Context) IsMITM() (ok bool) {
73 | if _, ok = c.conn.(*tls.Conn); c.parent != nil && ok {
74 | return true
75 | }
76 |
77 | return false
78 | }
79 |
80 | // SetDeadline sets the read and write deadlines associated with the connection.
81 | //
82 | // The difference is that our contexts can be nested, so we search for the
83 | // topmost parent context recursively and call SetDeadline for its connection
84 | // only as this is the real underlying network connection.
85 | func (c *Context) SetDeadline(t time.Time) (err error) {
86 | if c.parent == nil {
87 | return c.conn.SetDeadline(t)
88 | }
89 |
90 | return c.parent.ctx.SetDeadline(t)
91 | }
92 |
93 | // GetProp gets context property (previously saved using SetProp).
94 | func (c *Context) GetProp(key string) (v interface{}, ok bool) {
95 | v, ok = c.props[key]
96 |
97 | return v, ok
98 | }
99 |
100 | // SetProp sets the context's property.
101 | func (c *Context) SetProp(key string, val interface{}) {
102 | c.props[key] = val
103 | }
104 |
105 | // Session contains all the necessary information about the request-response
106 | // pair that is currently being processed.
107 | type Session struct {
108 | // id is a session identifier.
109 | id int64
110 | // lastChildID is the last child context's identifier. This field is
111 | // automatically incremented.
112 | lastChildID int64
113 |
114 | // ctx is a context of the connection this session belongs to.
115 | ctx *Context
116 |
117 | // req is the *http.Request that's being processed in this session.
118 | req *http.Request
119 |
120 | // res is the *http.Response that's being processed in this session.
121 | res *http.Response
122 |
123 | // props is a map with custom properties that can be used by gomitmproxy to
124 | // store additional session properties.
125 | props map[string]interface{}
126 | }
127 |
128 | // newSession creates a new Session instance.
129 | func newSession(ctx *Context, req *http.Request) (sess *Session) {
130 | sessionID := atomic.AddInt64(&ctx.lastSessionID, 1)
131 |
132 | return &Session{
133 | id: sessionID,
134 | ctx: ctx,
135 | req: req,
136 | props: map[string]interface{}{},
137 | }
138 | }
139 |
140 | // ID returns a unique session identifier.
141 | func (s *Session) ID() (id string) {
142 | return fmt.Sprintf("%s-%d", s.ctx.ID(), s.id)
143 | }
144 |
145 | // Request returns the HTTP request of this session.
146 | func (s *Session) Request() (req *http.Request) {
147 | return s.req
148 | }
149 |
150 | // Response returns the HTTP response of this session.
151 | func (s *Session) Response() (resp *http.Response) {
152 | return s.res
153 | }
154 |
155 | // Ctx returns this session's context.
156 | func (s *Session) Ctx() (ctx *Context) {
157 | return s.ctx
158 | }
159 |
160 | // GetProp gets session property (previously saved using SetProp).
161 | func (s *Session) GetProp(key string) (v interface{}, ok bool) {
162 | v, ok = s.props[key]
163 |
164 | return v, ok
165 | }
166 |
167 | // SetProp sets a session's property.
168 | func (s *Session) SetProp(key string, val interface{}) {
169 | s.props[key] = val
170 | }
171 |
172 | // RemoteAddr returns this session's remote address.
173 | func (s *Session) RemoteAddr() (addr string) {
174 | if s.ctx.IsMITM() {
175 | return s.ctx.parent.RemoteAddr()
176 | }
177 |
178 | host := s.req.URL.Host
179 | if _, _, err := net.SplitHostPort(host); err == nil {
180 | return host
181 | }
182 |
183 | if s.req.URL.Scheme == "https" {
184 | return fmt.Sprintf("%s:443", host)
185 | }
186 |
187 | return fmt.Sprintf("%s:80", host)
188 | }
189 |
--------------------------------------------------------------------------------
/examples/auth/README.md:
--------------------------------------------------------------------------------
1 | # Auth proxy demo
2 |
3 | Runs an HTTPS proxy on `localhost:3333` with authorization:
4 |
5 | * Username: `user`
6 | * Password: `pass`
7 |
--------------------------------------------------------------------------------
/examples/auth/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net"
5 | "net/http"
6 | "os"
7 | "os/signal"
8 | "syscall"
9 |
10 | "github.com/AdguardTeam/golibs/log"
11 | "github.com/AdguardTeam/gomitmproxy"
12 | )
13 |
14 | func main() {
15 | log.SetLevel(log.DEBUG)
16 |
17 | go func() {
18 | log.Println(http.ListenAndServe("localhost:6060", nil))
19 | }()
20 |
21 | // Prepare the proxy.
22 | addr := &net.TCPAddr{
23 | IP: net.IPv4(0, 0, 0, 0),
24 | Port: 3333,
25 | }
26 |
27 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
28 | ListenAddr: addr,
29 |
30 | Username: "user",
31 | Password: "pass",
32 | APIHost: "gomitmproxy",
33 | })
34 |
35 | err := proxy.Start()
36 | if err != nil {
37 | log.Fatal(err)
38 | }
39 |
40 | signalChannel := make(chan os.Signal, 1)
41 | signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
42 | <-signalChannel
43 |
44 | // Stop the proxy.
45 | proxy.Close()
46 | }
47 |
--------------------------------------------------------------------------------
/examples/mitm/README.md:
--------------------------------------------------------------------------------
1 | # MITM demo
2 |
3 | Runs an HTTPS proxy on `localhost:3333` with authorization:
4 |
5 | * Username: `user`
6 | * Password: `pass`
7 |
8 | Can be tested in Chrome using SwitchyOmega.
9 |
10 | Note, that you need to install `demo.crt` to the trusted roots storage.
11 |
--------------------------------------------------------------------------------
/examples/mitm/demo.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIDGTCCAgGgAwIBAgIUS/F/3DxviRqvtvuzkSTwmPdn+PIwDQYJKoZIhvcNAQEL
3 | BQAwHDEaMBgGA1UEAwwRRE9fTk9UX1RSVVNUX0NFUlQwHhcNMjIxMTA2MTgyMTMw
4 | WhcNMjMxMDI4MTgyMTMwWjAcMRowGAYDVQQDDBFET19OT1RfVFJVU1RfQ0VSVDCC
5 | ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAI4SU1jm74ih7YGJB+TQUUQ6
6 | +Kt32zk0TrYLcslj6igiuyZf1XvKJvHdhGBzSCA6KjgwpqazVBoMOtV48n3GJZFf
7 | R10joBdOqaMphcPBk+0hm97QNgawqquUE2PwEaaoWzBtpUJLOsA8yRXUl2+nzGcj
8 | mIIeAePRVc1xk8gEpn/tzca1806mDEJ90jFHJEij4Ps79RosGsPzuP51l/5mIcNp
9 | EE1oYN49Q1VpShxNZBbUB9dCaDUZiZbgp3Hyl6BvjpzJwtDEhHmfn9LK457R/Swr
10 | 3y5DsXqK6VCPeT37O/+gHfNtZWBieLW6M6eIEeertJcpQRZQWPAuFyykIoyD3oMC
11 | AwEAAaNTMFEwHQYDVR0OBBYEFK+9ZFY6OhSLdXF3MSUoPGT17pq8MB8GA1UdIwQY
12 | MBaAFK+9ZFY6OhSLdXF3MSUoPGT17pq8MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI
13 | hvcNAQELBQADggEBACXtY1/HyLKCj7wFV97dceEyC0pzYV6NZ9NnYcQ2m6WDe8+L
14 | qNRoe5UOKR+xRN9CTp095EFDfhI/iqLfrdSIKldz/a1Dvnuyk7k+sN+FIex0bGuQ
15 | ZRKOp53HDGQN6Z+3k2dGXTE1HbF5CLbp3y/N9pAqkTHIN85FUU5vbr/gdYuQiBg+
16 | N9lk7yYHppQCBikG2Q1uVpcg4RuawbsSPPMBgf5RZ2PhO8VDlBUWAGXSedZO/hbt
17 | U+FJGqdxlXS3HYwDlnW4d5PqLG3+VDDcIX2qD6gqorwrJS1VEFNgiZoxeFSV4rjb
18 | KmWrWMmj3/mlJ0tapRlSdMh6yuDWa77dtel9N94=
19 | -----END CERTIFICATE-----
20 |
--------------------------------------------------------------------------------
/examples/mitm/demo.key:
--------------------------------------------------------------------------------
1 | -----BEGIN PRIVATE KEY-----
2 | MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCOElNY5u+Ioe2B
3 | iQfk0FFEOvird9s5NE62C3LJY+ooIrsmX9V7yibx3YRgc0ggOio4MKams1QaDDrV
4 | ePJ9xiWRX0ddI6AXTqmjKYXDwZPtIZve0DYGsKqrlBNj8BGmqFswbaVCSzrAPMkV
5 | 1Jdvp8xnI5iCHgHj0VXNcZPIBKZ/7c3GtfNOpgxCfdIxRyRIo+D7O/UaLBrD87j+
6 | dZf+ZiHDaRBNaGDePUNVaUocTWQW1AfXQmg1GYmW4Kdx8pegb46cycLQxIR5n5/S
7 | yuOe0f0sK98uQ7F6iulQj3k9+zv/oB3zbWVgYni1ujOniBHnq7SXKUEWUFjwLhcs
8 | pCKMg96DAgMBAAECggEAMM06tB8fyN9Wplhbzc2BHN7k7IGPXGcLYp0sIOGhXYgQ
9 | oW3p90vJdOuSvU7cR7WzKvoLRNf02723t/yDz5Bw9y6zZNsH8vmia9mniUbFeX9B
10 | +5ep90JYXffPcVTVu1m5eTkwu0T8OWyn5kfQfRo2rHcdvBRysb8GqjuJd/ug9fBG
11 | wDHaDKrj4fsVeuuAtebHOEZhh59cXNWjn30nnsfJv+ePXgHZ9RtMtNp70uD5gLBr
12 | gCGdN9uNqKzaqwnZc5Zyv00AEFkQ/ZwsHPNoFTtZIHovYLBwPK5LtMNH3Pz+QaUE
13 | d0R7e2cNHw4ouEGNy9i2QV514ztEC8DWYeRu+unBAQKBgQDIeh3eFzNXQmls7Z40
14 | iFfEi8rRcjMpcqNONSSYwmrNGPvT3yHA0cnt73hFA91plZd1vBcOlmpADT7FqDe+
15 | LWSXI/Xx23FgADijo3su54SUWZ/4Bt01L0KcfUebWHZRkRb5R2+Lga1Ycwqa+jsg
16 | kcn/5HWdsBPKL38RtiwZjwBcWQKBgQC1az7P6VYikXenbMTS/Mz2a0jRQbU2gDva
17 | FHOrCfP0sSTUSyVrkZOEhVYsyjyHUC4O6nCzwhCQ/q/amjCzRQLjkwfcROn2LwSf
18 | eEcY3u2Ktk6WnAfcwkrvFm5Lyiv/Xwhv2730zKp55CB/UDVnFcMdYpdameWBBtwe
19 | uPBK3NiGOwKBgAtOV8DerhaNuERcYj+0ML7040tMlXYQ8QTIGnhC/qLydcFNJCor
20 | qqewiafav/HkbdZF9UbtVLCoDpI3Gm2vQa0Eaipppcs0N/2Cir/qbp+vLkZenLsT
21 | Hz6UEiXAp2uSMyl7zd6gQZZrZn22/v6nOi0kRT3PYE5Wv2PQUkxetDaBAoGBAKTo
22 | 0NcDnwWbP64URDIaFGInEbENzqC1HjLVhnNCf9y8reLAUEqgsPy0i6n5R94kd0md
23 | uEbesFps+QN4R66dm8usWmfSyO28vbIMDmzAMCN4JqXnPYphnuYIeMgyBZ6ED1JG
24 | 6Dw/UvOr+BJiobiL4qmydiyoWiPYTX0r1VnnuHcDAoGAJ2DTMFEtSCzoxgisA0vv
25 | C/4csyH04hDn4M9J9XXufiHDjvFjOYhR0rB4NLHzzc+D+qjolMfwuyZ9rFO17u5C
26 | eRpmLc4toMUVuNl5+mprNYrcWsArsisTeOS+isz7Pi3jKWnCjzrwYda7Wslu7kL8
27 | 85NjxgzM9+PeSHHnOLy3L8U=
28 | -----END PRIVATE KEY-----
29 |
--------------------------------------------------------------------------------
/examples/mitm/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "crypto/rsa"
6 | "crypto/tls"
7 | "crypto/x509"
8 | "io"
9 | "net"
10 | "net/http"
11 | "os"
12 | "os/signal"
13 | "strings"
14 | "syscall"
15 | "time"
16 |
17 | "github.com/AdguardTeam/golibs/log"
18 | "github.com/AdguardTeam/gomitmproxy"
19 | "github.com/AdguardTeam/gomitmproxy/mitm"
20 | "github.com/AdguardTeam/gomitmproxy/proxyutil"
21 |
22 | _ "net/http/pprof"
23 | )
24 |
25 | func main() {
26 | log.SetLevel(log.DEBUG)
27 |
28 | go func() {
29 | log.Println(http.ListenAndServe("localhost:6060", nil))
30 | }()
31 |
32 | // Read the MITM cert and key.
33 | tlsCert, err := tls.LoadX509KeyPair("demo.crt", "demo.key")
34 | if err != nil {
35 | log.Fatal(err)
36 | }
37 | privateKey := tlsCert.PrivateKey.(*rsa.PrivateKey)
38 |
39 | x509c, err := x509.ParseCertificate(tlsCert.Certificate[0])
40 | if err != nil {
41 | log.Fatal(err)
42 | }
43 |
44 | mitmConfig, err := mitm.NewConfig(x509c, privateKey, &CustomCertsStorage{
45 | certsCache: map[string]*tls.Certificate{}},
46 | )
47 |
48 | if err != nil {
49 | log.Fatal(err)
50 | }
51 |
52 | // Generate certs valid for 7 days.
53 | mitmConfig.SetValidity(time.Hour * 24 * 7)
54 | // Set certs organization.
55 | mitmConfig.SetOrganization("gomitmproxy")
56 |
57 | // Generate a cert-key pair for the HTTP-over-TLS proxy.
58 | proxyCert, err := mitmConfig.GetOrCreateCert("127.0.0.1")
59 | if err != nil {
60 | panic(err)
61 | }
62 | tlsConfig := &tls.Config{
63 | Certificates: []tls.Certificate{*proxyCert},
64 | }
65 |
66 | // Prepare the proxy.
67 | addr := &net.TCPAddr{
68 | IP: net.IPv4(0, 0, 0, 0),
69 | Port: 3333,
70 | }
71 |
72 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
73 | ListenAddr: addr,
74 | TLSConfig: tlsConfig,
75 |
76 | Username: "user",
77 | Password: "pass",
78 | APIHost: "gomitmproxy",
79 |
80 | MITMConfig: mitmConfig,
81 | MITMExceptions: []string{"example.com"},
82 |
83 | OnRequest: onRequest,
84 | OnResponse: onResponse,
85 | OnConnect: onConnect,
86 | })
87 |
88 | err = proxy.Start()
89 | if err != nil {
90 | log.Fatal(err)
91 | }
92 |
93 | signalChannel := make(chan os.Signal, 1)
94 | signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
95 | <-signalChannel
96 |
97 | // Stop the proxy.
98 | proxy.Close()
99 | }
100 |
101 | func onRequest(session *gomitmproxy.Session) (*http.Request, *http.Response) {
102 | req := session.Request()
103 |
104 | log.Printf("onRequest: %s %s", req.Method, req.URL.String())
105 |
106 | if req.URL.Host == "example.net" {
107 | body := strings.NewReader("Replaced response
")
108 | res := proxyutil.NewResponse(http.StatusOK, body, req)
109 | res.Header.Set("Content-Type", "text/html")
110 | session.SetProp("blocked", true)
111 | return nil, res
112 | }
113 |
114 | if req.URL.Host == "testgomitmproxy" {
115 | body := strings.NewReader("Served by gomitmproxy
")
116 | res := proxyutil.NewResponse(http.StatusOK, body, req)
117 | res.Header.Set("Content-Type", "text/html")
118 | return nil, res
119 | }
120 |
121 | return nil, nil
122 | }
123 |
124 | func onResponse(session *gomitmproxy.Session) *http.Response {
125 | log.Printf("onResponse: %s", session.Request().URL.String())
126 |
127 | if _, ok := session.GetProp("blocked"); ok {
128 | log.Printf("onResponse: was blocked")
129 | return nil
130 | }
131 |
132 | res := session.Response()
133 | req := session.Request()
134 |
135 | if strings.Index(res.Header.Get("Content-Type"), "text/html") != 0 {
136 | // Do nothing with non-HTML responses
137 | return nil
138 | }
139 |
140 | b, err := proxyutil.ReadDecompressedBody(res)
141 | // Close the original body.
142 | _ = res.Body.Close()
143 | if err != nil {
144 | return proxyutil.NewErrorResponse(req, err)
145 | }
146 |
147 | // Use latin1 before modifying the body. Using this 1-byte encoding will
148 | // let us preserve all original characters regardless of what exactly is
149 | // the encoding.
150 | body, err := proxyutil.DecodeLatin1(bytes.NewReader(b))
151 | if err != nil {
152 | return proxyutil.NewErrorResponse(session.Request(), err)
153 | }
154 |
155 | // Modifying the original body.
156 | modifiedBody, err := proxyutil.EncodeLatin1(body + "")
157 | if err != nil {
158 | return proxyutil.NewErrorResponse(session.Request(), err)
159 | }
160 |
161 | res.Body = io.NopCloser(bytes.NewReader(modifiedBody))
162 | res.Header.Del("Content-Encoding")
163 | res.ContentLength = int64(len(modifiedBody))
164 |
165 | return res
166 | }
167 |
168 | func onConnect(_ *gomitmproxy.Session, _ string, addr string) (conn net.Conn) {
169 | host, _, err := net.SplitHostPort(addr)
170 |
171 | if err == nil && host == "testgomitmproxy" {
172 | // Don't let it connecting there, we'll serve it by ourselves.
173 | return &proxyutil.NoopConn{}
174 | }
175 |
176 | return nil
177 | }
178 |
179 | // CustomCertsStorage is an example of a custom cert storage.
180 | type CustomCertsStorage struct {
181 | // certsCache is a cache with the generated certificates.
182 | certsCache map[string]*tls.Certificate
183 | }
184 |
185 | // Get gets the certificate from the storage.
186 | func (c *CustomCertsStorage) Get(key string) (cert *tls.Certificate, ok bool) {
187 | cert, ok = c.certsCache[key]
188 |
189 | return cert, ok
190 | }
191 |
192 | // Set saves the certificate to the storage.
193 | func (c *CustomCertsStorage) Set(key string, cert *tls.Certificate) {
194 | c.certsCache[key] = cert
195 | }
196 |
--------------------------------------------------------------------------------
/examples/simple/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "net"
5 | "os"
6 | "os/signal"
7 | "syscall"
8 |
9 | "github.com/AdguardTeam/golibs/log"
10 | "github.com/AdguardTeam/gomitmproxy"
11 | )
12 |
13 | func main() {
14 | proxy := gomitmproxy.NewProxy(gomitmproxy.Config{
15 | ListenAddr: &net.TCPAddr{
16 | IP: net.IPv4(0, 0, 0, 0),
17 | Port: 8080,
18 | },
19 | })
20 | err := proxy.Start()
21 | if err != nil {
22 | log.Fatal(err)
23 | }
24 |
25 | signalChannel := make(chan os.Signal, 1)
26 | signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)
27 | <-signalChannel
28 |
29 | // Clean up.
30 | proxy.Close()
31 | }
32 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/AdguardTeam/gomitmproxy
2 |
3 | go 1.20
4 |
5 | require (
6 | github.com/AdguardTeam/golibs v0.13.2
7 | github.com/pkg/errors v0.9.1
8 | github.com/stretchr/testify v1.8.2
9 | golang.org/x/text v0.8.0
10 | )
11 |
12 | require (
13 | github.com/davecgh/go-spew v1.1.1 // indirect
14 | github.com/kr/text v0.2.0 // indirect
15 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
16 | github.com/pmezard/go-difflib v1.0.0 // indirect
17 | gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
18 | gopkg.in/yaml.v3 v3.0.1 // indirect
19 | )
20 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/AdguardTeam/golibs v0.13.2 h1:BPASsyQKmb+b8VnvsNOHp7bKfcZl9Z+Z2UhPjOiupSc=
2 | github.com/AdguardTeam/golibs v0.13.2/go.mod h1:7ylQLv2Lqsc3UW3jHoITynYk6Y1tYtgEMkR09ppfsN8=
3 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
4 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
5 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
6 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
7 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
8 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
9 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
10 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
11 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
12 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
13 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
14 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
15 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
16 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
17 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
18 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
19 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
20 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
21 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
22 | github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
23 | github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
24 | golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
25 | golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
26 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
27 | gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
28 | gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
29 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
30 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
31 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
32 |
--------------------------------------------------------------------------------
/helper.go:
--------------------------------------------------------------------------------
1 | package gomitmproxy
2 |
3 | import (
4 | "errors"
5 | "io"
6 | "net"
7 | )
8 |
9 | var errShutdown = errors.New("proxy is shutting down")
10 | var errClose = errors.New("closing connection")
11 |
12 | // isCloseable checks if the error signals about connection being closed
13 | // or the proxy shutting down.
14 | func isCloseable(err error) (ok bool) {
15 | // TODO(ameshkov): use errors.Is.
16 | if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
17 | return true
18 | }
19 |
20 | switch err {
21 | case io.EOF, io.ErrClosedPipe, errClose, errShutdown:
22 | return true
23 | }
24 |
25 | return false
26 | }
27 |
28 | // A peekedConn subverts the net.Conn.Read implementation, primarily so that
29 | // sniffed bytes can be transparently prepended.
30 | type peekedConn struct {
31 | net.Conn
32 | r io.Reader
33 | }
34 |
35 | // Read allows control over the embedded net.Conn's read data. By using an
36 | // io.MultiReader one can read from a conn, and then replace what they read, to
37 | // be read again.
38 | func (c *peekedConn) Read(buf []byte) (int, error) { return c.r.Read(buf) }
39 |
--------------------------------------------------------------------------------
/hopbyhop.go:
--------------------------------------------------------------------------------
1 | package gomitmproxy
2 |
3 | import (
4 | "net/http"
5 | "strings"
6 | )
7 |
8 | // Hop-by-hop headers as defined by RFC2616.
9 | //
10 | // http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-7.1.3.1
11 | var hopByHopHeaders = []string{
12 | "Connection",
13 | "Keep-Alive",
14 | "Proxy-Authenticate",
15 | "Proxy-Authorization",
16 | "Proxy-Connection", // Non-standard, but required for HTTP/2.
17 | "Te",
18 | "Trailer",
19 | "Transfer-Encoding",
20 | "Upgrade",
21 | }
22 |
23 | // removeHopByHopHeaders removes hop-by-hop headers.
24 | func removeHopByHopHeaders(header http.Header) {
25 | // Additional hop-by-hop headers may be specified in `Connection` headers.
26 | // http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-14#section-9.1
27 | for _, vs := range header["Connection"] {
28 | for _, v := range strings.Split(vs, ",") {
29 | k := http.CanonicalHeaderKey(strings.TrimSpace(v))
30 | header.Del(k)
31 | }
32 | }
33 |
34 | for _, k := range hopByHopHeaders {
35 | header.Del(k)
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/mitm/mitm.go:
--------------------------------------------------------------------------------
1 | // Package mitm implements methods for working with certificates and TLS configurations
2 | // that are used for MITMing connections.
3 | package mitm
4 |
5 | import (
6 | "crypto/rand"
7 | "crypto/rsa"
8 | "crypto/sha1"
9 | "crypto/tls"
10 | "crypto/x509"
11 | "crypto/x509/pkix"
12 | "math/big"
13 | "net"
14 | "sync"
15 | "sync/atomic"
16 | "time"
17 |
18 | "github.com/AdguardTeam/golibs/log"
19 | )
20 |
21 | // While generating a new certificate, in order to get a unique serial
22 | // number every time we increment this value.
23 | var currentSerialNumber = time.Now().Unix()
24 |
25 | // Config is a set of configuration values that are used to build TLS configs
26 | // capable of MITM.
27 | type Config struct {
28 | ca *x509.Certificate // Root certificate authority
29 | caPrivateKey *rsa.PrivateKey // CA private key
30 |
31 | // roots is a CertPool that contains the root CA GetOrCreateCert
32 | // it serves a single purpose -- to verify the cached domain certs
33 | roots *x509.CertPool
34 |
35 | // privateKey is the private key that will be used to generate leaf certificates
36 | // TODO: insecure approach, generating a new key would be better
37 | privateKey *rsa.PrivateKey
38 |
39 | validity time.Duration // Validity of the generated certificates
40 | keyID []byte // SKI to use in generated certificates (https://tools.ietf.org/html/rfc3280#section-4.2.1.2)
41 | organization string // Organization (will be used for generated certificates)
42 |
43 | certsStorage CertsStorage // cache with the generated certificates
44 | certsStorageMu sync.RWMutex
45 | }
46 |
47 | // CertsStorage is an interface for generated tls certificates storage
48 | type CertsStorage interface {
49 | // Get gets the certificate from the storage
50 | Get(key string) (*tls.Certificate, bool)
51 | // Set saves the certificate to the storage
52 | Set(key string, cert *tls.Certificate)
53 | }
54 |
55 | // CertsCache is a simple map-based CertsStorage implementation
56 | type CertsCache struct {
57 | certsCache map[string]*tls.Certificate // cache with the generated certificates
58 | }
59 |
60 | // Get gets the certificate from the storage
61 | func (c *CertsCache) Get(key string) (*tls.Certificate, bool) {
62 | v, ok := c.certsCache[key]
63 | return v, ok
64 | }
65 |
66 | // Set saves the certificate to the storage
67 | func (c *CertsCache) Set(key string, cert *tls.Certificate) {
68 | c.certsCache[key] = cert
69 | }
70 |
71 | // NewAuthority creates a new CA certificate and associated private key.
72 | // name -- certificate subject name
73 | // organization -- certificate organization
74 | // validity -- time for which the certificate is valid
75 | func NewAuthority(name, organization string, validity time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
76 | priv, err := rsa.GenerateKey(rand.Reader, 2048)
77 | if err != nil {
78 | return nil, nil, err
79 | }
80 | pub := priv.Public()
81 |
82 | // Subject Key Identifier support for end entity certificate.
83 | // https://tools.ietf.org/html/rfc3280#section-4.2.1.2
84 | pkixpub, err := x509.MarshalPKIXPublicKey(pub)
85 | if err != nil {
86 | return nil, nil, err
87 | }
88 | h := sha1.New()
89 | _, err = h.Write(pkixpub)
90 | if err != nil {
91 | return nil, nil, err
92 | }
93 | keyID := h.Sum(nil)
94 |
95 | // Increment the serial number
96 | serial := atomic.AddInt64(¤tSerialNumber, 1)
97 |
98 | tmpl := &x509.Certificate{
99 | SerialNumber: big.NewInt(serial),
100 | Subject: pkix.Name{
101 | CommonName: name,
102 | Organization: []string{organization},
103 | },
104 | SubjectKeyId: keyID,
105 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
106 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
107 | BasicConstraintsValid: true,
108 | NotBefore: time.Now().Add(-validity),
109 | NotAfter: time.Now().Add(validity),
110 | DNSNames: []string{name},
111 | IsCA: true,
112 | }
113 |
114 | raw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, priv)
115 | if err != nil {
116 | return nil, nil, err
117 | }
118 |
119 | // Parse certificate bytes so that we have a leaf certificate.
120 | x509c, err := x509.ParseCertificate(raw)
121 | if err != nil {
122 | return nil, nil, err
123 | }
124 |
125 | return x509c, priv, nil
126 | }
127 |
128 | // NewConfig creates a new MITM configuration
129 | // ca -- root certificate authority to use for generating domain certs
130 | // privateKey -- private key of this CA GetOrCreateCert
131 | // storage -- a custom certs storage or null if you want to use the default implementation
132 | func NewConfig(ca *x509.Certificate, privateKey *rsa.PrivateKey, storage CertsStorage) (*Config, error) {
133 | roots := x509.NewCertPool()
134 | roots.AddCert(ca)
135 |
136 | // Generating the private key that will be used for domain certificates
137 | priv, err := rsa.GenerateKey(rand.Reader, 2048)
138 | if err != nil {
139 | return nil, err
140 | }
141 | pub := priv.Public()
142 |
143 | // Subject Key Identifier support for end entity certificate.
144 | // https://tools.ietf.org/html/rfc3280#section-4.2.1.2
145 | pkixpub, err := x509.MarshalPKIXPublicKey(pub)
146 | if err != nil {
147 | return nil, err
148 | }
149 | h := sha1.New()
150 | _, err = h.Write(pkixpub)
151 | if err != nil {
152 | return nil, err
153 | }
154 | keyID := h.Sum(nil)
155 |
156 | if storage == nil {
157 | storage = &CertsCache{certsCache: make(map[string]*tls.Certificate)}
158 | }
159 |
160 | return &Config{
161 | ca: ca,
162 | caPrivateKey: privateKey,
163 | privateKey: priv,
164 | keyID: keyID,
165 | validity: time.Hour,
166 | organization: "gomitmproxy",
167 | certsStorage: storage,
168 | roots: roots,
169 | }, nil
170 | }
171 |
172 | // GetCA returns the authority cert
173 | func (c *Config) GetCA() *x509.Certificate {
174 | return c.ca
175 | }
176 |
177 | // SetOrganization sets the organization name that
178 | // will be used in generated certs
179 | func (c *Config) SetOrganization(organization string) {
180 | c.organization = organization
181 | }
182 |
183 | // SetValidity sets validity period for the generated certs
184 | func (c *Config) SetValidity(validity time.Duration) {
185 | c.validity = validity
186 | }
187 |
188 | // NewTLSConfigForHost creates a *tls.Config that will generate
189 | // domain certificates on-the-fly using the SNI extension (if specified)
190 | // or the hostname
191 | func (c *Config) NewTLSConfigForHost(hostname string) *tls.Config {
192 | tlsConfig := &tls.Config{
193 | GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
194 | host := clientHello.ServerName
195 | if host == "" {
196 | host = hostname
197 | }
198 |
199 | return c.GetOrCreateCert(host)
200 | },
201 | NextProtos: []string{"http/1.1"},
202 | }
203 |
204 | // Accept client certs without verifying them
205 | // Note that we will still verify remote server certs
206 | // nolint:gosec
207 | tlsConfig.InsecureSkipVerify = true
208 |
209 | return tlsConfig
210 | }
211 |
212 | // GetOrCreateCert gets or creates a certificate for the specified hostname
213 | func (c *Config) GetOrCreateCert(hostname string) (cert *tls.Certificate, err error) {
214 | // Remove the port if it exists.
215 | host, _, err := net.SplitHostPort(hostname)
216 | if err == nil {
217 | hostname = host
218 | }
219 |
220 | c.certsStorageMu.RLock()
221 | cert, ok := c.certsStorage.Get(hostname)
222 | c.certsStorageMu.RUnlock()
223 |
224 | if ok {
225 | log.Debug("mitm: cache hit for %s", hostname)
226 |
227 | // Check validity of the certificate for hostname match, expiry, etc. In
228 | // particular, if the cached certificate has expired, create a new one.
229 | if _, err = cert.Leaf.Verify(x509.VerifyOptions{
230 | DNSName: hostname,
231 | Roots: c.roots,
232 | }); err == nil {
233 | return cert, nil
234 | }
235 |
236 | log.Debug("mitm: invalid certificate in the cache for %s", hostname)
237 | }
238 |
239 | log.Debug("mitm: cache miss for %s", hostname)
240 |
241 | // Increment the serial number
242 | serial := atomic.AddInt64(¤tSerialNumber, 1)
243 |
244 | tmpl := &x509.Certificate{
245 | SerialNumber: big.NewInt(serial),
246 | Subject: pkix.Name{
247 | CommonName: hostname,
248 | Organization: []string{c.organization},
249 | },
250 | SubjectKeyId: c.keyID,
251 | KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
252 | ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
253 | BasicConstraintsValid: true,
254 | NotBefore: time.Now().Add(-c.validity),
255 | NotAfter: time.Now().Add(c.validity),
256 | }
257 |
258 | if ip := net.ParseIP(hostname); ip != nil {
259 | tmpl.IPAddresses = []net.IP{ip}
260 | } else {
261 | tmpl.DNSNames = []string{hostname}
262 | }
263 |
264 | raw, err := x509.CreateCertificate(rand.Reader, tmpl, c.ca, c.privateKey.Public(), c.caPrivateKey)
265 | if err != nil {
266 | return nil, err
267 | }
268 |
269 | // Parse certificate bytes so that we have a leaf certificate.
270 | x509c, err := x509.ParseCertificate(raw)
271 | if err != nil {
272 | return nil, err
273 | }
274 |
275 | cert = &tls.Certificate{
276 | Certificate: [][]byte{raw, c.ca.Raw},
277 | PrivateKey: c.privateKey,
278 | Leaf: x509c,
279 | }
280 |
281 | c.certsStorageMu.Lock()
282 | c.certsStorage.Set(hostname, cert)
283 | c.certsStorageMu.Unlock()
284 |
285 | return cert, nil
286 | }
287 |
--------------------------------------------------------------------------------
/mitm/mitm_test.go:
--------------------------------------------------------------------------------
1 | package mitm
2 |
3 | import (
4 | "crypto/tls"
5 | "crypto/x509"
6 | "net"
7 | "testing"
8 | "time"
9 |
10 | "github.com/stretchr/testify/assert"
11 | )
12 |
13 | func TestMITM(t *testing.T) {
14 | ca, privateKey, err := NewAuthority("gomitmproxy ca", "gomitmproxy", 24*time.Hour)
15 |
16 | assert.Nil(t, err)
17 | assert.NotNil(t, ca)
18 | assert.NotNil(t, privateKey)
19 |
20 | c, err := NewConfig(ca, privateKey, nil)
21 | assert.Nil(t, err)
22 |
23 | c.SetValidity(20 * time.Hour)
24 | c.SetOrganization("Test Organization")
25 |
26 | conf := c.NewTLSConfigForHost("example.org")
27 | assert.Equal(t, []string{"http/1.1"}, conf.NextProtos)
28 | assert.True(t, conf.InsecureSkipVerify)
29 |
30 | // Test generating a certificate
31 | clientHello := &tls.ClientHelloInfo{
32 | ServerName: "example.org",
33 | }
34 | tlsCert, err := conf.GetCertificate(clientHello)
35 | assert.Nil(t, err)
36 | assert.NotNil(t, tlsCert)
37 |
38 | // Assert certificate details
39 | x509c := tlsCert.Leaf
40 | assert.Equal(t, "example.org", x509c.Subject.CommonName)
41 | assert.Nil(t, x509c.VerifyHostname("example.org"))
42 | assert.Equal(t, []string{"Test Organization"}, x509c.Subject.Organization)
43 | assert.NotNil(t, x509c.SubjectKeyId)
44 | assert.True(t, x509c.BasicConstraintsValid)
45 | assert.True(t, x509c.KeyUsage&x509.KeyUsageKeyEncipherment == x509.KeyUsageKeyEncipherment)
46 | assert.True(t, x509c.KeyUsage&x509.KeyUsageDigitalSignature == x509.KeyUsageDigitalSignature)
47 | assert.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, x509c.ExtKeyUsage)
48 | assert.Equal(t, []string{"example.org"}, x509c.DNSNames)
49 | assert.True(t, x509c.NotBefore.Before(time.Now().Add(-2*time.Hour)))
50 | assert.True(t, x509c.NotAfter.After(time.Now().Add(2*time.Hour)))
51 |
52 | // Check that certificate is cached
53 | tlsCert2, err := c.GetOrCreateCert("example.org")
54 | assert.Nil(t, err)
55 | assert.True(t, tlsCert == tlsCert2)
56 |
57 | // Check the certificate for an IP
58 | tlsCertForIP, err := c.GetOrCreateCert("192.168.0.1:443")
59 | assert.Nil(t, err)
60 | x509c = tlsCertForIP.Leaf
61 | assert.Equal(t, 1, len(x509c.IPAddresses))
62 | assert.True(t, net.ParseIP("192.168.0.1").Equal(x509c.IPAddresses[0]))
63 | }
64 |
--------------------------------------------------------------------------------
/proxy.go:
--------------------------------------------------------------------------------
1 | // Package gomitmproxy implements a configurable mitm proxy wring purely in go.
2 | package gomitmproxy
3 |
4 | import (
5 | "bufio"
6 | "bytes"
7 | "crypto/tls"
8 | "encoding/pem"
9 | "io"
10 | "net"
11 | "net/http"
12 | "strings"
13 | "sync"
14 | "time"
15 |
16 | "github.com/AdguardTeam/golibs/log"
17 | "github.com/AdguardTeam/gomitmproxy/proxyutil"
18 | "github.com/pkg/errors"
19 | )
20 |
21 | var errClientCertRequested = errors.New("tls: client cert authentication unsupported")
22 |
23 | // defaultTimeout is the default value for reading from local connections.
24 | // By default we have no timeout.
25 | //
26 | // TODO(ameshkov): rework deadlines (see #13 for example).
27 | const defaultTimeout = 0
28 | const dialTimeout = 30 * time.Second
29 | const tlsHandshakeTimeout = 10 * time.Second
30 |
31 | // Proxy is a structure with the proxy server configuration and current state.
32 | type Proxy struct {
33 | // addr is the address the proxy listens to.
34 | addr net.Addr
35 |
36 | // transport is an http.RoundTripper instance that we use for plain HTTP
37 | // requests.
38 | transport http.RoundTripper
39 |
40 | // listener is used to accept incoming connections to this proxy.
41 | listener net.Listener
42 |
43 | // dial is a function for creating net.Conn. Can be useful to override in
44 | // unit-tests.
45 | dial func(string, string) (net.Conn, error)
46 |
47 | // timeout is the remote connection's read/write timeout.
48 | timeout time.Duration
49 |
50 | // closing is the channel that signals that proxy is closing.
51 | closing chan bool
52 |
53 | // connsWg is a wait group that's used to keep track of active connections.
54 | connsWg sync.WaitGroup
55 |
56 | // The proxy will not attempt MITM for these hostnames. A hostname can be
57 | // added to this list in runtime if proxy fails to verify the certificate.
58 | invalidTLSHosts map[string]bool
59 | invalidTLSHostsMu sync.RWMutex
60 |
61 | // Config is the proxy's configuration.
62 | // TODO(ameshkov): make it a field.
63 | Config
64 | }
65 |
66 | // NewProxy creates a new instance of the Proxy.
67 | func NewProxy(config Config) *Proxy {
68 | proxy := &Proxy{
69 | Config: config,
70 | transport: &http.Transport{
71 | // This forces http.Transport to not upgrade requests to HTTP/2.
72 | // TODO: Remove when HTTP/2 can be supported.
73 | TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper),
74 | Proxy: http.ProxyFromEnvironment,
75 | TLSHandshakeTimeout: tlsHandshakeTimeout,
76 | ExpectContinueTimeout: time.Second,
77 | TLSClientConfig: &tls.Config{
78 | GetClientCertificate: func(info *tls.CertificateRequestInfo) (certificate *tls.Certificate, e error) {
79 | // We purposefully cause an error here so that the
80 | // http.Transport.RoundTrip method failed. In this case
81 | // we'll receive the error and will be able to add the host
82 | // to invalidTLSHosts.
83 | return nil, errClientCertRequested
84 | },
85 | },
86 | },
87 | timeout: defaultTimeout,
88 | invalidTLSHosts: map[string]bool{},
89 | closing: make(chan bool),
90 | }
91 | proxy.dial = (&net.Dialer{
92 | Timeout: dialTimeout,
93 | KeepAlive: dialTimeout,
94 | }).Dial
95 |
96 | if len(config.MITMExceptions) > 0 {
97 | for _, hostname := range config.MITMExceptions {
98 | proxy.invalidTLSHosts[hostname] = true
99 | }
100 | }
101 |
102 | return proxy
103 | }
104 |
105 | // Addr returns the address this proxy listens to.
106 | func (p *Proxy) Addr() (addr net.Addr) {
107 | return p.addr
108 | }
109 |
110 | // Closing returns true if the proxy is in the closing state.
111 | func (p *Proxy) Closing() (ok bool) {
112 | select {
113 | case <-p.closing:
114 | return true
115 | default:
116 | return false
117 | }
118 | }
119 |
120 | // Start starts the proxy server in a separate goroutine.
121 | func (p *Proxy) Start() (err error) {
122 | l, err := net.ListenTCP("tcp", p.ListenAddr)
123 | if err != nil {
124 | return err
125 | }
126 | p.addr = l.Addr()
127 |
128 | var listener net.Listener
129 | listener = l
130 | if p.TLSConfig != nil {
131 | listener = tls.NewListener(l, p.TLSConfig)
132 | }
133 |
134 | p.listener = listener
135 | go p.Serve(listener)
136 | return nil
137 | }
138 |
139 | // Serve starts reading and processing requests from the specified listener.
140 | // Please note, that it will close the listener in the end.
141 | func (p *Proxy) Serve(l net.Listener) {
142 | log.Printf("start listening to %s", l.Addr())
143 | err := p.serve(l)
144 | if err != nil {
145 | log.Printf("finished serving due to: %v", err)
146 | }
147 | _ = l.Close()
148 | }
149 |
150 | // Close sets the proxy to the closing state so it stops receiving new
151 | // connections, finishes processing any inflight requests, and closes existing
152 | // connections without reading anymore requests from them.
153 | //
154 | // TODO(ameshkov): make it return an error.
155 | func (p *Proxy) Close() {
156 | log.Printf("Closing proxy")
157 |
158 | log.OnCloserError(p.listener, log.DEBUG)
159 |
160 | // This will prevent waiting for the proxy.timeout until an incoming
161 | // request has been read.
162 | close(p.closing)
163 |
164 | log.Printf("Waiting for all active connections to close")
165 | p.connsWg.Wait()
166 | log.Printf("All connections closed")
167 | }
168 |
169 | // serve accepts connections from the specified listener and passes them further
170 | // to Proxy.handleConnection.
171 | func (p *Proxy) serve(l net.Listener) (err error) {
172 | for {
173 | if p.Closing() {
174 | return nil
175 | }
176 |
177 | conn, err := l.Accept()
178 | if err != nil {
179 | return err
180 | }
181 |
182 | localRW := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
183 | ctx := newContext(conn, localRW, nil)
184 | log.Debug("id=%s: accepted connection from %s", ctx.ID(), ctx.conn.RemoteAddr())
185 |
186 | if tcpConn, ok := conn.(*net.TCPConn); ok {
187 | _ = tcpConn.SetKeepAlive(true)
188 | _ = tcpConn.SetKeepAlivePeriod(3 * time.Minute)
189 | }
190 |
191 | go p.handleConnection(ctx)
192 | }
193 | }
194 |
195 | // handleConnection starts processing a new network connection.
196 | func (p *Proxy) handleConnection(ctx *Context) {
197 | // Increment the active connections count.
198 | p.connsWg.Add(1)
199 |
200 | // Clean up on exit.
201 | defer p.connsWg.Done()
202 | defer log.OnCloserError(ctx.conn, log.DEBUG)
203 |
204 | if p.Closing() {
205 | return
206 | }
207 |
208 | p.handleLoop(ctx)
209 | }
210 |
211 | // handleLoop processes requests in a loop.
212 | func (p *Proxy) handleLoop(ctx *Context) {
213 | for {
214 | if p.timeout > 0 {
215 | // TODO(ameshkov): rework deadlines (see #13 for example).
216 | deadline := time.Now().Add(p.timeout)
217 | _ = ctx.SetDeadline(deadline)
218 | }
219 |
220 | if err := p.handleRequest(ctx); err != nil {
221 | log.Debug("id=%s: closing connection due to: %v", ctx.ID(), err)
222 |
223 | return
224 | }
225 | }
226 | }
227 |
228 | // handleRequest reads an incoming request and processes it.
229 | func (p *Proxy) handleRequest(ctx *Context) (err error) {
230 | origReq, err := p.readRequest(ctx)
231 | if err != nil {
232 | return err
233 | }
234 |
235 | defer log.OnCloserError(origReq.Body, log.DEBUG)
236 |
237 | session := newSession(ctx, origReq)
238 | p.prepareRequest(origReq, session)
239 | log.Debug("id=%s: handle request %s %s", session.ID(), origReq.Method, origReq.URL.String())
240 |
241 | customRes := false
242 | if p.OnRequest != nil {
243 | newReq, newRes := p.OnRequest(session)
244 | if newReq != nil {
245 | log.Debug("id=%s: request was overridden by: %s", session.ID(), newReq.URL.String())
246 | session.req = newReq
247 | }
248 | if newRes != nil {
249 | log.Debug("id=%s: response was overridden by: %s", session.ID(), newRes.Status)
250 | session.res = newRes
251 | customRes = true
252 | }
253 | }
254 |
255 | if session.req.Host == p.APIHost {
256 | return p.handleAPIRequest(session)
257 | }
258 |
259 | if !customRes {
260 | // check proxy authorization first.
261 | if p.Username != "" {
262 | auth, res := p.authorize(session)
263 | if !auth {
264 | log.Debug("id=%s: proxy auth required", session.ID())
265 | session.res = res
266 |
267 | defer log.OnCloserError(res.Body, log.DEBUG)
268 |
269 | _ = p.writeResponse(session)
270 |
271 | // Do not return any error here as we must keep the connection
272 | // alive. When the client receives 407 error, it can write
273 | // another request with user credentials to the same connection.
274 | // See https://github.com/AdguardTeam/gomitmproxy/pull/19.
275 | return nil
276 | }
277 | }
278 |
279 | if session.req.Header.Get("Upgrade") == "websocket" {
280 | // connection protocol will be upgraded.
281 | return p.handleTunnel(session)
282 | }
283 |
284 | // connection, proxy-connection, etc, etc.
285 | removeHopByHopHeaders(session.req.Header)
286 |
287 | if session.req.Method == http.MethodConnect {
288 | return p.handleConnect(session)
289 | }
290 |
291 | // not a CONNECT request, processing a plain HTTP request.
292 | res, err := p.transport.RoundTrip(session.req)
293 | if err != nil {
294 | log.Error("id=%s: failed to round trip: %v", session.ID(), err)
295 | p.raiseOnError(session, err)
296 |
297 | res = proxyutil.NewErrorResponse(session.req, err)
298 |
299 | if strings.Contains(err.Error(), "x509: ") ||
300 | strings.Contains(err.Error(), errClientCertRequested.Error()) {
301 | log.Printf("id=%s: adding %s to invalid TLS hosts due to: %v", session.ID(), session.req.Host, err)
302 | p.invalidTLSHostsMu.Lock()
303 | p.invalidTLSHosts[session.req.Host] = true
304 | p.invalidTLSHostsMu.Unlock()
305 | }
306 | }
307 |
308 | log.Debug("id=%s: received response %s", session.ID(), res.Status)
309 | removeHopByHopHeaders(res.Header)
310 | session.res = res
311 | }
312 |
313 | // Make sure the response body is always closed.
314 | defer log.OnCloserError(session.res.Body, log.DEBUG)
315 |
316 | err = p.writeResponse(session)
317 | if err != nil {
318 | return err
319 | }
320 |
321 | // TODO(ameshkov): Think about refactoring this, looks not good
322 | if p.isClosing(session) {
323 | return errClose
324 | }
325 |
326 | if p.Closing() {
327 | log.Debug("id=%s: proxy is shutting down, closing response", session.ID())
328 | return errShutdown
329 | }
330 |
331 | return nil
332 | }
333 |
334 | // handleAPIRequest handles a request to gomitmproxy's API.
335 | func (p *Proxy) handleAPIRequest(session *Session) (err error) {
336 | if session.req.URL.Path == "/cert.crt" && p.MITMConfig != nil {
337 | // serve ca
338 | b := pem.EncodeToMemory(&pem.Block{
339 | Type: "CERTIFICATE",
340 | Bytes: p.MITMConfig.GetCA().Raw,
341 | })
342 |
343 | session.res = proxyutil.NewResponse(http.StatusOK, bytes.NewReader(b), session.req)
344 | defer log.OnCloserError(session.res.Body, log.DEBUG)
345 |
346 | session.res.Close = true
347 | session.res.Header.Set("Content-Type", "application/x-x509-ca-cert")
348 | session.res.ContentLength = int64(len(b))
349 |
350 | return p.writeResponse(session)
351 | }
352 |
353 | session.res = proxyutil.NewErrorResponse(session.req, errors.Errorf("wrong API method"))
354 | defer log.OnCloserError(session.res.Body, log.DEBUG)
355 |
356 | session.res.Close = true
357 |
358 | return p.writeResponse(session)
359 | }
360 |
361 | // isClosing returns true if this session's response or request signals that
362 | // the connection must be closed.
363 | func (p *Proxy) isClosing(session *Session) (ok bool) {
364 | // See http.Response.Write implementation for the details on this.
365 | //
366 | // If we're sending a non-chunked HTTP/1.1 response without a
367 | // content-length, the only way to do that is the old HTTP/1.0 way, by
368 | // noting the EOF with a connection close, so we need to set Close.
369 | if (session.res.ContentLength == 0 || session.res.ContentLength == -1) &&
370 | !session.res.Close &&
371 | session.res.ProtoAtLeast(1, 1) &&
372 | !session.res.Uncompressed &&
373 | (len(session.res.TransferEncoding) == 0 || session.res.TransferEncoding[0] != "chunked") {
374 | log.Debug("id=%s: received close request (http/1.0 way)", session.ID())
375 |
376 | return true
377 | }
378 |
379 | if session.req.Close || session.res.Close {
380 | log.Debug("id=%s: received close request", session.ID())
381 |
382 | return true
383 | }
384 |
385 | return false
386 | }
387 |
388 | // handleTunnel tunnels data to the remote connection.
389 | func (p *Proxy) handleTunnel(session *Session) (err error) {
390 | log.Debug("id=%s: handling connection to host: %s", session.ID(), session.req.URL.Host)
391 |
392 | conn, err := p.connect(session, "tcp", session.RemoteAddr())
393 | if err != nil {
394 | log.Error("id=%s: failed to connect to %s: %v", session.ID(), session.req.URL.Host, err)
395 | p.raiseOnError(session, err)
396 | session.res = proxyutil.NewErrorResponse(session.req, err)
397 | _ = p.writeResponse(session)
398 | log.OnCloserError(session.res.Body, log.DEBUG)
399 |
400 | return err
401 | }
402 |
403 | remoteConn := conn
404 | defer log.OnCloserError(remoteConn, log.DEBUG)
405 |
406 | // If we're inside a MITMed connection, we should open a TLS connection
407 | // instead.
408 | if session.ctx.IsMITM() {
409 | getClientCert := func(
410 | info *tls.CertificateRequestInfo,
411 | ) (certificate *tls.Certificate, e error) {
412 | // We purposefully cause an error here so that the
413 | // http.Transport.RoundTrip method failed. In this case we'll
414 | // receive the error and will be able to add the host to
415 | // invalidTLSHosts.
416 | return nil, errClientCertRequested
417 | }
418 |
419 | tlsConn := tls.Client(conn, &tls.Config{
420 | ServerName: session.req.URL.Host,
421 | GetClientCertificate: getClientCert,
422 | })
423 |
424 | // Handshake with the remote server.
425 | if err = tlsConn.Handshake(); err != nil {
426 | // TODO(ameshkov): Consider adding to invalidTLSHosts.
427 | // We should do this if this happens a couple of times in a short
428 | // period of time.
429 | log.Error("id=%s: failed to handshake with the server: %v", session.ID(), err)
430 |
431 | return err
432 | }
433 |
434 | // Prepare to process the data.
435 | remoteConn = tlsConn
436 | }
437 |
438 | // Write the original request to the connection.
439 | err = session.req.Write(remoteConn)
440 | if err != nil {
441 | log.Error("id=%s: failed to write request: %v", session.ID(), err)
442 |
443 | return err
444 | }
445 |
446 | // Note that we don't use buffered reader/writer for local connection as it
447 | // causes a noticeable delay when we work as an HTTP over TLS proxy.
448 | donec := make(chan bool, 2)
449 | go copyConnectTunnel(session, remoteConn, session.ctx.conn, donec)
450 | go copyConnectTunnel(session, session.ctx.conn, remoteConn, donec)
451 |
452 | log.Debug("id=%s: established tunnel, proxying traffic", session.ID())
453 | <-donec
454 | <-donec
455 | log.Debug("id=%s: closed tunnel", session.ID())
456 |
457 | return errClose
458 | }
459 |
460 | // handleConnect processes HTTP CONNECT requests.
461 | func (p *Proxy) handleConnect(session *Session) (err error) {
462 | log.Debug("id=%s: connecting to host: %s", session.ID(), session.req.URL.Host)
463 |
464 | // TODO(ameshkov): find a way to use remoteConn when the request is MITMed.
465 | remoteConn, err := p.connect(session, "tcp", session.RemoteAddr())
466 | if remoteConn != nil {
467 | defer log.OnCloserError(remoteConn, log.DEBUG)
468 | }
469 |
470 | if err != nil {
471 | log.Error("id=%s: failed to connect to %s: %v", session.ID(), session.req.URL.Host, err)
472 | p.raiseOnError(session, err)
473 |
474 | session.res = proxyutil.NewErrorResponse(session.req, err)
475 | _ = p.writeResponse(session)
476 | defer log.OnCloserError(session.res.Body, log.DEBUG)
477 |
478 | return err
479 | }
480 |
481 | if p.canMITM(session.req.URL.Host) {
482 | log.Debug("id=%s: attempting MITM for connection", session.ID())
483 | session.res = proxyutil.NewResponse(http.StatusOK, nil, session.req)
484 | err = p.writeResponse(session)
485 |
486 | log.OnCloserError(session.res.Body, log.DEBUG)
487 |
488 | if err != nil {
489 | return err
490 | }
491 |
492 | b := make([]byte, 1)
493 | if _, err = session.ctx.localRW.Read(b); err != nil {
494 | log.Error("id=%s: error peeking message through CONNECT tunnel to determine type: %v", session.ID(), err)
495 | return err
496 | }
497 |
498 | // Drain all of the rest of the buffered data.
499 | buf := make([]byte, session.ctx.localRW.Reader.Buffered())
500 | _, _ = session.ctx.localRW.Read(buf)
501 |
502 | // Prepend the previously read data to be read again by
503 | // http.ReadRequest.
504 | pc := &peekedConn{
505 | session.ctx.conn,
506 | io.MultiReader(bytes.NewReader(b), bytes.NewReader(buf), session.ctx.conn),
507 | }
508 |
509 | // 22 is the TLS handshake.
510 | // https://tools.ietf.org/html/rfc5246#section-6.2.1
511 | if b[0] == 22 {
512 | tlsConn := tls.Server(pc, p.MITMConfig.NewTLSConfigForHost(session.req.URL.Host))
513 |
514 | // Handshake with the local client.
515 | if err = tlsConn.Handshake(); err != nil {
516 | // TODO(ameshkov): Consider adding to invalidTLSHosts.
517 | // We should do this if this happens a couple of times in a
518 | // short period of time.
519 | log.Error("id=%s: failed to handshake with the client: %v", session.ID(), err)
520 |
521 | return err
522 | }
523 |
524 | newLocalRW := bufio.NewReadWriter(bufio.NewReader(tlsConn), bufio.NewWriter(tlsConn))
525 | newCtx := newContext(tlsConn, newLocalRW, session)
526 | p.handleLoop(newCtx)
527 |
528 | return errClose
529 | }
530 |
531 | newLocalRW := bufio.NewReadWriter(bufio.NewReader(pc), bufio.NewWriter(pc))
532 | newCtx := newContext(pc, newLocalRW, session)
533 | p.handleLoop(newCtx)
534 |
535 | return errClose
536 | }
537 |
538 | session.res = proxyutil.NewResponse(http.StatusOK, nil, session.req)
539 | defer log.OnCloserError(session.res.Body, log.DEBUG)
540 |
541 | session.res.ContentLength = -1
542 | err = p.writeResponse(session)
543 | if err != nil {
544 | return err
545 | }
546 |
547 | // Note that we don't use buffered reader/writer for local connection
548 | // as it causes a noticeable delay when we work as an HTTP over TLS proxy
549 | donec := make(chan bool, 2)
550 | go copyConnectTunnel(session, remoteConn, session.ctx.conn, donec)
551 | go copyConnectTunnel(session, session.ctx.conn, remoteConn, donec)
552 |
553 | log.Debug("id=%s: established CONNECT tunnel, proxying traffic", session.ID())
554 | <-donec
555 | <-donec
556 | log.Debug("id=%s: closed CONNECT tunnel", session.ID())
557 |
558 | return errClose
559 | }
560 |
561 | // copyConnectTunnel copies data from reader to writer and then signals about
562 | // finishing to the "donec" channel.
563 | func copyConnectTunnel(session *Session, w io.Writer, r io.Reader, donec chan<- bool) {
564 | if _, err := io.Copy(w, r); err != nil && !isCloseable(err) {
565 | log.Error("id=%s: failed to tunnel: %v", session.ID(), err)
566 | }
567 |
568 | log.Debug("id=%s: tunnel finished copying", session.ID())
569 | donec <- true
570 | }
571 |
572 | // readRequest reads incoming http request.
573 | func (p *Proxy) readRequest(ctx *Context) (req *http.Request, err error) {
574 | log.Debug("id=%s: waiting for request", ctx.ID())
575 |
576 | reqc := make(chan *http.Request, 1)
577 | errc := make(chan error, 1)
578 |
579 | // Try reading the HTTP request in a separate goroutine. The idea is to make
580 | // this process cancelable. When reading the request is finished, it will
581 | // write the results to one of the channels, either reqc or errc. At the
582 | // same time we'll be reading from the "closing" channel. When the proxy is
583 | // shutting down, the "closing" channel is closed so we'll immediately
584 | // return.
585 | go func() {
586 | r, readErr := http.ReadRequest(ctx.localRW.Reader)
587 | if readErr != nil {
588 | if isCloseable(readErr) {
589 | log.Debug("id=%s: connection closed prematurely: %v", ctx.ID(), readErr)
590 | } else {
591 | log.Debug("id=%s: failed to read request: %v", ctx.ID(), readErr)
592 | }
593 |
594 | errc <- readErr
595 | return
596 | }
597 | reqc <- r
598 | }()
599 |
600 | // Waiting for the result or for proxy to shutdown
601 | select {
602 | case err = <-errc:
603 | return nil, err
604 | case req = <-reqc:
605 | case <-p.closing:
606 | return nil, errShutdown
607 | }
608 |
609 | return req, nil
610 | }
611 |
612 | // writeResponse writes the response from session.res to the local client.
613 | func (p *Proxy) writeResponse(session *Session) (err error) {
614 | if p.OnResponse != nil {
615 | res := p.OnResponse(session)
616 | if res != nil {
617 | origBody := res.Body
618 | defer log.OnCloserError(origBody, log.DEBUG)
619 | log.Debug("id=%s: response was overridden by: %s", session.ID(), res.Status)
620 | session.res = res
621 | }
622 | }
623 |
624 | if err = session.res.Write(session.ctx.localRW); err != nil {
625 | log.Error(
626 | "id=%s: got error while writing response back to client: %v",
627 | session.ID(),
628 | err,
629 | )
630 | }
631 |
632 | if err = session.ctx.localRW.Flush(); err != nil {
633 | log.Error(
634 | "id=%s: got error while flushing response back to client: %v",
635 | session.ID(),
636 | err,
637 | )
638 | }
639 |
640 | return err
641 | }
642 |
643 | // connect opens a network connection to the specified remote address.
644 | //
645 | // This method can be called in two cases:
646 | // 1. When the proxy handles the HTTP CONNECT.
647 | // IMPORTANT: In this case we don't actually use the remote connections.
648 | // It is only used to check if the remote endpoint is available
649 | // 2. When the proxy bypasses data from the client to the remote endpoint.
650 | // For instance, it could happen when there's a WebSocket connection.
651 | func (p *Proxy) connect(session *Session, proto string, addr string) (conn net.Conn, err error) {
652 | log.Debug("id=%s: connecting to %s://%s", session.ID(), proto, addr)
653 |
654 | if p.OnConnect != nil {
655 | conn = p.OnConnect(session, proto, addr)
656 | if conn != nil {
657 | log.Debug("id=%s: connection was overridden", session.ID())
658 |
659 | return conn, nil
660 | }
661 | }
662 |
663 | host, _, err := net.SplitHostPort(addr)
664 | if err == nil && host == p.APIHost {
665 | log.Debug("id=%s: connecting to the API host, return dummy connection", session.ID())
666 |
667 | return &proxyutil.NoopConn{}, nil
668 | }
669 |
670 | return p.dial(proto, addr)
671 | }
672 |
673 | // prepareRequest prepares an HTTP request to be sent to the remote server.
674 | func (p *Proxy) prepareRequest(req *http.Request, session *Session) {
675 | if req.URL.Host == "" {
676 | req.URL.Host = req.Host
677 | }
678 | // http by default.
679 | req.URL.Scheme = "http"
680 |
681 | // Check if this is an HTTPS connection inside an HTTP CONNECT tunnel.
682 | if session.ctx.IsMITM() {
683 | tlsConn := session.ctx.conn.(*tls.Conn)
684 | cs := tlsConn.ConnectionState()
685 | req.TLS = &cs
686 |
687 | // Force HTTPS for secure sessions.
688 | req.URL.Scheme = "https"
689 | }
690 | req.RemoteAddr = session.ctx.conn.RemoteAddr().String()
691 |
692 | // Remove unsupported encodings.
693 | if req.Header.Get("Accept-Encoding") != "" {
694 | req.Header.Set("Accept-Encoding", "gzip")
695 | }
696 | }
697 |
698 | // raiseOnError calls Proxy.OnError callback if needed.
699 | func (p *Proxy) raiseOnError(session *Session, err error) {
700 | if p.OnError != nil {
701 | p.OnError(session, err)
702 | }
703 | }
704 |
705 | // canMITM checks if we can perform MITM for this host.
706 | func (p *Proxy) canMITM(hostname string) (ok bool) {
707 | if p.MITMConfig == nil {
708 | return false
709 | }
710 |
711 | // Remove the port if it exists.
712 | host, port, err := net.SplitHostPort(hostname)
713 | if err == nil {
714 | hostname = host
715 | }
716 |
717 | // TODO(ameshkov): change this, should be exposed via a callback.
718 | if port != "443" {
719 | log.Debug("do not attempt to MITM connections to a port different from 443")
720 |
721 | return false
722 | }
723 |
724 | p.invalidTLSHostsMu.RLock()
725 | _, found := p.invalidTLSHosts[hostname]
726 | p.invalidTLSHostsMu.RUnlock()
727 |
728 | return !found
729 | }
730 |
--------------------------------------------------------------------------------
/proxyutil/util.go:
--------------------------------------------------------------------------------
1 | // Package proxyutil contains different utility methods that will be helpful to
2 | // gomitmproxy users.
3 | package proxyutil
4 |
5 | import (
6 | "bytes"
7 | "compress/gzip"
8 | "fmt"
9 | "io"
10 | "net"
11 | "net/http"
12 | "time"
13 |
14 | "github.com/AdguardTeam/golibs/log"
15 | "golang.org/x/text/encoding/charmap"
16 | "golang.org/x/text/transform"
17 | )
18 |
19 | // NewResponse builds a new HTTP response. If body is nil, an empty byte.Buffer
20 | // will be provided to be consistent with the guarantees provided by
21 | // http.Transport and http.Client.
22 | func NewResponse(code int, body io.Reader, req *http.Request) (resp *http.Response) {
23 | if body == nil {
24 | body = &bytes.Buffer{}
25 | }
26 |
27 | rc, ok := body.(io.ReadCloser)
28 | if !ok {
29 | rc = io.NopCloser(body)
30 | }
31 |
32 | res := &http.Response{
33 | StatusCode: code,
34 | Status: fmt.Sprintf("%d %s", code, http.StatusText(code)),
35 | Proto: "HTTP/1.1",
36 | ProtoMajor: 1,
37 | ProtoMinor: 1,
38 | Header: http.Header{},
39 | Body: rc,
40 | Request: req,
41 | }
42 |
43 | if req != nil {
44 | res.Close = req.Close
45 | res.Proto = req.Proto
46 | res.ProtoMajor = req.ProtoMajor
47 | res.ProtoMinor = req.ProtoMinor
48 | }
49 |
50 | return res
51 | }
52 |
53 | // NewErrorResponse creates a new HTTP response with status code
54 | // "502 Bad Gateway". "Warning" header is populated with the error details.
55 | // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning.
56 | func NewErrorResponse(req *http.Request, err error) (resp *http.Response) {
57 | resp = NewResponse(http.StatusBadGateway, nil, req)
58 | resp.Close = true
59 |
60 | date := resp.Header.Get("Date")
61 | if date == "" {
62 | date = time.Now().Format(http.TimeFormat)
63 | }
64 |
65 | w := fmt.Sprintf(`199 "gomitmproxy" %q %q`, err.Error(), date)
66 | resp.Header.Add("Warning", w)
67 | return resp
68 | }
69 |
70 | // ReadDecompressedBody reads full response body and decompresses it if
71 | // necessary.
72 | func ReadDecompressedBody(res *http.Response) (b []byte, err error) {
73 | rBody := res.Body
74 | if res.Header.Get("Content-Encoding") == "gzip" {
75 | var gzReader io.ReadCloser
76 | gzReader, err = gzip.NewReader(rBody)
77 | if err != nil {
78 | return nil, err
79 | }
80 |
81 | rBody = gzReader
82 |
83 | defer log.OnCloserError(gzReader, log.DEBUG)
84 | }
85 |
86 | return io.ReadAll(rBody)
87 | }
88 |
89 | // DecodeLatin1 decodes Latin1 string from the reader. This method is useful
90 | // for editing response bodies when you don't want to handle different
91 | // encodings.
92 | func DecodeLatin1(reader io.Reader) (str string, err error) {
93 | r := transform.NewReader(reader, charmap.ISO8859_1.NewDecoder())
94 | b, err := io.ReadAll(r)
95 | if err != nil {
96 | return "", err
97 | }
98 |
99 | return string(b), nil
100 | }
101 |
102 | // EncodeLatin1 encodes the string as a byte array using Latin1.
103 | func EncodeLatin1(str string) ([]byte, error) {
104 | return charmap.ISO8859_1.NewEncoder().Bytes([]byte(str))
105 | }
106 |
107 | // NoopConn is a struct that implements net.Conn and does nothing.
108 | type NoopConn struct{}
109 |
110 | // LocalAddr always returns 0.0.0.0:0.
111 | func (NoopConn) LocalAddr() net.Addr { return &net.TCPAddr{} }
112 |
113 | // RemoteAddr always returns 0.0.0.0:0.
114 | func (NoopConn) RemoteAddr() net.Addr { return &net.TCPAddr{} }
115 |
116 | // SetDeadline does nothing, returns nil.
117 | func (NoopConn) SetDeadline(time.Time) error { return nil }
118 |
119 | // SetReadDeadline does nothing, returns nil.
120 | func (NoopConn) SetReadDeadline(time.Time) error { return nil }
121 |
122 | // SetWriteDeadline does nothing, returns nil.
123 | func (NoopConn) SetWriteDeadline(time.Time) error { return nil }
124 |
125 | // Read does nothing, returns io.EOF.
126 | func (NoopConn) Read([]byte) (int, error) { return 0, io.EOF }
127 |
128 | // Write does nothing, returns len(b).
129 | func (NoopConn) Write(b []byte) (int, error) { return len(b), nil }
130 |
131 | // Close does nothing, returns nil.
132 | func (NoopConn) Close() error { return nil }
133 |
--------------------------------------------------------------------------------