├── .gitignore
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── RedWarden.py
├── ca-cert
├── ca.crt
├── ca.key
└── cert.key
├── data
├── banned_ips.txt
├── banned_words.txt
└── banned_words_override.txt
├── example-config.yaml
├── images
├── 0.png
├── 1.png
├── 2.png
└── 3.png
├── lib
├── __init__.py
├── ipLookupHelper.py
├── optionsparser.py
├── pluginsloader.py
├── proxyhandler.py
├── proxylogger.py
├── sslintercept.py
└── utils.py
├── plugins
├── IProxyPlugin.py
├── __init__.py
└── malleable_redirector.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | Mariusz Banach (mgeeky, @mariuszbit, mb@binary-offensive.com).
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
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 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant 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 install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | 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 updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
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 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper 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 appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RedWarden - Flexible CobaltStrike Malleable Redirector
2 |
3 | (previously known as [proxy2's](https://github.com/mgeeky/proxy2) _malleable_redirector_ plugin)
4 |
5 | **Let's raise the bar in C2 redirectors IR resiliency, shall we?**
6 |
7 | 
8 |
9 | Red Teaming business has seen [several](https://bluescreenofjeff.com/2016-04-12-combatting-incident-responders-with-apache-mod_rewrite/) [different](https://posts.specterops.io/automating-apache-mod-rewrite-and-cobalt-strike-malleable-c2-profiles-d45266ca642) [great](https://gist.github.com/curi0usJack/971385e8334e189d93a6cb4671238b10) ideas on how to combat incident responders and misdirect them while offering resistant C2 redirectors network at the same time.
10 |
11 | This work combines many of those great ideas into a one, lightweight utility, mimicking Apache2 in it's roots of being a simple HTTP(S) reverse-proxy.
12 |
13 | Combining Malleable C2 profiles understanding, knowledge of bad IP addresses pool and a flexibility of easily adding new inspection and misrouting logic - resulted in having a crafty repellent for IR inspections.
14 |
15 |
16 | 
17 |
18 | Should any invalid inbound packet reach RedWarden - you can `redirect`, `reset` or just `proxy` it away!
19 |
20 |
21 | ## Abstract
22 |
23 | This program acts as a HTTP/HTTPS reverse-proxy with several restrictions imposed upon inbound C2 HTTP requests selecting which packets to direct to the Teamserver and which to drop, similarly to the .htaccess file restrictions mandated in Apache2's `mod_rewrite`.
24 |
25 | `RedWarden` was created to solve the problem of IR/AV/EDRs/Sandboxes evasion on the C2 redirector layer. It's intended to supersede classical Apache2 + mod_rewrite setups used for that purpose.
26 |
27 | **Features:**
28 |
29 | - Malleable C2 Profile parser able to validate inbound HTTP/S requests strictly according to malleable's contract and drop outlaying packets in case of violation (Malleable Profiles 4.0+ with variants covered)
30 | - Ability to unfilter/repair unexpected and unwanted HTTP headers added by interim systems such as proxies and caches (think CloudFlare) in order to conform to a valid Malleable contract.
31 | - Integrated curated massive blacklist of IPv4 pools and ranges known to be associated with IT Security vendors
32 | - Grepable output log entries (in both Apache2 combined access log and custom RedWarden formats) useful to track peer connectivity events/issues
33 | - Ability to query connecting peer's IPv4 address against IP Geolocation/whois information and confront that with predefined regular expressions to rule out peers connecting outside of trusted organizations/countries/cities etc.
34 | - Built-in Replay attacks mitigation enforced by logging accepted requests' MD5 hashsums into locally stored SQLite database and preventing requests previously accepted.
35 | - Allows to define ProxyPass statemtents to pass requests matching specific URL onto other Hosts
36 | - Support for multiple Teamservers
37 | - Support for many reverse-proxying Hosts/redirection sites giving in a randomized order - which lets load-balance traffic or build more versatile infrastructures
38 | - Can repair HTTP packets according to expected malleable contract in case some of the headers were corrupted in traffic
39 | - Sleepless nights spent on troubleshooting "why my Beacon doesn't work over CloudFlare/CDN/Domain Fronting" are over now thanks to detailed verbose HTTP(S) requests/responses logs
40 |
41 | The RedWarden takes Malleable C2 profile and teamserver's `hostname:port` on its input. It then parses supplied malleable profile sections to understand the contract and pass through only those inbound requests that satisfied it while misdirecting others.
42 |
43 | Sections such as `http-stager`, `http-get`, `http-post` and their corresponding uris, headers, prepend/append patterns, User-Agent are all used to distinguish between legitimate beacon's request and unrelated Internet noise or IR/AV/EDRs out of bound packets.
44 |
45 | The program benefits from the marvelous known bad IP ranges coming from:
46 | curi0usJack and the others:
47 | [https://gist.github.com/curi0usJack/971385e8334e189d93a6cb4671238b10](https://gist.github.com/curi0usJack/971385e8334e189d93a6cb4671238b10)
48 |
49 | Using an IP addresses blacklisting along with known bad keywords lookup through Reverse-IP DNS queries and HTTP headers inspection, brings the reliability to considerably increase redirector's resiliency to the unauthorized peers wanting to examine attacker infrastructures.
50 |
51 | Invalid packets may be misrouted according to three strategies:
52 |
53 | - **redirect**: Simply redirect peer to another websites, such as Rick Roll.
54 | - **reset**: Kill TCP connection straightaway.
55 | - **proxy**: Fetch a response from another website, to mimic cloned/hijacked website as closely as possible.
56 |
57 | This configuration is mandated in configuration file:
58 |
59 | ```yaml
60 | #
61 | # What to do with the request originating not conforming to Beacon, whitelisting or
62 | # ProxyPass inclusive statements:
63 | # - 'redirect' it to another host with (HTTP 301),
64 | # - 'reset' a TCP connection with connecting client
65 | # - 'proxy' the request, acting as a reverse-proxy against specified action_url
66 | # (may be dangerous if client fetches something it shouldn't supposed to see!)
67 | #
68 | # Valid values: 'reset', 'redirect', 'proxy'.
69 | #
70 | # Default: redirect
71 | #
72 | drop_action: redirect
73 | ```
74 |
75 | Below example shows outcome of `redirect` to `https://googole.com`:
76 |
77 | 
78 |
79 |
80 | Use wisely, stay safe.
81 |
82 | ### Requirements
83 |
84 | This program can run only on Linux systems as it uses fork to spawn multiple processes.
85 |
86 | Also, the `openssl` system command is expected to be installed as it is used to generate SSL certificates.
87 |
88 | Finally, install all of the Python3 PIP requirements easily with:
89 |
90 | ```shell
91 | bash $ sudo pip3 install -r requirements.txt
92 | ```
93 |
94 |
95 | ## Usage
96 |
97 | ### Example usage
98 |
99 | The minimal RedWarden's **config.yaml** configuration file could contain:
100 |
101 | ```yaml
102 | port:
103 | - 80/http
104 | - 443/https
105 |
106 | profile: jquery-c2.3.14.profile
107 |
108 | ssl_cacert: /etc/letsencrypt/live/attacker.com/fullchain.pem
109 | ssl_cakey: /etc/letsencrypt/live/attacker.com/privkey.pem
110 |
111 | teamserver_url:
112 | - 1.2.3.4:8080
113 |
114 | drop_action: reset
115 | ```
116 |
117 | Then, the program can be launched by giving it a path to the config file:
118 |
119 | ```shell
120 | bash$ sudo python3 RedWarden.py -c config.yaml
121 |
122 | [INFO] 19:21:42: Loading 1 plugin...
123 | [INFO] 19:21:42: Plugin "malleable_redirector" has been installed.
124 | [INFO] 19:21:42: Preparing SSL certificates and keys for https traffic interception...
125 | [INFO] 19:21:42: Using provided CA key file: ca-cert/ca.key
126 | [INFO] 19:21:42: Using provided CA certificate file: ca-cert/ca.crt
127 | [INFO] 19:21:42: Using provided Certificate key: ca-cert/cert.key
128 | [INFO] 19:21:42: Serving http proxy on: 0.0.0.0, port: 80...
129 | [INFO] 19:21:42: Serving https proxy on: 0.0.0.0, port: 443...
130 | [INFO] 19:21:42: [REQUEST] GET /jquery-3.3.1.min.js
131 | [INFO] 19:21:42: == Valid malleable http-get request inbound.
132 | [INFO] 19:21:42: Plugin redirected request from [code.jquery.com] to [1.2.3.4:8080]
133 | [INFO] 19:21:42: [RESPONSE] HTTP 200 OK, length: 5543
134 | [INFO] 19:21:45: [REQUEST] GET /jquery-3.3.1.min.js
135 | [INFO] 19:21:45: == Valid malleable http-get request inbound.
136 | [INFO] 19:21:45: Plugin redirected request from [code.jquery.com] to [1.2.3.4:8080]
137 | [INFO] 19:21:45: [RESPONSE] HTTP 200 OK, length: 5543
138 | [INFO] 19:21:46: [REQUEST] GET /
139 | [...]
140 | [ERROR] 19:24:46: [DROP, reason:1] inbound User-Agent differs from the one defined in C2 profile.
141 | [...]
142 | [INFO] 19:24:46: [RESPONSE] HTTP 301 Moved Permanently, length: 212
143 | [INFO] 19:24:48: [REQUEST] GET /jquery-3.3.1.min.js
144 | [INFO] 19:24:48: == Valid malleable http-get request inbound.
145 | [INFO] 19:24:48: Plugin redirected request from [code.jquery.com] to [1.2.3.4:8080]
146 | [...]
147 | ```
148 |
149 | The above output contains a line pointing out that there has been an unauthorized, not compliant with our C2 profile inbound request, which got dropped due to incompatible User-Agent string presented:
150 | ```
151 | [...]
152 | [DROP, reason:1] inbound User-Agent differs from the one defined in C2 profile.
153 | [...]
154 | ```
155 |
156 |
157 | ## Use Cases
158 |
159 | ### Impose IP Geolocation on your Beacon traffic originators
160 |
161 | You've done your Pre-Phish and OSINT very well. You now know where your targets live and have some clues where traffic should be originating from, or at least how to detect completely auxiliary traffic.
162 | How to impose IP Geolocation on Beacon requests on a redirector?
163 |
164 | RedWarden comes at help!
165 |
166 | Let's say, you want only to accept traffic originating from Poland, Europe.
167 | Your Pre-Phish/OSINT results indicate that:
168 |
169 | - `89.64.64.150` is a legitimate IP of one of your targets, originating from Poland
170 | - `59.99.140.76` whereas this one is not and it reached your systems as a regular Internet noise packet.
171 |
172 | You can use RedWarden's utility `lib/ipLookupHelper.py` to collect IP Geo metadata about these two addresses:
173 |
174 | ```shell
175 | bash$ python3 ipLookupHelper.py
176 |
177 | Usage: ./ipLookupHelper.py [malleable-redirector-config]
178 |
179 | Use this small utility to collect IP Lookup details on your target IPv4 address and verify whether
180 | your 'ip_geolocation_requirements' section of proxy2 malleable-redirector-config.yaml would match that
181 | IP address. If second param is not given - no
182 | ```
183 |
184 | The former brings:
185 |
186 | ```shell
187 | bash$ python3 ipLookupHelper.py 89.64.64.150
188 | [dbg] Following IP Lookup providers will be used: ['ip_api_com', 'ipapi_co']
189 | [.] Lookup of: 89.64.64.150
190 | [dbg] Calling IP Lookup provider: ipapi_co
191 | [dbg] Calling IP Lookup provider: ip_api_com
192 | [dbg] New IP lookup entry cached: 89.64.64.150
193 | [.] Output:
194 | {
195 | "organization": [
196 | "UPC Polska Sp. z o.o.",
197 | "UPC.pl",
198 | "AS6830 Liberty Global B.V."
199 | ],
200 | "continent": "Europe",
201 | "continent_code": "EU",
202 | "country": "Poland",
203 | "country_code": "PL",
204 | "ip": "89.64.64.150",
205 | "city": "Warsaw",
206 | "timezone": "Europe/Warsaw",
207 | "fulldata": {
208 | "status": "success",
209 | "country": "Poland",
210 | "countryCode": "PL",
211 | "region": "14",
212 | "regionName": "Mazovia",
213 | "city": "Warsaw",
214 | "zip": "00-202",
215 | "lat": 52.2484,
216 | "lon": 21.0026,
217 | "timezone": "Europe/Warsaw",
218 | "isp": "UPC.pl",
219 | "org": "UPC Polska Sp. z o.o.",
220 | "as": "AS6830 Liberty Global B.V.",
221 | "query": "89.64.64.150"
222 | },
223 | "reverse_ip": "89-64-64-150.dynamic.chello.pl"
224 | }
225 | ```
226 |
227 | and the latter gives:
228 |
229 | ```shell
230 | bash$ python3 ipLookupHelper.py 59.99.140.76
231 | [dbg] Following IP Lookup providers will be used: ['ip_api_com', 'ipapi_co']
232 | [dbg] Read 1 cached entries from file.
233 | [.] Lookup of: 59.99.140.76
234 | [dbg] Calling IP Lookup provider: ip_api_com
235 | [dbg] New IP lookup entry cached: 59.99.140.76
236 | [.] Output:
237 | {
238 | "organization": [
239 | "",
240 | "BSNL Internet",
241 | "AS9829 National Internet Backbone"
242 | ],
243 | "continent": "Asia",
244 | "continent_code": "AS",
245 | "country": "India",
246 | "country_code": "IN",
247 | "ip": "59.99.140.76",
248 | "city": "Palakkad",
249 | "timezone": "Asia/Kolkata",
250 | "fulldata": {
251 | "status": "success",
252 | "country": "India",
253 | "countryCode": "IN",
254 | "region": "KL",
255 | "regionName": "Kerala",
256 | "city": "Palakkad",
257 | "zip": "678001",
258 | "lat": 10.7739,
259 | "lon": 76.6487,
260 | "timezone": "Asia/Kolkata",
261 | "isp": "BSNL Internet",
262 | "org": "",
263 | "as": "AS9829 National Internet Backbone",
264 | "query": "59.99.140.76"
265 | },
266 | "reverse_ip": ""
267 | }
268 | ```
269 |
270 | Now you see that the former one had `"country": "Poland"` whereas the latter `"country": "India"`. With that knowledge we are ready to devise our constraints in form of a hefty YAML dictionary:
271 |
272 | ```yaml
273 | ip_geolocation_requirements:
274 | organization:
275 | continent:
276 | continent_code:
277 | country:
278 | - Poland
279 | - PL
280 | - Polska
281 | country_code:
282 | city:
283 | timezone:
284 | ```
285 |
286 | Each of that dictionary's entries accept regular expression to be matched upon determined IP Geo metadata of inbound peer's IP address.
287 | We use three entries in `country` property to allow requests having one of specified values.
288 |
289 | Having that set in your configuration, you can verify whether another IP address would get passed through RedWarden's IP Geolocation discriminator or not with `ipLookupHelper` utility accepting second parameter:
290 |
291 | 
292 |
293 | The very last line tells you whether packet would be blocked or accepted.
294 |
295 | And that's all! Configure your IP Geolocation constraints wisely and safely, carefully inspect RedWarden logs for any IP Geo-related DROP entries and keep your C2 traffic nice and tidy!
296 |
297 |
298 | ### Repair tampered Beacon requests
299 |
300 | If you happen to use interim systems such as AWS Lambda or CloudFlare as your Domain Fronting / redirectors, you have surely came across a situation where some of your packets couldn't get accepted by the Teamserver as they deviated from the agreed malleable contract. Was it a tampered or removed HTTP header, reordered cookies or anything else - I bet that wasted plenty hours of your life.
301 |
302 | To combat C2 channels setup process issues and interim systems tamperings, RedWarden offers functionality to repair Beacon packets.
303 |
304 | It does so by checking what Malleable Profile expects packet to be and can restore configured HTTP headers to their agreed values according to the profile's requirements.
305 |
306 | Consider following simple profile:
307 |
308 | ```
309 | http-get {
310 | set uri "/api/abc";
311 | client {
312 |
313 | header "Accept-Encoding" "gzip, deflate";
314 |
315 | metadata {
316 | base64url;
317 | netbios;
318 | base64url;
319 | parameter "auth";
320 | }
321 | }
322 | ...
323 | ```
324 |
325 | You see this `Accept-Encoding`? Every Beacon request has to come up with that Header and that value. What happens if your Beacon hits CloudFlare systems and they emit a request that will be stripped from that Header or will have `Accept-Encoding: gzip` instead? Teamserver will drop the request on the spot.
326 |
327 | By setting this header in RedWarden configuration section dubbed `repair_these_headers` you can safe your connection.:
328 |
329 | ```yaml
330 | #
331 | # This option repairs Beacon requests's header value by restoring to what was expected in Malleable C2 profile.
332 | #
333 | # If RedWarden validates inbound request's HTTP headers, according to policy drop_malleable_without_expected_header_value:
334 | # "[IP: DROP, reason:6] HTTP request did not contain expected header value:"
335 | #
336 | # and detects some header is missing or was overwritten along the wire, the request will be dropped.
337 | #
338 | # We can relax this policy a bit however, since there are situations in which Cache systems (such as Cloudflare) could tamper with our
339 | # requests thus breaking Malleable contracts. What we can do is to specify list of headers, that should be overwritten back to their values
340 | # defined in provided Malleable profile.
341 | #
342 | # So for example, if our profile expects:
343 | # header "Accept-Encoding" "gzip, deflate";
344 | #
345 | # but we receive a request having following header set instead:
346 | # Accept-Encoding: gzip
347 | #
348 | # Because it was tampered along the wire by some of the interim systems (such as web-proxies or caches), we can
349 | # detect that and set that header's value back to what was expected in Malleable profile.
350 | #
351 | # In order to protect Accept-Encoding header, as an example, the following configuration could be used:
352 | # repair_these_headers:
353 | # - Accept-Encoding
354 | #
355 | # Default:
356 | #
357 | repair_these_headers:
358 | - Accept-Encoding
359 | ```
360 |
361 |
362 | ### Remove problematic Response Headers
363 |
364 | With Cobalt Strike 4.7+ I noticed that Teamserver removes Content-Encoding header automatically without any notice, thus violating our malleable `http-(get|post).server` contract.
365 |
366 | Since RedWarden followed the contract, Beacon was either dropping responses or decompressing them incorrectly.
367 |
368 | This option specifies which headers coming from Teamserver responses should be removed before reaching Beacon process:
369 |
370 | ```yaml
371 |
372 | remove_these_response_headers:
373 | - Content-Encoding
374 | ```
375 |
376 | RedWarden will now remove `Content-Encoding` header by default from Teamserver responses, to maintain operability with CS4.7+ versions.
377 |
378 |
379 | ### Example outputs
380 |
381 | Let's take a look at the output the proxy produces.
382 |
383 | Under `verbose: True` option, the verbosity will be set to INFO at most telling accepted requests from dropped ones.
384 |
385 | The request may be accepted if it confronted to all of the criterias configured in RedWarden's configuration file. Such a situation will be followed with `[ALLOW, ...]` entry log:
386 |
387 | ```
388 | [INFO] 2021-04-24/17:30:48: [REQUEST] GET /js/scripts.js
389 | [INFO] 2021-04-24/17:30:48: == Valid malleable http-get (variant: default) request inbound.
390 | [INFO] 2021-04-24/17:30:48: [ALLOW, 2021-04-24/19:30:48, 111.222.223.224] "/js/scripts.js" - UA: "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko"
391 | [INFO] 2021-04-24/17:30:48: Connected peer sent 2 valid http-get and 0 valid http-post requests so far, out of 15/5 required to consider him temporarily trusted
392 | [INFO] 2021-04-24/17:30:48: Plugin redirected request from [attacker.com] to [127.0.0.1:5555]
393 | ```
394 |
395 | Should the request fail any of the checks RedWarden carries on each request, the corresponding `[DROP, ...]` line will be emitted containing information about the drop **reason**.:
396 |
397 | ```
398 | [INFO] 2021-04-24/16:48:28: [REQUEST] GET /
399 | [ERROR] 2021-04-24/16:48:29: [DROP, 2021-04-24/18:48:28, reason:1, 128.14.211.186] inbound User-Agent differs from the one defined in C2 profile.
400 | [INFO] 2021-04-24/16:48:29: [DROP, 2021-04-24/18:48:28, 128.14.211.186] "/" - UA: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
401 | [ERROR] 2021-04-24/16:48:29: [REDIRECTING invalid request from 128.14.211.186 (zl-dal-us-gp3-wk107.internet-census.org)] GET /
402 | ```
403 |
404 |
405 | ### Drop Policies Fine-Tuning
406 |
407 | There are plenty of reasons dictating whether request can be dropped. Each of these checks can be independently turned on and off according to requirements or in a process of fine-tuning or erroneus decision fixing:
408 |
409 | Excerpt from `example-config.yaml`:
410 |
411 | ```yaml
412 | #
413 | # Fine-grained requests dropping policy - lets you decide which checks
414 | # you want to have enforced and which to skip by setting them to False
415 | #
416 | # Default: all checks enabled
417 | #
418 | policy:
419 | # [IP: ALLOW, reason:0] Request conforms ProxyPass entry (url="..." host="..."). Passing request to specified host
420 | allow_proxy_pass: True
421 | # [IP: ALLOW, reason:2] Peer's IP was added dynamically to a whitelist based on a number of allowed requests
422 | allow_dynamic_peer_whitelisting: True
423 | # [IP: DROP, reason:1] inbound User-Agent differs from the one defined in C2 profile.
424 | drop_invalid_useragent: True
425 | # [IP: DROP, reason:2] HTTP header name contained banned word
426 | drop_http_banned_header_names: True
427 | # [IP: DROP, reason:3] HTTP header value contained banned word:
428 | drop_http_banned_header_value: True
429 | # [IP: DROP, reason:4b] peer's reverse-IP lookup contained banned word
430 | drop_dangerous_ip_reverse_lookup: True
431 | # [IP: DROP, reason:4e] Peer's IP geolocation metadata contained banned keyword! Peer banned in generic fashion.
432 | drop_ipgeo_metadata_containing_banned_keywords: True
433 | # [IP: DROP, reason:5] HTTP request did not contain expected header
434 | drop_malleable_without_expected_header: True
435 | # [IP: DROP, reason:6] HTTP request did not contain expected header value:
436 | drop_malleable_without_expected_header_value: True
437 | # [IP: DROP, reason:7] HTTP request did not contain expected (metadata|id|output) section header:
438 | drop_malleable_without_expected_request_section: True
439 | # [IP: DROP, reason:8] HTTP request was expected to contain (metadata|id|output) section with parameter in URI:
440 | drop_malleable_without_request_section_in_uri: True
441 | # [IP: DROP, reason:9] Did not found append pattern:
442 | drop_malleable_without_prepend_pattern: True
443 | # [IP: DROP, reason:10] Did not found append pattern:
444 | drop_malleable_without_apppend_pattern: True
445 | # [IP: DROP, reason:11] Requested URI does not aligns any of Malleable defined variants:
446 | drop_malleable_unknown_uris: True
447 | # [IP: DROP, reason:12] HTTP request was expected to contain <> section with URI-append containing prepend/append fragments
448 | drop_malleable_with_invalid_uri_append: True
449 | ```
450 |
451 |
452 | By default all of these checks are enforced.
453 |
454 | Turning `debug: True` will swamp your console buffer with plenty of log lines describing each step RedWarden takes in its complex decisioning process.
455 | If you want to see your requests and responses full bodies - set `debug` and `trace` to true and get buried in logging burden!
456 |
457 |
458 | ## FAQ
459 |
460 | **- Can this program run without Malleable Profile?**
461 |
462 | Yes it can. However request inspection logic will be turned off, the rest should work fine: IP Geolocation enforcement, reverse-lookup logic, banned IPs list, etc.
463 |
464 | **- Can this program be easily adapted to other C2 frameworks as well? Like Mythic, Covenant, etc?**
465 |
466 | Easily no. With some efforts - yes. As I've described below, the tool is written badly that will make other C2s adaptation a pain. However that's totally doable given some time and effort.
467 |
468 | **- My packets are getting dropped. Why?**
469 |
470 | Try to enable `debug: True` and `trace: True` to collect as many log as possible. Then you would need to go through logs and inspect what's going on. Do the packets look exactly how you expected them in your Malleable profile? Or maybe there was a subtle tamperation along the network that causes RedWarden to drop the packet (and it could make Teamserver drop it as well?).
471 |
472 |
473 | ## Known Issues
474 |
475 | - It _may_ add a slight overhead to the interactive sleep throughput
476 | - ProxyPass processing logic is far from perfect and is _really_ buggy (and oh boy its ugly!).
477 | - Weird forms of configuration files can derail RedWarden parser and make it complain. Easiest approach to overcome this would be to copy `example-config.yaml` and work on it instead.
478 |
479 |
480 | ## Oh my god why is this code such an engineerical piece of crap?
481 |
482 | The code is _ONE FUCKING BIG HELL OF A MESS_ - I admit that - and there's an honest reason for that too: the project was being developed 90% during the actual Red Team engagements. As we all know, these sorts of engagements entail so many things to do, leaving close to no time for a proper complex tool development. Not to mention criticality of this program in project's setup. The tool initialy started as a simple proxy script written in Python2, to then evolve as a proxy with plugins, received `malleable_redirector` plugin - and since then I've been trying really hard to keep `proxy2` maintain backwards compatibility (poor me, I was like Microsoft!) with other plugins I've made for it and stick to its original purpose.
483 |
484 | Time has come though to let it go, rebrand it and start fixing all the bad code smells introduced.
485 |
486 | With all that said, please do express some level of compassion for me when raising issues, submitting pull requests and try to help rather than judge! :-)
487 | Thanks!
488 |
489 |
490 | ## TODO
491 |
492 | - Research possibility to use Threat Intelligence feeds to nefarious purposes - like for instance detecting Security Vendors based on IPs
493 | - Add support for MaxMind GeoIP database/API
494 | - Implement support for JA3 signatures in both detection & blocking and impersonation to fake nginx/Apache2/custom setups.
495 | - Add some unique beacons tracking logic to offer flexilibity of refusing staging and communication processes at the proxy's own discretion
496 | - Introduce day of time constraint when offering redirection capabilities (_proxy only during office hours_)
497 | - Add Proxy authentication and authorization logic on CONNECT/relay.
498 | - Add Mobile users targeted redirection
499 | - Add configuration options to define custom HTTP headers to be injected, or ones to be removed
500 | - Add configuration options to require specific HTTP headers to be present in requests passing ProxyPass criteria.
501 | - Interactive interface allowing to type simple characters controlling output logging verbosity, similarly to Nmap's
502 | - Rewrite Malleable profile parser logic to [pyMalleableC2](https://github.com/Porchetta-Industries/pyMalleableC2). When I first started coding my own parser logic, there was no such toolkit on Github.
503 | - Refactor all the codebase
504 |
505 |
506 | ---
507 |
508 | ### ☕ Show Support ☕
509 |
510 | This and other projects are outcome of sleepless nights and **plenty of hard work**. If you like what I do and appreciate that I always give back to the community,
511 | [Consider buying me a coffee](https://github.com/sponsors/mgeeky) _(or better a beer)_ just to say thank you! 💪
512 |
513 | ---
514 |
515 | ## Author
516 |
517 | ```
518 | Mariusz Banach / mgeeky, '19-'21
519 |
520 | (https://github.com/mgeeky)
521 | ```
522 |
--------------------------------------------------------------------------------
/RedWarden.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # RedWarden
5 | #
6 | # TODO:
7 | # - implement dynamic plugins directory scanning method in the PluginsLoader
8 | # - perform severe code refactoring as for now it's kinda ugly
9 | # - add more advanced logging capabilities, redesign packets contents dumping
10 | #
11 | # Changelog:
12 | # 0.1 original fork from inaz2 repository.
13 | # 0.2 added plugins loading functionality,
14 | # ssl interception as a just-in-time setup,
15 | # more elastic logging facilities,
16 | # separation of program options in form of a globally accessible dictonary,
17 | # program's help text with input parameters handling,
18 | # 0.3 added python3 support, enhanced https capabilities and added more versatile
19 | # plugins support.
20 | # 0.4 improved reverse-proxy's capabilities, added logic to avoid inifinite loops
21 | # 0.5 fixed plenty of bugs, improved a bit server's resilience against slow/misbehaving peers
22 | # by disconnecting them/timeouting connections, improved logging facility and output format,
23 | # added options to protected HTTP headers, apply fine-grained DROP policy, and plenty more.
24 | # 0.6 rewritten RedWarden from BaseHTTPServer (SimpleHTTPServer) to Tornado, improved
25 | # support for proxy_pass allowing to fetch responses cross-scheme
26 | # 0.8 fixed two issues with config param processing logic and added support for multi-line
27 | # prepend/append instructions in Malleable profiles.
28 | # 0.9 added support for RedELK logs generation.
29 | #
30 | # Author:
31 | # Mariusz Banach / mgeeky, '16-'22
32 | #
33 | #
34 | # (originally based on: @inaz2 implementation: https://github.com/futuresimple/proxy2)
35 | # (now obsoleted)
36 | #
37 |
38 | VERSION = '0.9.3'
39 |
40 | import sys, os
41 |
42 | import logging
43 | import tornado.web
44 | import tornado.httpserver
45 | import tornado.netutil
46 | import asyncio
47 |
48 | from lib.proxylogger import ProxyLogger
49 | from lib.proxyhandler import *
50 |
51 |
52 | normpath = lambda p: os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), p))
53 |
54 |
55 | # Global options dictonary, that will get modified after parsing
56 | # program arguments. Below state represents default values.
57 | options = {
58 | 'bind': 'http://0.0.0.0',
59 | 'port': [8080, ],
60 | 'debug': False, # Print's out debuging informations
61 | 'verbose': False,
62 | 'tee': False,
63 | 'log': None,
64 | 'proxy_self_url': 'http://RedWarden.test/',
65 | 'timeout': 90,
66 | 'access_log' : '',
67 | 'access_log_format' : 'apache2',
68 | 'redelk_frontend_name' : 'http-redwarden',
69 | 'redelk_backend_name_c2' : 'c2',
70 | 'redelk_backend_name_decoy' : 'decoy',
71 | 'no_ssl': False,
72 | 'drop_invalid_http_requests': True,
73 | 'no_proxy': False,
74 | 'cakey': normpath('ca-cert/ca.key'),
75 | 'cacert': normpath('ca-cert/ca.crt'),
76 | 'certkey': normpath('ca-cert/cert.key'),
77 | 'certdir': normpath('certs/'),
78 | 'cacn': 'RedWarden CA',
79 | 'plugins': set(),
80 | 'plugin_class_name': 'ProxyPlugin',
81 | }
82 |
83 | logger = None
84 |
85 |
86 | def create_ssl_context():
87 | ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
88 | ssl_ctx.load_cert_chain(options['cacert'], options['cakey'])
89 |
90 | return ssl_ctx
91 |
92 | async def server_loop(servers):
93 | # Schedule calls *concurrently*:
94 | L = await asyncio.gather(*servers)
95 |
96 | async def serve_proxy(bind, port, _ssl, foosock):
97 | ProxyRequestHandler.protocol_version = "HTTP/1.1"
98 | scheme = None
99 | certpath = ''
100 |
101 | if not bind or len(bind) == 0:
102 | if options['bind'].startswith('http') and '://' in options['bind']:
103 | colon = options['bind'].find(':')
104 | scheme = options['bind'][:colon].lower()
105 | if scheme == 'https' and not _ssl:
106 | logger.fatal('You can\'t specify different schemes in bind address (-B) and on the port at the same time! Pick one place for that.\nSTOPPING THIS SERVER.')
107 |
108 | bind = options['bind'][colon + 3:].replace('/', '').lower()
109 | else:
110 | bind = options['bind']
111 |
112 | if _ssl:
113 | scheme = 'https'
114 |
115 | if scheme == None: scheme = 'http'
116 |
117 | server_address = (bind, port)
118 | app = None
119 |
120 | logging.getLogger('tornado.access').disabled = True
121 |
122 | try:
123 | params = dict(server_bind=bind, server_port=port)
124 | app = tornado.web.Application([
125 | (r'/.*', ProxyRequestHandler, params),
126 | (scheme + r'://.*', ProxyRequestHandler, params),
127 | ],
128 | transforms=[RemoveXProxy2HeadersTransform, ])
129 |
130 | except OSError as e:
131 | if 'Address already in use' in str(e):
132 | logger.err("Could not bind to specified port as it is already in use!")
133 | return
134 | else:
135 | raise
136 |
137 | logger.info("Serving proxy on: {}://{}:{} ...".format(scheme, bind, port),
138 | color=ProxyLogger.colors_map['yellow'])
139 |
140 | server = None
141 | if scheme == 'https':
142 | ssl_ctx = create_ssl_context()
143 | server = tornado.httpserver.HTTPServer(
144 | app,
145 | ssl_options=ssl_ctx,
146 | idle_connection_timeout = options['timeout'],
147 | body_timeout = options['timeout'],
148 | )
149 | else:
150 | server = tornado.httpserver.HTTPServer(
151 | app,
152 | idle_connection_timeout = options['timeout'],
153 | body_timeout = options['timeout'],
154 | )
155 |
156 | server.add_sockets(foosock)
157 | await asyncio.Event().wait()
158 |
159 | def main():
160 | global options
161 | global logger
162 |
163 | try:
164 | (options, logger) = init(options, VERSION)
165 |
166 | logger.info(r'''
167 |
168 | ____ ___ __ __
169 | / __ \___ ____/ / | / /___ __________/ /__ ____
170 | / /_/ / _ \/ __ /| | /| / / __ `/ ___/ __ / _ \/ __ \
171 | / _, _/ __/ /_/ / | |/ |/ / /_/ / / / /_/ / __/ / / /
172 | /_/ |_|\___/\__,_/ |__/|__/\__,_/_/ \__,_/\___/_/ /_/
173 |
174 | :: RedWarden - Keeps your malleable C2 packets slipping through AVs,
175 | EDRs, Blue Teams and club bouncers like nothing else!
176 |
177 | by Mariusz Banach / mgeeky, '19-'22
178 |
179 |
180 | v{}
181 |
182 | '''.format(VERSION))
183 |
184 | threads = []
185 | if len(options['port']) == 0:
186 | options['port'].append('8080/http')
187 |
188 | servers = []
189 | portsBound = set()
190 |
191 | for port in options['port']:
192 | p = 0
193 | scheme = 'http'
194 | bind = ''
195 |
196 | if port in portsBound:
197 | logger.err(f'TCP Port {port} already bound. Possibly a duplicate configuration line. Skipping it.')
198 | continue
199 |
200 | portsBound.add(port)
201 |
202 | try:
203 | _port = port
204 |
205 | if type(port) == int:
206 | bind = options['bind']
207 |
208 | if ':' in port:
209 | bind, port = _port.split(':')
210 |
211 | if '/http' in port:
212 | _port, scheme = port.split('/')
213 |
214 | p = int(_port)
215 | if p < 0 or p > 65535: raise Exception()
216 | if not bind:
217 | bind = '0.0.0.0'
218 |
219 | foosock = tornado.netutil.bind_sockets(p, address = bind)
220 | servers.append((bind, p, scheme.lower() == 'https', foosock, options))
221 |
222 | except OSError as e:
223 | logger.err('Could not bind to specified TCP port: {}\nException: {}\n'.format(port, e))
224 | raise
225 | return False
226 |
227 | except Exception as e:
228 | logger.err('Specified port ({}) is not a valid number in range of 1-65535!\n'.format(port))
229 | raise
230 | return False
231 |
232 | # https://www.tornadoweb.org/en/stable/tcpserver.html
233 | # advanced multi-process:
234 | tornado.process.fork_processes(0)
235 |
236 | statements = []
237 | for srv in servers:
238 | statements.append(serve_proxy(srv[0], srv[1], srv[2], srv[3]))
239 | asyncio.run(server_loop(statements))
240 |
241 | except KeyboardInterrupt:
242 | logger.info('\nProxy serving interrupted by user.', noprefix=True)
243 |
244 | except Exception as e:
245 | print(ProxyLogger.with_color(ProxyLogger.colors_map['red'], 'Fatal error has occured.'))
246 | print(ProxyLogger.with_color(ProxyLogger.colors_map['red'], '\t%s\nTraceback:' % e))
247 | print(ProxyLogger.with_color(ProxyLogger.colors_map['red'], '-'*30))
248 | traceback.print_exc()
249 | print(ProxyLogger.with_color(ProxyLogger.colors_map['red'], '-'*30))
250 |
251 | finally:
252 | cleanup()
253 |
254 | if __name__ == '__main__':
255 | main()
256 |
--------------------------------------------------------------------------------
/ca-cert/ca.crt:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIC+zCCAeOgAwIBAgIJANTTZNmoSV/qMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV
3 | BAMMCXByb3h5MiBDQTAeFw0xOTAxMTMxMzI0MjNaFw0yOTAxMTAxMzI0MjNaMBQx
4 | EjAQBgNVBAMMCXByb3h5MiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
5 | ggEBAKwJPhLJsfao0pfKFxwNNQTa9Xblm30jJUuACl+JARBJAy44Q6qCZPKoE1AY
6 | WaNsgH64U4UcgVj+d+vzHLjhK0jeBkSYtnj1nKODIfHagOrrknSVVxSdYf3WcVoR
7 | 8aGiDJOzBek/KUenGz+DxU08U7Hyuw2K/fZae7x6btEn1gbsxFn9b9lGvib7NtO2
8 | cfI+AVB+kT5tlMTHcw/pnuVWHQM78PZGTe44FaASMeH4VhnFj87RstHbmVnqvxb4
9 | IEuAlLrMrbUVYalejsM5QPqwksmZgS2G8UElQOWY4eKg9NxyBjjrkPwCE/DhXSIF
10 | WzHHbq1EBeEqUR85GtLGUpbWrnECAwEAAaNQME4wHQYDVR0OBBYEFHJxb0wgqh5m
11 | OCYpVd+VrCXbVkioMB8GA1UdIwQYMBaAFHJxb0wgqh5mOCYpVd+VrCXbVkioMAwG
12 | A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAAxhjxq7Ij9pc8EPicgkLA32
13 | w8ybuDcp49x1k5OqC8jKV04LdOHUGFD46VIWpTb19TxKDy6kRX0tZ0QWH9r/7Tgf
14 | xUWy0jUd+05z/3qN7cDGVGm+BCfv4UsfD5zO6lkfOk0mpsAYo/IxfThH/BbjCEp/
15 | 7hk6aVqhk96xQy7qlcEt3lGwDwqfiS84UixcPgDsckyt50ln/zzBL6Whzjnnahx2
16 | PNCy5USV5udjyzugaOiPLeGnEbLq0LaZEsQTC6+wvPjURg9fgd8e4foV2SCKhhI5
17 | rZAkmSX6Q0ymtbMlmSLkWvLquTBZsvO+o64MWDifZQ52RtTNCuBGvuW1B8rmWZE=
18 | -----END CERTIFICATE-----
19 |
--------------------------------------------------------------------------------
/ca-cert/ca.key:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEowIBAAKCAQEArAk+Esmx9qjSl8oXHA01BNr1duWbfSMlS4AKX4kBEEkDLjhD
3 | qoJk8qgTUBhZo2yAfrhThRyBWP536/McuOErSN4GRJi2ePWco4Mh8dqA6uuSdJVX
4 | FJ1h/dZxWhHxoaIMk7MF6T8pR6cbP4PFTTxTsfK7DYr99lp7vHpu0SfWBuzEWf1v
5 | 2Ua+Jvs207Zx8j4BUH6RPm2UxMdzD+me5VYdAzvw9kZN7jgVoBIx4fhWGcWPztGy
6 | 0duZWeq/FvggS4CUusyttRVhqV6OwzlA+rCSyZmBLYbxQSVA5Zjh4qD03HIGOOuQ
7 | /AIT8OFdIgVbMcdurUQF4SpRHzka0sZSltaucQIDAQABAoIBAFNCAdWL4WHTYF/v
8 | gPGlfqRD54nMI00Thkgcxmhn4Kjl/PEQb8cEZiB9sSMRNch+iU1KnbkNC5hrRtRd
9 | Cuh6qL0SHoxyL9UoYM9Ndk8bBUssCOv9HnCuni7/6knB52PnDhkpCdJRLAQuXmSF
10 | vCXd7U9wfpBWVQQ11C5qPllg4xbkEfggDEesVranAQVprgex6KlJKBQcRfjwZmv3
11 | /MRyDwUFOpYjx7riQm+B/TNSQgy6wiqXh14ejp0FEHWlVd9I4K0MWUMXD2zkjKcE
12 | h2qiIrIBuTmIOEL2IeelVhCLgBc7yd9Dh3cXGpGTP8sqGZl1IHPBH5wOK/PwVXic
13 | FwGU+gECgYEA2gAOnM4hbuTbNXnM1E2D4k9Z3KH/XFRoGmUkzoxy/ZQK9ZvTfwsQ
14 | BVsazJ3jm1r4jm5o8t5usWDwIeyEpULs40Si9IzW1vOvydqueBR8K3al+u8BIs4H
15 | IH4aofsijhIxK+p0Z8JnzfZOGKBmkUbcT/1HmOKrjZHO8XXa38rroNECgYEAygYa
16 | eJ0xQItTn9h3Vm04e9kWKn/fBHD/vvoXTjV2m32nOxLqu9mC42LmU7M6b5vis7wz
17 | CwzDGDHFlMH+MPD4XBt5Bad6nOtLArTTy4NXizM+Vg5XTQHp0zo+OMEFX8UlJqMb
18 | V9tAbO0CPPCqzQVIIpxwybVpG7koxaIo2bvIm6ECgYEAk3fIasByE18S/pi3O8J3
19 | /aZqBns7kAy1I23aOTL/MpRr2Xug1Wb5XnYjqdkAt/4Q9+Cuc+SOAsWti3VAwb6F
20 | GrQ6e62uQ1gzSRv6O9a3rHslipsVLKMsZQmJIJwO4wZhZvDB79Ktf8EnUTdoSswh
21 | iqauQTjMjgbdc6+i8RKG1JECgYAKIeo7+G5a9WH5V2sM26eElqvE7+rolx5MntCC
22 | bK4JOHElxlodl9g3vWMd+ZRJusDREPRibn5ufTiSsHQmUj+ypvIX9YFx019MwHMK
23 | 9whyA9zxhgCc7SakIHy0bgHt/r5RRMb/ThDaJb0B/3Qhmk025y/E/iNKb6v61ZpE
24 | 6WUzYQKBgClLRIUjVRXxRoWaGgZi2hHF1s3VzmO4kOLDs7z939Ygx5tJzNaNBw4L
25 | hF5+mRi3C1nvcS4OP4xv4IstKB+RR03Vp1Q5bvouYwLiPV+rBDzjRyQQXfJPJbnt
26 | Ok+nI4uku5efUQbcCRjVdS9UgSonfwEz+q7eqD3BJidFFIHXzIec
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/ca-cert/cert.key:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEowIBAAKCAQEA4R1UwUsGO4SSXavpoNu1gqQsfLW1flR/PMFkNVRxwwHFnekV
3 | 62Ig4EreYXLQE49cZs3HzFR5sM+TaWTUWdtxVwqr9e1eTyF15vG9o3zAcdCRwefF
4 | AxrOoBcICw6Y66JYczpg+Fhc+gzfisG5s86dPzgFKIDXvBED31Q5FYhWWMv0uaTh
5 | 1UlhobH/yUBEJrMRW2U7Q5vkk1vsG/LGoN9Obssyu96qjFH0xg5s+pgLWIhaggP/
6 | geM7+FI4XiCkDh1uIdZf5TJh5565bZYWI20r0KZRQwdoi4+ynkY4O+/iGoW30eSx
7 | KqGFGwrtR4G6OEg8ZNqHEoAqzFTgnj0HGSD8nQIDAQABAoIBAH6yeGI1rHNRAOOx
8 | ftMm9PhrGBK0XkqUmewC2Dhfp4tecu+WIN0SpHg4CwMDkHKBzDqb9KhenwLRQSEf
9 | O5i7NgYMHo5SIzMcHPR2+AmMi+9CuNZOcIZ3zvUxITi/5XcxLuDjaXI8oU+mcSXy
10 | NGcrkTrkd5q9MS5K0UgfaeVhj193lKfJe0QY7qdt9xlv2S2v5PE1sRcoOuTKkyVu
11 | bg5wO7IA5z5c2sbMSAeHlTs+RB8pL2BVzPhzCxcnwPCc5WNWaBfkYfOjWMD4sE/8
12 | cYnCux+Kdm6za+dUiwtystMOK/99ZMIzETSWhnPHot7t2llCj592FlEafP8aRTen
13 | QoRzXUECgYEA9GkHrn684GJR4XIFb/PB818gKOjTqFCseRxEBTPEpqxhz/NMUF0C
14 | AUYORY6cUkFgJ0YtVq4Hk3QwX34iPdpbEhoj9jmdwGTSLh6YcdRpsIUo7vkAKYIN
15 | flSYD62y68DNJhhujmKGZqMAylRu9wQNMX+eHjK4/vH3qgDGoaiXEC0CgYEA68oQ
16 | lDIPshzwe+cXuDmgA1xpervULfvXK4oXxMzYn1+ogEA+8ot9Eo9c0ziSVghmQFc5
17 | dlHj669RKOrHyNT14fj3RT1NElxxWeFxm1qfiEyqZKlkQ/PmVsvGTzdCisZ0deHN
18 | AdZpgvcQV/+qTmNJrIaDoKkU0+fqwy5uoO989DECgYA9znWn1drzr0lfhpMDbZQF
19 | dG/QiJhFvyjuc4xr+Fxpfbw6dx88T1jbc5jWVCsJzgh/xgpfGiFGU6KL83y7QYW4
20 | PS4M7SMMbTKNgSUx2/JiNjpUvFkjJgU9hizyAg31+kqmsJT8osO0HtJrWBC7nKWt
21 | d8VHg7Iunofv0MRqSxTwfQKBgCAWvNDeS0KLK7NBDPpWZU9vyS8Z1tN3PZ5ASeHP
22 | mv99jjn+BFMP5rKa7iAUx92LgRbqh/hxRppxnpL5+Lx9NwVM06IJqK6CBC8ePk7N
23 | M37iKCJQ50NUMxnG27M2Kwkl3v2YAEVqv6tCImhHdA789i7Tk6BOwnXgTxPHAulG
24 | DnRRAoGBAPMXCtGbPGjXOwa+lOKhKNMVeneGGXsq2YfJUU4C3LiPxCW/PgPXHfDx
25 | B3eNm4tLSKwzklU0OqHo/QEWLaQ7wQOoLDjJT3s2QZLW2F7DmtJCn8qigA66ig/D
26 | j9RNWkS8PXTiCG726+AjJSok4djSoKK04EXaChNtvogZR0qb0PL7
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/data/banned_words.txt:
--------------------------------------------------------------------------------
1 | #
2 | # Words from this file will be matched against inbound request
3 | # by several checks to determine whether request originates from
4 | # Security-vendor, Blue Team or other defensive clients.
5 | #
6 | # These words will be checked against:
7 | # - reverse-ip lookup hostname
8 | # - IP geolocation data, such as organization name
9 | # - HTTP header names and values
10 | # - User-agent string
11 | #
12 |
13 | # Dodgy User-Agents words
14 | curl
15 | wget
16 | python-urllib
17 | lynx
18 | slackbot-linkexpanding
19 |
20 | # Generic bad words
21 | security
22 | scanning
23 | scanner
24 | defender
25 | appengine-google
26 |
27 | # Bots
28 | googlebot
29 | adsbot-google
30 | msnbot
31 | altavista
32 | slurp
33 | mj12bot
34 | bingbot
35 | duckduckbot
36 | baiduspider
37 | yandexbot
38 | simplepie
39 | sogou
40 | exabot
41 | facebookexternalhit
42 | ia_archiver
43 | virustotalcloud
44 | virustotal
45 |
46 | # EDRs
47 | bitdefender
48 | carbonblack
49 | carbon
50 | code42
51 | countertack
52 | countercept
53 |
54 | crowdstrike
55 | cylance
56 | druva
57 | forcepoint
58 | ivanti
59 | sentinelone
60 |
61 | trend micro
62 | gravityzone
63 | trusteer
64 | cybereason
65 | encase
66 | ensilo
67 |
68 | huntress
69 | bluvector
70 | cynet360
71 | endgame
72 | falcon
73 | fortil
74 | gdata
75 |
76 | lightcyber
77 | secureworks
78 | apexone
79 | emsisoft
80 | netwitness
81 | fidelis
82 |
83 |
84 | # AVs
85 | acronis
86 | adaware
87 | aegislab
88 | ahnlab
89 | antiy
90 | secureage
91 |
92 | arcabit
93 | avast
94 | avg
95 | avira
96 | bitdefender
97 | clamav
98 |
99 | comodo
100 | crowdstrike
101 | cybereason
102 | cylance
103 | cyren
104 |
105 | drweb
106 | emsisoft
107 | endgame
108 | escan
109 | eset
110 | f-secure
111 |
112 | fireeye
113 | fortinet
114 | gdata
115 | ikarussecurity
116 | k7antivirus
117 |
118 | k7computing
119 | kaspersky
120 | malwarebytes
121 | mcafee
122 | nanoav
123 | paloalto
124 | paloaltonetworks
125 | panda
126 | 360totalsecurity
127 | sentinelone
128 |
129 | sophos
130 | symantec
131 | tencent
132 | trapmine
133 | trendmicro
134 | virusblokada
135 |
136 | anti-virus
137 | antivirus
138 | yandex
139 | zillya
140 | zonealarm
141 |
142 | checkpoint
143 | baidu
144 | kingsoft
145 | superantispyware
146 | tachyon
147 |
148 | totaldefense
149 | webroot
150 | egambit
151 | trustlook
152 | proofpoint
153 |
154 | # Other proxies
155 | sandboxes etc
156 | zscaler
157 | barracuda
158 | sonicwall
159 | f5 network
160 | palo alto network
161 | juniper
162 | check point
163 | microsoft corporation
164 | fortigate
--------------------------------------------------------------------------------
/data/banned_words_override.txt:
--------------------------------------------------------------------------------
1 | #
2 | # Words from this file OVERRIDE words from banned_words.txt and from
3 | # banned_ips.txt (based on reverse IP lookup result) wordlists.
4 | #
5 | # Consider situation where the request originates from Azure Functions serverless
6 | # redirector. Such request will egress from IP with geolocation's organization
7 | # field containing phrase:
8 | # "Microsoft Azure Cloud (westeurope)"
9 | #
10 | # Should there be "Microsoft" keyword specified in banned_words.txt wordlist,
11 | # the request would be banned. If we don't want that, this wordlist can override
12 | # blocking behaviour for specific phrases.
13 | #
14 | # The same goes if your beacon operates over Amazon AWS Lambda service. Typically AWS CIDRs
15 | # are going to be blacklisted, but you can easily override that here.
16 | #
17 |
18 | Microsoft Azure Cloud
19 | amazonaws.com
20 | azurewebsites.com
21 |
--------------------------------------------------------------------------------
/example-config.yaml:
--------------------------------------------------------------------------------
1 | #
2 | # This is a sample config file for RedWarden.
3 | #
4 |
5 |
6 | #
7 | # ====================================================
8 | # General proxy related settings
9 | # ====================================================
10 | #
11 |
12 | # Print verbose output. Implied if debug=True. Default: False
13 | verbose: True
14 |
15 | # Print debugging output that includes HTTP request/response trace. Default: False
16 | debug: False
17 |
18 | # Redirect RedWarden's output to file. Default: stdout.
19 | # Creates a file in the same directory that this config file is situated.
20 | output: redwarden_redirector.log
21 |
22 | # Write web server access attempts in Apache2 access.log format into this file.
23 | access_log: redwarden_access.log
24 |
25 | # Switches between one of the following pre-defined log formats:
26 | # - 'apache2' combined access_log
27 | # - 'redelk' log format
28 | access_log_format: apache2
29 |
30 | #
31 | # ===================================
32 | # RedELK Integration
33 | #
34 | #
35 | # If RedWarden is to be integrated with RedElk, following three variables will have to be set
36 | # according to this redirector server role.
37 | #
38 |
39 | # Label marking packets coming from this specific Proxy server.
40 | # Can be anything, but nice candidates are:
41 | # - http, http-proxy, http-trackingpixel1, phishingwebsite, etc
42 | redelk_frontend_name: http-redwarden
43 |
44 | # Label for packets that are passed to the C2 server.
45 | # This value MUST start with "c2" and cannot contain spaces.
46 | redelk_backend_name_c2: c2
47 |
48 | # Label for packets that are NOT passed to the C2 (they either dropped, redirected, proxied away).
49 | # This value MUST start wtih "decoy" and cannot contain spaces.
50 | redelk_backend_name_decoy: decoy
51 |
52 | # ===================================
53 |
54 | # If 'output' is specified, tee program's output to file and stdout at the same time.
55 | # Default: False
56 | tee: True
57 |
58 |
59 | #
60 | # Ports on which RedWarden should bind & listen
61 | #
62 | port:
63 | - 80/http
64 | - 443/https
65 |
66 | #
67 | # SSL certificate CAcert (pem, crt, cert) and private key CAkey
68 | #
69 | ssl_cacert: /etc/letsencrypt/live/attacker.com/fullchain.pem
70 | ssl_cakey: /etc/letsencrypt/live/attacker.com/privkey.pem
71 |
72 |
73 | #
74 | # Drop invalid HTTP requests
75 | #
76 | # If a stream that doesn't resemble valid HTTP protocol reaches RedWarden listener,
77 | # should we drop it or process it? By default we drop it.
78 | #
79 | # Default: True
80 | #
81 | drop_invalid_http_requests: True
82 |
83 |
84 | #
85 | # Path to the Malleable C2 profile file.
86 | # If not given, most of the request-validation logic won't be used.
87 | #
88 | profile: malleable.profile
89 |
90 |
91 | #
92 | # (Required) Address where to redirect legitimate inbound beacon requests.
93 | # A.k.a. TeamServer's Listener bind address, in a form of:
94 | # [inport:][http(s)://]host:port
95 | #
96 | # If RedWarden was configured to listen on more than one port, specifying "inport" will
97 | # help the plugin decide to which teamserver's listener redirect inbound request.
98 | #
99 | # If 'inport' values are not specified in the below option (teamserver_url) the script
100 | # will pick destination teamserver at random.
101 | #
102 | # Having RedWarden listening on only one port does not mandate to include the "inport" part.
103 | # This field can be either string or list of strings.
104 | #
105 | teamserver_url:
106 | - 1.2.3.4:5555
107 |
108 |
109 | #
110 | # Report only instead of actually dropping/blocking/proxying bad/invalid requests.
111 | # If this is true, will notify that the request would be block if that option wouldn't be
112 | # set.
113 | #
114 | # Default: False
115 | #
116 | report_only: False
117 |
118 |
119 | #
120 | # Log full bodies of dropped requests.
121 | #
122 | # Default: False
123 | #
124 | log_dropped: False
125 |
126 |
127 | #
128 | # Throttle down number of log entries emitted for single Peer to lower I/O overhead.
129 | #
130 | # When you operate your Beacon in interactive mode, the RedWarden can go crazy with logging
131 | # all of the allowed requests. We can throttle that down to minimize I/O and CPU impact.
132 | #
133 | # This option specifies number of seconds to wait before adding next log entry for specific IP,
134 | # regardless of whether it was allowed or dropped.
135 | #
136 | # Default:
137 | # log_request_delay: 60
138 | # requests_threshold: 3
139 | #
140 | throttle_down_peer_logging:
141 | log_request_delay: 60
142 | requests_threshold: 3
143 |
144 |
145 | #
146 | # What to do with the request originating not conforming to Beacon, whitelisting or
147 | # ProxyPass inclusive statements:
148 | # - 'redirect' it to another host with (HTTP 301),
149 | # - 'reset' a TCP connection with connecting client
150 | # - 'proxy' the request, acting as a reverse-proxy against specified action_url
151 | # (may be dangerous if client fetches something it shouldn't supposed to see!)
152 | #
153 | # Valid values: 'reset', 'redirect', 'proxy'.
154 | #
155 | # Default: redirect
156 | #
157 | drop_action: redirect
158 |
159 |
160 | #
161 | # If someone who is not a beacon hits the proxy, or the inbound proxy does not meet
162 | # malleable profile's requirements - where we should proxy/redirect his requests.
163 | # The protocol HTTP/HTTPS used for proxying will be the same as originating
164 | # requests' protocol. Redirection in turn respects protocol given in action_url.
165 | #
166 | # This value may be a comma-separated list of hosts, or a YAML array to specify that
167 | # target action_url should be picked at random:
168 | # action_url: https://google.com, https://gmail.com, https://calendar.google.com
169 | #
170 | # Default: https://google.com
171 | #
172 | action_url:
173 | - https://google.com
174 |
175 |
176 | #
177 | # ProxyPass alike functionality known from mod_proxy.
178 | #
179 | # If inbound request matches given conditions, proxy that request to specified host,
180 | # fetch response from target host and return to the client. Useful when you want to
181 | # pass some requests targeting for instance attacker-hosted files onto another host, but
182 | # through the one protected with malleable_redirector.
183 | #
184 | # Protocol used for ProxyPass will match the one from originating request unless specified explicitely.
185 | # If host part contains http:// or https:// schema - that schema will be used.
186 | #
187 | # Syntax:
188 | # proxy_pass:
189 | # - /url_to_be_passed example.com
190 | # - /url_to_be_passed_onto_http http://example.com
191 | #
192 | # The first parameter 'url' is a regex (case-insensitive). Must start with '/'.
193 | # The regex begin/end operators are implied and will constitute following regex to be
194 | # matched against inbound request's URL:
195 | # '^/' + url_to_be_passed + '$'
196 | #
197 | # Here are the URL rewriting rules:
198 | # Example, inbound request:
199 | # https://attacker.com/dl/file-to-be-served.txt
200 | #
201 | # Rules:
202 | # a) Entire URL to be substituted for proxy pass:
203 | # proxy_pass:
204 | # - /dl/.+ https://localhost:8888/
205 | # ====> will redirect to https://localhost:8888/
206 | #
207 | # b) Only host to be substituted for proxy pass:
208 | # proxy_pass:
209 | # - /dl/.+ localhost:8888
210 | # ====> will redirect to https://localhost:8888/dl/file-to-be-served.txt
211 | #
212 | # Following options are supported:
213 | # - nodrop - Process this rule at first, before evaluating any DROP-logic.
214 | # Does not let processed request to be dropped.
215 | #
216 | # Default: No proxy pass rules.
217 | #
218 | proxy_pass:
219 | # These are example proxy_pass definitions:
220 | #- /foobar\d* bing.com
221 | #- /myip http://ip-api.com/json/
222 | #- /alwayspass google.com nodrop
223 |
224 |
225 | #
226 | # If set, removes all HTTP headers sent by Client that are not expected by Teamserver according
227 | # to the supplied Malleable profile and its client { header ... } section statements. Some CDNs/WebProxy
228 | # providers such as CloudFlare may add tons of their own metadata headers (like: CF-IPCountry, CF-RAY,
229 | # CF-Visitor, CF-Request-ID, etc.) that can make Teamserver unhappy about inbound HTTP Request which could
230 | # cause its refusal.
231 | #
232 | # We can strip all of these superfluous, not expected by Teamserver HTTP headers delivering a vanilla plain
233 | # request. This is recommended setting in most scenarios.
234 | #
235 | # Do note however, that Teamserver by itself ignores superfluous headers it receives in requests, as long as they
236 | # don't compromise integrity of the malleable transaction.
237 | #
238 | # Default: True
239 | #
240 | remove_superfluous_headers: True
241 |
242 |
243 | #
244 | # Every time malleable_redirector decides to pass request to the Teamserver, as it conformed
245 | # malleable profile's contract, a MD5 sum may be computed against that request and saved in sqlite
246 | # file. Should there be any subsequent request evaluating to a hash value that was seen & stored
247 | # previously, that request is considered as Replay-Attack attempt and thus should be banned.
248 | #
249 | # CobaltStrike's Teamserver has built measures aginst replay-attacks, however malleable_redirector may
250 | # assist in that activity as well.
251 | #
252 | # Default: False
253 | #
254 | mitigate_replay_attack: False
255 |
256 |
257 | #
258 | # List of whitelisted IP addresses/CIDR ranges.
259 | # Inbound packets from these IP address/ranges will always be passed towards specified TeamServer without
260 | # any sort of verification or validation.
261 | #
262 | whitelisted_ip_addresses:
263 | - 127.0.0.0/24
264 |
265 |
266 | #
267 | # Maintain a volatile, dynamic list of whitelisted Peers (IPv4 addresses) based on a number of requests
268 | # they originate that were allowed and passed to Teamserver.
269 | #
270 | # This option cuts down request processing time since whenever a request coming from a previously whitelisted
271 | # peers gets processed, it will be accepted right away having observed that the peer was allowed to pass
272 | # N requests to the Teamserver on a previous occassions.
273 | #
274 | # This whitelist gets cleared along with RedWarden being terminated. It is only held up in script's memory.
275 | #
276 | # Paramters:
277 | # - number_of_valid_http_get_requests: defines number of successful http-get requests (polling Teamserver)
278 | # that determine whether Peer can be trusted.
279 | # - number_of_valid_http_post_requests: defines number of successful http-post requests (sending command
280 | # results to the TS) that determine whether Peer can be trusted.
281 | #
282 | # Value of 0 denotes disabled counting of a corresponding type of requests.
283 | # Function disabled if configuration option is missing.
284 | #
285 | # Default: (dynamic whitelist enabled)
286 | # number_of_valid_http_get_requests: 15
287 | # number_of_valid_http_post_requests: 5
288 | #
289 | add_peers_to_whitelist_if_they_sent_valid_requests:
290 | number_of_valid_http_get_requests: 15
291 | number_of_valid_http_post_requests: 5
292 |
293 |
294 | #
295 | # Ban peers based on their IPv4 address. The blacklist with IP address to check against is specified
296 | # in 'ip_addresses_blacklist_file' option.
297 | #
298 | # Default: True
299 | #
300 | ban_blacklisted_ip_addresses: True
301 |
302 |
303 | #
304 | # Specifies external list of CIDRs with IPv4 addresses to ban. Each entry in that file
305 | # can contain a single IPv4, a CIDR or a line with commentary in following format:
306 | # 1.2.3.4/24 # Super Security System
307 | #
308 | # Default: data/banned_ips.txt
309 | #
310 | ip_addresses_blacklist_file: data/banned_ips.txt
311 |
312 |
313 | #
314 | # Specifies external list of keywords to ban during reverse-IP lookup, User-Agents or
315 | # HTTP headers analysis stage. The file can contain lines beginning with '#' to mark comments.
316 | #
317 | # Default: data/banned_words.txt
318 | #
319 | banned_agents_words_file: data/banned_words.txt
320 |
321 |
322 | #
323 | # Specifies external list of phrases that should override banned phrases in case of ambiguity.
324 | # If the request was to be banned because of a ambigue phrase, the override agents file can
325 | # make the request pass blocking logic if it contained "allowed" phrase.
326 | #
327 | # Default: data/banned_words_override.txt
328 | #
329 | override_banned_agents_file: data/banned_words_override.txt
330 |
331 |
332 | #
333 | # Ban peers based on their IPv4 address' resolved ISP/Organization value or other details.
334 | # Whenever a peer connects to our proxy, we'll take its IPv4 address and use one of the specified
335 | # APIs to collect all the available details about the address. Whenever a banned word
336 | # (of a security product) is found in those details - peer will be banned.
337 | # List of API keys for supported platforms are specified in ''. If there are no keys specified,
338 | # only providers that don't require API keys will be used (e.g. ip-api.com, ipapi.co)
339 | #
340 | # This setting affects execution of policy:
341 | # - drop_ipgeo_metadata_containing_banned_keywords
342 | #
343 | # Default: True
344 | #
345 | verify_peer_ip_details: True
346 |
347 |
348 | #
349 | # Specifies a list of API keys for supported API details collection platforms.
350 | # If 'verify_peer_ip_details' is set to True and there is at least one API key given in this option, the
351 | # proxy will collect details of inbound peer's IPv4 address and verify them for occurences of banned words
352 | # known from various security vendors. Do take a note that various API details platforms have their own
353 | # thresholds for amount of lookups per month. By giving more than one API keys, the script will
354 | # utilize them in a random order.
355 | #
356 | # To minimize number of IP lookups against each platform, the script will cache performed lookups in an
357 | # external file named 'ip-lookups-cache.json'
358 | #
359 | # Supported IP Lookup providers:
360 | # - ip-api.com: No API key needed, free plan: 45 requests / minute
361 | # - ipapi.co: No API key needed, free plan: up to 30000 IP lookups/month and up to 1000/day.
362 | # - ipgeolocation.io: requires an API key, up to 30000 IP lookups/month and up to 1000/day.
363 | #
364 | # Default: empty dictionary
365 | #
366 | ip_details_api_keys:
367 | #ipgeolocation_io: 0123456789abcdef0123456789abcdef
368 | ipgeolocation_io:
369 |
370 |
371 | #
372 | # Restrict incoming peers based on their IP Geolocation information.
373 | # Available only if 'verify_peer_ip_details' was set to True.
374 | # IP Geolocation determination may happen based on the following supported characteristics:
375 | # - organization,
376 | # - continent,
377 | # - continent_code,
378 | # - country,
379 | # - country_code,
380 | # - city,
381 | # - timezone
382 | #
383 | # The Peer will be served if at least one geolocation condition holds true for him
384 | # (inclusive/alternative arithmetics).
385 | #
386 | # If no determinants are specified, IP Geolocation will not be taken into consideration while accepting peers.
387 | # If determinants are specified, only those peers whose IP address matched geolocation determinants will be accepted.
388 | #
389 | # Each of the requirement values may be regular expression. Matching is case-insensitive.
390 | #
391 | # Following (continents_code, continent) pairs are supported:
392 | # ('AF', 'Africa'),
393 | # ('AN', 'Antarctica'),
394 | # ('AS', 'Asia'),
395 | # ('EU', 'Europe'),
396 | # ('NA', 'North america'),
397 | # ('OC', 'Oceania'),
398 | # ('SA', 'South america)'
399 | #
400 | # Proper IP Lookup details values can be established by issuing one of the following API calls:
401 | # $ curl -s 'https://ipapi.co/TARGET-IP-ADDRESS/json/'
402 | # $ curl -s 'http://ip-api.com/json/TARGET-IP-ADDRESS'
403 | #
404 | # The organization/isp/as/asn/org fields will be merged into a common organization list of values.
405 | #
406 | ip_geolocation_requirements:
407 | organization:
408 | #- My\s+Target\+Company(?: Inc.)?
409 | continent:
410 | continent_code:
411 | country:
412 | country_code:
413 | city:
414 | timezone:
415 |
416 |
417 | #
418 | # Fine-grained requests dropping policy - lets you decide which checks
419 | # you want to have enforced and which to skip by setting them to False
420 | #
421 | # Default: all checks enabled
422 | #
423 | policy:
424 | # [IP: ALLOW, reason:0] Request conforms ProxyPass entry (url="..." host="..."). Passing request to specified host
425 | allow_proxy_pass: True
426 | # [IP: ALLOW, reason:2] Peer's IP was added dynamically to a whitelist based on a number of allowed requests
427 | allow_dynamic_peer_whitelisting: True
428 | # [IP: DROP, reason:1] inbound User-Agent differs from the one defined in C2 profile.
429 | drop_invalid_useragent: True
430 | # [IP: DROP, reason:2] HTTP header name contained banned word
431 | drop_http_banned_header_names: True
432 | # [IP: DROP, reason:3] HTTP header value contained banned word:
433 | drop_http_banned_header_value: True
434 | # [IP: DROP, reason:4b] peer's reverse-IP lookup contained banned word
435 | drop_dangerous_ip_reverse_lookup: True
436 | # [IP: DROP, reason:4e] Peer's IP geolocation metadata contained banned keyword! Peer banned in generic fashion.
437 | drop_ipgeo_metadata_containing_banned_keywords: True
438 | # [IP: DROP, reason:5] HTTP request did not contain expected header
439 | drop_malleable_without_expected_header: True
440 | # [IP: DROP, reason:6] HTTP request did not contain expected header value:
441 | drop_malleable_without_expected_header_value: True
442 | # [IP: DROP, reason:7] HTTP request did not contain expected (metadata|id|output) section header:
443 | drop_malleable_without_expected_request_section: True
444 | # [IP: DROP, reason:8] HTTP request was expected to contain (metadata|id|output) section with parameter in URI:
445 | drop_malleable_without_request_section_in_uri: True
446 | # [IP: DROP, reason:9] Did not found append pattern (this logic is known to cause troubles, use with caution):
447 | drop_malleable_without_prepend_pattern: False
448 | # [IP: DROP, reason:10] Did not found append pattern (this logic is known to cause troubles, use with caution):
449 | drop_malleable_without_apppend_pattern: False
450 | # [IP: DROP, reason:11] Requested URI does not aligns any of Malleable defined variants:
451 | drop_malleable_unknown_uris: True
452 | # [IP: DROP, reason:12] HTTP request was expected to contain <> section with URI-append containing prepend/append fragments
453 | drop_malleable_with_invalid_uri_append: True
454 |
455 |
456 | #
457 | # This option repairs Beacon requests's header value by restoring to what was expected in Malleable C2 profile.
458 | #
459 | # If RedWarden validates inbound request's HTTP headers, according to policy drop_malleable_without_expected_header_value:
460 | # "[IP: DROP, reason:6] HTTP request did not contain expected header value:"
461 | #
462 | # and detects some header is missing or was overwritten along the wire, the request will be dropped.
463 | #
464 | # We can relax this policy a bit however, since there are situations in which Cache systems (such as Cloudflare) could tamper with our
465 | # requests thus breaking Malleable contracts. What we can do is to specify list of headers, that should be overwritten back to their values
466 | # defined in provided Malleable profile.
467 | #
468 | # So for example, if our profile expects:
469 | # header "Accept-Encoding" "gzip, deflate";
470 | #
471 | # but we receive a request having following header set instead:
472 | # Accept-Encoding: gzip
473 | #
474 | # Because it was tampered along the wire by some of the interim systems (such as web-proxies or caches), we can
475 | # detect that and set that header's value back to what was expected in Malleable profile.
476 | #
477 | # In order to protect Accept-Encoding header, as an example, the following configuration could be used:
478 | # repair_these_headers:
479 | # - Accept-Encoding
480 | #
481 | # Default:
482 | #
483 | #repair_these_headers:
484 | # - Accept-Encoding
485 |
486 | #
487 | # This option specifies which headers coming from Teamserver responses should be removed before
488 | # reaching Beacon process. With Cobalt Strike 4.7+ I noticed that Teamserver removes Content-Encoding header
489 | # automatically without any notice, thus violating our malleable http-(get|post).server contract.
490 | # Since RedWarden followed the contract, Beacon was either dropping responses or decompressing them incorrectly.
491 | #
492 | # Either way, with Cobalt Strike 4.7+ we need to remove Content-Encoding header from responses to keep on going.
493 | #
494 | remove_these_response_headers:
495 | - Content-Encoding
496 |
497 |
498 | #
499 | # Malleable Redirector plugin can act as a basic oracle API responding to calls
500 | # containing full request contents with classification whether that request would be
501 | # blocked or passed along. The API may be used by custom payload droppers, HTML Smuggling
502 | # payloads or any other javascript-based landing pages.
503 | #
504 | # The way to invoke it is as follows:
505 | # 1. Issue a POST request to the RedWarden server with the below specified URI in path.
506 | # 2. Include following JSON in your POST request:
507 | #
508 | # POST /malleable_redirector_hidden_api_endpoint
509 | # Content-Type: application/json
510 | #
511 | # {
512 | # "peerIP" : "IP-of-connecting-Peer",
513 | # "headers" : {
514 | # "headerName1" : "headerValue1",
515 | # ...
516 | # "headerNameN" : "headerValueN",
517 | # },
518 | # }
519 | #
520 | # If "peerIP" is empty (or was not given), RedWarden will try to extract peer's IP from HTTP
521 | # headers such as (X-Forwarded-For, CF-Connecting-IP, X-Real-IP, etc.). If no IP will be present
522 | # in headers, an error will be returned.:
523 | #
524 | # HTTP 404 Not Found
525 | # {
526 | # "error" : "number",
527 | # "message" : "explanation"
528 | # }
529 | #
530 | # RedWarden will take any non-empty field from a given JSON and evaluate it as it would do
531 | # under currently provided configuration and all the knowledge it possesses.
532 | # The response will contain following JSON:
533 | #
534 | # {
535 | # "action": "allow|drop",
536 | # "peerIP" : "returned-peerIP",
537 | # "ipgeo" : {ip-geo-metadata-extracted}
538 | # "message": "explanation",
539 | # "reason": "reason",
540 | # "drop_type": "proxy|reset|redirect",
541 | # "action_url": ["proxy-URL-1|redirect-URL-1", ..., "proxy-URL-N|redirect-URL-N"]
542 | # }
543 | #
544 | # Availbale Allow/Drop reasons for this endpoint:
545 | # ALLOW:
546 | # - Reason: 99 - Peer IP and HTTP headers did not contain anything suspicious
547 | # - Reason: 1 - peer's IP address is whitelisted
548 | # - Reason: 2 - Peer's IP was added dynamically to a whitelist based on a number of allowed requests
549 | # DROP:
550 | # - Reason: 2 - HTTP header name contained banned word
551 | # - Reason: 3 - HTTP header value contained banned word
552 | # - Reason: 4a - Peer's IP address is blacklisted
553 | # - Reason: 4b - Peer's reverse-IP lookup contained banned word
554 | # - Reason: 4c - Peer's IP lookup organization field contained banned word
555 | # - Reason: 4d - Peer's IP geolocation DID NOT met expected conditions
556 | # - Reason: 4e - Peer's IP geolocation metadata contained banned keyword! Peer banned in generic fashion
557 | #
558 | # Sample curl to debug:
559 | # $ curl -sD- --request POST --data "{\"headers\":{\"Accept\": \"*/*\", \"Sec-Fetch-Site\": \"same-origin\", \
560 | # \"Sec-Fetch-Mode\": \"no-cors\", \"Sec-Fetch-Dest\": \"script\", \"Accept-Language\": \"en-US,en;q=0.9\", \
561 | # \"Cookie\": \"__cfduid2=cHux014r17SG3v4gPUrZ0BZjDabMTY2eWDj1tuYdREBg\", \"User-Agent\": \
562 | # \"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko\"}}" \
563 | # https://attacker.com/12345678-9abc-def0-1234-567890abcdef
564 | #
565 | # Default: Turned off / not available
566 | #
567 | #malleable_redirector_hidden_api_endpoint: /12345678-9abc-def0-1234-567890abcdef
568 |
--------------------------------------------------------------------------------
/images/0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mgeeky/RedWarden/04ee73b684a84353a97aa9bff2d6b0d23bd16b73/images/0.png
--------------------------------------------------------------------------------
/images/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mgeeky/RedWarden/04ee73b684a84353a97aa9bff2d6b0d23bd16b73/images/1.png
--------------------------------------------------------------------------------
/images/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mgeeky/RedWarden/04ee73b684a84353a97aa9bff2d6b0d23bd16b73/images/2.png
--------------------------------------------------------------------------------
/images/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mgeeky/RedWarden/04ee73b684a84353a97aa9bff2d6b0d23bd16b73/images/3.png
--------------------------------------------------------------------------------
/lib/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mgeeky/RedWarden/04ee73b684a84353a97aa9bff2d6b0d23bd16b73/lib/__init__.py
--------------------------------------------------------------------------------
/lib/ipLookupHelper.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # IP Lookup utility aiming to help gather expected details of a specific IPv4 address.
5 | #
6 | # Usage: ./ipLookupHelper.py [malleable-redirector-config]
7 | #
8 | # Use this small utility to collect IP Lookup details on your target IPv4 address and verify whether
9 | # your 'ip_geolocation_requirements' section of RedWarden malleable-redirector-config.yaml would match that
10 | # IP address. If second param is not given - no IP Geolocation evaluation will be performed.
11 | #
12 | # Author:
13 | # Mariusz Banach / mgeeky, 20
14 | #
15 | #
16 |
17 | VERSION = '0.4'
18 |
19 | import sys
20 | import socket
21 | import pprint
22 | import json, re
23 | import requests
24 | import random
25 | import yaml
26 | import urllib3, ssl
27 |
28 | from urllib.parse import urlparse, parse_qsl
29 |
30 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
31 | ssl._create_default_https_context = ssl._create_unverified_context
32 |
33 | API_KEYS = {
34 | 'ipgeolocation_io': '',
35 | }
36 |
37 |
38 | class Logger:
39 | @staticmethod
40 | def _out(x, color = ''):
41 | sys.stdout.write(x + '\n')
42 |
43 | @staticmethod
44 | def dbg(x, color = ''):
45 | sys.stdout.write('[dbg] ' + x + '\n')
46 |
47 | @staticmethod
48 | def out(x, color = ''):
49 | Logger._out('[.] ' + x)
50 |
51 | @staticmethod
52 | def info(x, color = ''):
53 | Logger._out('[?] ' + x)
54 |
55 | @staticmethod
56 | def err(x, color = ''):
57 | sys.stdout.write('[!] ' + x + '\n')
58 |
59 | @staticmethod
60 | def fail(x, color = ''):
61 | Logger._out('[-] ' + x)
62 |
63 | @staticmethod
64 | def ok(x, color = ''):
65 | Logger._out('[+] ' + x)
66 |
67 |
68 | class IPLookupHelper:
69 | supported_providers = (
70 | 'ipapi_co',
71 | 'ip_api_com',
72 | 'ipgeolocation_io',
73 | )
74 |
75 | cached_lookups_file = 'ip-lookups-cache.json'
76 |
77 | def __init__(self, logger, apiKeys):
78 | self.logger = logger
79 | self.apiKeys = {
80 | 'ip_api_com': 'this-provider-not-requires-api-key-for-free-plan',
81 | 'ipapi_co': 'this-provider-not-requires-api-key-for-free-plan',
82 | }
83 |
84 | if len(apiKeys) > 0:
85 | for prov in IPLookupHelper.supported_providers:
86 | if prov in apiKeys.keys():
87 | if apiKeys[prov] == None or len(apiKeys[prov].strip()) < 2: continue
88 | self.apiKeys[prov] = apiKeys[prov].strip()
89 |
90 | self.cachedLookups = {}
91 |
92 | self.logger.dbg('Following IP Lookup providers will be used: ' + str(list(self.apiKeys.keys())))
93 |
94 | try:
95 | with open(IPLookupHelper.cached_lookups_file) as f:
96 | data = f.read()
97 | if len(data) > 0:
98 | cached = json.loads(data)
99 | self.cachedLookups = cached
100 | self.logger.dbg(f'Read {len(cached)} cached entries from file.')
101 |
102 | except json.decoder.JSONDecodeError as e:
103 | self.logger.err(f'Corrupted JSON data in cache file: {IPLookupHelper.cached_lookups_file}! Error: {e}')
104 | raise
105 |
106 | except FileNotFoundError as e:
107 | with open(IPLookupHelper.cached_lookups_file, 'w') as f:
108 | json.dump({}, f)
109 |
110 | except Exception as e:
111 | self.logger.err(f'Exception raised while loading cached lookups from file ({IPLookupHelper.cached_lookups_file}: {e}')
112 | raise
113 |
114 | def lookup(self, ipAddress):
115 | if len(self.apiKeys) == 0:
116 | return {}
117 |
118 | if ipAddress in self.cachedLookups.keys():
119 | self.logger.dbg(f'Returning cached entry for IP address: {ipAddress}')
120 | return self.cachedLookups[ipAddress]
121 |
122 | leftProvs = list(self.apiKeys.keys())
123 | result = {}
124 |
125 | while len(leftProvs) > 0:
126 | prov = random.choice(leftProvs)
127 |
128 | if hasattr(self, prov) != None:
129 | method = getattr(self, prov)
130 | self.logger.dbg(f'Calling IP Lookup provider: {prov}')
131 | result = method(ipAddress)
132 |
133 | if len(result) > 0:
134 | result = self.normalizeResult(result)
135 | break
136 |
137 | leftProvs.remove(prov)
138 |
139 | if len(result) > 0:
140 | self.cachedLookups[ipAddress] = result
141 |
142 | with open(IPLookupHelper.cached_lookups_file, 'w') as f:
143 | json.dump(self.cachedLookups, f)
144 |
145 | self.logger.dbg(f'New IP lookup entry cached: {ipAddress}')
146 |
147 | return result
148 |
149 | def normalizeResult(self, result):
150 | # Returns JSON similar to the below:
151 | # {
152 | # "organization": [
153 | # "Tinet SpA",
154 | # "Zscaler inc.",
155 | # "AS62044 Zscaler Switzerland GmbH"
156 | # ],
157 | # "continent": "Europe",
158 | # "country": "Germany",
159 | # "continent_code": "EU",
160 | # "ip": "89.167.131.40",
161 | # "city": "Frankfurt am Main",
162 | # "timezone": "Europe/Berlin",
163 | # "fulldata": {
164 | # "status": "success",
165 | # "country": "Germany",
166 | # "countryCode": "DE",
167 | # "region": "HE",
168 | # "regionName": "Hesse",
169 | # "city": "Frankfurt am Main",
170 | # "zip": "60314",
171 | # "lat": 50.1103,
172 | # "lon": 8.7147,
173 | # "timezone": "Europe/Berlin",
174 | # "isp": "Zscaler inc.",
175 | # "org": "Tinet SpA",
176 | # "as": "AS62044 Zscaler Switzerland GmbH",
177 | # "query": "89.167.131.40"
178 | # }
179 | # }
180 |
181 | def update(out, data, keydst, keysrc):
182 | if keysrc in data.keys():
183 | if type(out[keydst]) == list: out[keydst].append(data[keysrc])
184 | else: out[keydst] = data[keysrc]
185 |
186 | output = {
187 | 'organization' : [],
188 | 'continent' : '',
189 | 'continent_code' : '',
190 | 'country' : '',
191 | 'country_code' : '',
192 | 'ip' : '',
193 | 'city' : '',
194 | 'timezone' : '',
195 | 'fulldata' : {}
196 | }
197 |
198 | continentCodeToName = {
199 | 'AF' : 'Africa',
200 | 'AN' : 'Antarctica',
201 | 'AS' : 'Asia',
202 | 'EU' : 'Europe',
203 | 'NA' : 'North america',
204 | 'OC' : 'Oceania',
205 | 'SA' : 'South america'
206 | }
207 |
208 | output['fulldata'] = result
209 |
210 | update(output, result, 'organization', 'org')
211 | update(output, result, 'organization', 'isp')
212 | update(output, result, 'organization', 'as')
213 | update(output, result, 'organization', 'organization')
214 | update(output, result, 'ip', 'ip')
215 | update(output, result, 'ip', 'query')
216 | update(output, result, 'timezone', 'timezone')
217 | if 'time_zone' in result.keys():
218 | update(output, result['time_zone'], 'timezone', 'name')
219 | update(output, result, 'city', 'city')
220 |
221 | reverseIp = ''
222 | try:
223 | reverseIp = socket.gethostbyaddr(output['ip'])[0]
224 | except:
225 | pass
226 |
227 | output['reverse_ip'] = reverseIp
228 |
229 | update(output, result, 'country', 'country_name')
230 | if ('country' not in output.keys() or output['country'] == '') and \
231 | ('country' in result.keys() and result['country'] != ''):
232 | update(output, result, 'country', 'country')
233 |
234 | update(output, result, 'country_code', 'country_code')
235 | if ('country_code' not in output.keys() or output['country_code'] == '') and \
236 | ('country_code2' in result.keys() and result['country_code2'] != ''):
237 | update(output, result, 'country_code', 'country_code2')
238 |
239 | update(output, result, 'country_code', 'countryCode')
240 |
241 | update(output, result, 'continent', 'continent')
242 | update(output, result, 'continent', 'continent_name')
243 | update(output, result, 'continent_code', 'continent_code')
244 |
245 | if ('continent_code' not in result.keys() or result['continent_code'] == '') and \
246 | ('continent_name' in result.keys() and result['continent_name'] != ''):
247 | cont = result['continent_name'].lower()
248 | for k, v in continentCodeToName.items():
249 | if v.lower() == cont:
250 | output['continent_code'] = k
251 | break
252 |
253 | elif ('continent_code' in result.keys() and result['continent_code'] != '') and \
254 | ('continent_name' not in result.keys() or result['continent_name'] == ''):
255 | output['continent'] = continentCodeToName[result['continent_code'].upper()]
256 |
257 | elif 'timezone' in result.keys() and result['timezone'] != '':
258 | cont = result['timezone'].split('/')[0].strip().lower()
259 | for k, v in continentCodeToName.items():
260 | if v.lower() == cont:
261 | output['continent_code'] = k
262 | output['continent'] = v
263 | break
264 |
265 | return output
266 |
267 | def ip_api_com(self, ipAddress):
268 | # $ curl -s ip-api.com/json/89.167.131.40 [21:05]
269 | # {
270 | # "status": "success",
271 | # "country": "Germany",
272 | # "countryCode": "DE",
273 | # "region": "HE",
274 | # "regionName": "Hesse",
275 | # "city": "Frankfurt am Main",
276 | # "zip": "60314",
277 | # "lat": 50.1103,
278 | # "lon": 8.7147,
279 | # "timezone": "Europe/Berlin",
280 | # "isp": "Zscaler inc.",
281 | # "org": "Tinet SpA",
282 | # "as": "AS62044 Zscaler Switzerland GmbH",
283 | # "query": "89.167.131.40"
284 | # }
285 |
286 | try:
287 | r = requests.get(f'http://ip-api.com/json/{ipAddress}')
288 |
289 | if r.status_code != 200:
290 | out = r.json()
291 | if not out: out = ''
292 | if type(out) != str: out = str(out)
293 |
294 | raise Exception(f'ip-api.com returned unexpected status code: {r.status_code}.\nOutput text:\n{out}')
295 |
296 | return r.json()
297 |
298 | except Exception as e:
299 | self.logger.err(f'Exception catched while querying ip-api.com with {ipAddress}:\nName: {e}', color='cyan')
300 |
301 | return {}
302 |
303 | def ipapi_co(self, ipAddress):
304 | # $ curl 'https://ipapi.co/89.167.131.40/json/'
305 | # {
306 | # "ip": "89.167.131.40",
307 | # "city": "Frankfurt am Main",
308 | # "region": "Hesse",
309 | # "region_code": "HE",
310 | # "country": "DE",
311 | # "country_code": "DE",
312 | # "country_code_iso3": "DEU",
313 | # "country_capital": "Berlin",
314 | # "country_tld": ".de",
315 | # "country_name": "Germany",
316 | # "continent_code": "EU",
317 | # "in_eu": true,
318 | # "postal": "60314",
319 | # "latitude": 50.1103,
320 | # "longitude": 8.7147,
321 | # "timezone": "Europe/Berlin",
322 | # "utc_offset": "+0200",
323 | # "country_calling_code": "+49",
324 | # "currency": "EUR",
325 | # "currency_name": "Euro",
326 | # "languages": "de",
327 | # "country_area": 357021.0,
328 | # "country_population": 81802257.0,
329 | # "asn": "AS62044",
330 | # "org": "Zscaler Switzerland GmbH"
331 | # }
332 |
333 | try:
334 | r = requests.get(f'https://ipapi.co/{ipAddress}/json/')
335 |
336 | if r.status_code != 200:
337 | out = r.json()
338 | if not out: out = ''
339 |
340 | if type(out) == dict and 'error' in out.keys() and 'reason' in out.keys():
341 | if out['error'] and out['reason'].lower() == 'ratelimited':
342 | return {}
343 |
344 | if type(out) != str: out = str(out)
345 |
346 | raise Exception(f'ipapi.co returned unexpected status code: {r.status_code}.\nOutput text:\n{out}')
347 |
348 | return r.json()
349 |
350 | except Exception as e:
351 | self.logger.err(f'Exception catched while querying ipapi.co with {ipAddress}:\nName: {e}', color='cyan')
352 |
353 | return {}
354 |
355 | def ipgeolocation_io(self, ipAddress):
356 | # $ curl 'https://api.ipgeolocation.io/ipgeo?apiKey=API_KEY&ip=89.167.131.40'
357 | # {
358 | # "ip": "89.167.131.40",
359 | # "continent_code": "EU",
360 | # "continent_name": "Europe",
361 | # "country_code2": "DE",
362 | # "country_code3": "DEU",
363 | # "country_name": "Germany",
364 | # "country_capital": "Berlin",
365 | # "state_prov": "Hesse",
366 | # "district": "Innenstadt III",
367 | # "city": "Frankfurt am Main",
368 | # "zipcode": "60314",
369 | # "latitude": "50.12000",
370 | # "longitude": "8.73527",
371 | # "is_eu": true,
372 | # "calling_code": "+49",
373 | # "country_tld": ".de",
374 | # "languages": "de",
375 | # "country_flag": "https://ipgeolocation.io/static/flags/de_64.png",
376 | # "geoname_id": "6946227",
377 | # "isp": "Tinet SpA",
378 | # "connection_type": "",
379 | # "organization": "Zscaler Switzerland GmbH",
380 | # "currency": {
381 | # "code": "EUR",
382 | # "name": "Euro",
383 | # "symbol": "€"
384 | # },
385 | # "time_zone": {
386 | # "name": "Europe/Berlin",
387 | # "offset": 1,
388 | # "current_time": "2020-07-29 22:31:23.293+0200",
389 | # "current_time_unix": 1596054683.293,
390 | # "is_dst": true,
391 | # "dst_savings": 1
392 | # }
393 | # }
394 | try:
395 | r = requests.get(f'https://api.ipgeolocation.io/ipgeo?apiKey={self.apiKeys["ipgeolocation_io"]}&ip={ipAddress}')
396 |
397 | if r.status_code != 200:
398 | out = r.json()
399 | if not out: out = ''
400 | if type(out) != str: out = str(out)
401 |
402 | raise Exception(f'ipapi.co returned unexpected status code: {r.status_code}.\nOutput text:\n{out}')
403 |
404 | return r.json()
405 |
406 | except Exception as e:
407 | self.logger.err(f'Exception catched while querying ipapi.co with {ipAddress}:\nName: {e}', color='cyan')
408 |
409 | return {}
410 |
411 | class IPGeolocationDeterminant:
412 | supported_determinants = (
413 | 'organization',
414 | 'continent',
415 | 'continent_code',
416 | 'country',
417 | 'country_code',
418 | 'city',
419 | 'timezone'
420 | )
421 |
422 | def __init__(self, logger, determinants):
423 | self.logger = logger
424 | if type(determinants) != dict:
425 | raise Exception('Specified ip_geolocation_requirements must be a valid dictonary!')
426 |
427 | self.determinants = {}
428 |
429 | for k, v in determinants.items():
430 | k = k.lower()
431 | if k in IPGeolocationDeterminant.supported_determinants:
432 | if type(v) == str:
433 | self.determinants[k] = [v, ]
434 | elif type(v) == list or type(v) == tuple:
435 | self.determinants[k] = v
436 | elif type(v) == type(None):
437 | self.determinants[k] = []
438 | else:
439 | raise Exception(f'Specified ip_geolocation_requirements[{k}] must be either string or list! Unknown type met: {type(v)}')
440 |
441 | for i in range(len(self.determinants[k])):
442 | if self.determinants[k][i] == None:
443 | self.determinants[k][i] = ''
444 |
445 | def determine(self, ipLookupResult):
446 | if type(ipLookupResult) != dict or len(ipLookupResult) == 0:
447 | self.logger.err(f'Given IP geolocation results object was either empty or not a dictionary: {ipLookupResult}')
448 | return ''
449 |
450 | result = True
451 | checked = 0
452 |
453 | for determinant, expected in self.determinants.items():
454 | if len(expected) == 0 or sum([len(x) for x in expected]) == 0: continue
455 |
456 | if determinant in ipLookupResult.keys():
457 | checked += 1
458 | matched = False
459 |
460 | results = []
461 |
462 | if type(ipLookupResult[determinant]) == str:
463 | results.append(ipLookupResult[determinant])
464 | else:
465 | results.extend(ipLookupResult[determinant])
466 |
467 | for georesult in results:
468 | georesult = georesult.lower()
469 |
470 | for exp in expected:
471 | if georesult in exp.lower():
472 | self.logger.dbg(f'IP Geo result {determinant} value "{georesult}" met expected value "{exp}"')
473 | matched = True
474 | break
475 |
476 | m = re.search(exp, georesult, re.I)
477 | if m:
478 | self.logger.dbg(f'IP Geo result {determinant} value "{georesult}" met expected regular expression: ({exp})')
479 | matched = True
480 | break
481 |
482 | if matched:
483 | break
484 |
485 | if not matched:
486 | self.logger.dbg(f'IP Geo result {determinant} values {ipLookupResult[determinant]} DID NOT met expected set {expected}')
487 | result = False
488 |
489 | return result
490 |
491 | @staticmethod
492 | def getValues(v, n = 0):
493 | values = []
494 |
495 | if type(v) == str:
496 | if ' ' in v:
497 | values.extend(v.split(' '))
498 | values.append(v)
499 | elif type(v) == int or type(v) == float:
500 | values.extend([str(v)])
501 | elif type(v) == tuple or type(v) == list:
502 | for w in v:
503 | values.extend(IPGeolocationDeterminant.getValues(w, n+1))
504 | elif type(v) == dict and n < 10:
505 | values.extend(IPGeolocationDeterminant.getValuesDict(v, n+1))
506 |
507 | return values
508 |
509 | @staticmethod
510 | def getValuesDict(data, n = 0):
511 | values = []
512 |
513 | for k, v in data.items():
514 | if type(v) == dict and n < 10:
515 | values.extend(IPGeolocationDeterminant.getValuesDict(v, n+1))
516 | elif n < 10:
517 | values.extend(IPGeolocationDeterminant.getValues(v, n+1))
518 |
519 | return values
520 |
521 | def validateIpGeoMetadata(self, ipLookupDetails, bannedAgents, overrideBannedAgents = []):
522 | if len(ipLookupDetails) == 0: return (True, '')
523 |
524 | words = set(list(filter(None, IPGeolocationDeterminant.getValuesDict(ipLookupDetails))))
525 | if len(words) == 0: return (True, '')
526 |
527 | if not bannedAgents:
528 | self.logger.fatal("No bannedAgents provided, cannot validateIpGeoMetadata!")
529 |
530 | self.logger.dbg(f"Extracted keywords from Peer's IP Geolocation metadata: ({words})")
531 |
532 | for w in words:
533 | if not w: continue
534 | for x in bannedAgents:
535 | if not x: continue
536 | if ((' ' in x) and (x.lower() in w.lower())):
537 | overridden = False
538 | if len(overrideBannedAgents) > 0:
539 | for a in overrideBannedAgents:
540 | for w2 in words:
541 | if a.lower() in w2.lower():
542 | overridden = True
543 | break
544 | if overridden: break
545 |
546 | if not overridden:
547 | self.logger.dbg(f"Peer's IP Geolocation metadata contained banned phrase: ({w})")
548 | return (False, w)
549 |
550 | elif (w.lower() == x.lower()):
551 | overridden = False
552 | if len(overrideBannedAgents) > 0:
553 | for a in overrideBannedAgents:
554 | for w2 in words:
555 | if a.lower() in w2.lower():
556 | overridden = True
557 | break
558 | if overridden: break
559 |
560 | if not overridden:
561 | self.logger.dbg(f"Peer's IP Geolocation metadata contained banned keyword: ({w})")
562 | return (False, w)
563 |
564 | self.logger.dbg(f"Peer's IP Geolocation metadata didn't raise any suspicion.")
565 | return (True, '')
566 |
567 | def usage():
568 | print ('''
569 | Usage: ./ipLookupHelper.py [malleable-redirector-config]
570 |
571 | Use this small utility to collect IP Lookup details on your target IPv4 address and verify whether
572 | your 'ip_geolocation_requirements' section of RedWarden malleable-redirector-config.yaml would match that
573 | IP address. If second param is not given - no IP Geolocation evaluation will be performed.
574 |
575 | ''')
576 |
577 | def main(argv):
578 | if len(argv) < 2:
579 | usage()
580 | return False
581 |
582 | ipaddr = sys.argv[1]
583 |
584 | if not re.match(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', ipaddr, re.I):
585 | usage()
586 | return False
587 |
588 | conf = ''
589 | if len(argv) == 3: conf = sys.argv[2]
590 |
591 | logger = Logger()
592 | lookup = IPLookupHelper(logger, API_KEYS)
593 |
594 | print('[.] Lookup of: ' + ipaddr)
595 | result = lookup.lookup(ipaddr)
596 | print('[.] Output:\n' + str(json.dumps(result, indent=2)))
597 |
598 | if conf != '':
599 | config = {}
600 | with open(conf) as f:
601 | try:
602 | config = yaml.load(f, Loader=yaml.FullLoader)
603 | except Exception as e:
604 | self.logger.fatal(f'Could not parse {f} YAML file:\n\n{e}\n\n')
605 |
606 | deter = IPGeolocationDeterminant(logger, config['ip_geolocation_requirements'])
607 | out = deter.determine(result)
608 | print('[.] IP Geolocation determination as instructed by malleable config returned: ' + str(out))
609 |
610 | if __name__ == '__main__':
611 | main(sys.argv)
--------------------------------------------------------------------------------
/lib/optionsparser.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import yaml
4 | import os, sys
5 | from lib.pluginsloader import PluginsLoader
6 | from lib.proxylogger import ProxyLogger
7 | from argparse import ArgumentParser
8 |
9 | ProxyOptionsDefaultValues = {
10 | }
11 |
12 | ImpliedParams = {
13 | 'plugin' : ['malleable_redirector',],
14 | }
15 |
16 | def parse_options(opts, version):
17 |
18 | global ProxyOptionsDefaultValues
19 | ProxyOptionsDefaultValues.update(opts)
20 |
21 | usage = "Usage: %%prog [options]"
22 | parser = ArgumentParser(usage=usage, prog="%prog " + version)
23 |
24 | parser.add_argument("-c", "--config", dest='config',
25 | help="External configuration file. Defines values for below options, however specifying them on command line will supersed ones from file.")
26 |
27 | # General options
28 | parser.add_argument("-v", "--verbose", dest='verbose',
29 | help="Displays verbose output.", action="store_true")
30 | parser.add_argument("-d", "--debug", dest='debug',
31 | help="Displays debugging informations (implies verbose output).", action="store_true")
32 | parser.add_argument("-s", "--silent", dest='silent',
33 | help="Surpresses all of the output logging.", action="store_true")
34 | parser.add_argument("-z", "--allow-invalid", dest='allow_invalid',
35 | help="Process invalid HTTP requests. By default if a stream not resembling HTTP protocol reaches RedWarden listener - it will be dropped.", action="store_true")
36 | parser.add_argument("-N", "--no-proxy", dest='no_proxy',
37 | help="Disable standard HTTP/HTTPS proxy capability (will not serve CONNECT requests). Useful when we only need plugin to run.", action="store_true")
38 | parser.add_argument("-W", "--tee", dest='tee',
39 | help="While logging to output file, print to stdout also.", action="store_true")
40 | parser.add_argument("-w", "--output", dest='log',
41 | help="Specifies output log file.", metavar="PATH", type=str)
42 | parser.add_argument("-A", "--access-log", dest='access_log',
43 | help="Specifies where to write access attempts in Apache2 combined log format.", metavar="PATH", type=str)
44 | parser.add_argument("--access-log-format", dest='access_log_format', default='apache2',
45 | help="Specifies pre-defined format for access log lines. Supported values: apache2, redelk.", choices=('apache2', 'redelk'), metavar="PATH", type=str)
46 | parser.add_argument("--redelk-backend-c2", dest='redelk_backend_name_c2', default='c2',
47 | help="Backend name (label) for packets that are to be passed to C2 server. Must start with 'c2' phrase.", metavar="NAME", type=str)
48 | parser.add_argument("--redelk-backend-decoy", dest='redelk_backend_name_decoy', default='decoy',
49 | help="Backend name (label) for packets that are NOT to be passed to C2 server. Must start with 'decoy' phrase.", metavar="NAME", type=str)
50 | parser.add_argument("-B", "--bind", dest='bind', metavar='NAME',
51 | help="Specifies proxy's binding address along with protocol to serve (http/https). If scheme is specified here, don't add another scheme specification to the listening port number (123/https). Default: "+ opts['bind'] +".",
52 | type=str, default=opts['bind'])
53 | parser.add_argument("-P", "--port", dest='port', metavar='NUM',
54 | help="Specifies proxy's binding port number(s). A value can be followed with either '/http' or '/https' to specify which type of server to bound on this port. Supports multiple binding ports by repeating this option: '--port 80 --port 443/https'. The port specification may also override globally used --bind address by preceding it with address and colon (--port 127.0.0.1:80/http). Default: "+ str(opts['port'][0]) +".",
55 | type=str, action="append", default = [])
56 | parser.add_argument("-t", "--timeout", dest='timeout', metavar='SECS',
57 | help="Specifies timeout for proxy's response in seconds. Default: "+ str(opts['timeout']) +".",
58 | type=int, default=opts['timeout'])
59 | parser.add_argument("-u", "--proxy-url", dest='proxy_self_url', metavar='URL',
60 | help="Specifies proxy's self url. Default: "+ opts['proxy_self_url'] +".",
61 | type=str, default=opts['proxy_self_url'])
62 |
63 |
64 | # SSL Interception
65 | sslgroup = parser.add_argument_group("SSL Interception setup")
66 | sslgroup.add_argument("-S", "--no-ssl-mitm", dest='no_ssl',
67 | help="Turns off SSL interception/MITM and falls back on straight forwarding.", action="store_true")
68 | sslgroup.add_argument('--ssl-certdir', dest='certdir', metavar='DIR',
69 | help='Sets the destination for all of the SSL-related files, including keys, certificates (self and of'\
70 | ' the visited websites). If not specified, a default value will be used to create a directory and remove it upon script termination. Default: "'+ opts['certdir'] +'"', default=opts['certdir'])
71 | sslgroup.add_argument('--ssl-cakey', dest='cakey', metavar='NAME',
72 | help='Specifies this proxy server\'s (CA) certificate private key. Default: "'+ opts['cakey'] +'"', default=opts['cakey'])
73 | sslgroup.add_argument('--ssl-cacert', dest='cacert', metavar='NAME',
74 | help='Specifies this proxy server\'s (CA) certificate. Default: "'+ opts['cacert'] +'"', default=opts['cacert'])
75 | sslgroup.add_argument('--ssl-certkey', dest='certkey', metavar='NAME',
76 | help='Specifies CA certificate\'s public key. Default: "'+ opts['certkey'] +'"', default=opts['certkey'])
77 | sslgroup.add_argument('--ssl-cacn', dest='cacn', metavar='CN',
78 | help='Sets the common name of the proxy\'s CA authority. If this option is not set, will use --hostname instead. It is required only when no --ssl-cakey/cert were specified and RedWarden will need to generate ones automatically. Default: "'+ opts['cacn'] +'"', default=opts['cacn'])
79 |
80 | # Plugins handling
81 | plugins = parser.add_argument_group("Plugins handling")
82 | plugins.add_argument('-L', '--list-plugins', action='store_true', help='List available plugins.')
83 | plugins.add_argument('-p', '--plugin', dest='plugin', action='append', metavar='PATH', type=str,
84 | help="Specifies plugin's path to be loaded.")
85 |
86 | feed_with_plugin_options(opts, parser)
87 |
88 | params = parser.parse_args()
89 |
90 | for k, v in ImpliedParams.items():
91 | setattr(params, k, v)
92 |
93 | if hasattr(params, 'config') and params.config != '':
94 | try:
95 | params = parseParametersFromConfigFile(params)
96 | except Exception as e:
97 | parser.error(str(e))
98 |
99 | opts.update(params)
100 | else:
101 | opts.update(vars(params))
102 |
103 | if opts['list_plugins']:
104 | files = sorted([f for f in os.scandir(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plugins/'))], key = lambda f: f.name)
105 | for _, entry in enumerate(files):
106 | if entry.name.endswith(".py") and entry.is_file() and entry.name.lower() not in ['iproxyplugin.py', '__init__.py']:
107 | print('[+] Plugin: {}'.format(entry.name))
108 |
109 | sys.exit(0)
110 |
111 | if opts['plugin'] != None and len(opts['plugin']) > 0:
112 | for i, opt in enumerate(opts['plugin']):
113 | decomposed = PluginsLoader.decompose_path(opt)
114 | if not os.path.isfile(decomposed['path']):
115 | opt = opt.replace('.py', '')
116 | opt2 = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plugins/{}.py'.format(opt)))
117 | if not os.path.isfile(opt2):
118 | raise Exception('Specified plugin: "%s" does not exist.' % decomposed['path'])
119 | else:
120 | opt = opt2
121 |
122 | opts['plugins'].add(opt)
123 |
124 | if opts['silent'] and opts['log']:
125 | parser.error("Options -s and -w are mutually exclusive.")
126 |
127 | if opts['silent']:
128 | opts['log'] = 'none'
129 | elif opts['log'] and len(opts['log']) > 0:
130 | try:
131 | if not os.path.isfile(opts['log']):
132 | with open(opts['log'], 'w') as f:
133 | pass
134 | opts['log'] = opts['log']
135 |
136 | except Exception as e:
137 | raise Exception('[ERROR] Failed to open log file for writing. Error: "%s"' % e)
138 | else:
139 | opts['log'] = sys.stdout
140 |
141 | if opts['log'] and opts['log'] != sys.stdout:
142 | opts['log'] = os.path.normpath(opts['log'])
143 |
144 | if opts['cakey']:
145 | opts['cakey'] = os.path.normpath(opts['cakey'])
146 |
147 | if opts['certdir']:
148 | opts['certdir'] = os.path.normpath(opts['certdir'])
149 |
150 | if opts['certkey']:
151 | opts['certkey'] = os.path.normpath(opts['certkey'])
152 |
153 | if 'redelk_backend_name_c2' in opts.keys():
154 | if not opts['redelk_backend_name_c2'].startswith('c2'):
155 | raise Exception('[ERROR] redelk_backend_name_c2 option must start with "c2"!')
156 |
157 | if 'redelk_backend_name_decoy' in opts.keys():
158 | if not opts['redelk_backend_name_decoy'].startswith('decoy'):
159 | raise Exception('[ERROR] redelk_backend_name_decoy option must start with "decoy"!')
160 |
161 | if 'redelk_backend_name_c2' in opts.keys() and 'redelk_backend_name_decoy' in opts.keys():
162 | if opts['redelk_backend_name_c2'].find(' ') != -1 or opts['redelk_backend_name_decoy'].find(' ') != -1:
163 | raise Exception('[ERROR] redelk_backend_name_c2 and redelk_backend_name_decoy options cannot contain spaces!')
164 |
165 | if 'profile' in opts.keys() and opts['profile'] != None:
166 | profile = opts['profile']
167 |
168 | if not os.path.isfile(profile) and 'config' in opts.keys() and os.path.isfile(opts['config']):
169 | p = os.path.normpath(os.path.join(os.path.dirname(opts['config']), opts['profile']))
170 |
171 | if not os.path.isfile(p):
172 | p = os.path.normpath(os.path.join(os.path.join(os.path.dirname(__file__), '..'), opts['profile']))
173 |
174 |
175 | if os.path.isfile(p):
176 | print('[.] Found Malleable C2 profile at: "{}"'.format(p))
177 | opts['profile'] = p
178 |
179 |
180 | def parseParametersFromConfigFile(_params):
181 | parametersRequiringDirectPath = (
182 | 'log',
183 | 'output',
184 | 'access_log',
185 | 'certdir',
186 | 'certkey',
187 | 'cakey',
188 | 'cacert',
189 | 'ssl_certdir',
190 | 'ssl_certkey',
191 | 'ssl_cakey',
192 | 'ssl_cacert',
193 | )
194 |
195 | parametersWithPathThatMayNotExist = (
196 | 'log',
197 | 'output',
198 | 'access_log',
199 | 'ssl_certdir'
200 | )
201 |
202 | translateParamNames = {
203 | 'output' : 'log',
204 | 'proxy_url' : 'proxy_self_url',
205 | 'no_ssl_mitm' : 'no_ssl',
206 | 'ssl_certdir' : 'certdir',
207 | 'ssl_certkey' : 'certkey',
208 | 'ssl_cakey' : 'cakey',
209 | 'ssl_cacert' : 'cacert',
210 | 'ssl_cacn' : 'cacn',
211 | 'drop_invalid_http_requests': 'allow_invalid',
212 | 'repair_these_headers': 'protect_these_headers_from_tampering',
213 | 'restore_these_headers': 'protect_these_headers_from_tampering',
214 | 'redelk_frontend': 'redelk_frontend_name',
215 | 'redelk_backend_c2': 'redelk_backend_name_c2',
216 | 'redelk_backend_decoy': 'redelk_backend_name_decoy',
217 | 'throttle_peer_logging': 'throttle_down_peer_logging',
218 | 'proxypass': 'proxy_pass',
219 | 'remove_unnecessary_headers': 'remove_superfluous_headers',
220 | 'anti_replay_attack': 'mitigate_replay_attack',
221 | }
222 |
223 | valuesThatNeedsToBeList = (
224 | 'port',
225 | 'plugin',
226 | )
227 |
228 | outparams = vars(_params)
229 | config = {}
230 | configBasePath = ''
231 |
232 | if outparams['config'] != None and len(outparams['config']) > 0:
233 | if not 'config' in outparams.keys() or not os.path.isfile(outparams['config']):
234 | raise Exception(f'RedWarden config file not found: ({outparams["config"]}) or --config not specified!')
235 | else:
236 | return outparams
237 |
238 | try:
239 | with open(outparams['config']) as f:
240 | try:
241 | config = yaml.load(f, Loader=yaml.FullLoader)
242 | except Exception as e:
243 | self.logger.fatal(f'Could not parse {f} YAML file:\n\n{e}\n\n')
244 |
245 | outparams.update(config)
246 |
247 | for val in valuesThatNeedsToBeList:
248 | if val in outparams.keys() and val in config.keys():
249 | if type(config[val]) == str:
250 | outparams[val] = [config[val], ]
251 | else:
252 | outparams[val] = config[val]
253 |
254 | for k, v in ProxyOptionsDefaultValues.items():
255 | if k not in outparams.keys():
256 | outparams[k] = v
257 |
258 | for k, v in translateParamNames.items():
259 | if k in outparams.keys():
260 | outparams[v] = outparams[k]
261 | if v in outparams.keys():
262 | outparams[k] = outparams[v]
263 |
264 | configBasePath = os.path.dirname(os.path.abspath(outparams['config']))
265 |
266 | for paramName in parametersRequiringDirectPath:
267 | if paramName in outparams.keys() and \
268 | outparams[paramName] != '' and outparams[paramName] != None:
269 | p1 = outparams[paramName]
270 | if not os.path.isfile(outparams[paramName]):
271 | outparams[paramName] = os.path.join(configBasePath, outparams[paramName])
272 | p = ''
273 | if paramName in translateParamNames.values():
274 | p = list(translateParamNames.keys())[list(translateParamNames.values()).index(paramName)]
275 |
276 | if not os.path.isfile(outparams[paramName]) and \
277 | not ((paramName in parametersWithPathThatMayNotExist) or (p in parametersWithPathThatMayNotExist)):
278 | p2 = outparams[paramName]
279 | raise Exception(f'\n\nCould not find file pointed to by "{paramName}" / "{p}" parameter in specified config file!\nTried these paths:\n\t- {p1}\n\t- {p2}\n\nMake sure to correct the path of this parameter in your config file.')
280 |
281 | return outparams
282 |
283 | except FileNotFoundError as e:
284 | raise Exception(f'RedWarden config file not found: ({outparams["config"]})!')
285 |
286 | except Exception as e:
287 | raise Exception(f'Unhandled exception occured while parsing RedWarden config file: {e}')
288 |
289 | return outparams
290 |
291 | def feed_with_plugin_options(opts, parser):
292 | logger = ProxyLogger()
293 | plugins = []
294 | files = sorted([f for f in os.scandir(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../plugins/'))], key = lambda f: f.name)
295 | for _, entry in enumerate(files):
296 | if entry.name.endswith(".py") and entry.is_file() and entry.name.lower() not in ['iproxyplugin.py', '__init__.py']:
297 | plugins.append(entry.path)
298 |
299 | options = opts.copy()
300 | options['plugins'] = plugins
301 | options['verbose'] = True
302 | options['debug'] = False
303 |
304 | plugin_own_options = {}
305 |
306 | pl = PluginsLoader(logger, options)
307 | for name, plugin in pl.get_plugins().items():
308 | logger.dbg("Fetching plugin {} options.".format(name))
309 | if hasattr(plugin, 'help'):
310 | plugin_options = parser.add_argument_group("Plugin '{}' options".format(plugin.get_name()))
311 | plugin.help(plugin_options)
312 |
--------------------------------------------------------------------------------
/lib/pluginsloader.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | import os
3 | import sys
4 | import inspect
5 | from io import StringIO
6 | import csv
7 |
8 | from lib.proxylogger import ProxyLogger
9 |
10 |
11 | #
12 | # Plugin that attempts to load all of the supplied plugins from
13 | # program launch options.
14 | class PluginsLoader:
15 | class InjectedLogger(ProxyLogger):
16 | def __init__(self, name, options = None):
17 | self.name = name
18 | super().__init__(options)
19 |
20 | def _text(self, txt):
21 | return '[{}] {}'.format(self.name, txt)
22 |
23 | # Info shall be used as an ordinary logging facility, for every desired output.
24 | def info(self, txt, forced = False, **kwargs):
25 | super().info(self._text(txt), forced, **kwargs)
26 |
27 | # Trace by default does not uses [TRACE] prefix. Shall be used
28 | # for dumping packets, headers, metadata and longer technical output.
29 | def trace(self, txt, **kwargs):
30 | super().trace(self._text(txt), **kwargs)
31 |
32 | def dbg(self, txt, **kwargs):
33 | super().dbg(self._text(txt), **kwargs)
34 |
35 | def err(self, txt, **kwargs):
36 | super().err(self._text(txt), **kwargs)
37 |
38 | def fatal(self, txt, **kwargs):
39 | super().fatal(self._text(txt), **kwargs)
40 |
41 | def __init__(self, logger, options, instantiate = True):
42 | self.options = options
43 | self.plugins = {}
44 | self.called = False
45 | self.logger = logger
46 | self.instantiate = instantiate
47 | plugins_count = len(self.options['plugins'])
48 |
49 | if plugins_count > 0:
50 | self.logger.info('Loading %d plugin%s...' % (plugins_count, '' if plugins_count == 1 else 's'))
51 |
52 | for plugin in self.options['plugins']:
53 | self.load(plugin)
54 |
55 | self.called = True
56 |
57 | # Output format:
58 | # plugins = {'plugin1': instance, 'plugin2': instance, ...}
59 | def get_plugins(self):
60 | return self.plugins
61 |
62 | #
63 | # Following function parses input plugin path with parameters and decomposes
64 | # them to extract plugin's arguments along with it's path.
65 | # For instance, having such string:
66 | # -p "plugins/my_plugin.py",argument1="test",argument2,argument3=test2
67 | #
68 | # It will return:
69 | # {'path':'plugins/my_plugin.py', 'argument1':'t,e,s,t', 'argument2':'', 'argument3':'test2'}
70 | #
71 | @staticmethod
72 | def decompose_path(p):
73 | decomposed = {}
74 | f = StringIO(p)
75 | rows = list(csv.reader(f, quoting=csv.QUOTE_ALL, skipinitialspace=True))
76 |
77 | for i in range(len(rows[0])):
78 | row = rows[0][i]
79 | if i == 0:
80 | decomposed['path'] = row
81 | continue
82 |
83 | if '=' in row:
84 | s = row.split('=')
85 | decomposed[s[0]] = s[1].replace('"', '')
86 | else:
87 | decomposed[row] = ''
88 |
89 | return decomposed
90 |
91 |
92 | def load(self, path):
93 | instance = None
94 |
95 | self.logger.dbg('Plugin string: "%s"' % path)
96 | decomposed = PluginsLoader.decompose_path(path)
97 | self.logger.dbg('Decomposed as: %s' % str(decomposed))
98 |
99 | plugin = decomposed['path'].strip()
100 |
101 | if not os.path.isfile(plugin):
102 | _plugin = os.path.normpath(os.path.join(os.path.dirname(__file__), '../plugins/{}'.format(plugin)))
103 | if os.path.isfile(_plugin):
104 | plugin = _plugin
105 | elif os.path.isfile(_plugin+'.py'):
106 | plugin = _plugin + '.py'
107 |
108 | name = os.path.basename(plugin).lower().replace('.py', '')
109 |
110 | if name in self.plugins or name in ['iproxyplugin', '__init__']:
111 | # Plugin already loaded.
112 | return
113 |
114 | self.logger.dbg('Attempting to load plugin: %s ("%s")...' % (name, plugin))
115 |
116 | try:
117 | sys.path.append(os.path.dirname(plugin))
118 | __import__(name)
119 | module = sys.modules[name]
120 | self.logger.dbg('Module imported.')
121 |
122 | try:
123 | handler = getattr(module, self.options['plugin_class_name'])
124 |
125 | found = False
126 | for base in inspect.getmro(handler):
127 | if base.__name__ == 'IProxyPlugin':
128 | found = True
129 | break
130 |
131 | if not found:
132 | raise TypeError('Plugin does not inherit from IProxyPlugin.')
133 |
134 | # Call plugin's __init__ with the `logger' instance passed to it.
135 | if self.instantiate:
136 | instance = handler(PluginsLoader.InjectedLogger(name), self.options)
137 | else:
138 | instance = handler
139 |
140 | self.logger.dbg('Found class "%s".' % self.options['plugin_class_name'])
141 |
142 | except AttributeError as e:
143 | self.logger.err('Plugin "%s" loading has failed: "%s".' %
144 | (name, self.options['plugin_class_name']))
145 | self.logger.err('\tError: %s' % e)
146 | if self.options['debug']:
147 | raise
148 |
149 | except TypeError as e:
150 | self.logger.err('Plugin "{}" instantiation failed due to interface incompatibility.'.format(name))
151 | raise
152 |
153 | if not instance:
154 | self.logger.err('Didn\'t find supported class in module "%s"' % name)
155 | else:
156 | self.plugins[name] = instance
157 | self.logger.info('Plugin "%s" has been installed.' % name)
158 |
159 | except ImportError as e:
160 | self.logger.err('Couldn\'t load specified plugin: "%s". Error: %s' % (plugin, e))
161 | if self.options['debug']:
162 | raise
163 |
--------------------------------------------------------------------------------
/lib/proxyhandler.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | #
4 |
5 | import time
6 | import html
7 | import sys, os
8 | import brotli
9 | import base64
10 | import string
11 | import http.client
12 | import gzip, zlib
13 | import json, re
14 | import traceback
15 | import requests
16 | import urllib3
17 | import socket, ssl, select
18 | import threading
19 |
20 | from datetime import datetime
21 | from urllib.parse import urlparse, parse_qsl
22 | from subprocess import Popen, PIPE
23 | from io import StringIO, BytesIO
24 | from html.parser import HTMLParser
25 |
26 | import lib.optionsparser
27 | from lib.proxylogger import ProxyLogger
28 | from lib.pluginsloader import PluginsLoader
29 | from lib.sslintercept import SSLInterception
30 | from lib.utils import *
31 |
32 | from http.server import BaseHTTPRequestHandler
33 |
34 | from tornado.httpclient import AsyncHTTPClient
35 | import tornado.web
36 | import tornado.httpserver
37 |
38 | from sqlitedict import SqliteDict
39 | import plugins.malleable_redirector
40 |
41 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
42 | ssl._create_default_https_context = ssl._create_unverified_context
43 |
44 | # Global instance that will be passed to every loaded plugin at it's __init__.
45 | logger = None
46 |
47 | # For holding loaded plugins' instances
48 | pluginsloaded = None
49 |
50 | # SSL Interception setup object
51 | sslintercept = None
52 |
53 | options = {}
54 |
55 | class RemoveXProxy2HeadersTransform(tornado.web.OutputTransform):
56 | def transform_first_chunk(self, status_code, headers, chunk, finishing):
57 | xhdrs = [x.lower() for x in plugins.IProxyPlugin.proxy2_metadata_headers.values()]
58 |
59 | for k, v in headers.items():
60 | if k.lower() in xhdrs:
61 | headers.pop(k)
62 |
63 | return status_code, headers, chunk
64 |
65 |
66 | class ProxyRequestHandler(tornado.web.RequestHandler):
67 | client = AsyncHTTPClient(max_buffer_size=1024*1024*150)
68 |
69 | SUPPORTED_METHODS = tornado.web.RequestHandler.SUPPORTED_METHODS + ('PROPFIND', 'CONNECT')
70 | SUPPORTED_ENCODINGS = ('gzip', 'x-gzip', 'identity', 'deflate', 'br')
71 |
72 | def __init__(self, *args, **kwargs):
73 | global pluginsloaded
74 |
75 | self.logger = logger
76 | self.options = options
77 | self.origverbose = options['verbose']
78 | self.logger.options.update(self.options)
79 |
80 | self.plugins = pluginsloaded.get_plugins()
81 | self.server_address, self.all_server_addresses = ProxyRequestHandler.get_ip()
82 |
83 | for name, plugin in self.plugins.items():
84 | plugin.logger = logger
85 |
86 | super().__init__(*args, **kwargs)
87 |
88 | def initialize(self, server_bind, server_port):
89 | self.server_port = server_port
90 | self.server_bind = server_bind
91 |
92 | def set_default_headers(self):
93 | if 'Server' in self._headers.keys():
94 | self.set_header('Server', 'nginx')
95 |
96 | @staticmethod
97 | def get_ip():
98 | all_addresses = sorted([f[4][0] for f in socket.getaddrinfo(socket.gethostname(), None)] + ['127.0.0.1'])
99 | if '0.0.0.0' not in options['bind']:
100 | out = urlparse(options['bind'])
101 | if len(out.netloc) > 1: return out.netloc
102 | else:
103 | return (out.path.replace('/', ''), all_addresses)
104 |
105 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
106 | try:
107 | # doesn't even have to be reachable
108 | s.connect(('10.255.255.255', 1))
109 | IP = s.getsockname()[0]
110 | except:
111 | IP = '127.0.0.1'
112 | finally:
113 | s.close()
114 |
115 | return (IP, all_addresses)
116 |
117 | def log_message(self, format, *args):
118 | if (self.options['verbose'] or \
119 | self.options['debug']) or (type(self.options['log']) == str and self.options['log'] != 'none'):
120 |
121 | txt = "%s - - [%s] %s\n" % \
122 | (self.address_string(),
123 | self.log_date_time_string(),
124 | format%args)
125 |
126 | self.logger.out(txt, self.options['log'], '')
127 |
128 | def log_error(self, format, *args):
129 | # Surpress "Request timed out: timeout('timed out',)" if not in debug mode.
130 | if isinstance(args[0], socket.timeout) and not self.options['debug']:
131 | return
132 |
133 | if not options['debug']:
134 | return
135 |
136 | self.log_message(format, *args)
137 |
138 | def connectMethod(self):
139 | if options['no_proxy']: return
140 | self.logger.dbg(str(sslintercept))
141 | if sslintercept.status:
142 | self.connect_intercept()
143 | else:
144 | self.connect_relay()
145 |
146 | def compute_etag(self):
147 | return None
148 |
149 | @staticmethod
150 | def isValidRequest(req, req_body):
151 | def readable(x):
152 | return all(c in string.printable for c in x)
153 |
154 | try:
155 | if not readable(req.method): return False
156 | if not readable(req.uri): return False
157 |
158 | for k, v in req.headers.items():
159 | if not readable(k): return False
160 | if not readable(v): return False
161 | except:
162 | return False
163 |
164 | return True
165 |
166 | @staticmethod
167 | def generate_ssl_certificate(hostname):
168 | certpath = os.path.join(options['certdir'], hostname + '.crt')
169 | stdout = stderr = ''
170 |
171 | if not os.path.isfile(certpath):
172 | self.logger.dbg('Generating valid SSL certificate for ({})...'.format(hostname))
173 | epoch = "%d" % (time.time() * 1000)
174 |
175 | # Workaround for the Windows' RANDFILE bug
176 | if not 'RANDFILE' in os.environ.keys():
177 | os.environ["RANDFILE"] = os.path.normpath("%s/.rnd" % (options['certdir'].rstrip('/')))
178 |
179 | cmd = ["openssl", "req", "-new", "-key", options['certkey'], "-subj", "/CN=%s" % hostname]
180 | cmd2 = ["openssl", "x509", "-req", "-days", "3650", "-CA", options['cacert'], "-CAkey", options['cakey'], "-set_serial", epoch, "-out", certpath]
181 |
182 | try:
183 | p1 = Popen(cmd, stdout=PIPE, stderr=PIPE)
184 | p2 = Popen(cmd2, stdin=p1.stdout, stdout=PIPE, stderr=PIPE)
185 | (stdout, stderr) = p2.communicate()
186 |
187 | except FileNotFoundError as e:
188 | logger.err("Can't serve HTTPS traffic because there is no 'openssl' tool installed on the system!")
189 | return ''
190 |
191 | else:
192 | #logger.dbg('Using supplied SSL certificate: {}'.format(certpath))
193 | pass
194 |
195 | if not certpath or not os.path.isfile(certpath):
196 | if stdout or stderr:
197 | logger.err('Openssl x509 crt request failed:\n{}'.format((stdout + stderr).decode()))
198 |
199 | logger.fatal('Could not create interception Certificate: "{}"'.format(certpath))
200 | return ''
201 |
202 | return certpath
203 |
204 | def connect_intercept(self):
205 | hostname = self.request.uri.split(':')[0]
206 | certpath = ''
207 |
208 | self.logger.dbg('CONNECT intercepted: "%s"' % self.request.uri)
209 |
210 | certpath = ProxyRequestHandler.generate_ssl_certificate(hostname)
211 | if not certpath:
212 | self._set_status(500, 'Internal Server Error')
213 |
214 | self._set_status(200, 'Connection Established')
215 |
216 | try:
217 | self.request.connection.stream = tornado.iostream.IOStream(ssl.wrap_socket(
218 | self.request.connection.stream,
219 | keyfile=self.options['certkey'],
220 | certfile=certpath,
221 | server_side=True
222 | ))
223 | except:
224 | self.logger.err('Connection reset by peer: "{}"'.format(self.request.uri))
225 | self._send_error(502)
226 | return
227 |
228 | conntype = self.request.headers.get('Proxy-Connection', '')
229 | if conntype.lower() == 'close':
230 | self.request.connection.no_keep_alive = True
231 |
232 | elif (conntype.lower() == 'keep-alive' and self.protocol_version >= "HTTP/1.1"):
233 | self.request.connection.no_keep_alive = False
234 |
235 | def connect_relay(self):
236 | address = self.request.uri.split(':', 1)
237 | address[1] = int(address[1]) or 443
238 |
239 | self.logger.dbg('CONNECT relaying: "%s"' % self.request.uri)
240 |
241 | try:
242 | s = socket.create_connection(address, timeout=self.options['timeout'])
243 | except Exception as e:
244 | self.logger.err("Could not relay connection: ({})".format(str(e)))
245 | self._send_error(502)
246 | return
247 |
248 | self._set_status(200, 'Connection Established')
249 |
250 | conns = [self.request.connection.stream, s]
251 | self.request.connection.no_keep_alive = False
252 |
253 | while not self.close_connection:
254 | rlist, wlist, xlist = select.select(conns, [], conns, self.options['timeout'])
255 | if xlist or not rlist:
256 | break
257 | for r in rlist:
258 | other = conns[1] if r is conns[0] else conns[0]
259 | data = r.recv(8192)
260 | if not data:
261 | self.request.connection.no_keep_alive = True
262 | break
263 | other.sendall(data)
264 |
265 | def reverse_proxy_loop_detected(self, command, fetchurl, req_body):
266 | self.logger.err('[Reverse-proxy loop detected from peer {}] {} {}'.format(
267 | self.client_address[0], command, fetchurl
268 | ))
269 |
270 | self._send_error(500)
271 | return
272 |
273 | def my_handle_request(self, *args, **kwargs):
274 | # http://httpd.apache.org/docs/current/logs.html#combined
275 | # [day/month/year:hour:minute:second zone]
276 | # day = 2*digit
277 | # month = 3*letter
278 | # year = 4*digit
279 | # hour = 2*digit
280 | # minute = 2*digit
281 | # second = 2*digit
282 | # zone = (`+' | `-') 4*digit
283 | timestamp = datetime.utcnow()
284 |
285 | if hasattr(self, 'request') and hasattr(self.request, 'uri') and type(self.request.uri) == str:
286 | if self.request.uri.startswith('//'):
287 | self.request.uri = self.request.uri[1:]
288 |
289 | self._internal_my_handle_request(*args, **kwargs)
290 |
291 | remote_host = self.request.client_address
292 | if (type(self.request.client_address) == list or type(self.request.client_address) == tuple) and len(self.request.client_address) > 0:
293 | remote_host = self.request.client_address[0]
294 |
295 | user_identity = '-'
296 | http_basic_auth = '-'
297 |
298 | if len(self.request.headers.get('Authorization', '')) > 0:
299 | auth = self.request.headers.get('Authorization', '').strip()
300 | if auth.lower().startswith('basic '):
301 | try:
302 | auth_decoded = base64.b64decode(auth[len('Basic '):])
303 | if ':' in auth_decoded:
304 | http_basic_auth = auth_decoded.split(':')[0]
305 | except:
306 | pass
307 |
308 | timezone = '+0000'
309 | month = timestamp.strftime('%b')
310 | request_timestamp = f'[{timestamp.day:02}/{month}/{timestamp.year:04}:{timestamp.hour:02}:{timestamp.minute:02}:{timestamp.second:02} {timezone}]'
311 | request_line = f'{self.request.method} {self.request.uri} {self.request_version}'
312 | http_referer = '-'
313 | http_useragent = '-'
314 |
315 | if len(self.request.headers.get('Referer', '')) > 0:
316 | http_referer = self.request.headers.get('Referer', '-')
317 |
318 | if len(self.request.headers.get('User-Agent', '')) > 0:
319 | http_useragent = self.request.headers.get('User-Agent', '-')
320 |
321 | line = ''
322 | override_suppress_log = False
323 |
324 | if 'access_log_format' in self.options.keys():
325 | if self.options['access_log_format'] == None:
326 | self.options['access_log_format'] = 'apache2'
327 |
328 | if self.options['access_log_format'].lower() == 'apache2':
329 | # src: https://httpd.apache.org/docs/2.4/logs.html
330 | # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined
331 | line = f'{remote_host} {user_identity} {http_basic_auth} {request_timestamp} "{request_line}" {self.response_status} {self.response_length} "{http_referer}" "{http_useragent}"'
332 |
333 | elif self.options['access_log_format'].lower() == 'redelk':
334 | # src: https://github.com/outflanknl/RedELK/wiki/Redirector-installation#Apache%20specifics
335 | # LogFormat "%t %{hostname}e apache[%P]: frontend:%{frontend_name}e/%A:%{local}p backend:%{backend_name}e client:%h:%{remote}p xforwardedfor:%{X-Forwarded-For}i headers:{%{User-Agent}i|%{Host}i|%{X-Forwarded-For}i|%{X-Forwarded-Proto}i|%{X-Host}i|%{Forwarded}i|%{Via}i|} statuscode:%s request:%r" redelklogformat
336 |
337 | hostname = socket.gethostname()
338 | pid = os.getpid()
339 |
340 | frontend_name = 'http-redwarden'
341 |
342 | backend_name_c2 = 'c2'
343 | backend_name_decoy = 'decoy'
344 |
345 | if 'redelk_frontend_name' in self.options.keys():
346 | frontend_name = self.options['redelk_frontend_name']
347 |
348 | if 'redelk_backend_name_c2' in self.options.keys():
349 | backend_name_c2 = self.options['redelk_backend_name_c2']
350 |
351 | if 'redelk_backend_name_decoy' in self.options.keys():
352 | backend_name_decoy = self.options['redelk_backend_name_decoy']
353 |
354 | local_address = socket.gethostbyname(socket.gethostname())
355 | local_port = self.request.server_port
356 | x_forwarded_for = self.request.headers.get('X-Forwarded-For', '-')
357 |
358 | # %{User-Agent}i|%{Host}i|%{X-Forwarded-For}i|%{X-Forwarded-Proto}i|%{X-Host}i|%{Forwarded}i|%{Via}i|
359 | hdr_host = self.request.headers.get('Host', '-')
360 | hdr_xforwardedproto = self.request.headers.get('X-Forwarded-Proto', '-')
361 | hdr_xhost = self.request.headers.get('X-Host', '-')
362 | hdr_forwarded = self.request.headers.get('Forwarded', '-')
363 | hdr_via = self.request.headers.get('Via', '-')
364 | headers_string = f"{http_useragent}|{hdr_host}|{x_forwarded_for}|{hdr_xforwardedproto}|{hdr_xhost}|{hdr_forwarded}|{hdr_via}|"
365 |
366 | try:
367 | remote_host_port = self.request.connection.stream.socket.getpeername()[1]
368 | except:
369 | remote_host_port = 0
370 |
371 | backend_name = backend_name_decoy
372 |
373 | if self.request.redirected_to_c2:
374 | backend_name = backend_name_c2
375 |
376 | line = f'{request_timestamp} {hostname} apache[{pid}]: frontend:{frontend_name}/{local_address}:{local_port} backend:{backend_name} client:{remote_host}:{remote_host_port} xforwardedfor:{x_forwarded_for} headers:{{{headers_string}}} statuscode:{self.response_status} request:{request_line}'
377 |
378 | override_suppress_log = True
379 |
380 | if 'access_log' in self.options.keys() and self.options['access_log'] != None and len(self.options['access_log']) > 0:
381 | if not self.request.suppress_log_entry or override_suppress_log:
382 | with open(self.options['access_log'], 'a') as f:
383 | f.write(line + '\n')
384 |
385 | if not self.request.suppress_log_entry:
386 | print(line)
387 |
388 | def _internal_my_handle_request(self, *args, **kwargs):
389 | handler = self._my_handle_request
390 | if self.request.method.lower() == 'connect':
391 | handler = self.connectMethod
392 |
393 | self.headers = self.request.headers.copy()
394 | self.request.headers = self.headers
395 | self.request.method = self.request.method
396 | self.request.client_address = [self.request.remote_ip,]
397 | self.request.connection.no_keep_alive = False
398 | self.request_version = 'HTTP/1.1'
399 | self.request.server_port = self.server_port
400 | self.request.server_bind = self.server_bind
401 | self.request.suppress_log_entry = False
402 | self.request.redirected_to_c2 = False
403 | self.options['verbose'] = self.origverbose
404 |
405 | self.response_status = 0
406 | self.response_reason = ''
407 | self.response_headers = {}
408 | self.response_length = 0
409 |
410 | if self.request.uri.startswith('http://') or self.request.uri.startswith('https://'):
411 | newpath = ''
412 | parsed = urlparse(self.request.uri)
413 | if len(parsed.path) > 0:
414 | newpath += parsed.path
415 | if len(parsed.query) > 0:
416 | newpath += '?' + parsed.query
417 | if len(parsed.fragment) > 0:
418 | newpath += '#' + parsed.fragment
419 |
420 | self.request.uri = newpath
421 |
422 | output = handler()
423 |
424 | self.request.method = self.request.method
425 | self.request.host = self.request.headers['Host']
426 |
427 | def _send_error(self, code, msg = ''):
428 | self.response_status = code
429 | self.response_reason = ''
430 | if len(msg) > 0:
431 | self.response_reason = msg
432 | else:
433 | try:
434 | self.response_reason = requests.status_codes._codes[code][0]
435 | except:
436 | pass
437 |
438 | self.send_error(code)
439 |
440 | def _set_status(self, code, msg = ''):
441 | self.response_status = code
442 | self.response_reason = ''
443 | if len(msg) > 0:
444 | self.response_reason = msg
445 | else:
446 | try:
447 | self.response_reason = requests.status_codes._codes[code][0]
448 | except:
449 | pass
450 |
451 | self.set_status(code, self.response_reason)
452 |
453 | def on_finish(self):
454 | if self.request.connection.no_keep_alive:
455 | self.request.connection.stream.close()
456 |
457 | def _my_handle_request(self):
458 | if self.request.uri == self.options['proxy_self_url']:
459 | self.logger.dbg('Sending CA certificate.')
460 | self.send_cacert()
461 | return
462 |
463 | self.is_ssl = isinstance(self.request.connection.stream, tornado.iostream.SSLIOStream)
464 | self.request.is_ssl = self.is_ssl
465 |
466 | content_length = int(self.request.headers.get('Content-Length', 0))
467 | if not self.options['allow_invalid']:
468 | if not ProxyRequestHandler.isValidRequest(self.request, self.request.body):
469 | self.logger.dbg('[DROP] Invalid HTTP request from: {}'.format(self.client_address[0]))
470 | return
471 |
472 | req_body_modified = ""
473 | dont_fetch_response = False
474 | res = None
475 | res_body_plain = None
476 | content_encoding = 'identity'
477 | inbound_origin = self.request.host
478 | outbound_origin = inbound_origin
479 | origuri = self.request.uri
480 | newuri = self.request.uri
481 | originChanged = False
482 | ignore_response_decompression_errors = False
483 | if 'Host' not in self.request.headers.keys():
484 | self.request.headers['Host'] = self.request.host
485 |
486 | if 'throttle_down_peer_logging' in self.options.keys() and len(self.options['throttle_down_peer_logging']) > 0:
487 | with SqliteDict(plugins.malleable_redirector.ProxyPlugin.DynamicWhitelistFile, autocommit=True) as mydict:
488 | if 'peers' not in mydict.keys():
489 | mydict['peers'] = {}
490 |
491 | prev = mydict.get('peers', {})
492 | peerIP = plugins.malleable_redirector.ProxyPlugin.get_peer_ip(self.request)
493 | elapsed = 0
494 |
495 | if peerIP not in mydict.get('peers', {}):
496 | prev[peerIP] = {
497 | 'last': time.time(),
498 | 'count': 1
499 | }
500 |
501 | else:
502 | last = prev[peerIP]['last']
503 | elapsed = time.time() - last
504 |
505 | if elapsed < 0: elapsed = 0
506 | prev[peerIP]['count'] += 1
507 |
508 | if int(elapsed) > int(self.options['throttle_down_peer_logging']['log_request_delay']):
509 | prev[peerIP]['count'] = 1
510 | self.request.suppress_log_entry = False
511 | self.options['verbose'] = self.origverbose
512 |
513 | if prev[peerIP]['count'] <= self.options['throttle_down_peer_logging']['requests_threshold']:
514 | prev[peerIP]['last'] = time.time()
515 | else:
516 | self.request.suppress_log_entry = True
517 | self.options['verbose'] = False
518 |
519 | mydict['peers'] = prev
520 |
521 | self.logger.dbg('Logging stats for peer {}: elapsed: {}, count: {}'.format(
522 | peerIP, elapsed, prev[peerIP]['count']
523 | ), color = 'yellow')
524 |
525 | self.logger.info('[REQUEST] {} {}'.format(self.request.method, self.request.uri), color=ProxyLogger.colors_map['green'])
526 | self.save_handler(self.request, self.request.body, None, None)
527 |
528 | try:
529 | (modified, req_body_modified) = self.request_handler(self.request, self.request.body)
530 | newuri = self.request.uri
531 |
532 | if modified != None and type(modified) == bool:
533 | modified |= (origuri != newuri)
534 |
535 | if 'DropConnectionException' in str(type(req_body_modified)) or \
536 | 'DontFetchResponseException' in str(type(req_body_modified)):
537 | raise req_body_modified
538 |
539 | elif modified and req_body_modified is not None:
540 | self.request.body = req_body_modified
541 | if self.request.body != None:
542 | reqhdrs = [x.lower() for x in self.request.headers.keys()]
543 | if 'content-length' in reqhdrs: del self.request.headers['Content-Length']
544 | self.request.headers['Content-length'] = str(len(self.request.body))
545 |
546 | parsed = urlparse(newuri)
547 | if parsed.netloc != inbound_origin and parsed.netloc != None and len(parsed.netloc) > 1:
548 | self.logger.info('Plugin redirected request from [{}] to [{}]'.format(inbound_origin, parsed.netloc))
549 | outbound_origin = parsed.netloc
550 | originChanged = True
551 | #newuri = (parsed.path + '?' + parsed.query if parsed.query else parsed.path)
552 |
553 | except Exception as e:
554 | if 'DropConnectionException' in str(e):
555 | self.logger.err("Plugin demanded to drop the request: ({})".format(str(e)))
556 | self.request.connection.no_keep_alive = True
557 | return
558 |
559 | elif 'DontFetchResponseException' in str(e):
560 | dont_fetch_response = True
561 | self.request.connection.no_keep_alive = True
562 | res_body_plain = 'DontFetchResponseException'
563 | class Response(object):
564 | pass
565 | res = Response()
566 |
567 | else:
568 | self.logger.err('Exception catched in request_handler: {}'.format(str(e)))
569 | if options['debug']:
570 | raise
571 |
572 | req_path_full = ''
573 | if not newuri: newuri = '/'
574 | if newuri[0] == '/':
575 | if self.is_ssl:
576 | req_path_full = "https://%s%s" % (self.request.headers['Host'], newuri)
577 | else:
578 | req_path_full = "http://%s%s" % (self.request.headers['Host'], newuri)
579 |
580 | elif newuri.startswith('http://') or newuri.startswith('https://'):
581 | self.logger.dbg(f"Plugin redirected request to a full URL: ({newuri})")
582 | req_path_full = newuri
583 | parsed = urlparse(req_path_full)
584 | newpath = ''
585 | if len(parsed.path) > 0:
586 | newpath = parsed.path
587 | else:
588 | newpath = '/'
589 |
590 | if len(parsed.query) > 0:
591 | newpath += '?' + parsed.query
592 |
593 | if len(parsed.fragment) > 0:
594 | newpath += '#' + parsed.fragment
595 |
596 | req_path_full = parsed.scheme + '://' + parsed.netloc + newpath
597 |
598 | if not req_path_full:
599 | req_path_full = newuri
600 |
601 | u = urlparse(req_path_full)
602 | scheme, netloc, path = u.scheme, u.netloc, (u.path + '?' + u.query if u.query else u.path)
603 |
604 | if netloc == '':
605 | netloc = inbound_origin
606 |
607 | origin = (scheme, inbound_origin)
608 | neworigin = (scheme, netloc)
609 | res_msg_hdrs = {}
610 |
611 | class MyResponse(http.client.HTTPResponse):
612 | def __init__(self, req, origreq):
613 | self.headers = {}
614 | self.msg = self.headers
615 | self.response_version = origreq.protocol_version
616 |
617 | if req != None:
618 | self.status = req.status_code
619 | self.headers = req.headers.copy()
620 | self.reason = req.reason
621 | else:
622 | if hasattr(origreq, 'status'): self.status = origreq.status
623 | else: self.status = 0
624 |
625 | if hasattr(origreq, 'reason'): self.reason = origreq.reason
626 | else: self.reason = ''
627 |
628 | if hasattr(origreq, 'headers'): self.headers = origreq.headers.copy()
629 | else: self.headers = {}
630 |
631 | if not dont_fetch_response:
632 | try:
633 | assert scheme in ('http', 'https')
634 |
635 | fetchurl = req_path_full.replace(netloc, outbound_origin)
636 |
637 | ip = ''
638 | try:
639 | #ip = socket.gethostbyname(urlparse(fetchurl).netloc)
640 | ip = socket.gethostbyname(outbound_origin)
641 |
642 | except:
643 | ip = urlparse(fetchurl).netloc
644 | if not ip:
645 | ip = outbound_origin
646 |
647 | if ':' in ip:
648 | ip = ip.split(':')[0]
649 |
650 | if plugins.IProxyPlugin.proxy2_metadata_headers['ignore_response_decompression_errors'] in self.request.headers.keys():
651 | ignore_response_decompression_errors = True
652 |
653 | #if (ip == self.server_address or ip in self.all_server_addresses) or \
654 | if (outbound_origin != '' and outbound_origin == inbound_origin) and \
655 | (ip == self.server_address or ip in self.all_server_addresses):
656 | self.logger.dbg(f'About to catch reverse-proxy loop detection: outbound_origin: {outbound_origin}, ip: {ip}, server_address: {self.server_address}')
657 | return self.reverse_proxy_loop_detected(self.request.method, fetchurl, self.request.body)
658 |
659 | reqhdrskeys = [x.lower() for x in self.request.headers.keys()]
660 | if plugins.IProxyPlugin.proxy2_metadata_headers['override_host_header'].lower() in reqhdrskeys:
661 | if 'Host' not in self.request.headers.keys():
662 | self.request.headers['Host'] = self.request.host
663 | self.set_header('Host', self.request.host)
664 |
665 | o = self.request.headers['Host']
666 | n = self.request.headers[plugins.IProxyPlugin.proxy2_metadata_headers['override_host_header']]
667 | self.logger.dbg(f'Plugin overidden host header: [{o}] => [{n}]')
668 | fetchurl = fetchurl.replace(o, n)
669 |
670 | while 'Host' in self.request.headers.keys():
671 | del self.request.headers['Host']
672 |
673 | self.request.headers['Host'] = n
674 |
675 | #ProxyRequestHandler.filter_headers(self.request.headers, self.logger)
676 | req_body = ''
677 | if self.request.body == None: req_body = ''
678 | else:
679 | try:
680 | if type(self.request.body) == bytes:
681 | req_body = self.request.body
682 | else:
683 | req_body = self.request.body.encode()
684 |
685 | except UnicodeDecodeError:
686 | pass
687 | except AttributeError:
688 | pass
689 |
690 | new_req_headers = self.request.headers.copy()
691 | #del new_req_headers['Host']
692 |
693 | if plugins.IProxyPlugin.proxy2_metadata_headers['domain_front_host_header'] in new_req_headers.keys():
694 | if 'Host' in new_req_headers.keys():
695 | del new_req_headers['Host']
696 |
697 | self.logger.dbg('Adjusting Host header for Domain-Fronting needs as requested by Plugin')
698 | new_req_headers['Host'] = self.request.headers[plugins.IProxyPlugin.proxy2_metadata_headers['domain_front_host_header']]
699 |
700 | fetchurl = req_path_full.replace(netloc, outbound_origin)
701 | self.logger.dbg('DEBUG REQUESTS: request("{}", "{}", "{}", ...'.format(
702 | self.request.method, fetchurl, req_body.decode(errors='ignore')[:30].strip()
703 | ))
704 |
705 | myreq = None
706 | try:
707 | myreq = requests.request(
708 | method = self.request.method,
709 | url = fetchurl,
710 | data = req_body,
711 | headers = new_req_headers,
712 | timeout = self.options['timeout'],
713 | allow_redirects = False,
714 | stream = ignore_response_decompression_errors,
715 | verify = False
716 | )
717 |
718 | except Exception as e:
719 | self.logger.err(f'COULD NOT FETCH RESPONSE FROM REMOTE AGENT: {e}')
720 |
721 | if self.options['debug']:
722 | raise
723 |
724 | res = MyResponse(myreq, self)
725 | self.response_headers = res.headers
726 | res_msg_hdrs = res.msg.copy()
727 |
728 | if len(res.msg) == 0 and len(res.headers) > 0:
729 | res_msg_hdrs = res.headers.copy()
730 |
731 | res_body = ""
732 | if ignore_response_decompression_errors:
733 | res_body = myreq.raw.read()
734 | else:
735 | res_body = myreq.content
736 |
737 | self.logger.dbg("Response from reverse-proxy fetch came at {} bytes.".format(len(res_body)))
738 |
739 | if 'Content-Length' not in res.headers.keys() and len(res_body) != 0:
740 | res.headers['Content-Length'] = str(len(res_body))
741 | self.response_length = len(res_body)
742 |
743 | myreq.close()
744 |
745 | if type(res_body) == str: res_body = str.encode(res_body)
746 |
747 | except requests.exceptions.ConnectionError as e:
748 | self.logger.err("Exception occured while reverse-proxy fetching resource : URL({}).\nException: ({})".format(
749 | fetchurl, str(e)
750 | ))
751 |
752 | self.request.connection.no_keep_alive = True
753 |
754 | if res == None:
755 | res = MyResponse(None, self)
756 |
757 | self.response_headers = res.headers
758 | self._send_error(502)
759 | #if options['debug']: raise
760 | return
761 |
762 | except Exception as e:
763 | self.logger.err("Could not proxy request: ({})".format(str(e)))
764 | if 'RemoteDisconnected' in str(e) or 'Read timed out' in str(e):
765 | return
766 |
767 | if res == None:
768 | res = MyResponse(None, self)
769 |
770 | self.request.connection.no_keep_alive = True
771 | self.response_headers = res.headers
772 | self._send_error(502)
773 | if options['debug']: raise
774 | return
775 |
776 | setattr(res, 'headers', res_msg_hdrs)
777 | self.response_headers = res_msg_hdrs
778 |
779 | content_encoding = res.headers.get('Content-Encoding', 'identity')
780 | if ignore_response_decompression_errors:
781 | content_encoding = 'identity'
782 |
783 | res_body_plain = self.decode_content_body(res_body, content_encoding)
784 |
785 | else:
786 | self.logger.dbg("Response deliberately not fetched as for plugin's request.")
787 |
788 | self.request.uri = origuri
789 |
790 | (modified, res_body_modified) = self.response_handler(
791 | self.request, self.request.body, res, res_body_plain
792 | )
793 |
794 | newuri = self.request.uri
795 | self.request.uri = origuri
796 |
797 | if type(modified) == bool:
798 | modified |= (newuri != origuri)
799 |
800 | if modified:
801 | self.logger.dbg('Plugin has modified the response body. Using it instead')
802 | res_body_plain = res_body_modified
803 | res_body = self.encode_content_body(res_body_plain, content_encoding)
804 |
805 | reshdrs = [x.lower() for x in res.headers.keys()]
806 | if 'content-length' in reshdrs: del res.headers['Content-Length']
807 |
808 | try:
809 | res.headers['Content-Length'] = str(len(res_body))
810 | self.response_length = len(res_body)
811 | except Exception as e:
812 | self.logger.dbg("Could not set proper Content-Length as running len on res_body failed")
813 |
814 | if 'Transfer-Encoding' in res.headers.keys() and \
815 | res.headers['Transfer-Encoding'] == 'chunked':
816 | del res.headers['Transfer-Encoding']
817 |
818 | if (not ignore_response_decompression_errors) and ('Accept-Encoding' in self.request.headers.keys()):
819 | encToUse = self.request.headers['Accept-Encoding'].split(' ')[0].replace(',','')
820 |
821 | override_resp_enc = plugins.IProxyPlugin.proxy2_metadata_headers['override_response_content_encoding']
822 |
823 | if override_resp_enc in res.headers.keys():
824 | self.logger.dbg('Plugin asked to override response content encoding without changing header\'s value.')
825 | self.logger.dbg('Yielding content in {} whereas header pointing at: {}'.format(
826 | res.headers[override_resp_enc], self.request.headers['Accept-Encoding']))
827 | enc = res.headers[override_resp_enc]
828 | del res.headers[override_resp_enc]
829 |
830 | else:
831 | encs = [x.strip() for x in self.request.headers['Accept-Encoding'].split(',')]
832 | if content_encoding not in encs:
833 | reencoded = False
834 | for enc in encs:
835 | if enc in ProxyRequestHandler.SUPPORTED_ENCODINGS:
836 | encToUse = encs[0]
837 | reencoded = True
838 | break
839 | if not reencoded:
840 | self.logger.err("Server returned response encoded in {} but client expected one of: {} - we couldn't handle any of these. The client will receive INCORRECTLY formatted response!".format(
841 | res.headers.get('Content-Encoding', 'identity'),
842 | ','.join(encs)
843 | ))
844 |
845 | self.logger.dbg('Encoding response body to: {}'.format(encToUse))
846 | res_body = self.encode_content_body(res_body, encToUse)
847 | reskeys = [x.lower() for x in res.headers.keys()]
848 | if 'content-length' in reskeys: del res.headers['Content-Length']
849 | if 'content-encoding' in reskeys: del res.headers['Content-Encoding']
850 | res.headers['Content-Length'] = str(len(res_body))
851 | self.response_length = len(res_body)
852 | res.headers['Content-Encoding'] = encToUse
853 |
854 | if 'DropConnectionException' in str(res_body) or 'DontFetchResponseException' in str(res_body):
855 | res_body = ''
856 |
857 | if type(res_body) == str: res_body = str.encode(res_body)
858 |
859 | #ProxyRequestHandler.filter_headers(res.headers, self.logger)
860 | res_headers = res.headers
861 | self.response_status = res.status
862 | self.response_reason = res.reason
863 | self.response_headers = res.headers
864 |
865 | ka = 'no' if self.request.connection.no_keep_alive else 'yes'
866 |
867 | if plugins.IProxyPlugin.proxy2_metadata_headers['keep_alive_this_connection'] in res.headers.keys():
868 | self.request.connection.no_keep_alive = False
869 | ka = 'yes'
870 |
871 | self.logger.info('[RESPONSE] HTTP {} {}, length: {}, keep-alive: {}'.format(res.status, res.reason, len(res_body), ka), color=ProxyLogger.colors_map['yellow'])
872 |
873 | self._set_status(res.status, res.reason)
874 |
875 | for k, v in res_headers.items():
876 | if k in plugins.IProxyPlugin.proxy2_metadata_headers.values(): continue
877 |
878 | self.set_header(k, v)
879 |
880 | try:
881 | self.response_length = len(res_body)
882 | self.write(res_body)
883 |
884 | if options['debug']:
885 | if originChanged:
886 | del self.request.headers['Host']
887 | if plugins.IProxyPlugin.proxy2_metadata_headers['override_host_header'] in self.request.headers.keys():
888 | outbound_origin = self.request.headers[plugins.IProxyPlugin.proxy2_metadata_headers['override_host_header']]
889 |
890 | self.request.headers['Host'] = outbound_origin
891 | self.save_handler(self.request, self.request.body, res, res_body_plain)
892 |
893 | except BrokenPipeError as e:
894 | self.logger.err("Broken pipe. Client must have disconnected/timed-out.")
895 |
896 | @staticmethod
897 | def filter_headers(headers, logger):
898 | # http://tools.ietf.org/html/rfc2616#section-13.5.1
899 | hop_by_hop = (
900 | 'connection',
901 | 'keep-alive',
902 | 'proxy-authenticate',
903 | 'proxy-authorization',
904 | 'te',
905 | 'trailers',
906 | 'transfer-encoding',
907 | 'upgrade'
908 | )
909 | for k in hop_by_hop:
910 | if k in headers.keys():
911 | del headers[k]
912 | return headers
913 |
914 | def encode_content_body(self, text, encoding):
915 | logger.dbg('Encoding content to {}'.format(encoding))
916 | data = text
917 | if encoding == 'identity':
918 | pass
919 | elif encoding in ('gzip', 'x-gzip'):
920 | _io = BytesIO()
921 | with gzip.GzipFile(fileobj=_io, mode='wb') as f:
922 | f.write(text)
923 | data = _io.getvalue()
924 | elif encoding == 'deflate':
925 | data = zlib.compress(text)
926 | elif encoding == 'br':
927 | # Brotli algorithm
928 | try:
929 | data = brotli.compress(text)
930 | except Exception as e:
931 | #raise Exception('Could not compress Brotli stream: "{}"'.format(str(e)))
932 | logger.err('Could not compress Brotli stream: "{}"'.format(str(e)))
933 | else:
934 | #raise Exception("Unknown Content-Encoding: %s" % encoding)
935 | logger.err('Unknown Content-Encoding: "{}"'.format(encoding))
936 | return data
937 |
938 | def decode_content_body(self, data, encoding):
939 | self.logger.dbg('Decoding content from {}'.format(encoding))
940 | text = data
941 | if encoding == 'identity':
942 | pass
943 | elif encoding in ('gzip', 'x-gzip'):
944 | try:
945 | _io = BytesIO(data)
946 | with gzip.GzipFile(fileobj=_io) as f:
947 | text = f.read()
948 | except:
949 | return data
950 | elif encoding == 'deflate':
951 | try:
952 | text = zlib.decompress(data)
953 | except zlib.error:
954 | text = zlib.decompress(data, -zlib.MAX_WBITS)
955 | elif encoding == 'br':
956 | # Brotli algorithm
957 | try:
958 | text = brotli.decompress(data)
959 | except Exception as e:
960 | #raise Exception('Could not decompress Brotli stream: "{}"'.format(str(e)))
961 | self.logger.err('Could not decompress Brotli stream: "{}"'.format(str(e)))
962 | else:
963 | #raise Exception("Unknown Content-Encoding: %s" % encoding)
964 | self.logger.err('Unknown Content-Encoding: "{}"'.format(encoding))
965 | return text
966 |
967 | def send_cacert(self):
968 | with open(self.options['cacert'], 'rb') as f:
969 | data = f.read()
970 |
971 | self._set_status(200)
972 | self.set_header('Content-Type', 'application/x-x509-ca-cert')
973 | self.set_header('Content-Length', len(data))
974 | self.set_header('Connection', 'close')
975 |
976 | self.response_length = len(data)
977 | self.write(data)
978 |
979 | def print_info(self, req, req_body, res, res_body):
980 | def _parse_qsl(s):
981 | return '\n'.join("%-20s %s" % (k, v) for k, v in parse_qsl(s, keep_blank_values=True))
982 |
983 | if not options['debug']:
984 | return
985 |
986 | req_header_text = "%s %s %s\n%s" % (req.method, req.uri, self.request_version, req.headers)
987 |
988 | if res is not None:
989 | reshdrs = res.headers
990 |
991 | if type(reshdrs) == dict or 'CaseInsensitiveDict' in str(type(reshdrs)):
992 | reshdrs = ''
993 | for k, v in res.headers.items():
994 | if k in plugins.IProxyPlugin.proxy2_metadata_headers.values(): continue
995 | if k.lower().startswith('x-proxy2-'): continue
996 | reshdrs += '{}: {}\n'.format(k, v)
997 |
998 | res_header_text = "%s %d %s\n%s" % (res.response_version, res.status, res.reason, reshdrs)
999 |
1000 | self.logger.trace("==== REQUEST ====\n%s" % req_header_text, color=ProxyLogger.colors_map['yellow'])
1001 |
1002 | u = urlparse(req.uri)
1003 | if u.query:
1004 | query_text = _parse_qsl(u.query)
1005 | self.logger.trace("==== QUERY PARAMETERS ====\n%s\n" % query_text, color=ProxyLogger.colors_map['green'])
1006 |
1007 | cookie = req.headers.get('Cookie', '')
1008 | if cookie:
1009 | cookie = _parse_qsl(re.sub(r';\s*', '&', cookie))
1010 | self.logger.trace("==== COOKIES ====\n%s\n" % cookie, color=ProxyLogger.colors_map['green'])
1011 |
1012 | auth = req.headers.get('Authorization', '')
1013 | if auth.lower().startswith('basic'):
1014 | token = auth.split()[1].decode('base64')
1015 | self.logger.trace("==== BASIC AUTH ====\n%s\n" % token, color=ProxyLogger.colors_map['red'])
1016 |
1017 | if req_body is not None:
1018 | req_body_text = None
1019 | content_type = req.headers.get('Content-Type', '')
1020 |
1021 | if content_type.startswith('application/x-www-form-urlencoded'):
1022 | req_body_text = _parse_qsl(req_body)
1023 | elif content_type.startswith('application/json'):
1024 | try:
1025 | json_obj = json.loads(req_body)
1026 | json_str = json.dumps(json_obj, indent=2)
1027 | if json_str.count('\n') < 50:
1028 | req_body_text = json_str
1029 | else:
1030 | lines = json_str.splitlines()
1031 | req_body_text = "%s\n(%d lines)" % ('\n'.join(lines[:50]), len(lines))
1032 | except ValueError:
1033 | req_body_text = req_body
1034 | elif len(req_body) < 1024:
1035 | req_body_text = req_body
1036 |
1037 | if req_body_text:
1038 | self.logger.trace("==== REQUEST BODY ====\n%s\n" % req_body_text.strip(), color=ProxyLogger.colors_map['white'])
1039 |
1040 | if res is not None:
1041 | self.logger.trace("\n==== RESPONSE ====\n%s" % res_header_text, color=ProxyLogger.colors_map['cyan'])
1042 |
1043 | cookies = res.headers.get('Set-Cookie')
1044 | if cookies:
1045 | if type(cookies) == list or type(cookies) == tuple:
1046 | cookies = '\n'.join(cookies)
1047 |
1048 | self.logger.trace("==== SET-COOKIE ====\n%s\n" % cookies, color=ProxyLogger.colors_map['yellow'])
1049 |
1050 | if res_body is not None:
1051 | res_body_text = res_body
1052 | content_type = res.headers.get('Content-Type', '')
1053 |
1054 | if content_type.startswith('application/json'):
1055 | try:
1056 | json_obj = json.loads(res_body)
1057 | json_str = json.dumps(json_obj, indent=2)
1058 | if json_str.count('\n') < 50:
1059 | res_body_text = json_str
1060 | else:
1061 | lines = json_str.splitlines()
1062 | res_body_text = "%s\n(%d lines)" % ('\n'.join(lines[:50]), len(lines))
1063 | except ValueError:
1064 | res_body_text = res_body
1065 | elif content_type.startswith('text/html'):
1066 | if type(res_body) == str: res_body = str.encode(res_body)
1067 | m = re.search(r']*>\s*([^<]+?)\s*', res_body.decode(errors='ignore'), re.I)
1068 | if m:
1069 | self.logger.trace("==== HTML TITLE ====\n%s\n" % html.unescape(m.group(1)), color=ProxyLogger.colors_map['cyan'])
1070 | elif content_type.startswith('text/') and len(res_body) < 1024:
1071 | res_body_text = res_body
1072 |
1073 | if res_body_text:
1074 | res_body_text2 = ''
1075 | maxchars = 4096
1076 | halfmax = int(maxchars/2)
1077 | try:
1078 | if type(res_body_text) == bytes:
1079 | dec = res_body_text.decode()
1080 | else:
1081 | dec = res_body_text
1082 |
1083 | if dec != None and len(dec) > maxchars:
1084 | res_body_text2 = dec[:halfmax] + ' <<< ... >>> ' + dec[-halfmax:]
1085 | else:
1086 | res_body_text2 = dec
1087 |
1088 | except UnicodeDecodeError:
1089 | if len(res_body_text) > maxchars:
1090 | res_body_text2 = hexdump(list(res_body_text[:halfmax]))
1091 | res_body_text2 += '\n\t................\n'
1092 | res_body_text2 += hexdump(list(res_body_text[-halfmax:]))
1093 | else:
1094 | res_body_text2 = hexdump(list(res_body_text))
1095 |
1096 | self.logger.trace("==== RESPONSE BODY ====\n%s\n" % res_body_text2, color=ProxyLogger.colors_map['green'])
1097 |
1098 | def request_handler(self, req, req_body):
1099 | altered = False
1100 | req_body_current = req_body
1101 |
1102 | for plugin_name in self.plugins:
1103 | instance = self.plugins[plugin_name]
1104 | try:
1105 | handler = getattr(instance, 'request_handler')
1106 | #self.logger.dbg("Calling `request_handler' from plugin %s" % plugin_name)
1107 | origheaders = dict(req.headers).copy()
1108 |
1109 | req_body_current = handler(req, req_body_current)
1110 |
1111 | altered = (req_body != req_body_current and req_body_current is not None)
1112 | if req_body_current == None: req_body_current = req_body
1113 | for k, v in origheaders.items():
1114 | if k not in req.headers.keys():
1115 | altered = True
1116 |
1117 | elif origheaders[k] != req.headers[k]:
1118 | #self.logger.dbg('Plugin modified request header: "{}", from: "{}" to: "{}"'.format(
1119 | # k, origheaders[k], req.headers[k]))
1120 | altered = True
1121 |
1122 | except AttributeError as e:
1123 | if 'object has no attribute' in str(e):
1124 | self.logger.dbg('Plugin "{}" does not implement `request_handler\''.format(plugin_name))
1125 | if options['debug']:
1126 | raise
1127 | else:
1128 | self.logger.err("Plugin {} has thrown an exception: '{}'".format(plugin_name, str(e)))
1129 | if options['debug']:
1130 | raise
1131 |
1132 | return (altered, req_body_current)
1133 |
1134 | def response_handler(self, req, req_body, res, res_body):
1135 | res_body_current = res_body
1136 | altered = False
1137 |
1138 | for plugin_name in self.plugins:
1139 | instance = self.plugins[plugin_name]
1140 | try:
1141 | handler = getattr(instance, 'response_handler')
1142 | #self.logger.dbg("Calling `response_handler' from plugin %s" % plugin_name)
1143 | origheaders = {}
1144 | try:
1145 | origheaders = res.headers.copy()
1146 | except: pass
1147 |
1148 | res_body_current = handler(req, req_body, res, res_body_current)
1149 |
1150 | altered = (res_body_current != res_body)
1151 | for k, v in origheaders.items():
1152 | if origheaders[k] != res.headers[k]:
1153 | #self.logger.dbg('Plugin modified response header: "{}", from: "{}" to: "{}"'.format(
1154 | # k, origheaders[k], res.headers[k]))
1155 | altered = True
1156 |
1157 | if len(origheaders.keys()) != len(res.headers.keys()):
1158 | #self.logger.dbg('Plugin modified response headers.')
1159 | altered = True
1160 |
1161 | if altered:
1162 | self.logger.dbg('Plugin has altered the response.')
1163 | except AttributeError as e:
1164 | raise
1165 | if 'object has no attribute' in str(e):
1166 | self.logger.dbg('Plugin "{}" does not implement `response_handler\''.format(plugin_name))
1167 | else:
1168 | self.logger.err("Plugin {} has thrown an exception: '{}'".format(plugin_name, str(e)))
1169 | if options['debug']:
1170 | raise
1171 |
1172 | if not altered:
1173 | return (False, res_body)
1174 |
1175 | return (True, res_body_current)
1176 |
1177 | def save_handler(self, req, req_body, res, res_body):
1178 | self.print_info(req, req_body, res, res_body)
1179 |
1180 | async def get(self, *args, **kwargs):
1181 | self.my_handle_request()
1182 |
1183 | async def post(self, *args, **kwargs):
1184 | self.my_handle_request()
1185 |
1186 | async def head(self, *args, **kwargs):
1187 | self.my_handle_request()
1188 |
1189 | async def options(self, *args, **kwargs):
1190 | self.my_handle_request()
1191 |
1192 | async def put(self, *args, **kwargs):
1193 | self.my_handle_request()
1194 |
1195 | async def delete(self, *args, **kwargs):
1196 | self.my_handle_request()
1197 |
1198 | async def patch(self, *args, **kwargs):
1199 | self.my_handle_request()
1200 |
1201 | async def propfind(self, *args, **kwargs):
1202 | self.my_handle_request()
1203 |
1204 | async def connect(self, *args, **kwargs):
1205 | self.my_handle_request()
1206 |
1207 |
1208 | def init(opts, VERSION):
1209 | global options
1210 | global pluginsloaded
1211 | global logger
1212 | global sslintercept
1213 |
1214 | options = opts.copy()
1215 |
1216 | lib.optionsparser.parse_options(options, VERSION)
1217 | logger = ProxyLogger(options)
1218 | pluginsloaded = PluginsLoader(logger, options)
1219 | sslintercept = SSLInterception(logger, options)
1220 |
1221 | if options['log'] and options['log'] != None and options['log'] != sys.stdout:
1222 | if options['tee']:
1223 | logger.info("Teeing stdout output to {} log file.".format(options['log']))
1224 | else:
1225 | logger.info("Writing output to {} log file.".format(options['log']))
1226 |
1227 | monkeypatching(logger)
1228 |
1229 | for name, plugin in pluginsloaded.get_plugins().items():
1230 | plugin.logger = logger
1231 | plugin.help(None)
1232 |
1233 | return (options, logger)
1234 |
1235 | def cleanup():
1236 | global options
1237 |
1238 | # Close logging file descriptor unless it's stdout
1239 | #if options['log'] and options['log'] not in (sys.stdout, 'none'):
1240 | # options['log'].close()
1241 | # options['log'] = None
1242 |
1243 | if sslintercept:
1244 | sslintercept.cleanup()
1245 |
--------------------------------------------------------------------------------
/lib/proxylogger.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # To be used as a default proxy logging facility.
4 |
5 | import time
6 | import sys, os
7 | import threading
8 |
9 | globalLock = threading.Lock()
10 |
11 | class ProxyLogger:
12 | options = {
13 | 'debug': False,
14 | 'verbose': False,
15 | 'tee': False,
16 | 'log': sys.stdout,
17 | }
18 |
19 | colors_map = {
20 | 'red': 31,
21 | 'green': 32,
22 | 'yellow': 33,
23 | 'blue': 34,
24 | 'magenta': 35,
25 | 'cyan': 36,
26 | 'white': 30,
27 | 'grey': 37,
28 | }
29 |
30 | colors_dict = {
31 | 'error': colors_map['red'],
32 | 'trace': colors_map['magenta'],
33 | 'info ': colors_map['green'],
34 | 'debug': colors_map['grey'],
35 | 'other': colors_map['grey'],
36 | }
37 |
38 | def __init__(self, options = None):
39 | if options != None:
40 | self.options.update(options)
41 |
42 | @staticmethod
43 | def with_color(c, s):
44 | return "\x1b[1;{}m{}\x1b[0m".format(c, s)
45 |
46 |
47 | # Invocation:
48 | # def out(txt, mode='info ', fd=None, color=None, noprefix=False, newline=True):
49 | @staticmethod
50 | def out(txt, fd, mode='info ', **kwargs):
51 | if txt == None or fd == 'none':
52 | return
53 | elif fd == None:
54 | raise Exception('[ERROR] Logging descriptor has not been specified!')
55 |
56 | args = {
57 | 'color': None,
58 | 'noprefix': False,
59 | 'newline': True,
60 | }
61 | args.update(kwargs)
62 |
63 | if args['color']:
64 | col = args['color']
65 | if type(col) == str and col in ProxyLogger.colors_map.keys():
66 | col = ProxyLogger.colors_map[col]
67 | else:
68 | col = ProxyLogger.colors_dict.setdefault(mode, ProxyLogger.colors_map['grey'])
69 |
70 | tm = str(time.strftime("%Y-%m-%d/%H:%M:%S", time.gmtime()))
71 |
72 | prefix = ''
73 | if mode:
74 | mode = '[%s] ' % mode
75 |
76 | if not args['noprefix']:
77 | prefix = ProxyLogger.with_color(ProxyLogger.colors_dict['other'], '%s%s: '
78 | % (mode.upper(), tm))
79 |
80 | nl = ''
81 | if 'newline' in args:
82 | if args['newline']:
83 | nl = '\n'
84 |
85 | if type(fd) == str:
86 | prefix2 = '%s%s: ' % (mode.upper(), tm)
87 | line = prefix2 + txt + nl
88 | ProxyLogger.writeToLogfile(fd, line)
89 |
90 | if 'tee' in args.keys() and args['tee']:
91 | with globalLock:
92 | sys.stdout.write(prefix + ProxyLogger.with_color(col, txt) + nl)
93 | else:
94 | with globalLock:
95 | fd.write(prefix + ProxyLogger.with_color(col, txt) + nl)
96 |
97 | @staticmethod
98 | def writeToLogfile(fd, line):
99 | with globalLock:
100 | with open(fd, 'a') as f:
101 | f.write(line)
102 | f.flush()
103 |
104 | # Info shall be used as an ordinary logging facility, for every desired output.
105 | def info(self, txt, forced = False, **kwargs):
106 | if self.options['tee']:
107 | kwargs['tee'] = True
108 | if forced or (self.options['verbose'] or self.options['debug']):
109 | ProxyLogger.out(txt, self.options['log'], 'info', **kwargs)
110 |
111 | # Trace by default does not uses [TRACE] prefix. Shall be used
112 | # for dumping packets, headers, metadata and longer technical output.
113 | def trace(self, txt, **kwargs):
114 | if self.options['tee']:
115 | kwargs['tee'] = True
116 |
117 | if self.options['debug']:
118 | kwargs['noprefix'] = True
119 | ProxyLogger.out(txt, self.options['log'], 'trace', **kwargs)
120 |
121 | def dbg(self, txt, **kwargs):
122 | if self.options['tee']:
123 | kwargs['tee'] = True
124 | if self.options['debug']:
125 | ProxyLogger.out(txt, self.options['log'], 'debug', **kwargs)
126 |
127 | def err(self, txt, **kwargs):
128 | if self.options['tee']:
129 | kwargs['tee'] = True
130 | ProxyLogger.out(txt, self.options['log'], 'error', **kwargs)
131 |
132 | def fatal(self, txt, **kwargs):
133 | if self.options['tee']:
134 | kwargs['tee'] = True
135 | ProxyLogger.out(txt, self.options['log'], 'error', **kwargs)
136 | os._exit(1)
137 |
--------------------------------------------------------------------------------
/lib/sslintercept.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | #import shutil
4 | import glob
5 | import os
6 | from subprocess import Popen, PIPE
7 |
8 | class SSLInterception:
9 |
10 | def __init__(self, logger, options):
11 | self.logger = logger
12 | self.options = options
13 | self.status = False
14 |
15 | self.dontRemove = []
16 |
17 | if not options['no_ssl']:
18 | self.setup()
19 |
20 | def setup(self):
21 | def _setup(self):
22 | self.logger.dbg('Setting up SSL interception certificates')
23 |
24 | if not os.path.isabs(self.options['certdir']):
25 | self.logger.dbg('Certificate directory path was not absolute. Assuming relative to current programs\'s directory')
26 | path = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.options['certdir'])
27 | self.options['certdir'] = path
28 | self.logger.dbg('Using path: "%s"' % self.options['certdir'])
29 |
30 | # Step 1: Create directory for certificates and asynchronous encryption keys
31 | if not os.path.isdir(self.options['certdir']):
32 | try:
33 | self.logger.dbg("Creating directory for certificate: '%s'" % self.options['certdir'])
34 | os.mkdir(self.options['certdir'])
35 | except Exception as e:
36 | self.logger.fatal("Couldn't make directory for certificates: '%s'" % e)
37 | return False
38 |
39 | # Step 2: Create CA key
40 | if not self.options['cakey']:
41 | self.options['cakey'] = os.path.join(self.options['certdir'], 'ca.key')
42 |
43 | if not os.path.isdir(self.options['cakey']):
44 | self.logger.dbg("Creating CA key file: '%s'" % self.options['cakey'])
45 | p = Popen(["openssl", "genrsa", "-out", self.options['cakey'], "2048"], stdout=PIPE, stderr=PIPE)
46 | (out, error) = p.communicate()
47 | self.logger.dbg(out + error)
48 |
49 | if not self.options['cakey']:
50 | self.logger.fatal('Creating of CA key process has failed.')
51 | return False
52 | else:
53 | self.dontRemove.append(self.options['cakey'])
54 | self.logger.info('Using provided CA key file: {}'.format(self.options['cakey']))
55 |
56 | # Step 3: Create CA certificate
57 | if not self.options['cacert']:
58 | self.options['cacert'] = os.path.join(self.options['certdir'], 'ca.crt')
59 |
60 | if not os.path.isdir(self.options['cacert']):
61 | self.logger.dbg("Creating CA certificate file: '%s'" % self.options['cacert'])
62 | p = Popen(["openssl", "req", "-new", "-x509", "-days", "3650", "-key", self.options['cakey'], "-out", self.options['cacert'], "-subj", "/CN="+self.options['cacn']], stdout=PIPE, stderr=PIPE)
63 | (out, error) = p.communicate()
64 | self.logger.dbg(out + error)
65 |
66 | if not self.options['cacert']:
67 | self.logger.fatal('Creating of CA certificate process has failed.')
68 | return False
69 | else:
70 | self.dontRemove.append(self.options['cacert'])
71 | self.logger.info('Using provided CA certificate file: {}'.format(self.options['cacert']))
72 |
73 | # Step 4: Create certificate key file
74 | if not self.options['certkey']:
75 | self.options['certkey'] = os.path.join(self.options['certdir'], 'cert.key')
76 |
77 | if not os.path.isdir(self.options['certkey']):
78 | self.logger.dbg("Creating Certificate key file: '%s'" % self.options['certkey'])
79 | self.logger.dbg("Creating CA key file: '%s'" % self.options['cakey'])
80 | p = Popen(["openssl", "genrsa", "-out", self.options['certkey'], "2048"], stdout=PIPE, stderr=PIPE)
81 | (out, error) = p.communicate()
82 | self.logger.dbg(out + error)
83 |
84 | if not self.options['certkey'] or not os.path.isfile(self.options['certkey']):
85 | self.logger.fatal('Creating of Certificate key process has failed.')
86 | return False
87 | else:
88 | self.dontRemove.append(self.options['certkey'])
89 | self.logger.info('Using provided Certificate key: {}'.format(self.options['certkey']))
90 |
91 | self.logger.dbg('SSL interception has been setup.')
92 | return True
93 |
94 | self.logger.info('Preparing SSL certificates and keys for https traffic interception...')
95 | self.status = _setup(self)
96 | return self.status
97 |
98 | def cleanup(self):
99 | if not self.status:
100 | return
101 |
102 | try:
103 | #shutil.rmtree(self.options['certdir'])
104 |
105 | for i in range(len(self.dontRemove)):
106 | self.dontRemove[i] = os.path.abspath(self.dontRemove[i])
107 |
108 | for file in glob.glob(os.path.join(self.options['certdir'], '*.*')):
109 | absfile = os.path.abspath(file)
110 | if absfile in self.dontRemove:
111 | self.logger.dbg('SSL file not cleaned: "{}"'.format(absfile))
112 | continue
113 |
114 | self.logger.dbg('Removing old certificate: {}'.format(absfile))
115 | os.remove(absfile)
116 |
117 | self.logger.dbg('SSL interception files cleaned up.')
118 |
119 | except Exception as e:
120 | self.logger.err("Couldn't perform SSL interception files cleaning: '%s'" % e)
121 |
122 | def __str__(self):
123 | return 'SSL %sbeing intercepted.' % ('NOT ' if not self.status else '')
124 |
--------------------------------------------------------------------------------
/lib/utils.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 | #
4 |
5 | import http.client
6 | import plugins.IProxyPlugin
7 |
8 | logger = None
9 |
10 | drop_this_header = 'IN-THE-NAME-OF-REDWARDEN-REMOVE-THIS-HEADER-COMPLETELY'
11 |
12 | def hexdump(data):
13 | s = ''
14 | n = 0
15 | lines = []
16 | tableline = '-----+' + '-' * 24 + '|' \
17 | + '-' * 25 + '+' + '-' * 18 + '+\n'
18 | if isinstance(data, str):
19 | data = data.encode()
20 |
21 | if len(data) == 0:
22 | return ''
23 |
24 | for i in range(0, len(data), 16):
25 | line = ''
26 | line += '%04x | ' % (i)
27 | n += 16
28 |
29 | for j in range(n-16, n):
30 | if j >= len(data): break
31 | line += '%02x' % (data[j] & 0xff)
32 | if j % 8 == 7 and j % 16 != 15:
33 | line += '-'
34 | else:
35 | line += ' '
36 |
37 | line += ' ' * (3 * 16 + 7 - len(line)) + ' | '
38 | for j in range(n-16, n):
39 | if j >= len(data): break
40 | c = data[j] if not (data[j] < 0x20 or data[j] > 0x7e) else '.'
41 | line += '%c' % c
42 |
43 | line = line.ljust(74, ' ') + ' |'
44 | lines.append(line)
45 |
46 | return tableline + '\n'.join(lines) + '\n' + tableline
47 |
48 |
49 | def putheader_decorator(method):
50 | def new_putheader(self, header, *values):
51 | for v in values:
52 | if v == drop_this_header:
53 | return
54 |
55 | xhdrs = [x.lower() for x in plugins.IProxyPlugin.proxy2_metadata_headers.values()]
56 | if header.lower() in xhdrs:
57 | return
58 |
59 | return method(self, header, *values)
60 | return new_putheader
61 |
62 | def send_request_decorator(method):
63 | def new_send_request(self, _method, url, body, headers, encode_chunked):
64 | strips = ''
65 | headers2 = {}
66 | hdrnames = list(headers.keys())
67 | for k, v in headers.items():
68 | headers2[k.lower()] = v
69 |
70 | strip_these_headers = []
71 |
72 | if plugins.IProxyPlugin.proxy2_metadata_headers['strip_headers_during_forward'].lower() in headers2.keys():
73 | strips = headers2[plugins.IProxyPlugin.proxy2_metadata_headers['strip_headers_during_forward'].lower()]
74 | strip_these_headers = [x.strip() for x in strips.split(',')]
75 | strip_these_headers.append(plugins.IProxyPlugin.proxy2_metadata_headers['strip_headers_during_forward'])
76 |
77 | for k, v in plugins.IProxyPlugin.proxy2_metadata_headers.items():
78 | if v.lower() in headers2.keys():
79 | strip_these_headers.append(v)
80 |
81 | if len(strip_these_headers) > 0:
82 | for h in strip_these_headers:
83 | for h2 in hdrnames:
84 | if len(h2) > 0 and h.lower() == h2.lower():
85 | headers[h2] = drop_this_header
86 |
87 | if len(h) > 0 and h.lower() not in headers2.keys():
88 | headers[h] = drop_this_header
89 |
90 | headers3 = {}
91 |
92 | for k, v in headers.items():
93 | if k.lower().startswith('x-proxy2-'): continue
94 | if v == drop_this_header: continue
95 | headers3[k] = v
96 |
97 | reqhdrs = ''
98 | host = ''
99 | for k, v in headers3.items():
100 | if k.lower() == 'host': host = v
101 | if v == drop_this_header: continue
102 | reqhdrs += '\t{}: {}\r\n'.format(k, v)
103 |
104 | b = body
105 | if b != None and type(b) == bytes:
106 | b = body.decode(errors='ignore')
107 |
108 | request = '\t{} {} {}\r\n{}\r\n\t{}\n'.format(
109 | _method, url, 'HTTP/1.1', reqhdrs, b
110 | )
111 |
112 | logger.dbg('SENDING REVERSE-PROXY REQUEST to [{}]:\n\n{}'.format(host, request))
113 | return method(self, _method, url, body, headers3, encode_chunked)
114 |
115 | return new_send_request
116 |
117 | def monkeypatching(log):
118 | global logger
119 | logger = log
120 |
121 | setattr(http.client.HTTPConnection, 'putheader', putheader_decorator(http.client.HTTPConnection.putheader))
122 | setattr(http.client.HTTPConnection, '_send_request', send_request_decorator(http.client.HTTPConnection._send_request))
123 |
--------------------------------------------------------------------------------
/plugins/IProxyPlugin.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | # -*- coding: utf-8 -*-
3 |
4 | from abc import ABC, abstractmethod
5 |
6 | # These headers will be used by plugins to pass a message to the proxy,
7 | # and proxy will remove them from the output response. Keep this dict keys in lowercase.
8 | proxy2_metadata_headers = {
9 | 'override_response_content_encoding': 'X-Proxy2-Override-Response-Content-Encoding',
10 | 'strip_headers_during_forward' : 'X-Proxy2-Strip-Headers-During-Forward',
11 | 'ignore_response_decompression_errors' : 'X-Proxy2-Ignore-Response-Decompression-Errors',
12 | 'override_host_header' : 'X-Proxy2-Override-Host-Header',
13 | 'domain_front_host_header' : 'X-Proxy2-Domain-Front-Host-Header',
14 | 'keep_alive_this_connection' : 'X-Proxy2-Keep-Alive',
15 | }
16 |
17 | class DropConnectionException(Exception):
18 | def __init__(self, txt):
19 | super().__init__('DropConnectionException: ' + txt)
20 |
21 | class DontFetchResponseException(Exception):
22 | def __init__(self, txt):
23 | super().__init__('DontFetchResponseException: ' + txt)
24 |
25 | class IProxyPlugin(ABC):
26 | def __init__(self, logger, proxyOptions):
27 | super().__init__()
28 |
29 | @staticmethod
30 | @abstractmethod
31 | def get_name():
32 | return 'IProxyPlugin'
33 |
34 | @abstractmethod
35 | def help(self, parser):
36 | '''
37 | @param parser - If given, the plugin should return it's specific options using argparse
38 | interface. If not given, or passed as None - the plugin should perform it's options
39 | validation logic internally.
40 | '''
41 | pass
42 |
43 | @abstractmethod
44 | def request_handler(self, req, req_body):
45 | pass
46 |
47 | @abstractmethod
48 | def response_handler(self, req, req_body, res, res_body):
49 | pass
50 |
--------------------------------------------------------------------------------
/plugins/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mgeeky/RedWarden/04ee73b684a84353a97aa9bff2d6b0d23bd16b73/plugins/__init__.py
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | brotli
2 | requests
3 | PyYaml
4 | sqlitedict
5 | tornado
--------------------------------------------------------------------------------