Compare commits

..

19 Commits

Author SHA1 Message Date
8bdefcd10d Release 0.77.1 2016-03-07 09:46:01 +11:00
29b6e8301f Update GPL2 license text
Closes #73.
2016-03-06 17:27:02 +11:00
083293ea0d Version 0.77 2016-03-03 10:38:33 +11:00
2c07985924 Prepare documentation for release 2016-03-03 10:35:45 +11:00
756025b1bc Add date and version to docs 2016-03-03 10:30:20 +11:00
cedc8dc146 Add support for OpenBSD 2016-03-02 18:50:37 +11:00
e8047ce3a9 Fixed Python 3 issue 2016-03-02 18:38:43 +11:00
fae4cb1dbf Override the skip on lo that ends up in the chain
In some cases (see #43) it seems that some network configurations may
end up setting a skip on lo. As sshuttle adds rules that rely on
filtering/translating packets on lo, this causes problem. This fix
overrides the skip and makes the rules be applied again.
Should fix at least some of the problems reported on #43.
2016-03-02 18:36:14 +11:00
7d8309ef05 Refactor OS specific portions of PF
This will make it easier to support other platforms/versions in the
future, e.g., OpenBSD.
2016-03-02 18:04:43 +11:00
b7d37e44fb Remove legacy file 2016-03-02 12:47:45 +11:00
4a954c547a fix byte/string bug introduced in 1c46f25e
This is the error message that this commit fixes:
TypeError: sequence item 142: expected a bytes-like object, str found

Complete what 1c46f25e started, more or less.
2016-01-31 16:26:21 -05:00
4fcf7c73da Fix regression: ensure we do bind
Closes: #68
2016-01-31 19:15:02 +11:00
ba8e948c0d Don't allocate socket until we need it
Wew were trying to allocate an IPv6 socket even though we weren't using
IPv6, causing failures on systems without IPv6 support available.

This change means a number of methods on MultiListener, e.g. setsockopt,
should not be called until after the bind call.

Closes #68
2016-01-30 11:28:59 +11:00
e06f0240cb Make sure we use Python 3.5 2016-01-30 11:27:37 +11:00
517fc2c930 Remove references to number of years
Closes: #65
2016-01-21 08:42:34 +11:00
11533869a8 Fix description of excludes in Windows setup
And some subtle grammar.

Closes: #66
2016-01-21 08:38:38 +11:00
0392a779a2 Update usage documentation 2016-01-20 21:19:44 +11:00
ee26157faa Add Windows documentation
Copied from https://coderwall.com/p/adfxgw/sshuttle-on-windows

Closes #64
2016-01-20 20:55:10 +11:00
0bdfb883aa Don't distribute sshuttle/version.py
It is autogenerated.
2016-01-18 09:00:00 +11:00
17 changed files with 803 additions and 624 deletions

View File

@ -1,3 +1,20 @@
Release 0.77.1 (Mar 7, 2016)
============================
* Use semantic versioning. http://semver.org/
* Update GPL 2 license text.
* New release to fix PyPI.
Release 0.77 (Mar 3, 2016)
==========================
* Various bug fixes.
* Fix Documentation.
* Add fix for MacOS X issue.
* Add support for OpenBSD.
Release 0.76 (Jan 17, 2016) Release 0.76 (Jan 17, 2016)
=========================== ===========================

598
LICENSE
View File

@ -1,25 +1,22 @@
GNU LIBRARY GENERAL PUBLIC LICENSE GNU GENERAL PUBLIC LICENSE
Version 2, June 1991 Version 2, June 1991
Copyright (C) 1991 Free Software Foundation, Inc. Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
675 Mass Ave, Cambridge, MA 02139, USA 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed. of this license document, but changing it is not allowed.
[This is the first released version of the library GPL. It is Preamble
numbered 2 because it goes with version 2 of the ordinary GPL.]
Preamble
The licenses for most software are designed to take away your The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change License is intended to guarantee your freedom to share and change free
free software--to make sure the software is free for all its users. software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
This license, the Library General Public License, applies to some Foundation's software and to any other program whose authors commit to
specially designated Free Software Foundation software, and to any using it. (Some other Free Software Foundation software is covered by
other libraries whose authors decide to use it. You can use it for the GNU Lesser General Public License instead.) You can apply it to
your libraries, too. your programs, too.
When we speak of free software, we are referring to freedom, not When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you price. Our General Public Licenses are designed to make sure that you
@ -30,347 +27,195 @@ in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights. anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if These restrictions translate to certain responsibilities for you if you
you distribute copies of the library, or if you modify it. distribute copies of the software, or if you modify it.
For example, if you distribute copies of the library, whether gratis For example, if you distribute copies of such a program, whether
or for a fee, you must give the recipients all the rights that we gave gratis or for a fee, you must give the recipients all the rights that
you. You must make sure that they, too, receive or can get the source you have. You must make sure that they, too, receive or can get the
code. If you link a program with the library, you must provide source code. And you must show them these terms so they know their
complete object files to the recipients so that they can relink them rights.
with the library, after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
Our method of protecting your rights has two steps: (1) copyright We protect your rights with two steps: (1) copyright the software, and
the library, and (2) offer you this license which gives you legal (2) offer you this license which gives you legal permission to copy,
permission to copy, distribute and/or modify the library. distribute and/or modify the software.
Also, for each distributor's protection, we want to make certain Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free that everyone understands that there is no warranty for this free
library. If the library is modified by someone else and passed on, we software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original want its recipients to know that what they have is not the original, so
version, so that any problems introduced by others will not reflect on that any problems introduced by others will not reflect on the original
the original authors' reputations. authors' reputations.
Finally, any free program is threatened constantly by software Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that companies distributing free patents. We wish to avoid the danger that redistributors of a free
software will individually obtain patent licenses, thus in effect program will individually obtain patent licenses, in effect making the
transforming the program into proprietary software. To prevent this, program proprietary. To prevent this, we have made it clear that any
we have made it clear that any patent must be licensed for everyone's patent must be licensed for everyone's free use or not licensed at all.
free use or not licensed at all.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License, which was designed for utility programs. This
license, the GNU Library General Public License, applies to certain
designated libraries. This license is quite different from the ordinary
one; be sure to read it in full, and don't assume that anything in it is
the same as in the ordinary license.
The reason we have a separate public license for some libraries is that
they blur the distinction we usually make between modifying or adding to a
program and simply using it. Linking a program with a library, without
changing the library, is in some sense simply using the library, and is
analogous to running a utility program or application program. However, in
a textual and legal sense, the linked executable is a combined work, a
derivative of the original library, and the ordinary General Public License
treats it as such.
Because of this blurred distinction, using the ordinary General
Public License for libraries did not effectively promote software
sharing, because most developers did not use the libraries. We
concluded that weaker conditions might promote sharing better.
However, unrestricted linking of non-free programs would deprive the
users of those programs of all benefit from the free status of the
libraries themselves. This Library General Public License is intended to
permit developers of non-free programs to use free libraries, while
preserving your freedom as a user of such programs to change the free
libraries that are incorporated in them. (We have not seen how to achieve
this as regards changes in header files, but we have achieved it as regards
changes in the actual functions of the Library.) The hope is that this
will lead to faster development of free libraries.
The precise terms and conditions for copying, distribution and The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a modification follow.
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, while the latter only
works together with the library.
Note that it is possible for a library to be covered by the ordinary GNU GENERAL PUBLIC LICENSE
General Public License rather than by this special one.
GNU LIBRARY GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library which 0. This License applies to any program or other work which contains
contains a notice placed by the copyright holder or other authorized a notice placed by the copyright holder saying it may be distributed
party saying it may be distributed under the terms of this Library under the terms of this General Public License. The "Program", below,
General Public License (also called "this License"). Each licensee is refers to any such program or work, and a "work based on the Program"
addressed as "you". means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data Activities other than copying, distribution and modification are not
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from running the Program is not restricted, and the output from the Program
such a program is covered only if its contents constitute a work based is covered only if its contents constitute a work based on the
on the Library (independent of the use of the Library in a tool for Program (independent of having been made by running the Program).
writing it). Whether that is true depends on what the Library does Whether that is true depends on what the Program does.
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy, 1. You may copy and distribute verbatim copies of the Program's
and you may at your option offer warranty protection in exchange for a source code as you receive it, in any medium, provided that you
fee. conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
2. You may modify your copy or copies of the Library or any portion notices that refer to this License and to the absence of any warranty;
of it, thus forming a work based on the Library, and copy and and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1 distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions: above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library. a) You must cause the modified files to carry prominent notices
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change. stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no b) You must cause any work that you distribute or publish, that in
charge to all third parties under the terms of this License. whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a c) If the modified program normally reads commands interactively
table of data to be supplied by an application program that uses when run, you must cause it, when started running for such
the facility, other than as an argument passed when the facility interactive use in the most ordinary way, to print or display an
is invoked, then you must make a good faith effort to ensure that, announcement including an appropriate copyright notice and a
in the event an application does not supply such function or notice that there is no warranty (or else, saying that you provide
table, the facility still operates, and performs whatever part of a warranty) and that users may redistribute the program under
its purpose remains meaningful. these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
(For example, a function in a library to compute square roots has does not normally print such an announcement, your work based on
a purpose that is entirely well-defined independent of the the Program is not required to print an announcement.)
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library, identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote entire whole, and thus to each and every part regardless of who wrote it.
it.
Thus, it is not the intent of this section to claim rights or contest Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or exercise the right to control the distribution of derivative or
collective works based on the Library. collective works based on the Program.
In addition, mere aggregation of another work not based on the Library In addition, mere aggregation of another work not based on the Program
with the Library (or with a work based on the Library) on a volume of with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under a storage or distribution medium does not bring the other work under
the scope of this License. the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public 3. You may copy and distribute the Program (or a work based on it,
License instead of this License to a given copy of the Library. To do under Section 2) in object code or executable form under the terms of
this, you must alter all the notices that refer to this License, so Sections 1 and 2 above provided that you also do one of the following:
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of a) Accompany it with the complete corresponding machine-readable
the Library into a program that is not a library. source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
4. You may copy and distribute the Library (or a portion or b) Accompany it with a written offer, valid for at least three
derivative of it, under Section 2) in object code or executable form years, to give any third party, for a charge no more than your
under the terms of Sections 1 and 2 above provided that you accompany cost of physically performing source distribution, a complete
it with the complete corresponding machine-readable source code, which machine-readable copy of the corresponding source code, to be
must be distributed under the terms of Sections 1 and 2 above on a distributed under the terms of Sections 1 and 2 above on a medium
medium customarily used for software interchange. customarily used for software interchange; or,
If distribution of object code is made by offering access to copy c) Accompany it with the information you received as to the offer
from a designated place, then offering equivalent access to copy the to distribute corresponding source code. (This alternative is
source code from the same place satisfies the requirement to allowed only for noncommercial distribution and only if you
distribute the source code, even though third parties are not received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code. compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the 4. You may not copy, modify, sublicense, or distribute the Program
Library, but is designed to work with the Library by being compiled or except as expressly provided under this License. Any attempt
linked with it, is called a "work that uses the Library". Such a otherwise to copy, modify, sublicense or distribute the Program is
work, in isolation, is not a derivative work of the Library, and void, and will automatically terminate your rights under this License.
therefore falls outside the scope of this License. However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
However, linking a "work that uses the Library" with the Library 5. You are not required to accept this License, since you have not
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also compile or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
c) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
d) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the source code distributed need not include anything that is normally
distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the modifying or distributing the Program (or any work based on the
Library), you indicate your acceptance of this License to do so, and Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying all its terms and conditions for copying, distributing or modifying
the Library or works based on it. the Program or works based on it.
10. Each time you redistribute the Library (or any work based on the 6. Each time you redistribute the Program (or any work based on the
Library), the recipient automatically receives a license from the Program), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library original licensor to copy, distribute or modify the Program subject to
subject to these terms and conditions. You may not impose any further these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein. restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to You are not responsible for enforcing compliance by third parties to
this License. this License.
11. If, as a consequence of a court judgment or allegation of patent 7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues), infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library. refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any If any portion of this section is held invalid or unenforceable under
particular circumstance, the balance of the section is intended to apply, any particular circumstance, the balance of the section is intended to
and the section as a whole is intended to apply in other circumstances. apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is integrity of the free software distribution system, which is
implemented by public license practices. Many people have made implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that through that system in reliance on consistent application of that
@ -381,101 +226,114 @@ impose that choice.
This section is intended to make thoroughly clear what is believed to This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License. be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in 8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add original copyright holder who places the Program under this License
an explicit geographical distribution limitation excluding those countries, may add an explicit geographical distribution limitation excluding
so that distribution is permitted only in or among countries not thus those countries, so that distribution is permitted only in or among
excluded. In such case, this License incorporates the limitation as if countries not thus excluded. In such case, this License incorporates
written in the body of this License. the limitation as if written in the body of this License.
13. The Free Software Foundation may publish revised and/or new 9. The Free Software Foundation may publish revised and/or new versions
versions of the Library General Public License from time to time. of the General Public License from time to time. Such new versions will
Such new versions will be similar in spirit to the present version, be similar in spirit to the present version, but may differ in detail to
but may differ in detail to address new problems or concerns. address new problems or concerns.
Each version is given a distinguishing version number. If the Library Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and specifies a version number of this License which applies to it and "any
"any later version", you have the option of following the terms and later version", you have the option of following the terms and conditions
conditions either of that version or of any later version published by either of that version or of any later version published by the Free
the Free Software Foundation. If the Library does not specify a Software Foundation. If the Program does not specify a version number of
license version number, you may choose any version ever published by this License, you may choose any version ever published by the Free Software
the Free Software Foundation. Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY 10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO NO WARRANTY
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH REPAIR OR CORRECTION.
DAMAGES.
END OF TERMS AND CONDITIONS 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
Appendix: How to Apply These Terms to Your New Libraries REDISTRIBUTE 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.
If you develop a new library, and you want it to be of the greatest END OF TERMS AND CONDITIONS
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is How to Apply These Terms to Your New Programs
safest to attach them to the start of each source file to most effectively
convey 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 library's name and a brief idea of what it does.> 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
convey 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> Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or modify
modify it under the terms of the GNU Library General Public it under the terms of the GNU General Public License as published by
License as published by the Free Software Foundation; either the Free Software Foundation; either version 2 of the License, or
version 2 of the License, or (at your option) any later version. (at your option) any later version.
This library is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Library General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU Library General Public You should have received a copy of the GNU General Public License along
License along with this library; if not, write to the Free with this program; if not, write to the Free Software Foundation, Inc.,
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision 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, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names: necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the Yoyodyne, Inc., hereby disclaims all copyright interest in the program
library `Frob' (a library for tweaking knobs) written by James Random Hacker. `Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1990 <signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice Ty Coon, President of Vice
That's all there is to it! This 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.

View File

@ -5,6 +5,7 @@ include MANIFEST.in
include LICENSE include LICENSE
include run include run
include tox.ini include tox.ini
exclude sshuttle/version.py
recursive-include docs *.bat recursive-include docs *.bat
recursive-include docs *.py recursive-include docs *.py
recursive-include docs *.rst recursive-include docs *.rst

View File

@ -1 +0,0 @@
0.75

View File

@ -1,6 +1,9 @@
sshuttle: where transparent proxy meets VPN meets ssh sshuttle: where transparent proxy meets VPN meets ssh
===================================================== =====================================================
:Date: |today|
:Version: |version|
Contents: Contents:
.. toctree:: .. toctree::
@ -10,6 +13,7 @@ Contents:
requirements requirements
installation installation
usage usage
platform
Man Page <manpage> Man Page <manpage>
how-it-works how-it-works
support support

View File

@ -37,6 +37,12 @@ Options
netmask), and 0/0 ('just route everything through the netmask), and 0/0 ('just route everything through the
VPN'). VPN').
.. option:: --method [auto|nat|tproxy|pf]
Which firewall method should sshuttle use? For auto, sshuttle attempts to
guess the appropriate method depending on what it can find in PATH. The
default value is auto.
.. option:: -l, --listen=[ip:]port .. option:: -l, --listen=[ip:]port
Use this ip address and port number as the transparent Use this ip address and port number as the transparent
@ -278,7 +284,6 @@ there is no need for congestion control to be shared
between the two separate streams, so a tcp-based tunnel is between the two separate streams, so a tcp-based tunnel is
fine. fine.
.. seealso::
See Also :manpage:`ssh(1)`, :manpage:`python(1)`
--------
:manpage:`ssh(1)`, :manpage:`python(1)`

10
docs/platform.rst Normal file
View File

@ -0,0 +1,10 @@
Platform Specific Notes
=======================
Contents:
.. toctree::
:maxdepth: 2
tproxy
windows

View File

@ -37,11 +37,13 @@ Supports:
Full UDP or DNS support with the TPROXY method requires the ``recvmsg()`` Full UDP or DNS support with the TPROXY method requires the ``recvmsg()``
syscall. This is not available in Python 2, however is in Python 3.5 and syscall. This is not available in Python 2, however is in Python 3.5 and
later. Under Python 2 you might find it sufficient installing PyXAPI_ to get later. Under Python 2 you might find it sufficient installing PyXAPI_ to get
the ``recvmsg()`` function. the ``recvmsg()`` function. See :doc:`tproxy` for more information.
MacOS with PF method MacOS / FreeBSD / OpenBSD
~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~
Method: pf
Supports: Supports:
* IPv4 TCP * IPv4 TCP
@ -51,6 +53,12 @@ Requires:
* You need to have the pfctl command. * You need to have the pfctl command.
Windows
~~~~~~~
Not officially supported, however can be made to work with Vagrant. Requires
cmd.exe with Administrator access. See :doc:`windows` for more information.
Server side Requirements Server side Requirements
------------------------ ------------------------

42
docs/tproxy.rst Normal file
View File

@ -0,0 +1,42 @@
TPROXY
======
TPROXY is the only method that has full support of IPv6 and UDP.
There are some things you need to consider for TPROXY to work:
- The following commands need to be run first as root. This only needs to be
done once after booting up::
ip route add local default dev lo table 100
ip rule add fwmark 1 lookup 100
ip -6 route add local default dev lo table 100
ip -6 rule add fwmark 1 lookup 100
- The ``--auto-nets`` feature does not detect IPv6 routes automatically. Add IPv6
routes manually. e.g. by adding ``'::/0'`` to the end of the command line.
- The client needs to be run as root. e.g.::
sudo SSH_AUTH_SOCK="$SSH_AUTH_SOCK" $HOME/tree/sshuttle.tproxy/sshuttle --method=tproxy ...
- You may need to exclude the IP address of the server you are connecting to.
Otherwise sshuttle may attempt to intercept the ssh packets, which will not
work. Use the ``--exclude`` parameter for this.
- Similarly, UDP return packets (including DNS) could get intercepted and
bounced back. This is the case if you have a broad subnet such as
``0.0.0.0/0`` or ``::/0`` that includes the IP address of the client. Use the
``--exclude`` parameter for this.
- You need the ``--method=tproxy`` parameter, as above.
- The routes for the outgoing packets must already exist. For example, if your
connection does not have IPv6 support, no IPv6 routes will exist, IPv6
packets will not be generated and sshuttle cannot intercept them::
telnet -6 www.google.com 80
Trying 2404:6800:4001:805::1010...
telnet: Unable to connect to remote host: Network is unreachable
Add some dummy routes to external interfaces. Make sure they get removed
however after sshuttle exits.

View File

@ -3,7 +3,7 @@ Useless Trivia
This section written by the original author, Avery Pennarun This section written by the original author, Avery Pennarun
<apenwarr@gmail.com>. <apenwarr@gmail.com>.
Back in 1998 (12 years ago! Yikes!), I released the first version of `Tunnel Back in 1998, I released the first version of `Tunnel
Vision <http://alumnit.ca/wiki/?TunnelVisionReadMe>`_, a semi-intelligent VPN Vision <http://alumnit.ca/wiki/?TunnelVisionReadMe>`_, a semi-intelligent VPN
client for Linux. Unfortunately, I made two big mistakes: I implemented the client for Linux. Unfortunately, I made two big mistakes: I implemented the
key exchange myself (oops), and I ended up doing TCP-over-TCP (double oops). key exchange myself (oops), and I ended up doing TCP-over-TCP (double oops).
@ -31,6 +31,6 @@ intended.)
That project I did for Slipstream was what first gave me the idea to merge That project I did for Slipstream was what first gave me the idea to merge
the concepts of Fast Forward, Double Vision, and Tunnel Vision into a single the concepts of Fast Forward, Double Vision, and Tunnel Vision into a single
program that was the best of all worlds. And here we are, at last, 10 years program that was the best of all worlds. And here we are, at last.
later. You're welcome. You're welcome.

View File

@ -1,24 +1,33 @@
Usage Usage
===== =====
- Forward all traffic::
sshuttle -r username@sshserver 0.0.0.0/0 .. note::
For information on usage with Windows, see the :doc:`windows` section.
For information on using the TProxy method, see the :doc:`tproxy` section.
Forward all traffic::
sshuttle -r username@sshserver 0.0.0.0/0
- Use the :option:`sshuttle -r` parameter to specify a remote server.
- By default sshuttle will automatically choose a method to use. Override with - By default sshuttle will automatically choose a method to use. Override with
the ``--method=`` parameter. the :option:`sshuttle --method` parameter.
- There is a shortcut for 0.0.0.0/0 for those that value - There is a shortcut for 0.0.0.0/0 for those that value
their wrists:: their wrists::
sshuttle -r username@sshserver 0/0 sshuttle -r username@sshserver 0/0
- If you would also like your DNS queries to be proxied If you would also like your DNS queries to be proxied
through the DNS server of the server you are connect to:: through the DNS server of the server you are connect to::
sshuttle --dns -r username@sshserver 0/0 sshuttle --dns -r username@sshserver 0/0
The above is probably what you want to use to prevent The above is probably what you want to use to prevent
local network attacks such as Firesheep and friends. local network attacks such as Firesheep and friends.
See the documentation for the :option:`sshuttle --dns` parameter.
(You may be prompted for one or more passwords; first, the local password to (You may be prompted for one or more passwords; first, the local password to
become root using sudo, and then the remote ssh password. Or you might have become root using sudo, and then the remote ssh password. Or you might have
@ -51,45 +60,3 @@ the data back and forth through ssh.
Fun, right? A poor man's instant VPN, and you don't even have to have Fun, right? A poor man's instant VPN, and you don't even have to have
admin access on the server. admin access on the server.
Additional information for TPROXY
---------------------------------
TPROXY is the only method that supports full support of IPv6 and UDP.
There are some things you need to consider for TPROXY to work:
- The following commands need to be run first as root. This only needs to be
done once after booting up::
ip route add local default dev lo table 100
ip rule add fwmark 1 lookup 100
ip -6 route add local default dev lo table 100
ip -6 rule add fwmark 1 lookup 100
- The ``--auto-nets`` feature does not detect IPv6 routes automatically. Add IPv6
routes manually. e.g. by adding ``'::/0'`` to the end of the command line.
- The client needs to be run as root. e.g.::
sudo SSH_AUTH_SOCK="$SSH_AUTH_SOCK" $HOME/tree/sshuttle.tproxy/sshuttle --method=tproxy ...
- You may need to exclude the IP address of the server you are connecting to.
Otherwise sshuttle may attempt to intercept the ssh packets, which will not
work. Use the ``--exclude`` parameter for this.
- Similarly, UDP return packets (including DNS) could get intercepted and
bounced back. This is the case if you have a broad subnet such as
``0.0.0.0/0`` or ``::/0`` that includes the IP address of the client. Use the
``--exclude`` parameter for this.
- You need the ``--method=tproxy`` parameter, as above.
- The routes for the outgoing packets must already exist. For example, if your
connection does not have IPv6 support, no IPv6 routes will exist, IPv6
packets will not be generated and sshuttle cannot intercept them::
telnet -6 www.google.com 80
Trying 2404:6800:4001:805::1010...
telnet: Unable to connect to remote host: Network is unreachable
Add some dummy routes to external interfaces. Make sure they get removed
however after sshuttle exits.

19
docs/windows.rst Normal file
View File

@ -0,0 +1,19 @@
Microsoft Windows
=================
Currently there is no built in support for running sshuttle directly on
Microsoft Windows.
What we can really do is to create a Linux VM with Vagrant (or simply
Virtualbox if you like). In the Vagrant settings, remember to turn on bridged
NIC. Then, run sshuttle inside the VM like below::
sshuttle -l 0.0.0.0 -x 10.0.0.0/8 -x 192.168.0.0/16 0/0
10.0.0.0/8 excludes NAT traffic of Vagrant and 192.168.0.0/16 excludes
traffic to local area network (assuming that we're using 192.168.0.0 subnet).
Assuming the VM has the IP 192.168.1.200 obtained on the bridge NIC (we can
configure that in Vagrant), we can then ask Windows to route all its traffic
via the VM by running the following in cmd.exe with admin right::
route add 0.0.0.0 mask 0.0.0.0 192.168.1.200

2
run
View File

@ -1,6 +1,6 @@
#!/bin/sh #!/bin/sh
if python3.5 -V 2>/dev/null; then if python3.5 -V 2>/dev/null; then
exec python3 -m "sshuttle" "$@" exec python3.5 -m "sshuttle" "$@"
else else
exec python -m "sshuttle" "$@" exec python -m "sshuttle" "$@"
fi fi

View File

@ -95,16 +95,21 @@ def daemon_cleanup():
class MultiListener: class MultiListener:
def __init__(self, type=socket.SOCK_STREAM, proto=0): def __init__(self, type=socket.SOCK_STREAM, proto=0):
self.v6 = socket.socket(socket.AF_INET6, type, proto) self.type = type
self.v4 = socket.socket(socket.AF_INET, type, proto) self.proto = proto
self.v6 = None
self.v4 = None
self.bind_called = False
def setsockopt(self, level, optname, value): def setsockopt(self, level, optname, value):
assert(self.bind_called)
if self.v6: if self.v6:
self.v6.setsockopt(level, optname, value) self.v6.setsockopt(level, optname, value)
if self.v4: if self.v4:
self.v4.setsockopt(level, optname, value) self.v4.setsockopt(level, optname, value)
def add_handler(self, handlers, callback, method, mux): def add_handler(self, handlers, callback, method, mux):
assert(self.bind_called)
socks = [] socks = []
if self.v6: if self.v6:
socks.append(self.v6) socks.append(self.v6)
@ -119,6 +124,7 @@ class MultiListener:
) )
def listen(self, backlog): def listen(self, backlog):
assert(self.bind_called)
if self.v6: if self.v6:
self.v6.listen(backlog) self.v6.listen(backlog)
if self.v4: if self.v4:
@ -133,16 +139,23 @@ class MultiListener:
raise e raise e
def bind(self, address_v6, address_v4): def bind(self, address_v6, address_v4):
if address_v6 and self.v6: assert(not self.bind_called)
self.bind_called = True
if address_v6 is not None:
self.v6 = socket.socket(socket.AF_INET6, self.type, self.proto)
self.v6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.v6.bind(address_v6) self.v6.bind(address_v6)
else: else:
self.v6 = None self.v6 = None
if address_v4 and self.v4: if address_v4 is not None:
self.v4 = socket.socket(socket.AF_INET, self.type, self.proto)
self.v4.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.v4.bind(address_v4) self.v4.bind(address_v4)
else: else:
self.v4 = None self.v4 = None
def print_listening(self, what): def print_listening(self, what):
assert(self.bind_called)
if self.v6: if self.v6:
listenip = self.v6.getsockname() listenip = self.v6.getsockname()
debug1('%s listening on %r.\n' % (what, listenip)) debug1('%s listening on %r.\n' % (what, listenip))
@ -569,11 +582,9 @@ def main(listenip_v6, listenip_v4,
for port in ports: for port in ports:
debug2(' %d' % port) debug2(' %d' % port)
tcp_listener = MultiListener() tcp_listener = MultiListener()
tcp_listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if required.udp: if required.udp:
udp_listener = MultiListener(socket.SOCK_DGRAM) udp_listener = MultiListener(socket.SOCK_DGRAM)
udp_listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
else: else:
udp_listener = None udp_listener = None

View File

@ -11,6 +11,317 @@ from sshuttle.helpers import debug1, debug2, debug3, Fatal, family_to_string
from sshuttle.methods import BaseMethod from sshuttle.methods import BaseMethod
_pf_context = {'started_by_sshuttle': False, 'Xtoken': None}
_pf_fd = None
class Generic(object):
MAXPATHLEN = 1024
PF_CHANGE_ADD_TAIL = 2
PF_CHANGE_GET_TICKET = 6
PF_PASS = 0
PF_RDR = 8
PF_OUT = 2
ACTION_OFFSET = 0
POOL_TICKET_OFFSET = 8
ANCHOR_CALL_OFFSET = 1040
class pf_addr(Structure):
class _pfa(Union):
_fields_ = [("v4", c_uint32), # struct in_addr
("v6", c_uint32 * 4), # struct in6_addr
("addr8", c_uint8 * 16),
("addr16", c_uint16 * 8),
("addr32", c_uint32 * 4)]
_fields_ = [("pfa", _pfa)]
_anonymous_ = ("pfa",)
def __init__(self):
self.status = b''
self.pfioc_pooladdr = c_char * 1136
self.DIOCNATLOOK = (
(0x40000000 | 0x80000000) |
((sizeof(self.pfioc_natlook) & 0x1fff) << 16) |
((ord('D')) << 8) | (23))
self.DIOCCHANGERULE = (
(0x40000000 | 0x80000000) |
((sizeof(self.pfioc_rule) & 0x1fff) << 16) |
((ord('D')) << 8) | (26))
self.DIOCBEGINADDRS = (
(0x40000000 | 0x80000000) |
((sizeof(self.pfioc_pooladdr) & 0x1fff) << 16) |
((ord('D')) << 8) | (51))
def enable(self):
if b'INFO:\nStatus: Disabled' in self.status:
pfctl('-e')
_pf_context['started_by_sshuttle'] = True
def disable(self):
if _pf_context['started_by_sshuttle']:
pfctl('-d')
def query_nat(self, family, proto, src_ip, src_port, dst_ip, dst_port):
[proto, family, src_port, dst_port] = [
int(v) for v in [proto, family, src_port, dst_port]]
packed_src_ip = socket.inet_pton(family, src_ip)
packed_dst_ip = socket.inet_pton(family, dst_ip)
assert len(packed_src_ip) == len(packed_dst_ip)
length = len(packed_src_ip)
pnl = self.pfioc_natlook()
pnl.proto = proto
pnl.direction = self.PF_OUT
pnl.af = family
memmove(addressof(pnl.saddr), packed_src_ip, length)
memmove(addressof(pnl.daddr), packed_dst_ip, length)
self._add_natlook_ports(pnl, src_port, dst_port)
ioctl(pf_get_dev(), self.DIOCNATLOOK,
(c_char * sizeof(pnl)).from_address(addressof(pnl)))
ip = socket.inet_ntop(
pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw)
port = socket.ntohs(self._get_natlook_port(pnl.rdxport))
return (ip, port)
def _add_natlook_ports(self, pnl, src_port, dst_port):
pnl.sxport = socket.htons(src_port)
pnl.dxport = socket.htons(dst_port)
def _get_natlook_port(self, xport):
return xport
def add_anchors(self, status=None):
if status is None:
status = pfctl('-s all')[0]
self.status = status
if b'\nanchor "sshuttle"' not in status:
self._add_anchor_rule(self.PF_PASS, b"sshuttle")
def _add_anchor_rule(self, type, name, pr=None):
if pr is None:
pr = self.pfioc_rule()
memmove(addressof(pr) + self.ANCHOR_CALL_OFFSET, name,
min(self.MAXPATHLEN, len(name))) # anchor_call = name
memmove(addressof(pr) + self.RULE_ACTION_OFFSET,
struct.pack('I', type), 4) # rule.action = type
memmove(addressof(pr) + self.ACTION_OFFSET, struct.pack(
'I', self.PF_CHANGE_GET_TICKET), 4) # action = PF_CHANGE_GET_TICKET
ioctl(pf_get_dev(), pf.DIOCCHANGERULE, pr)
memmove(addressof(pr) + self.ACTION_OFFSET, struct.pack(
'I', self.PF_CHANGE_ADD_TAIL), 4) # action = PF_CHANGE_ADD_TAIL
ioctl(pf_get_dev(), pf.DIOCCHANGERULE, pr)
def add_rules(self, rules):
assert isinstance(rules, bytes)
debug3("rules:\n" + rules.decode("ASCII"))
pfctl('-a sshuttle -f /dev/stdin', rules)
class FreeBsd(Generic):
RULE_ACTION_OFFSET = 2968
def __new__(cls):
class pfioc_natlook(Structure):
pf_addr = Generic.pf_addr
_fields_ = [("saddr", pf_addr),
("daddr", pf_addr),
("rsaddr", pf_addr),
("rdaddr", pf_addr),
("sxport", c_uint16),
("dxport", c_uint16),
("rsxport", c_uint16),
("rdxport", c_uint16),
("af", c_uint8), # sa_family_t
("proto", c_uint8),
("proto_variant", c_uint8),
("direction", c_uint8)]
freebsd = Generic.__new__(cls)
freebsd.pfioc_rule = c_char * 3040
freebsd.pfioc_natlook = pfioc_natlook
return freebsd
def __init__(self):
super(FreeBsd, self).__init__()
def add_anchors(self):
status = pfctl('-s all')[0]
if b'\nrdr-anchor "sshuttle"' not in status:
self._add_anchor_rule(self.PF_RDR, b'sshuttle')
super(FreeBsd, self).add_anchors(status=status)
def _add_anchor_rule(self, type, name):
pr = self.pfioc_rule()
ppa = self.pfioc_pooladdr()
ioctl(pf_get_dev(), self.DIOCBEGINADDRS, ppa)
# pool ticket
memmove(addressof(pr) + self.POOL_TICKET_OFFSET, ppa[4:8], 4)
super(FreeBsd, self)._add_anchor_rule(type, name, pr=pr)
def add_rules(self, includes, port, dnsport, nslist):
tables = [
b'table <forward_subnets> {%s}' % b','.join(includes)
]
translating_rules = [
b'rdr pass on lo0 proto tcp '
b'to <forward_subnets> -> 127.0.0.1 port %r' % port
]
filtering_rules = [
b'pass out route-to lo0 inet proto tcp '
b'to <forward_subnets> keep state'
]
if len(nslist) > 0:
tables.append(
b'table <dns_servers> {%s}' %
b','.join([ns[1].encode("ASCII") for ns in nslist]))
translating_rules.append(
b'rdr pass on lo0 proto udp to '
b'<dns_servers> port 53 -> 127.0.0.1 port %r' % dnsport)
filtering_rules.append(
b'pass out route-to lo0 inet proto udp to '
b'<dns_servers> port 53 keep state')
rules = b'\n'.join(tables + translating_rules + filtering_rules) \
+ b'\n'
super(FreeBsd, self).add_rules(rules)
class OpenBsd(Generic):
POOL_TICKET_OFFSET = 4
RULE_ACTION_OFFSET = 3324
ANCHOR_CALL_OFFSET = 1036
def __init__(self):
class pfioc_natlook(Structure):
pf_addr = Generic.pf_addr
_fields_ = [("saddr", pf_addr),
("daddr", pf_addr),
("rsaddr", pf_addr),
("rdaddr", pf_addr),
("rdomain", c_uint16),
("rrdomain", c_uint16),
("sxport", c_uint16),
("dxport", c_uint16),
("rsxport", c_uint16),
("rdxport", c_uint16),
("af", c_uint8), # sa_family_t
("proto", c_uint8),
("proto_variant", c_uint8),
("direction", c_uint8)]
self.pfioc_rule = c_char * 3400
self.pfioc_natlook = pfioc_natlook
super(OpenBsd, self).__init__()
def add_anchors(self):
# before adding anchors and rules we must override the skip lo
# that comes by default in openbsd pf.conf so the rules we will add,
# which rely on translating/filtering packets on lo, can work
pfctl('-f /dev/stdin', b'match on lo\n')
super(OpenBsd, self).add_anchors()
def add_rules(self, includes, port, dnsport, nslist):
tables = [
b'table <forward_subnets> {%s}' % b','.join(includes)
]
translating_rules = [
b'pass in on lo0 inet proto tcp '
b'divert-to 127.0.0.1 port %r' % port
]
filtering_rules = [
b'pass out inet proto tcp '
b'to <forward_subnets> route-to lo0 keep state'
]
if len(nslist) > 0:
tables.append(
b'table <dns_servers> {%s}' %
b','.join([ns[1].encode("ASCII") for ns in nslist]))
translating_rules.append(
b'pass in on lo0 inet proto udp to <dns_servers>'
b'port 53 rdr-to 127.0.0.1 port %r' % dnsport)
filtering_rules.append(
b'pass out inet proto udp to '
b'<dns_servers> port 53 route-to lo0 keep state')
rules = b'\n'.join(tables + translating_rules + filtering_rules) \
+ b'\n'
super(OpenBsd, self).add_rules(rules)
class Darwin(FreeBsd):
RULE_ACTION_OFFSET = 3068
def __init__(self):
class pf_state_xport(Union):
_fields_ = [("port", c_uint16),
("call_id", c_uint16),
("spi", c_uint32)]
class pfioc_natlook(Structure):
pf_addr = Generic.pf_addr
_fields_ = [("saddr", pf_addr),
("daddr", pf_addr),
("rsaddr", pf_addr),
("rdaddr", pf_addr),
("sxport", pf_state_xport),
("dxport", pf_state_xport),
("rsxport", pf_state_xport),
("rdxport", pf_state_xport),
("af", c_uint8), # sa_family_t
("proto", c_uint8),
("proto_variant", c_uint8),
("direction", c_uint8)]
self.pfioc_rule = c_char * 3104
self.pfioc_natlook = pfioc_natlook
super(Darwin, self).__init__()
def enable(self):
o = pfctl('-E')
_pf_context['Xtoken'] = \
re.search(b'Token : (.+)', o[1]).group(1)
def disable(self):
if _pf_context['Xtoken'] is not None:
pfctl('-X %s' % _pf_context['Xtoken'].decode("ASCII"))
def add_anchors(self):
# before adding anchors and rules we must override the skip lo
# that in some cases ends up in the chain so the rules we will add,
# which rely on translating/filtering packets on lo, can work
pfctl('-f /dev/stdin', b'pass on lo\n')
super(Darwin, self).add_anchors()
def _add_natlook_ports(self, pnl, src_port, dst_port):
pnl.sxport.port = socket.htons(src_port)
pnl.dxport.port = socket.htons(dst_port)
def _get_natlook_port(self, xport):
return xport.port
if sys.platform == 'darwin':
pf = Darwin()
elif sys.platform.startswith('openbsd'):
pf = OpenBsd()
else:
pf = FreeBsd()
def pfctl(args, stdin=None): def pfctl(args, stdin=None):
argv = ['pfctl'] + list(args.split(" ")) argv = ['pfctl'] + list(args.split(" "))
debug1('>> %s\n' % ' '.join(argv)) debug1('>> %s\n' % ' '.join(argv))
@ -24,87 +335,6 @@ def pfctl(args, stdin=None):
return o return o
_pf_context = {'started_by_sshuttle': False, 'Xtoken': None}
_pf_fd = None
class OsDefs(object):
def __init__(self, platform=None):
if platform is None:
platform = sys.platform
self.platform = platform
# This are some classes and functions used to support pf in yosemite.
if platform == 'darwin':
class pf_state_xport(Union):
_fields_ = [("port", c_uint16),
("call_id", c_uint16),
("spi", c_uint32)]
else:
class pf_state_xport(Union):
_fields_ = [("port", c_uint16),
("call_id", c_uint16)]
class pf_addr(Structure):
class _pfa(Union):
_fields_ = [("v4", c_uint32), # struct in_addr
("v6", c_uint32 * 4), # struct in6_addr
("addr8", c_uint8 * 16),
("addr16", c_uint16 * 8),
("addr32", c_uint32 * 4)]
_fields_ = [("pfa", _pfa)]
_anonymous_ = ("pfa",)
class pfioc_natlook(Structure):
_fields_ = [("saddr", pf_addr),
("daddr", pf_addr),
("rsaddr", pf_addr),
("rdaddr", pf_addr),
("sxport", pf_state_xport),
("dxport", pf_state_xport),
("rsxport", pf_state_xport),
("rdxport", pf_state_xport),
("af", c_uint8), # sa_family_t
("proto", c_uint8),
("proto_variant", c_uint8),
("direction", c_uint8)]
self.pfioc_natlook = pfioc_natlook
# sizeof(struct pfioc_rule)
self.pfioc_rule = c_char * \
(3104 if platform == 'darwin' else 3040)
# sizeof(struct pfioc_pooladdr)
self.pfioc_pooladdr = c_char * 1136
self.MAXPATHLEN = 1024
self.DIOCNATLOOK = (
(0x40000000 | 0x80000000) |
((sizeof(pfioc_natlook) & 0x1fff) << 16) |
((ord('D')) << 8) | (23))
self.DIOCCHANGERULE = (
(0x40000000 | 0x80000000) |
((sizeof(self.pfioc_rule) & 0x1fff) << 16) |
((ord('D')) << 8) | (26))
self.DIOCBEGINADDRS = (
(0x40000000 | 0x80000000) |
((sizeof(self.pfioc_pooladdr) & 0x1fff) << 16) |
((ord('D')) << 8) | (51))
self.PF_CHANGE_ADD_TAIL = 2
self.PF_CHANGE_GET_TICKET = 6
self.PF_PASS = 0
self.PF_RDR = 8
self.PF_OUT = 2
osdefs = OsDefs()
def pf_get_dev(): def pf_get_dev():
global _pf_fd global _pf_fd
@ -114,59 +344,6 @@ def pf_get_dev():
return _pf_fd return _pf_fd
def pf_query_nat(family, proto, src_ip, src_port, dst_ip, dst_port):
[proto, family, src_port, dst_port] = [
int(v) for v in [proto, family, src_port, dst_port]]
packed_src_ip = socket.inet_pton(family, src_ip)
packed_dst_ip = socket.inet_pton(family, dst_ip)
assert len(packed_src_ip) == len(packed_dst_ip)
length = len(packed_src_ip)
pnl = osdefs.pfioc_natlook()
pnl.proto = proto
pnl.direction = osdefs.PF_OUT
pnl.af = family
memmove(addressof(pnl.saddr), packed_src_ip, length)
memmove(addressof(pnl.daddr), packed_dst_ip, length)
pnl.sxport.port = socket.htons(src_port)
pnl.dxport.port = socket.htons(dst_port)
ioctl(pf_get_dev(), osdefs.DIOCNATLOOK,
(c_char * sizeof(pnl)).from_address(addressof(pnl)))
ip = socket.inet_ntop(
pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw)
port = socket.ntohs(pnl.rdxport.port)
return (ip, port)
def pf_add_anchor_rule(type, name):
ACTION_OFFSET = 0
POOL_TICKET_OFFSET = 8
ANCHOR_CALL_OFFSET = 1040
RULE_ACTION_OFFSET = 3068 if osdefs.platform == 'darwin' else 2968
pr = osdefs.pfioc_rule()
ppa = osdefs.pfioc_pooladdr()
ioctl(pf_get_dev(), osdefs.DIOCBEGINADDRS, ppa)
memmove(addressof(pr) + POOL_TICKET_OFFSET, ppa[4:8], 4) # pool_ticket
memmove(addressof(pr) + ANCHOR_CALL_OFFSET, name,
min(osdefs.MAXPATHLEN, len(name))) # anchor_call = name
memmove(addressof(pr) + RULE_ACTION_OFFSET,
struct.pack('I', type), 4) # rule.action = type
memmove(addressof(pr) + ACTION_OFFSET, struct.pack(
'I', osdefs.PF_CHANGE_GET_TICKET), 4) # action = PF_CHANGE_GET_TICKET
ioctl(pf_get_dev(), osdefs.DIOCCHANGERULE, pr)
memmove(addressof(pr) + ACTION_OFFSET, struct.pack(
'I', osdefs.PF_CHANGE_ADD_TAIL), 4) # action = PF_CHANGE_ADD_TAIL
ioctl(pf_get_dev(), osdefs.DIOCCHANGERULE, pr)
class Method(BaseMethod): class Method(BaseMethod):
@ -214,45 +391,9 @@ class Method(BaseMethod):
snet.encode("ASCII"), snet.encode("ASCII"),
swidth)) swidth))
tables.append( pf.add_anchors()
b'table <forward_subnets> {%s}' % b','.join(includes)) pf.add_rules(includes, port, dnsport, nslist)
translating_rules.append( pf.enable()
b'rdr pass on lo0 proto tcp '
b'to <forward_subnets> -> 127.0.0.1 port %r' % port)
filtering_rules.append(
b'pass out route-to lo0 inet proto tcp '
b'to <forward_subnets> keep state')
if len(nslist) > 0:
tables.append(
b'table <dns_servers> {%s}' %
b','.join([ns[1].encode("ASCII") for ns in nslist]))
translating_rules.append(
b'rdr pass on lo0 proto udp to '
b'<dns_servers> port 53 -> 127.0.0.1 port %r' % dnsport)
filtering_rules.append(
b'pass out route-to lo0 inet proto udp to '
b'<dns_servers> port 53 keep state')
rules = b'\n'.join(tables + translating_rules + filtering_rules) \
+ b'\n'
assert isinstance(rules, bytes)
debug3("rules:\n" + rules.decode("ASCII"))
pf_status = pfctl('-s all')[0]
if b'\nrdr-anchor "sshuttle" all\n' not in pf_status:
pf_add_anchor_rule(osdefs.PF_RDR, b"sshuttle")
if b'\nanchor "sshuttle" all\n' not in pf_status:
pf_add_anchor_rule(osdefs.PF_PASS, b"sshuttle")
pfctl('-a sshuttle -f /dev/stdin', rules)
if osdefs.platform == "darwin":
o = pfctl('-E')
_pf_context['Xtoken'] = \
re.search(b'Token : (.+)', o[1]).group(1)
elif b'INFO:\nStatus: Disabled' in pf_status:
pfctl('-e')
_pf_context['started_by_sshuttle'] = True
def restore_firewall(self, port, family, udp): def restore_firewall(self, port, family, udp):
if family != socket.AF_INET: if family != socket.AF_INET:
@ -263,16 +404,12 @@ class Method(BaseMethod):
raise Exception("UDP not supported by pf method_name") raise Exception("UDP not supported by pf method_name")
pfctl('-a sshuttle -F all') pfctl('-a sshuttle -F all')
if osdefs.platform == "darwin": pf.disable()
if _pf_context['Xtoken'] is not None:
pfctl('-X %s' % _pf_context['Xtoken'].decode("ASCII"))
elif _pf_context['started_by_sshuttle']:
pfctl('-d')
def firewall_command(self, line): def firewall_command(self, line):
if line.startswith('QUERY_PF_NAT '): if line.startswith('QUERY_PF_NAT '):
try: try:
dst = pf_query_nat(*(line[13:].split(','))) dst = pf.query_nat(*(line[13:].split(',')))
sys.stdout.write('QUERY_PF_NAT_SUCCESS %s,%r\n' % dst) sys.stdout.write('QUERY_PF_NAT_SUCCESS %s,%r\n' % dst)
except IOError as e: except IOError as e:
sys.stdout.write('QUERY_PF_NAT_FAILURE %s\n' % e) sys.stdout.write('QUERY_PF_NAT_FAILURE %s\n' % e)

View File

@ -257,7 +257,7 @@ def main(latency_control):
if lines[-1]: if lines[-1]:
# no terminating newline: entry isn't complete yet! # no terminating newline: entry isn't complete yet!
hw.leftover = lines.pop() hw.leftover = lines.pop()
lines.append('') lines.append(b'')
else: else:
hw.leftover = b'' hw.leftover = b''
mux.send(0, ssnet.CMD_HOST_LIST, b'\n'.join(lines)) mux.send(0, ssnet.CMD_HOST_LIST, b'\n'.join(lines))

View File

@ -4,7 +4,7 @@ import socket
from sshuttle.methods import get_method from sshuttle.methods import get_method
from sshuttle.helpers import Fatal from sshuttle.helpers import Fatal
from sshuttle.methods.pf import OsDefs from sshuttle.methods.pf import FreeBsd, Darwin, OpenBsd
def test_get_supported_features(): def test_get_supported_features():
@ -85,7 +85,7 @@ def test_assert_features():
method.assert_features(features) method.assert_features(features)
@patch('sshuttle.methods.pf.osdefs', OsDefs('darwin')) @patch('sshuttle.methods.pf.pf', Darwin())
@patch('sshuttle.methods.pf.sys.stdout') @patch('sshuttle.methods.pf.sys.stdout')
@patch('sshuttle.methods.pf.ioctl') @patch('sshuttle.methods.pf.ioctl')
@patch('sshuttle.methods.pf.pf_get_dev') @patch('sshuttle.methods.pf.pf_get_dev')
@ -108,11 +108,11 @@ def test_firewall_command_darwin(mock_pf_get_dev, mock_ioctl, mock_stdout):
] ]
@patch('sshuttle.methods.pf.osdefs', OsDefs('notdarwin')) @patch('sshuttle.methods.pf.pf', FreeBsd())
@patch('sshuttle.methods.pf.sys.stdout') @patch('sshuttle.methods.pf.sys.stdout')
@patch('sshuttle.methods.pf.ioctl') @patch('sshuttle.methods.pf.ioctl')
@patch('sshuttle.methods.pf.pf_get_dev') @patch('sshuttle.methods.pf.pf_get_dev')
def test_firewall_command_notdarwin(mock_pf_get_dev, mock_ioctl, mock_stdout): def test_firewall_command_freebsd(mock_pf_get_dev, mock_ioctl, mock_stdout):
method = get_method('pf') method = get_method('pf')
assert not method.firewall_command("somthing") assert not method.firewall_command("somthing")
@ -131,6 +131,29 @@ def test_firewall_command_notdarwin(mock_pf_get_dev, mock_ioctl, mock_stdout):
] ]
@patch('sshuttle.methods.pf.pf', OpenBsd())
@patch('sshuttle.methods.pf.sys.stdout')
@patch('sshuttle.methods.pf.ioctl')
@patch('sshuttle.methods.pf.pf_get_dev')
def test_firewall_command_openbsd(mock_pf_get_dev, mock_ioctl, mock_stdout):
method = get_method('pf')
assert not method.firewall_command("somthing")
command = "QUERY_PF_NAT %d,%d,%s,%d,%s,%d\n" % (
socket.AF_INET, socket.IPPROTO_TCP,
"127.0.0.1", 1025, "127.0.0.2", 1024)
assert method.firewall_command(command)
assert mock_pf_get_dev.mock_calls == [call()]
assert mock_ioctl.mock_calls == [
call(mock_pf_get_dev(), 0xc0504417, ANY),
]
assert mock_stdout.mock_calls == [
call.write('QUERY_PF_NAT_SUCCESS 0.0.0.0,0\n'),
call.flush(),
]
def pfctl(args, stdin=None): def pfctl(args, stdin=None):
if args == '-s all': if args == '-s all':
return (b'INFO:\nStatus: Disabled\nanother mary had a little lamb\n', return (b'INFO:\nStatus: Disabled\nanother mary had a little lamb\n',
@ -141,7 +164,7 @@ def pfctl(args, stdin=None):
@patch('sshuttle.helpers.verbose', new=3) @patch('sshuttle.helpers.verbose', new=3)
@patch('sshuttle.methods.pf.osdefs', OsDefs('darwin')) @patch('sshuttle.methods.pf.pf', Darwin())
@patch('sshuttle.methods.pf.pfctl') @patch('sshuttle.methods.pf.pfctl')
@patch('sshuttle.methods.pf.ioctl') @patch('sshuttle.methods.pf.ioctl')
@patch('sshuttle.methods.pf.pf_get_dev') @patch('sshuttle.methods.pf.pf_get_dev')
@ -192,6 +215,7 @@ def test_setup_firewall_darwin(mock_pf_get_dev, mock_ioctl, mock_pfctl):
call(mock_pf_get_dev(), 0xCC20441A, ANY), call(mock_pf_get_dev(), 0xCC20441A, ANY),
] ]
assert mock_pfctl.mock_calls == [ assert mock_pfctl.mock_calls == [
call('-f /dev/stdin', b'pass on lo\n'),
call('-s all'), call('-s all'),
call('-a sshuttle -f /dev/stdin', call('-a sshuttle -f /dev/stdin',
b'table <forward_subnets> {!1.2.3.66/32,1.2.3.0/24}\n' b'table <forward_subnets> {!1.2.3.66/32,1.2.3.0/24}\n'
@ -222,11 +246,11 @@ def test_setup_firewall_darwin(mock_pf_get_dev, mock_ioctl, mock_pfctl):
@patch('sshuttle.helpers.verbose', new=3) @patch('sshuttle.helpers.verbose', new=3)
@patch('sshuttle.methods.pf.osdefs', OsDefs('notdarwin')) @patch('sshuttle.methods.pf.pf', FreeBsd())
@patch('sshuttle.methods.pf.pfctl') @patch('sshuttle.methods.pf.pfctl')
@patch('sshuttle.methods.pf.ioctl') @patch('sshuttle.methods.pf.ioctl')
@patch('sshuttle.methods.pf.pf_get_dev') @patch('sshuttle.methods.pf.pf_get_dev')
def test_setup_firewall_notdarwin(mock_pf_get_dev, mock_ioctl, mock_pfctl): def test_setup_firewall_freebsd(mock_pf_get_dev, mock_ioctl, mock_pfctl):
mock_pfctl.side_effect = pfctl mock_pfctl.side_effect = pfctl
method = get_method('pf') method = get_method('pf')
@ -300,3 +324,80 @@ def test_setup_firewall_notdarwin(mock_pf_get_dev, mock_ioctl, mock_pfctl):
mock_pf_get_dev.reset_mock() mock_pf_get_dev.reset_mock()
mock_pfctl.reset_mock() mock_pfctl.reset_mock()
mock_ioctl.reset_mock() mock_ioctl.reset_mock()
@patch('sshuttle.helpers.verbose', new=3)
@patch('sshuttle.methods.pf.pf', OpenBsd())
@patch('sshuttle.methods.pf.pfctl')
@patch('sshuttle.methods.pf.ioctl')
@patch('sshuttle.methods.pf.pf_get_dev')
def test_setup_firewall_openbsd(mock_pf_get_dev, mock_ioctl, mock_pfctl):
mock_pfctl.side_effect = pfctl
method = get_method('pf')
assert method.name == 'pf'
with pytest.raises(Exception) as excinfo:
method.setup_firewall(
1024, 1026,
[(10, u'2404:6800:4004:80c::33')],
10,
[(10, 64, False, u'2404:6800:4004:80c::'),
(10, 128, True, u'2404:6800:4004:80c::101f')],
True)
assert str(excinfo.value) \
== 'Address family "AF_INET6" unsupported by pf method_name'
assert mock_pf_get_dev.mock_calls == []
assert mock_ioctl.mock_calls == []
assert mock_pfctl.mock_calls == []
with pytest.raises(Exception) as excinfo:
method.setup_firewall(
1025, 1027,
[(2, u'1.2.3.33')],
2,
[(2, 24, False, u'1.2.3.0'), (2, 32, True, u'1.2.3.66')],
True)
assert str(excinfo.value) == 'UDP not supported by pf method_name'
assert mock_pf_get_dev.mock_calls == []
assert mock_ioctl.mock_calls == []
assert mock_pfctl.mock_calls == []
method.setup_firewall(
1025, 1027,
[(2, u'1.2.3.33')],
2,
[(2, 24, False, u'1.2.3.0'), (2, 32, True, u'1.2.3.66')],
False)
assert mock_ioctl.mock_calls == [
call(mock_pf_get_dev(), 0xcd48441a, ANY),
call(mock_pf_get_dev(), 0xcd48441a, ANY),
]
assert mock_pfctl.mock_calls == [
call('-f /dev/stdin', b'match on lo\n'),
call('-s all'),
call('-a sshuttle -f /dev/stdin',
b'table <forward_subnets> {!1.2.3.66/32,1.2.3.0/24}\n'
b'table <dns_servers> {1.2.3.33}\n'
b'pass in on lo0 inet proto tcp divert-to 127.0.0.1 port 1025\n'
b'pass in on lo0 inet proto udp to '
b'<dns_servers>port 53 rdr-to 127.0.0.1 port 1027\n'
b'pass out inet proto tcp to '
b'<forward_subnets> route-to lo0 keep state\n'
b'pass out inet proto udp to '
b'<dns_servers> port 53 route-to lo0 keep state\n'),
call('-e'),
]
mock_pf_get_dev.reset_mock()
mock_ioctl.reset_mock()
mock_pfctl.reset_mock()
method.restore_firewall(1025, 2, False)
assert mock_ioctl.mock_calls == []
assert mock_pfctl.mock_calls == [
call('-a sshuttle -F all'),
call("-d"),
]
mock_pf_get_dev.reset_mock()
mock_pfctl.reset_mock()
mock_ioctl.reset_mock()