Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Rouli
2013-03-18 14:24:13 +02:00
58 changed files with 1061 additions and 2370 deletions

View File

@@ -2,5 +2,5 @@
branch = True
[report]
omit = *contrib*, *tnetstring*, *platform*
omit = *contrib*, *tnetstring*, *platform*, *console*
include = *libmproxy*

1
.gitignore vendored
View File

@@ -3,6 +3,7 @@ MANIFEST
/dist
/tmp
/doc
/venv
*.py[cdo]
*.swp
*.swo

View File

@@ -1,18 +1,32 @@
485 Aldo Cortesi
18 Henrik Nordstrom
13 Thomas Roth
11 Stephen Altamirano
6 András Veres-Szentkirályi
4 Valtteri Virtanen
2 alts
2 Michael Frister
2 Mark E. Haase
2 Heikki Hannikainen
1 meeee
1 capt8bit
1 Yuangxuan Wang
1 Ulrich Petri
1 Rune Halvorsen
1 Rory McCann
1 Henrik Nordström
1 Felix Wolfsteller
730 Aldo Cortesi
18 Henrik Nordstrom
13 Thomas Roth
11 Stephen Altamirano
10 András Veres-Szentkirályi
6 Alexis Hildebrandt
4 Maximilian Hils
4 Bryan Bishop
4 Valtteri Virtanen
4 Rouli
3 Chris Neasbitt
2 Rob Wills
2 Jim Lloyd
2 alts
2 Mark E. Haase
2 israel
2 Michael Frister
2 Heikki Hannikainen
1 phil plante
1 Andy Smith
1 Felix Wolfsteller
1 Henrik Nordström
1 Jakub Nawalaniec
1 Mathieu Mitchell
1 Paul
1 Rory McCann
1 Rune Halvorsen
1 Sahn Lam
1 Ulrich Petri
1 Yuangxuan Wang
1 capt8bit
1 meeee

709
LICENSE
View File

@@ -1,690 +1,19 @@
mitmproxy is licensed under the terms of the GNU General Public
License version 3, with the following addition:
In addition, as a special exception, the copyright holders give
permission to link the code of this program or portions of this
program with the OpenSSL project's "OpenSSL" library (or with modified
versions of it that use the same license as the "OpenSSL" library),
and distribute linked combinations including the two.
You must obey the GNU General Public License in all respects for all
of the code used other than "OpenSSL". If you modify file(s) provided
under this license, you may extend this exception to your version of
the file, but you are not obligated to do so. If you do not wish to do
so, delete this exception statement from your version.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
Copyright (c) 2013, Aldo Cortesi. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -50,7 +50,7 @@ Requirements
------------
* [Python](http://www.python.org) 2.7.x.
* [netlib](http://pypi.python.org/pypi/netlib) 0.2.2 or newer.
* [netlib](http://pypi.python.org/pypi/netlib), version matching mitmproxy.
* [PyOpenSSL](http://pypi.python.org/pypi/pyOpenSSL) 0.13 or newer.
* [pyasn1](http://pypi.python.org/pypi/pyasn1) 0.1.2 or newer.
* [urwid](http://excess.org/urwid/) version 1.1 or newer.
@@ -67,7 +67,5 @@ Hacking
The following components are needed if you plan to hack on mitmproxy:
* The test suite uses the [nose](http://readthedocs.org/docs/nose/en/latest/) unit testing
framework and requires [human_curl](https://github.com/Lispython/human_curl),
[pathod](http://pathod.org) and [flask](http://flask.pocoo.org/).
framework and requires [pathod](http://pathod.org) and [flask](http://flask.pocoo.org/).
* Rendering the documentation requires [countershape](http://github.com/cortesi/countershape).

File diff suppressed because one or more lines are too long

View File

@@ -1,16 +1,12 @@
.terminal {
color: #c0c0c0;
font-size: 1em;
background: #000000;
body {
padding-top: 60px;
padding-bottom: 40px;
}
pre {
margin-top: 10px;
color: #333;
}
.tablenum {
font-weight: bold;
}
.nowrap {
white-space: nowrap;
}

View File

@@ -1,6 +1,6 @@
<div class="navbar">
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
@@ -12,15 +12,14 @@
</div>
</div>
<div class="container-fluid">
<div class="row-fluid">
<div class="container">
<div class="row">
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
$!nav("index.html", this, state)!$
$!nav("install.html", this, state)!$
$!nav("howmitmproxy.html", this, state)!$
$!nav("faq.html", this, state)!$
<li class="nav-header">Tools</li>
$!nav("mitmproxy.html", this, state)!$
@@ -38,12 +37,13 @@
$!nav("reverseproxy.html", this, state)!$
$!nav("upstreamcerts.html", this, state)!$
<li class="nav-header">SSL interception</li>
<li class="nav-header">Installing Certificates</li>
$!nav("ssl.html", this, state)!$
$!nav("certinstall/firefox.html", this, state)!$
$!nav("certinstall/osx.html", this, state)!$
$!nav("certinstall/windows7.html", this, state)!$
$!nav("certinstall/ios.html", this, state)!$
$!nav("certinstall/ios-simulator.html", this, state)!$
$!nav("certinstall/android.html", this, state)!$
<li class="nav-header">Transparent Proxying</li>
@@ -68,13 +68,11 @@
</div>
$!body!$
</div>
</div><!--/row-->
</div>
<hr>
<footer>
<p>@!copyright!@</p>
</footer>
</div><!--/.fluid-container-->
</div>

View File

@@ -1,42 +1,83 @@
<a href="http://github.com/cortesi/mitmproxy"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://d3nwyuy0nl342s.cloudfront.net/img/e6bef7a091f5f3138b8cd40bc3e114258dd68ddf/687474703a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub"></a>
<div class="yui-t7" id="doc">
<div style="" id="hd">
<div class="HorizontalNavBar">
<ul>
<li class="inactive"><a href="@!urlTo("/index.html")!@">home</a></li>
<li class="active"><a href="@!urlTo("doc/index.html")!@">docs</a></li>
<li class="inactive"><a href="@!urlTo("/about.html")!@">about</a></li>
</ul>
</div>
<h1><a href="@!urlTo("/index.html")!@">mitmproxy</a> </h1>
<br>
<p>an SSL-capable man-in-the-middle proxy</p>
</div>
<div id="bd">
<div id="yui-main">
<div style="" class="yui-b">
<!--(block nav)-->
<div id="nav">
<!--(block pb)-->
<a href="@!urlTo(previous)!@">prev</a>
<!--(end)-->
<!--(block nb)-->
<a href="@!urlTo(next)!@">next</a>
<!--(end)-->
$!pb if previous and not previous.parent.root else "prev"!$ |
<a href="@!urlTo('doc/index.html')!@">index</a> |
$!nb if next and not next.parent.root else "next"!$
</div>
<!--(end)-->
$!nav if this.title!="docs" else ""!$
$!title if this.title!="docs" else "<h1>mitmproxy 0.9 docs</h1>"!$
$!body!$
</div>
</div>
</div>
<div style="" id="ft">
<p>Copyright 2011 Aldo Cortesi</p>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="@!urlTo("/index.html")!@">mitmproxy</a>
<div class="nav">
<ul class="nav">
<li $!'class="active"' if this.match("/index.html", True) else ""!$> <a href="@!top!@/index.html">home</a> </li>
<li $!'class="active"' if this.under("/doc") else ""!$><a href="@!top!@/doc/index.html">docs</a></li>
<li $!'class="active"' if this.under("/about.html") else ""!$><a href="@!top!@/about.html">about</a></li>
</ul>
</div>
</div>
</div>
</div>
$!ga!$
<div class="container">
<div class="row">
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
$!nav("/doc/index.html", this, state)!$
$!nav("install.html", this, state)!$
$!nav("howmitmproxy.html", this, state)!$
<li class="nav-header">Tools</li>
$!nav("mitmproxy.html", this, state)!$
$!nav("mitmdump.html", this, state)!$
<li class="nav-header">Features</li>
$!nav("anticache.html", this, state)!$
$!nav("clientreplay.html", this, state)!$
$!nav("filters.html", this, state)!$
$!nav("proxyauth.html", this, state)!$
$!nav("replacements.html", this, state)!$
$!nav("serverreplay.html", this, state)!$
$!nav("setheaders.html", this, state)!$
$!nav("sticky.html", this, state)!$
$!nav("reverseproxy.html", this, state)!$
$!nav("upstreamcerts.html", this, state)!$
<li class="nav-header">SSL interception</li>
$!nav("ssl.html", this, state)!$
$!nav("certinstall/firefox.html", this, state)!$
$!nav("certinstall/osx.html", this, state)!$
$!nav("certinstall/windows7.html", this, state)!$
$!nav("certinstall/ios.html", this, state)!$
$!nav("certinstall/android.html", this, state)!$
<li class="nav-header">Transparent Proxying</li>
$!nav("transparent.html", this, state)!$
$!nav("transparent/linux.html", this, state)!$
$!nav("transparent/osx.html", this, state)!$
<li class="nav-header">Tutorials</li>
$!nav("tutorials/30second.html", this, state)!$
$!nav("tutorials/gamecenter.html", this, state)!$
<li class="nav-header">Scripting mitmproxy</li>
$!nav("scripting/inlinescripts.html", this, state)!$
$!nav("scripting/libmproxy.html", this, state)!$
</ul>
</div>
</div>
<div class="span9">
<div class="page-header">
<h1>@!this.title!@</h1>
</div>
$!body!$
</div>
</div>
<hr>
<footer>
<p>@!copyright!@</p>
</footer>
</div>

View File

@@ -12,23 +12,21 @@ We used an Asus Transformer Prime TF201 with Android 4.0.3 in the examples
below - your device may differ, but the broad process should be similar.
Installing the mitmproxy certificate
====================================
## Getting the certificate onto the device
The first step is to install mitmproxy's interception certificate on the
Android device. In your ~/.mitmproxy directory, there is a file called
__mitmproxy-ca-cert.cer__ - we need to transfer this file to
__/sdcard/Downloads__ on the Android device. If this file doesn't exist for
you, your certs were generated with an older version of mitmproxy - just copy
the __mitmproxy-ca-cert.pem__ file to __mitmproxy-ca-cert.cer__ and proceed
from there.
In this case, we're using wget from Better Terminal Emulator Pro to transfer
the certificate from a local HTTP server. Other terminal applications may work,
and you might also transfer the file via external media like an SDcard:
First we need to get the __mitmproxy-ca-cert.cer__ file into the
__/sdcard/Downloads__ folder on the device. There are a number of ways to do
this. If you have the Android Developer Tools installed, you can use [__adb
push__](http://developer.android.com/tools/help/adb.html) to accomplish this.
Depending on your device, you could also transfer the file using external media
like an SD Card. In this example, we're using wget from within a terminal
emulator to transfer the certificate from a local HTTP server:
<img src="android-shellwgetmitmproxyca.png"/>
## Installing the certificate
Once we have the certificate on the local disk, we need to import it into the
list of trusted CAs. Go to Settings -&gt; Security -&gt; Credential Storage,
and select "Install from storage":
@@ -46,8 +44,3 @@ store:
<img src="android-settingssecurityuserinstalledca.png"/>
If you're lucky enough to be working with an app that obeys the wireless proxy
settings, you're just about done - simply configure the settings to point at
mitmproxy. If not, proceed to the next step...

View File

@@ -1,19 +1,23 @@
How to install the __mitmproxy__ certificate authority in Firefox:
### 1. If needed, copy the ~/.mitmproxy/mitmproxy-ca-cert.pem file to the target.
<ol class="tlist">
<li> If needed, copy the ~/.mitmproxy/mitmproxy-ca-cert.pem file to the target. </li>
### 2: Open preferences, click on "Advanced", then select"Encryption":
<li>Open preferences, click on "Advanced", then select"Encryption":
<img src="@!urlTo('firefox3.jpg')!@"/>
</li>
<img src="@!urlTo('firefox3.jpg')!@"/>
<li> Click "View Certificates", "Import", and select the certificate file:
<img src="@!urlTo('firefox3-import.jpg')!@"/>
</li>
### 3: Click "View Certificates", "Import", and select the certificate file:
<li>Tick "Trust this CS to identify web sites", and click "Ok":
<img src="@!urlTo('firefox3-trust.jpg')!@"/>
</li>
<img src="@!urlTo('firefox3-import.jpg')!@"/>
<li> You should now see the mitmproxy certificate listed in the Authorities
tab.</li>
### 4: Tick "Trust this CS to identify web sites", and click "Ok":
<img src="@!urlTo('firefox3-trust.jpg')!@"/>
You should now see the mitmproxy certificate listed in the Authorities tab.
</ol>

View File

@@ -5,5 +5,6 @@ pages = [
Page("osx.html", "OSX"),
Page("windows7.html", "Windows 7"),
Page("ios.html", "IOS"),
Page("ios-simulator.html", "IOS Simulator"),
Page("android.html", "Android"),
]

View File

@@ -0,0 +1,23 @@
How to install the __mitmproxy__ certificate authority in the IOS simulator:
<ol class="tlist">
<li> First, check out the <a
href="https://github.com/ADVTOOLS/ADVTrustStore">ADVTrustStore</a> tool
from github.</li>
<li> Now, run the following command:
<pre class="terminal">./iosCertTrustManager.py -a ~/.mitmproxy/mitmproxy-ca-cert.pem</pre>
</li>
</ol>
Note that although the IOS simulator has its own certificate store, it shares
the proxy settings of the host operating system. You will therefore to have
configure your OSX host's proxy settings to use the mitmproxy instance you want
to test with.

View File

@@ -1,18 +1,21 @@
How to install the __mitmproxy__ certificate authority on IOS devices:
### 1: Set up the Mail app on the device to receive email.
<ol class="tlist">
<li>Set up the Mail app on the device to receive email.</li>
### 2: Mail the mitmproxy-ca-cert.pem file to the device, and tap on the attachment.
<li>Mail the mitmproxy-ca-cert.pem file to the device, and tap on the attachment.</li>
### 3: You will be prompted to install a profile. Click "Install":
<li>You will be prompted to install a profile. Click "Install":
<img src="@!urlTo('ios-profile.png')!@"/>
<img src="@!urlTo('ios-profile.png')!@"/></li>
### 4: Accept the warning by clicking "Install" again:
<li>Accept the warning by clicking "Install" again:
<img src="@!urlTo('ios-warning.png')!@"/>
<img src="@!urlTo('ios-warning.png')!@"/></li>
### 5: The certificate should now be trusted:
<li>The certificate should now be trusted:
<img src="@!urlTo('ios-installed.png')!@"/>
<img src="@!urlTo('ios-installed.png')!@"/></li>
</ol>

View File

@@ -1,13 +1,16 @@
How to install the __mitmproxy__ certificate authority in OSX:
### 1: Open Finder, and double-click on the mitmproxy-ca-cert.pem file.
<ol class="tlist">
<li>Open Finder, and double-click on the mitmproxy-ca-cert.pem file.</li>
### 2: You will be prompted to add the certificate. Click "Always Trust":
<li>You will be prompted to add the certificate. Click "Always Trust":
<img src="@!urlTo('osx-addcert-alwaystrust.png')!@"/>
<img src="@!urlTo('osx-addcert-alwaystrust.png')!@"/>
</li>
You may be prompted for your password. You should now see the mitmproxy cert
listed under "Certificates".
<li> You may be prompted for your password. You should now see the
mitmproxy cert listed under "Certificates".</li>
</ol>

View File

@@ -1,19 +1,32 @@
How to install the __mitmproxy__ certificate authority in Windows 7:
### 1: Copy the ~/.mitmproxy/mitmproxy-ca-cert.p12 file to the target system.
<ol class="tlist">
### 2: Double-click the certificate file. You should see a certificate import wizard:
<li> Copy the ~/.mitmproxy/mitmproxy-ca-cert.p12 file to the target system. </li>
<img src="@!urlTo('win7-wizard.png')!@"/>
<li>
Double-click the certificate file. You should see a certificate import wizard:
### 3: Click "Next" until you're prompted for the certificate store:
<img src="@!urlTo('win7-wizard.png')!@"/>
</li>
<img src="@!urlTo('win7-certstore.png')!@"/>
<li>
Click "Next" until you're prompted for the certificate store:
### 4: Select "Place all certificates in the following store", and select "Trusted Root Certification Authorities":
<img src="@!urlTo('win7-certstore.png')!@"/>
<img src="@!urlTo('win7-certstore-trustedroot.png')!@"/>
</li>
### 5: Click "Next" and "Finish".
<li>
<p>Select "Place all certificates in the following store", and select "Trusted Root Certification Authorities":</p>
<img src="@!urlTo('win7-certstore-trustedroot.png')!@"/>
</li>
<li> Click "Next" and "Finish". </li>
</ol>

View File

@@ -1,19 +0,0 @@
## Any tips for running mitmproxy on OSX?
You can use the OSX <b>open</b> program to create a simple and effective
<b>~/.mailcap</b> file to view HTTP bodies:
<pre>
application/*; /usr/bin/open -Wn %s
audio/*; /usr/bin/open -Wn %s
image/*; /usr/bin/open -Wn %s
video/*; /usr/bin/open -Wn %s
</pre>
## I'd like to hack on mitmproxy. What should I work on?
There's a __todo__ file at the top of the source tree that outlines a variety
of tasks, from simple to complex. If you don't have your own itch, feel free to
scratch one of those!

View File

@@ -1,8 +1,9 @@
Asks the user for authentication before they are permitted to use the proxy.
Authentication headers are stripped from the flows, so they are not passed to
upstream servers. For now, only HTTP Basic authentication is supported.
upstream servers. For now, only HTTP Basic authentication is supported. The
proxy auth options are ignored if the proxy is in transparent or reverse proxy
mode.
<table class="table">
<tbody>

View File

@@ -22,8 +22,7 @@ with the secured resources.
<th width="20%">command-line</th>
<td>
<ul>
<li>-t (sticky cookies on all requests)</li>
<li>-T FILTER (sticky cookies on requests matching filter</li>
<li>-t FILTER</li>
</ul>
</td>
</tr>
@@ -48,8 +47,7 @@ replay of HTTP Digest authentication.
<th width="20%">command-line</th>
<td>
<ul>
<li>-u (sticky auth on all requests)</li>
<li>-U FILTER (sticky auth on requests matching filter</li>
<li>-u FILTER</li>
</ul>
</td>
</tr>

View File

@@ -1,15 +1,11 @@
TODO:
- Clarify terminology: SSL vs TLS
Mitmproxy is an enormously flexible tool. Knowing exactly how the proxying
process works will help you deploy it more creatively, and let you understand
process works will help you deploy it creatively, and allow you to understand
its fundamental assumptions and how to work around them. This document explains
mitmproxy's proxy mechanism by example, starting with the simplest explicit
proxy configuration, and working up to the most complicated interaction -
transparent proxying of SSL-protected traffic in the presence of SNI.
mitmproxy's proxy mechanism in detail, starting with the simplest unencrypted
explicit proxying, and working up to the most complicated interaction -
transparent proxying of SSL-protected traffic[^ssl] in the presence of
[SNI](http://en.wikipedia.org/wiki/Server_Name_Indication).
<div class="page-header">
@@ -75,9 +71,11 @@ This is where mitmproxy's fundamental trick comes into play. The MITM in its
name stands for Man-In-The-Middle - a reference to the process we use to
intercept and interfere with these theoretially opaque data streams. The basic
idea is to pretend to be the server to the client, and pretend to be the client
to the server. The tricky part is that the Certificate Authority system is
to the server, while we sit in the middle decoding traffic from both sides. The
tricky part is that the [Certificate
Authority](http://en.wikipedia.org/wiki/Certificate_authority) system is
designed to prevent exactly this attack, by allowing a trusted third-party to
cryptographically sign a server's SSL certificates to verify that the certs are
cryptographically sign a server's SSL certificates to verify that they are
legit. If this signature is from a non-trusted party, a secure client will
simply drop the connection and refuse to proceed. Despite the many shortcomings
of the CA system as it exists today, this is usually fatal to attempts to MITM
@@ -86,7 +84,8 @@ an SSL connection for analysis.
Our answer to this conundrum is to become a trusted Certificate Authority
ourselves. Mitmproxy includes a full CA implementation that generates
interception certificates on the fly. To get the client to trust these
certificates, we register mitmproxy as a CA with the device manually.
certificates, we [register mitmproxy as a trusted CA with the device
manually](@!urlTo("ssl.html")!@).
## Complication 1: What's the remote hostname?
@@ -103,25 +102,27 @@ Using the IP address is perfectly legitimate because it gives us enough
information to initiate the pipe, even though it doesn't reveal the remote
hostname.
Mitmproxy has a cunning mechanism that smooths this over - upstream certificate
sniffing. As soon as we see the CONNECT request, we pause the client part of
the conversation, and initiate a simultaneous connection to the server. We
complete the SSL handshake with the server, and inspect the certificates it
used. Now, we use the Common Name in the upstream SSL certificates to generate
the dummy certificate for the client. Voila, we have the correct hostname to
present to the client, even if it was never specified.
Mitmproxy has a cunning mechanism that smooths this over - [upstream
certificate sniffing](@!urlTo("features/upstreamcerts.html")!@). As soon as we
see the CONNECT request, we pause the client part of the conversation, and
initiate a simultaneous connection to the server. We complete the SSL handshake
with the server, and inspect the certificates it used. Now, we use the Common
Name in the upstream SSL certificates to generate the dummy certificate for the
client. Voila, we have the correct hostname to present to the client, even if
it was never specified.
## Complication 2: Subject Alternate Name
## Complication 2: Subject Alternative Name
Enter the next complication. Sometimes, the certificate Common Name is not, in
fact, the hostname that the client is connecting to. This is because of the
optional Subject Alternate Name field in the SSL certificate that allows an
arbitrary number of alternate domains to be specified. If the expected domain
matches any of these, the client wil proceed, even though the domain doesn't
match the certificate Common Name. The answer here is simple: when extract the
CN from the upstream cert, we also extract the SANs, and add them to the
generated dummy certificate.
optional [Subject Alternative
Name](http://en.wikipedia.org/wiki/SubjectAltName) field in the SSL certificate
that allows an arbitrary number of alternative domains to be specified. If the
expected domain matches any of these, the client wil proceed, even though the
domain doesn't match the certificate Common Name. The answer here is simple:
when extract the CN from the upstream cert, we also extract the SANs, and add
them to the generated dummy certificate.
## Complication 3: Server Name Indication
@@ -130,9 +131,10 @@ One of the big limitations of conventional SSL is that each certificate
requires its own IP address. This means that you couldn't do virtual hosting
where multiple domains with independent certificates share the same IP address.
In a world with a rapidly shrinking IPv4 address pool this is a problem, and we
have a solution in the form of the Server Name Indication extension to the SSL
and TLS protocols. This lets the client specify the remote server name at the
start of the SSL handshake, which then lets the server select the right
have a solution in the form of the [Server Name
Indication](http://en.wikipedia.org/wiki/Server_Name_Indication) extension to
the SSL and TLS protocols. This lets the client specify the remote server name
at the start of the SSL handshake, which then lets the server select the right
certificate to complete the process.
SNI breaks our upstream certificate sniffing process, because when we connect
@@ -144,6 +146,15 @@ passed to us. Now we can pause the conversation, and initiate an upstream
connection using the correct SNI value, which then serves us the correct
upstream certificate, from which we can extract the expected CN and SANs.
There's another wrinkle here. Due to a limitation of the SSL library mitmproxy
uses, we can't detect that a connection _hasn't_ sent an SNI request until it's
too late for upstream certificate sniffing. In practice, we therefore make a
vanilla SSL connection upstream to sniff non-SNI certificates, and then discard
the connection if the client sends an SNI notification. If you're watching your
traffic with a packet sniffer, you'll see two connections to the server when an
SNI request is made, the first of which is immediately closed after the SSL
handshake. Luckily, this is almost never an issue in practice.
## Putting it all together
@@ -218,22 +229,28 @@ This makes transparent proxying ideal for those situations where you can't
change client behaviour - proxy-oblivious Android applications being a common
example.
To achieve this, we need to introduce two extra components. The first new
component is a router that transparently redirects the TCP connection to the
proxy. Once the client has initiated the connection, it makes a vanilla HTTP
request, which might look something like this:
To achieve this, we need to introduce two extra components. The first is a
redirection mechanism that transparently reroutes a TCP connection destined for
a server on the Internet to a listening proxy server. This usually takes the
form of a firewall on the same host as the proxy server -
[iptables](http://www.netfilter.org/) on Linux or
[pf](http://en.wikipedia.org/wiki/PF_(firewall)) on OSX. Once the client has
initiated the connection, it makes a vanilla HTTP request, which might look
something like this:
<pre>GET /index.html HTTP/1.1</pre>
Note that this request differs from the explicit proxy variation, in that it
omits the scheme and hostname. How, then, do we know which upstream host to
forward the request to? The routing mechanism that has performed the
redirection keeps track of the original destination. Each different routing
mechanism has its own ideosyncratic way of exposing this data, so this
introduces the second component required for working transparent proxying: a
host module that knows how to retrieve the original destination address from
the router. Once we have this information, the process is fairly
straight-forward.
redirection keeps track of the original destination for us. Each routing
mechanism has a different way of exposing this data, so this introduces the
second component required for working transparent proxying: a host module that
knows how to retrieve the original destination address from the router. In
mitmproxy, this takes the form of a built-in set of
[modules](https://github.com/cortesi/mitmproxy/tree/master/libmproxy/platform)
that know how to talk to each platform's redirection mechanism. Once we have
this information, the process is fairly straight-forward.
<img src="transparent.png"/>
@@ -338,4 +355,4 @@ and cope with SNI.
</table>
[^ssl]: I use "SSL" to refer to both SSL and TLS in the generic sense, unless otherwise specified.

View File

@@ -6,9 +6,15 @@ sys.path.insert(0, "..")
from libmproxy import filt
MITMPROXY_SRC = "~/git/public/mitmproxy"
this.layout = countershape.Layout("_layout.html")
if ns.options.website:
this.layout = countershape.Layout("_websitelayout.html")
else:
this.layout = countershape.Layout("_layout.html")
ns.title = countershape.template.Template(None, "<h1>@!this.title!@</h1>")
this.titlePrefix = "mitmproxy 0.9 - "
this.markup = markup.Markdown()
this.markup = markup.Markdown(extras=["footnotes"])
ns.docMaintainer = "Aldo Cortesi"
ns.docMaintainerEmail = "aldo@corte.si"
@@ -21,11 +27,12 @@ def mpath(p):
ns.index_contents = file(mpath("README.mkd")).read()
def example(s):
d = file(mpath(s)).read()
d = file(mpath(s)).read().rstrip()
extemp = """<div class="example">%s<div class="example_legend">(%s)</div></div>"""
return extemp%(countershape.template.Syntax("py")(d), s)
ns.example = example
filt_help = []
for i in filt.filt_unary:
filt_help.append(
@@ -73,5 +80,4 @@ pages = [
Directory("tutorials"),
Page("transparent.html", "Overview"),
Directory("transparent"),
Page("faq.html", "FAQ"),
]

View File

@@ -6,7 +6,10 @@ documentation.
## Example: saving traffic
# Examples
## Saving traffic
<pre class="terminal">
> mitmdump -w outfile
@@ -15,7 +18,18 @@ documentation.
Start up mitmdump in proxy mode, and write all traffic to __outfile__.
## Example: client replay
## Filtering saved traffic
<pre class="terminal">
> mitmdump -nr infile -w outfile "~m post"
</pre>
Start mitmdump without binding to the proxy port (_-n_), read all flows from
infile, apply the specified filter expression (only match POSTs), and write to
outfile.
## Client replay
<pre class="terminal">
> mitmdump -nc outfile
@@ -33,7 +47,7 @@ another:
See the [Client-side Replay](@!urlTo("clientreplay.html")!@) section for more information.
## Example: running a script
## Running a script
<pre class="terminal">
> mitmdump -s examples/add_header.py
@@ -43,7 +57,7 @@ This runs the __add_header.py__ example script, which simply adds a new header
to all responses.
## Example: scripted data transformation
## Scripted data transformation
<pre class="terminal">
> mitmdump -ns examples/add_header.py -r srcfile -w dstfile

View File

@@ -1,7 +1,9 @@
__mitmproxy__ is a console tool that allows interactive examination and
modification of HTTP traffic. Use the _?_ shortcut key to view,
context-sensitive documentation from any __mitmproxy__ screen.
modification of HTTP traffic. It differs from mitmdump in that all flows are
kept in memory, which means that it's intended for taking and manipulating
small-ish samples. Use the _?_ shortcut key to view, context-sensitive
documentation from any __mitmproxy__ screen.
## Flow list

View File

@@ -13,6 +13,15 @@ lets the script interact with the global mitmproxy state. The __response__
event also gets an instance of Flow, which we can use to manipulate the
response itself.
We can now run this script using mitmdump or mitmproxy as follows:
<pre class="terminal">
> mitmdump -s add_header.py
</pre>
The new header will be added to all responses passing through the proxy.
## Events
@@ -60,7 +69,7 @@ Called once on script shutdown, after any other events.
The main classes you will deal with in writing mitmproxy scripts are:
<table class="kvtable">
<table class="table">
<tr>
<th>libmproxy.flow.ClientConnection</th>
<td>Describes a client connection.</td>

View File

@@ -1,22 +1,27 @@
The first time __mitmproxy__ or __mitmdump__ is started, the following set of
certificate files for a dummy Certificate Authority are created in the config
directory (~/.mitmproxy by default):
The first time __mitmproxy__ or __mitmdump__ is run, a set of certificate files
for the mitmproxy Certificate Authority are created in the config directory
(~/.mitmproxy by default). The files are as follows:
<table>
<table class="table">
<tr>
<td>mitmproxy-ca.pem</td>
<td class="nowrap">mitmproxy-ca.pem</td>
<td>The private key and certificate in PEM format.</td>
</tr>
<tr>
<td>mitmproxy-ca-cert.pem</td>
<td class="nowrap">mitmproxy-ca-cert.pem</td>
<td>The certificate in PEM format. Use this to distribute to most
non-Windows platforms.</td>
</tr>
<tr>
<td>mitmproxy-ca-cert.p12</td>
<td class="nowrap">mitmproxy-ca-cert.p12</td>
<td>The certificate in PKCS12 format. For use on Windows.</td>
</tr>
<tr>
<td class="nowrap">mitmproxy-ca-cert.cer</td>
<td>Same file as .pem, but with an extension expected by some Android
devices.</td>
</tr>
</table>
This CA is used for on-the-fly generation of dummy certificates for SSL
@@ -24,16 +29,9 @@ interception. Since your browser won't trust the __mitmproxy__ CA out of the
box (and rightly so), you will see an SSL cert warning every time you visit a
new SSL domain through __mitmproxy__. When you're testing a single site through
a browser, just accepting the bogus SSL cert manually is not too much trouble,
but there are a number of cases where you will want to configure your testing
system or browser to trust the __mitmproxy__ CA as a signing root authority:
- If you are testing non-browser software that checks SSL cert validity using
the system certificate store.
- You are testing an app that makes non-interactive (JSONP, script src, etc.)
requests to SSL resources. Another workaround in this case is to manually visit
the page through the browser, and add a certificate exception.
- You just don't want to deal with the hassle of continuously adding cert
exceptions.
but there are a many circumstances where you will want to configure your
testing system or browser to trust the __mitmproxy__ CA as a signing root
authority.
Installing the mitmproxy CA
@@ -43,4 +41,6 @@ Installing the mitmproxy CA
* [OSX](@!urlTo("certinstall/osx.html")!@)
* [Windows 7](@!urlTo("certinstall/windows7.html")!@)
* [iPhone/iPad](@!urlTo("certinstall/ios.html")!@)
* [IOS Simulator](@!urlTo("certinstall/ios-simulator.html")!@)
* [Android](@!urlTo("certinstall/android.html")!@)

View File

@@ -0,0 +1,3 @@

View File

@@ -0,0 +1,68 @@
OSX Lion integrated the [pf](http://www.openbsd.org/faq/pf/) packet filter from
the OpenBSD project, which mitmproxy uses to implement transparent mode on OSX.
Note that this means we don't support transparent mode for earlier versions of
OSX.
<ol class="tlist">
<li> <a href="@!urlTo("ssl.html")!@">Install the mitmproxy
certificates on the test device</a>. </li>
<li> Enable IP forwarding:
<pre class="terminal">sudo sysctl -w net.inet.ip.forwarding=1</pre>
</li>
<li> Place the following two lines in a file called, say, <b>pf.conf</b>:
<pre class="terminal">rdr on en2 inet proto tcp to any port 80 -&gt; 127.0.0.1 port 8080
rdr on en2 inet proto tcp to any port 443 -&gt; 127.0.0.1 port 8080
</pre>
These rules tell pf to redirect all traffic destined for port 80 or 443
to the local mitmproxy instance running on port 8080. You should
replace <b>en2</b> with the interface on which your test device will
appear.
</li>
<li> Configure pf with the rules:
<pre class="terminal">sudo pfctl -f pf.conf</pre>
</li>
<li> And now enable it:
<pre class="terminal">sudo pfctl -e</pre>
</li>
<li> Configure your test device to use the host on which mitmproxy is
running as the default gateway.</li>
<li> Configure sudoers to allow mitmproxy to access pfctl. Edit the file
<b>/etc/sudoers</b> on your system as root. Add the following line to the end
of the file:
<pre>ALL ALL=NOPASSWD: /sbin/pfctl -s state</pre>
Note that this allows any user on the system to run the command
"/sbin/pfctl -s state" as root without a password. This only allows
inspection of the state table, so should not be an undue security risk. If
you're special feel free to tighten the restriction up to the user running
mitmproxy.</li>
<li> Finally, fire up mitmproxy. You probably want a command like this:
<pre class="terminal">mitmproxy -T --host</pre>
The <b>-T</b> flag turns on transparent mode, and the <b>--host</b>
argument tells mitmproxy to use the value of the Host header for URL
display.
</li>
</ol>

View File

@@ -39,14 +39,21 @@ The contents of the submission are particularly interesting:
<!--(block|syntax("xml"))-->
<plist version="1.0">
<dict>
<key>category</key>
<string>SMW_Adv_USA1</string>
<key>score-value</key>
<integer>55</integer>
<key>timestamp</key>
<integer>1301553284461</integer>
</dict>
<dict>
<key>scores</key>
<array>
<dict>
<key>category</key>
<string>SMW_Adv_USA1</string>
<key>context</key>
<integer>0</integer>
<key>score-value</key>
<integer>0</integer>
<key>timestamp</key>
<integer>1363515361321</integer>
</dict>
</array>
</dict>
</plist>
<!--(end)-->
@@ -66,14 +73,21 @@ now fire up. Lets bump the score up to something a bit more ambitious:
<!--(block|syntax("xml"))-->
<plist version="1.0">
<dict>
<key>category</key>
<string>SMW_Adv_USA1</string>
<key>score-value</key>
<integer>2200272667</integer>
<key>timestamp</key>
<integer>1301553284461</integer>
</dict>
<dict>
<key>scores</key>
<array>
<dict>
<key>category</key>
<string>SMW_Adv_USA1</string>
<key>context</key>
<integer>0</integer>
<key>score-value</key>
<integer>2200272667</integer>
<key>timestamp</key>
<integer>1363515361321</integer>
</dict>
</array>
</dict>
</plist>
<!--(end)-->
@@ -91,15 +105,18 @@ replay.
And that's it - according to the records, I am the greatest Super Mega Worm
player of all time.
Curiously, the top competitors' scores are all the same: 2,147,483,647. If you
think that number seems familiar, you're right: it's 2^31-1, the maximum value
you can fit into a signed 32-bit int. Now let me tell you another peculiar
thing about Super Mega Worm - at the end of every game, it submits your highest
previous score to the Game Center, not your current score. This means that it
stores your highscore somewhere, and I'm guessing that it reads that stored
score back into a signed integer. So, if you _were_ to cheat by the relatively
pedestrian means of modifying the saved score on your jailbroken phone, then
2^31-1 might well be the maximum score you could get. Then again, if the game
itself stores its score in a signed 32-bit int, you could get the same score
through perfect play, effectively beating the game. So, which is it in this
case? I'll leave that for you to decide.
There's a curious addendum to this tale. When I first wrote this tutorial, all
the top competitors' scores were the same: 2,147,483,647 (this is no longer the
case, beacause there are now so many fellow cheaters using this tutorial). If
you think that number seems familiar, you're right: it's 2^31-1, the maximum
value you can fit into a signed 32-bit int. Now let me tell you another
peculiar thing about Super Mega Worm - at the end of every game, it submits
your highest previous score to the Game Center, not your current score. This
means that it stores your highscore somewhere, and I'm guessing that it reads
that stored score back into a signed integer. So, if you _were_ to cheat by the
relatively pedestrian means of modifying the saved score on your jailbroken
phone, then 2^31-1 might well be the maximum score you could get. Then again,
if the game itself stores its score in a signed 32-bit int, you could get the
same score through perfect play, effectively beating the game. So, which is it
in this case? I'll leave that for you to decide.

View File

@@ -3,6 +3,7 @@ dup_and_replay.py Duplicates each request, changes it, and then replays th
flowbasic Basic use of mitmproxy as a library.
modify_form.py Modify all form submissions to add a parameter.
modify_querystring.py Modify all query strings to add a parameters.
proxapp How to embed a WSGI app in a mitmproxy server
stub.py Script stub with a method definition for every event.
stickycookies An example of writing a custom proxy with libmproxy.
upsidedownternet.py Rewrites traffic to turn PNGs upside down.

View File

@@ -3,8 +3,8 @@
This example shows how to build a proxy based on mitmproxy's Flow
primitives.
Note that request and response messages are not automatically acked, so we
need to implement handlers to do this.
Note that request and response messages are not automatically replied to,
so we need to implement handlers to do this.
"""
import os
from libmproxy import proxy, flow
@@ -19,13 +19,13 @@ class MyMaster(flow.FlowMaster):
def handle_request(self, r):
f = flow.FlowMaster.handle_request(self, r)
if f:
r._ack()
r.reply()
return f
def handle_response(self, r):
f = flow.FlowMaster.handle_response(self, r)
if f:
r._ack()
r.reply()
print f
return f

View File

@@ -23,14 +23,14 @@ class InjectingMaster(controller.Master):
def handle_request(self, msg):
if 'Accept-Encoding' in msg.headers:
msg.headers["Accept-Encoding"] = 'none'
msg._ack()
msg.reply()
def handle_response(self, msg):
if msg.content:
c = msg.replace('<body>', '<body><iframe src="%s" frameborder="0" height="0" width="0"></iframe>' % self._iframe_url)
if c > 0:
print 'Iframe injected!'
msg._ack()
msg.reply()
def main(argv):

View File

@@ -23,13 +23,13 @@ class MyMaster(flow.FlowMaster):
def handle_request(self, r):
f = flow.FlowMaster.handle_request(self, r)
if f:
r._ack()
r.reply()
return f
def handle_response(self, r):
f = flow.FlowMaster.handle_response(self, r)
if f:
r._ack()
r.reply()
print f
return f

View File

@@ -25,13 +25,13 @@ class StickyMaster(controller.Master):
self.stickyhosts[hid] = msg.headers["cookie"]
elif hid in self.stickyhosts:
msg.headers["cookie"] = self.stickyhosts[hid]
msg._ack()
msg.reply()
def handle_response(self, msg):
hid = (msg.request.host, msg.request.port)
if msg.headers["set-cookie"]:
self.stickyhosts[hid] = msg.headers["set-cookie"]
msg._ack()
msg.reply()
config = proxy.ProxyConfig(

View File

@@ -1,122 +0,0 @@
import binascii
import contrib.md5crypt as md5crypt
class NullProxyAuth():
"""
No proxy auth at all (returns empty challange headers)
"""
def __init__(self, password_manager):
self.password_manager = password_manager
self.username = ""
def clean(self, headers):
"""
Clean up authentication headers, so they're not passed upstream.
"""
pass
def authenticate(self, headers):
"""
Tests that the user is allowed to use the proxy
"""
return True
def auth_challenge_headers(self):
"""
Returns a dictionary containing the headers require to challenge the user
"""
return {}
class BasicProxyAuth(NullProxyAuth):
CHALLENGE_HEADER = 'Proxy-Authenticate'
AUTH_HEADER = 'Proxy-Authorization'
def __init__(self, password_manager, realm):
NullProxyAuth.__init__(self, password_manager)
self.realm = realm
def clean(self, headers):
del headers[self.AUTH_HEADER]
def authenticate(self, headers):
auth_value = headers.get(self.AUTH_HEADER, [])
if not auth_value:
return False
try:
scheme, username, password = self.parse_auth_value(auth_value[0])
except ValueError:
return False
if scheme.lower()!='basic':
return False
if not self.password_manager.test(username, password):
return False
self.username = username
return True
def auth_challenge_headers(self):
return {self.CHALLENGE_HEADER:'Basic realm="%s"'%self.realm}
def unparse_auth_value(self, scheme, username, password):
v = binascii.b2a_base64(username + ":" + password)
return scheme + " " + v
def parse_auth_value(self, auth_value):
words = auth_value.split()
if len(words) != 2:
raise ValueError("Invalid basic auth credential.")
scheme = words[0]
try:
user = binascii.a2b_base64(words[1])
except binascii.Error:
raise ValueError("Invalid basic auth credential: user:password pair not valid base64: %s"%words[1])
parts = user.split(':')
if len(parts) != 2:
raise ValueError("Invalid basic auth credential: decoded user:password pair not valid: %s"%user)
return scheme, parts[0], parts[1]
class PasswordManager():
def __init__(self):
pass
def test(self, username, password_token):
return False
class PermissivePasswordManager(PasswordManager):
def __init__(self):
PasswordManager.__init__(self)
def test(self, username, password_token):
if username:
return True
return False
class HtpasswdPasswordManager(PasswordManager):
"""
Read usernames and passwords from a file created by Apache htpasswd
"""
def __init__(self, filehandle):
PasswordManager.__init__(self)
entries = (line.strip().split(':') for line in filehandle)
valid_entries = (entry for entry in entries if len(entry)==2)
self.usernames = {username:token for username,token in valid_entries}
def test(self, username, password_token):
if username not in self.usernames:
return False
full_token = self.usernames[username]
dummy, magic, salt, hashed_password = full_token.split('$')
expected = md5crypt.md5crypt(password_token, salt, '$'+magic+'$')
return expected==full_token
class SingleUserPasswordManager(PasswordManager):
def __init__(self, username, password):
PasswordManager.__init__(self)
self.username = username
self.password = password
def test(self, username, password_token):
return self.username==username and self.password==password_token

View File

@@ -154,6 +154,7 @@ def get_common_options(options):
script = options.script,
stickycookie = stickycookie,
stickyauth = stickyauth,
showhost = options.showhost,
wfile = options.wfile,
verbosity = options.verbose,
nopop = options.nopop,
@@ -248,6 +249,11 @@ def common_options(parser):
help="Byte size limit of HTTP request and response bodies."\
" Understands k/m/g suffixes, i.e. 3m for 3 megabytes."
)
parser.add_argument(
"--host",
action="store_true", dest="showhost", default=False,
help="Use the Host header to construct URLs for display."
)
parser.add_argument(
"--no-upstream-cert", default=False,

View File

@@ -174,6 +174,8 @@ class StatusBar(common.WWrap):
opts.append("anticache")
if self.master.anticomp:
opts.append("anticomp")
if self.master.showhost:
opts.append("showhost")
if not self.master.refresh_server_playback:
opts.append("norefresh")
if self.master.killextra:
@@ -195,9 +197,6 @@ class StatusBar(common.WWrap):
if self.master.stream:
r.append("[W:%s]"%self.master.stream_path)
if self.master.state.last_saveload:
r.append("[%s]"%self.master.state.last_saveload)
return r
def redraw(self):
@@ -328,7 +327,7 @@ class ConsoleState(flow.State):
class Options(object):
__slots__ = [
attributes = [
"anticache",
"anticomp",
"client_replay",
@@ -341,6 +340,7 @@ class Options(object):
"refresh_server_playback",
"rfile",
"script",
"showhost",
"replacements",
"rheaders",
"setheaders",
@@ -355,7 +355,7 @@ class Options(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
for i in self.__slots__:
for i in self.attributes:
if not hasattr(self, i):
setattr(self, i, None)
@@ -401,6 +401,7 @@ class ConsoleMaster(flow.FlowMaster):
self.killextra = options.kill
self.rheaders = options.rheaders
self.nopop = options.nopop
self.showhost = options.showhost
self.eventlog = options.eventlog
self.eventlist = urwid.SimpleListWalker([])
@@ -429,7 +430,7 @@ class ConsoleMaster(flow.FlowMaster):
path = os.path.expanduser(path)
try:
f = file(path, "wb")
flow.FlowMaster.start_stream(self, f)
flow.FlowMaster.start_stream(self, f, None)
except IOError, v:
return str(v)
self.stream_path = path
@@ -921,6 +922,7 @@ class ConsoleMaster(flow.FlowMaster):
(
("anticache", "a"),
("anticomp", "c"),
("showhost", "h"),
("killextra", "k"),
("norefresh", "n"),
("no-upstream-certs", "u"),
@@ -960,6 +962,10 @@ class ConsoleMaster(flow.FlowMaster):
self.anticache = not self.anticache
if a == "c":
self.anticomp = not self.anticomp
if a == "h":
self.showhost = not self.showhost
self.sync_list_view()
self.refresh_flow(self.currentflow)
elif a == "k":
self.killextra = not self.killextra
elif a == "n":

View File

@@ -177,7 +177,7 @@ class FlowCache:
flowcache = FlowCache()
def format_flow(f, focus, extended=False, padding=2):
def format_flow(f, focus, extended=False, hostheader=False, padding=2):
d = dict(
intercepting = f.intercepting,
@@ -185,7 +185,7 @@ def format_flow(f, focus, extended=False, padding=2):
req_is_replay = f.request.is_replay(),
req_method = f.request.method,
req_acked = f.request.reply.acked,
req_url = f.request.get_url(),
req_url = f.request.get_url(hostheader=hostheader),
err_msg = f.error.msg if f.error else None,
resp_code = f.response.code if f.response else None,

View File

@@ -105,7 +105,7 @@ class ConnectionItem(common.WWrap):
common.WWrap.__init__(self, w)
def get_text(self):
return common.format_flow(self.flow, self.f)
return common.format_flow(self.flow, self.f, hostheader=self.master.showhost)
def selectable(self):
return True

View File

@@ -88,11 +88,11 @@ footer = [
class FlowViewHeader(common.WWrap):
def __init__(self, master, f):
self.master, self.flow = master, f
self.w = common.format_flow(f, False, extended=True, padding=0)
self.w = common.format_flow(f, False, extended=True, padding=0, hostheader=self.master.showhost)
def refresh_flow(self, f):
if f == self.flow:
self.w = common.format_flow(f, False, extended=True, padding=0)
self.w = common.format_flow(f, False, extended=True, padding=0, hostheader=self.master.showhost)
class CallbackCache:

View File

@@ -97,6 +97,10 @@ class HelpView(urwid.ListBox):
common.highlight_key("anticomp", "c") +
[("text", ": prevent compressed responses")]
),
(None,
common.highlight_key("showhost", "h") +
[("text", ": use Host header for URL display")]
),
(None,
common.highlight_key("killextra", "k") +
[("text", ": kill requests not part of server replay")]

View File

@@ -1,94 +0,0 @@
# Based on FreeBSD src/lib/libcrypt/crypt.c 1.2
# http://www.freebsd.org/cgi/cvsweb.cgi/~checkout~/src/lib/libcrypt/crypt.c?rev=1.2&content-type=text/plain
# Original license:
# * "THE BEER-WARE LICENSE" (Revision 42):
# * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you
# * can do whatever you want with this stuff. If we meet some day, and you think
# * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
# This port adds no further stipulations. I forfeit any copyright interest.
import md5
def md5crypt(password, salt, magic='$1$'):
# /* The password first, since that is what is most unknown */ /* Then our magic string */ /* Then the raw salt */
m = md5.new()
m.update(password + magic + salt)
# /* Then just as many characters of the MD5(pw,salt,pw) */
mixin = md5.md5(password + salt + password).digest()
for i in range(0, len(password)):
m.update(mixin[i % 16])
# /* Then something really weird... */
# Also really broken, as far as I can tell. -m
i = len(password)
while i:
if i & 1:
m.update('\x00')
else:
m.update(password[0])
i >>= 1
final = m.digest()
# /* and now, just to make sure things don't run too fast */
for i in range(1000):
m2 = md5.md5()
if i & 1:
m2.update(password)
else:
m2.update(final)
if i % 3:
m2.update(salt)
if i % 7:
m2.update(password)
if i & 1:
m2.update(final)
else:
m2.update(password)
final = m2.digest()
# This is the bit that uses to64() in the original code.
itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
rearranged = ''
for a, b, c in ((0, 6, 12), (1, 7, 13), (2, 8, 14), (3, 9, 15), (4, 10, 5)):
v = ord(final[a]) << 16 | ord(final[b]) << 8 | ord(final[c])
for i in range(4):
rearranged += itoa64[v & 0x3f]; v >>= 6
v = ord(final[11])
for i in range(2):
rearranged += itoa64[v & 0x3f]; v >>= 6
return magic + salt + '$' + rearranged
if __name__ == '__main__':
def test(clear_password, the_hash):
magic, salt = the_hash[1:].split('$')[:2]
magic = '$' + magic + '$'
return md5crypt(clear_password, salt, magic) == the_hash
test_cases = (
(' ', '$1$yiiZbNIH$YiCsHZjcTkYd31wkgW8JF.'),
('pass', '$1$YeNsbWdH$wvOF8JdqsoiLix754LTW90'),
('____fifteen____', '$1$s9lUWACI$Kk1jtIVVdmT01p0z3b/hw1'),
('____sixteen_____', '$1$dL3xbVZI$kkgqhCanLdxODGq14g/tW1'),
('____seventeen____', '$1$NaH5na7J$j7y8Iss0hcRbu3kzoJs5V.'),
('__________thirty-three___________', '$1$HO7Q6vzJ$yGwp2wbL5D7eOVzOmxpsy.'),
('apache', '$apr1$J.w5a/..$IW9y6DR0oO/ADuhlMF5/X1')
)
for clearpw, hashpw in test_cases:
if test(clearpw, hashpw):
print '%s: pass' % clearpw
else:
print '%s: FAIL' % clearpw

View File

@@ -21,7 +21,7 @@ class DumpError(Exception): pass
class Options(object):
__slots__ = [
attributes = [
"anticache",
"anticomp",
"client_replay",
@@ -37,6 +37,7 @@ class Options(object):
"setheaders",
"server_replay",
"script",
"showhost",
"stickycookie",
"stickyauth",
"verbosity",
@@ -45,7 +46,7 @@ class Options(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
for i in self.__slots__:
for i in self.attributes:
if not hasattr(self, i):
setattr(self, i, None)
@@ -57,12 +58,12 @@ def str_response(resp):
return r
def str_request(req):
def str_request(req, showhost):
if req.client_conn:
c = req.client_conn.address[0]
else:
c = "[replay]"
r = "%s %s %s"%(c, req.method, req.get_url())
r = "%s %s %s"%(c, req.method, req.get_url(showhost))
if req.stickycookie:
r = "[stickycookie] " + r
return r
@@ -76,6 +77,7 @@ class DumpMaster(flow.FlowMaster):
self.anticache = options.anticache
self.anticomp = options.anticomp
self.eventlog = options.eventlog
self.showhost = options.showhost
self.refresh_server_playback = options.refresh_server_playback
if filtstr:
@@ -93,7 +95,7 @@ class DumpMaster(flow.FlowMaster):
path = os.path.expanduser(options.wfile)
try:
f = file(path, "wb")
self.start_stream(f)
self.start_stream(f, self.filt)
except IOError, v:
raise DumpError(v.strerror)
@@ -155,6 +157,7 @@ class DumpMaster(flow.FlowMaster):
return "\n".join(" "*n + i for i in l)
def _process_flow(self, f):
self.state.delete_flow(f)
if self.filt and not f.match(self.filt):
return
@@ -178,16 +181,16 @@ class DumpMaster(flow.FlowMaster):
result = " << %s"%f.error.msg
if self.o.verbosity == 1:
print >> self.outfile, str_request(f.request)
print >> self.outfile, str_request(f.request, self.showhost)
print >> self.outfile, result
elif self.o.verbosity == 2:
print >> self.outfile, str_request(f.request)
print >> self.outfile, str_request(f.request, self.showhost)
print >> self.outfile, self.indent(4, f.request.headers)
print >> self.outfile
print >> self.outfile, result
print >> self.outfile, "\n"
elif self.o.verbosity >= 3:
print >> self.outfile, str_request(f.request)
print >> self.outfile, str_request(f.request, self.showhost)
print >> self.outfile, self.indent(4, f.request.headers)
if utils.isBin(f.request.content):
print >> self.outfile, self.indent(4, netlib.utils.hexdump(f.request.content))
@@ -198,7 +201,6 @@ class DumpMaster(flow.FlowMaster):
print >> self.outfile, "\n"
if self.o.verbosity:
self.outfile.flush()
self.state.delete_flow(f)
def handle_log(self, l):
self.add_event(l.msg)

View File

@@ -459,11 +459,19 @@ class Request(HTTPMsg):
query = utils.urlencode(odict.lst)
self.set_url(urlparse.urlunparse([scheme, netloc, path, params, query, fragment]))
def get_url(self):
def get_url(self, hostheader=False):
"""
Returns a URL string, constructed from the Request's URL compnents.
If hostheader is True, we use the value specified in the request
Host header to construct the URL.
"""
return utils.unparse_url(self.scheme, self.host.decode("idna"), self.port, self.path).encode('ascii')
if hostheader:
host = self.headers.get_first("host") or self.host
else:
host = self.host
host = host.encode("idna")
return utils.unparse_url(self.scheme, host, self.port, self.path).encode('ascii')
def set_url(self, url):
"""
@@ -1306,7 +1314,7 @@ class State(object):
if f.request in self._flow_map:
del self._flow_map[f.request]
self._flow_list.remove(f)
if f.match(self._limit):
if f in self.view:
self.view.remove(f)
return True
@@ -1593,8 +1601,8 @@ class FlowMaster(controller.Master):
self.stream.add(i)
self.stop_stream()
def start_stream(self, fp):
self.stream = FlowWriter(fp)
def start_stream(self, fp, filt):
self.stream = FilteredFlowWriter(fp, filt)
def stop_stream(self):
self.stream.fo.close()
@@ -1640,3 +1648,16 @@ class FlowReader:
return
raise FlowReadError("Invalid data format.")
class FilteredFlowWriter:
def __init__(self, fo, filt):
self.fo = fo
self.filt = filt
def add(self, f):
if self.filt and not f.match(self.filt):
return
d = f._get_state()
tnetstring.dump(d, self.fo)

View File

@@ -16,9 +16,8 @@ import sys, os, string, socket, time
import shutil, tempfile, threading
import SocketServer
from OpenSSL import SSL
from netlib import odict, tcp, http, wsgi, certutils, http_status
from netlib import odict, tcp, http, wsgi, certutils, http_status, http_auth
import utils, flow, version, platform, controller
import authentication
KILL = 0
@@ -80,8 +79,7 @@ class ServerConnection(tcp.TCPClient):
def terminate(self):
try:
if not self.wfile.closed:
self.wfile.flush()
self.wfile.flush()
self.connection.close()
except IOError:
pass
@@ -110,6 +108,27 @@ class RequestReplayThread(threading.Thread):
self.channel.ask(err)
class HandleSNI:
def __init__(self, handler, client_conn, host, port, cert, key):
self.handler, self.client_conn, self.host, self.port = handler, client_conn, host, port
self.cert, self.key = cert, key
def __call__(self, connection):
try:
sn = connection.get_servername()
if sn:
self.handler.get_server_connection(self.client_conn, "https", self.host, self.port, sn)
new_context = SSL.Context(SSL.TLSv1_METHOD)
new_context.use_privatekey_file(self.key)
new_context.use_certificate_file(self.cert)
connection.set_context(new_context)
self.handler.sni = sn.decode("utf8").encode("idna")
# An unhandled exception in this method will core dump PyOpenSSL, so
# make dang sure it doesn't happen.
except Exception, e: # pragma: no cover
pass
class ProxyHandler(tcp.BaseHandler):
def __init__(self, config, connection, client_address, server, channel, server_version):
self.channel, self.server_version = channel, server_version
@@ -120,7 +139,16 @@ class ProxyHandler(tcp.BaseHandler):
tcp.BaseHandler.__init__(self, connection, client_address, server)
def get_server_connection(self, cc, scheme, host, port, sni):
"""
When SNI is in play, this means we have an SSL-encrypted
connection, which means that the entire handler is dedicated to a
single server connection - no multiplexing. If this assumption ever
breaks, we'll have to do something different with the SNI host
variable on the handler object.
"""
sc = self.server_conn
if not sni:
sni = host
if sc and (scheme, host, port, sni) != (sc.scheme, sc.host, sc.port, sc.sni):
sc.terminate()
self.server_conn = None
@@ -194,7 +222,7 @@ class ProxyHandler(tcp.BaseHandler):
# the case, we want to reconnect without sending an error
# to the client.
while 1:
sc = self.get_server_connection(cc, scheme, host, port, host)
sc = self.get_server_connection(cc, scheme, host, port, self.sni)
sc.send(request)
sc.rfile.reset_timestamps()
try:
@@ -209,6 +237,8 @@ class ProxyHandler(tcp.BaseHandler):
continue
else:
raise
except http.HttpError, v:
raise ProxyError(502, "Invalid server response.")
else:
break
@@ -250,7 +280,6 @@ class ProxyHandler(tcp.BaseHandler):
)
else:
self.log(cc, cc.error)
if isinstance(e, ProxyError):
self.send_error(e.code, e.msg, e.headers)
else:
@@ -266,21 +295,18 @@ class ProxyHandler(tcp.BaseHandler):
l = Log(msg)
self.channel.tell(l)
def find_cert(self, host, port, sni):
def find_cert(self, cc, host, port, sni):
if self.config.certfile:
return self.config.certfile
else:
sans = []
if not self.config.no_upstream_cert:
try:
cert = certutils.get_remote_cert(host, port, sni)
except tcp.NetLibError, v:
raise ProxyError(502, "Unable to get remote cert: %s"%str(v))
sans = cert.altnames
host = cert.cn.decode("utf8").encode("idna")
conn = self.get_server_connection(cc, "https", host, port, sni)
sans = conn.cert.altnames
host = conn.cert.cn.decode("utf8").encode("idna")
ret = self.config.certstore.get_cert(host, sans, self.config.cacert)
if not ret:
raise ProxyError(502, "mitmproxy: Unable to generate dummy cert.")
raise ProxyError(502, "Unable to generate dummy cert.")
return ret
def get_line(self, fp):
@@ -292,26 +318,25 @@ class ProxyHandler(tcp.BaseHandler):
line = fp.readline()
return line
def handle_sni(self, conn):
sn = conn.get_servername()
if sn:
self.sni = sn.decode("utf8").encode("idna")
def read_request_transparent(self, client_conn):
orig = self.config.transparent_proxy["resolver"].original_addr(self.connection)
if not orig:
raise ProxyError(502, "Transparent mode failure: could not resolve original destination.")
host, port = orig
if not self.ssl_established and (port in self.config.transparent_proxy["sslports"]):
if port in self.config.transparent_proxy["sslports"]:
scheme = "https"
certfile = self.find_cert(host, port, None)
try:
self.convert_to_ssl(certfile, self.config.certfile or self.config.cacert)
except tcp.NetLibError, v:
raise ProxyError(400, str(v))
if not self.ssl_established:
dummycert = self.find_cert(client_conn, host, port, host)
sni = HandleSNI(
self, client_conn, host, port,
dummycert, self.config.certfile or self.config.cacert
)
try:
self.convert_to_ssl(dummycert, self.config.certfile or self.config.cacert, handle_sni=sni)
except tcp.NetLibError, v:
raise ProxyError(400, str(v))
else:
scheme = "http"
host = self.sni or host
line = self.get_line(self.rfile)
if line == "":
return None
@@ -332,27 +357,29 @@ class ProxyHandler(tcp.BaseHandler):
line = self.get_line(self.rfile)
if line == "":
return None
if http.parse_init_connect(line):
r = http.parse_init_connect(line)
if not r:
raise ProxyError(400, "Bad HTTP request line: %s"%repr(line))
host, port, httpversion = r
headers = self.read_headers(authenticate=True)
self.wfile.write(
'HTTP/1.1 200 Connection established\r\n' +
('Proxy-agent: %s\r\n'%self.server_version) +
'\r\n'
)
self.wfile.flush()
certfile = self.find_cert(host, port, None)
try:
self.convert_to_ssl(certfile, self.config.certfile or self.config.cacert)
except tcp.NetLibError, v:
raise ProxyError(400, str(v))
self.proxy_connect_state = (host, port, httpversion)
line = self.rfile.readline(line)
if not self.proxy_connect_state:
connparts = http.parse_init_connect(line)
if connparts:
host, port, httpversion = connparts
headers = self.read_headers(authenticate=True)
self.wfile.write(
'HTTP/1.1 200 Connection established\r\n' +
('Proxy-agent: %s\r\n'%self.server_version) +
'\r\n'
)
self.wfile.flush()
dummycert = self.find_cert(client_conn, host, port, host)
sni = HandleSNI(
self, client_conn, host, port,
dummycert, self.config.certfile or self.config.cacert
)
try:
self.convert_to_ssl(dummycert, self.config.certfile or self.config.cacert, handle_sni=sni)
except tcp.NetLibError, v:
raise ProxyError(400, str(v))
self.proxy_connect_state = (host, port, httpversion)
line = self.rfile.readline(line)
if self.proxy_connect_state:
r = http.parse_init_http(line)
@@ -479,10 +506,7 @@ class ProxyServer(tcp.TCPServer):
def handle_connection(self, request, client_address):
h = ProxyHandler(self.config, request, client_address, self, self.channel, self.server_version)
h.handle()
try:
h.finish()
except tcp.NetLibDisconnect, e:
pass
h.finish()
def handle_shutdown(self):
self.config.certstore.cleanup()
@@ -515,7 +539,7 @@ class DummyServer:
def __init__(self, config):
self.config = config
def start_slave(self, klass, channel):
def start_slave(self, *args):
pass
def shutdown(self):
@@ -548,22 +572,19 @@ def process_proxy_options(parser, options):
if options.cert:
options.cert = os.path.expanduser(options.cert)
if not os.path.exists(options.cert):
parser.error("Manually created certificate does not exist: %s"%options.cert)
return parser.error("Manually created certificate does not exist: %s"%options.cert)
cacert = os.path.join(options.confdir, "mitmproxy-ca.pem")
cacert = os.path.expanduser(cacert)
if not os.path.exists(cacert):
certutils.dummy_ca(cacert)
if getattr(options, "cache", None) is not None:
options.cache = os.path.expanduser(options.cache)
body_size_limit = utils.parse_size(options.body_size_limit)
if options.reverse_proxy and options.transparent_proxy:
parser.errror("Can't set both reverse proxy and transparent proxy.")
return parser.error("Can't set both reverse proxy and transparent proxy.")
if options.transparent_proxy:
if not platform.resolver:
parser.error("Transparent mode not supported on this platform.")
return parser.error("Transparent mode not supported on this platform.")
trans = dict(
resolver = platform.resolver(),
sslports = TRANSPARENT_SSL_PORTS
@@ -574,33 +595,36 @@ def process_proxy_options(parser, options):
if options.reverse_proxy:
rp = utils.parse_proxy_spec(options.reverse_proxy)
if not rp:
parser.error("Invalid reverse proxy specification: %s"%options.reverse_proxy)
return parser.error("Invalid reverse proxy specification: %s"%options.reverse_proxy)
else:
rp = None
if options.clientcerts:
options.clientcerts = os.path.expanduser(options.clientcerts)
if not os.path.exists(options.clientcerts) or not os.path.isdir(options.clientcerts):
parser.error("Client certificate directory does not exist or is not a directory: %s"%options.clientcerts)
return parser.error("Client certificate directory does not exist or is not a directory: %s"%options.clientcerts)
if options.certdir:
options.certdir = os.path.expanduser(options.certdir)
if not os.path.exists(options.certdir) or not os.path.isdir(options.certdir):
parser.error("Dummy cert directory does not exist or is not a directory: %s"%options.certdir)
return parser.error("Dummy cert directory does not exist or is not a directory: %s"%options.certdir)
if (options.auth_nonanonymous or options.auth_singleuser or options.auth_htpasswd):
if options.auth_singleuser:
if len(options.auth_singleuser.split(':')) != 2:
parser.error("Please specify user in the format username:password")
return parser.error("Invalid single-user specification. Please use the format username:password")
username, password = options.auth_singleuser.split(':')
password_manager = authentication.SingleUserPasswordManager(username, password)
password_manager = http_auth.PassManSingleUser(username, password)
elif options.auth_nonanonymous:
password_manager = authentication.PermissivePasswordManager()
password_manager = http_auth.PassManNonAnon()
elif options.auth_htpasswd:
password_manager = authentication.HtpasswdPasswordManager(options.auth_htpasswd)
authenticator = authentication.BasicProxyAuth(password_manager, "mitmproxy")
try:
password_manager = http_auth.PassManHtpasswd(options.auth_htpasswd)
except ValueError, v:
return parser.error(v.message)
authenticator = http_auth.BasicProxyAuth(password_manager, "mitmproxy")
else:
authenticator = authentication.NullProxyAuth(None)
authenticator = http_auth.NullProxyAuth(None)
return ProxyConfig(
certfile = options.cert,

View File

@@ -92,5 +92,5 @@ setup(
"Topic :: Internet :: Proxy Servers",
"Topic :: Software Development :: Testing"
],
install_requires=["netlib", "urwid>=1.1", "pyasn1>0.1.2", "pyopenssl>=0.12", "PIL", "lxml"],
install_requires=["netlib>=%s"%version.VERSION, "urwid>=1.1", "pyasn1>0.1.2", "pyopenssl>=0.12", "PIL", "lxml"],
)

1
test/data/htpasswd Normal file
View File

@@ -0,0 +1 @@
test:$apr1$/LkYxy3x$WI4.YbiJlu537jLGEW2eu1

View File

@@ -0,0 +1 @@
foo

22
test/fuzzing/go_proxy Executable file
View File

@@ -0,0 +1,22 @@
#!/bin/sh
# Assuming:
# mitmproxy/mitmdump is running on port 8080 in straight proxy mode.
# pathod is running on port 9999
BASE_HTTP="/Users/aldo/git/public/pathod/pathoc -Tt 1 -eo -I 200,400,405,502 -p 8080 localhost "
#$BASE_HTTP -n 10000 "get:'http://localhost:9999':ir,@1"
#$BASE_HTTP -n 100 "get:'http://localhost:9999':dr"
#$BASE_HTTP -n 10000 "get:'http://localhost:9999/p/200:ir,@300.0
# Assuming:
# mitmproxy/mitmdump is running on port 8080 in straight proxy mode.
# pathod with SSL enabled is running on port 9999
BASE_HTTPS="/Users/aldo/git/public/pathod/pathoc -sc localhost:9999 -Tt 1 -eo -I 200,400,404,405,502,800 -p 8080 localhost "
$BASE_HTTPS -en 10000 "get:'/p/200:b@10:ir,@1'"
#$BASE_HTTPS -en 10000 "get:'/p/200:ir,@1'"
#$BASE_HTTPS -n 100 "get:'/p/200:dr'"
#$BASE_HTTPS -n 10000 "get:'/p/200:ir,@3000'"
#$BASE_HTTPS -n 10000 "get:'/p/200:ir,\"\\n\"'"

View File

@@ -1,58 +0,0 @@
import binascii
from libmproxy import authentication
from netlib import odict
import tutils
class TestNullProxyAuth:
def test_simple(self):
na = authentication.NullProxyAuth(authentication.PermissivePasswordManager())
assert not na.auth_challenge_headers()
assert na.authenticate("foo")
na.clean({})
class TestBasicProxyAuth:
def test_simple(self):
ba = authentication.BasicProxyAuth(authentication.PermissivePasswordManager(), "test")
h = odict.ODictCaseless()
assert ba.auth_challenge_headers()
assert not ba.authenticate(h)
def test_parse_auth_value(self):
ba = authentication.BasicProxyAuth(authentication.PermissivePasswordManager(), "test")
vals = ("basic", "foo", "bar")
assert ba.parse_auth_value(ba.unparse_auth_value(*vals)) == vals
tutils.raises(ValueError, ba.parse_auth_value, "")
tutils.raises(ValueError, ba.parse_auth_value, "foo bar")
v = "basic " + binascii.b2a_base64("foo")
tutils.raises(ValueError, ba.parse_auth_value, v)
def test_authenticate_clean(self):
ba = authentication.BasicProxyAuth(authentication.PermissivePasswordManager(), "test")
hdrs = odict.ODictCaseless()
vals = ("basic", "foo", "bar")
hdrs[ba.AUTH_HEADER] = [ba.unparse_auth_value(*vals)]
assert ba.authenticate(hdrs)
ba.clean(hdrs)
assert not ba.AUTH_HEADER in hdrs
hdrs[ba.AUTH_HEADER] = [""]
assert not ba.authenticate(hdrs)
hdrs[ba.AUTH_HEADER] = ["foo"]
assert not ba.authenticate(hdrs)
vals = ("foo", "foo", "bar")
hdrs[ba.AUTH_HEADER] = [ba.unparse_auth_value(*vals)]
assert not ba.authenticate(hdrs)
ba = authentication.BasicProxyAuth(authentication.PasswordManager(), "test")
vals = ("basic", "foo", "bar")
hdrs[ba.AUTH_HEADER] = [ba.unparse_auth_value(*vals)]
assert not ba.authenticate(hdrs)

View File

@@ -0,0 +1,10 @@
import libmproxy.console.common as common
from libmproxy import utils, flow, encoding
import tutils
def test_format_flow():
f = tutils.tflow_full()
assert common.format_flow(f, True)
assert common.format_flow(f, True, hostheader=True)
assert common.format_flow(f, True, extended=True)

12
test/test_controller.py Normal file
View File

@@ -0,0 +1,12 @@
import mock
from libmproxy import controller
class TestMaster:
def test_default_handler(self):
m = controller.Master(None)
msg = mock.MagicMock()
m.handle(msg)
assert msg.reply.call_count == 1

View File

@@ -1,6 +1,5 @@
import os
from cStringIO import StringIO
import libpry
from libmproxy import dump, flow, proxy
import tutils
import mock
@@ -13,8 +12,10 @@ def test_strfuncs():
t = tutils.treq()
t.client_conn = None
t.stickycookie = True
assert "stickycookie" in dump.str_request(t)
assert "replay" in dump.str_request(t)
assert "stickycookie" in dump.str_request(t, False)
assert "stickycookie" in dump.str_request(t, True)
assert "replay" in dump.str_request(t, False)
assert "replay" in dump.str_request(t, True)
class TestDumpMaster:
@@ -65,7 +66,7 @@ class TestDumpMaster:
cs = StringIO()
o = dump.Options(server_replay="nonexistent", kill=True)
libpry.raises(dump.DumpError, dump.DumpMaster, None, o, None, outfile=cs)
tutils.raises(dump.DumpError, dump.DumpMaster, None, o, None, outfile=cs)
with tutils.tmpdir() as t:
p = os.path.join(t, "rep")
@@ -90,7 +91,7 @@ class TestDumpMaster:
self._flowfile(p)
assert "GET" in self._dummy_cycle(0, None, "", verbosity=1, rfile=p)
libpry.raises(
tutils.raises(
dump.DumpError, self._dummy_cycle,
0, None, "", verbosity=1, rfile="/nonexistent"
)
@@ -101,7 +102,6 @@ class TestDumpMaster:
def test_options(self):
o = dump.Options(verbosity = 2)
assert o.verbosity == 2
libpry.raises(AttributeError, dump.Options, nonexistent = 2)
def test_filter(self):
assert not "GET" in self._dummy_cycle(1, "~u foo", "", verbosity=1)
@@ -131,7 +131,7 @@ class TestDumpMaster:
assert len(list(flow.FlowReader(open(p)).stream())) == 1
def test_write_err(self):
libpry.raises(
tutils.raises(
dump.DumpError,
self._dummy_cycle,
1,
@@ -149,11 +149,11 @@ class TestDumpMaster:
assert "XREQUEST" in ret
assert "XRESPONSE" in ret
assert "XCLIENTDISCONNECT" in ret
libpry.raises(
tutils.raises(
dump.DumpError,
self._dummy_cycle, 1, None, "", script="nonexistent"
)
libpry.raises(
tutils.raises(
dump.DumpError,
self._dummy_cycle, 1, None, "", script="starterr.py"
)

View File

@@ -498,6 +498,23 @@ class TestSerialize:
fm.load_flows(r)
assert len(s._flow_list) == 6
def test_filter(self):
sio = StringIO()
fl = filt.parse("~c 200")
w = flow.FilteredFlowWriter(sio, fl)
f = tutils.tflow_full()
f.response.code = 200
w.add(f)
f = tutils.tflow_full()
f.response.code = 201
w.add(f)
sio.seek(0)
r = flow.FlowReader(sio)
assert len(list(r.stream()))
def test_error(self):
sio = StringIO()
@@ -723,7 +740,7 @@ class TestFlowMaster:
fm = flow.FlowMaster(None, s)
tf = tutils.tflow_full()
fm.start_stream(file(p, "ab"))
fm.start_stream(file(p, "ab"), None)
fm.handle_request(tf.request)
fm.handle_response(tf.response)
fm.stop_stream()
@@ -731,7 +748,7 @@ class TestFlowMaster:
assert r()[0].response
tf = tutils.tflow_full()
fm.start_stream(file(p, "ab"))
fm.start_stream(file(p, "ab"), None)
fm.handle_request(tf.request)
fm.shutdown()
@@ -766,6 +783,17 @@ class TestRequest:
r.content = flow.CONTENT_MISSING
assert not r._assemble()
def test_get_url(self):
h = flow.ODictCaseless()
h["test"] = ["test"]
c = flow.ClientConnect(("addr", 2222))
r = flow.Request(c, (1, 1), "host", 22, "https", "GET", "/", h, "content")
assert r.get_url() == "https://host:22/"
assert r.get_url(hostheader=True) == "https://host:22/"
r.headers["Host"] = ["foo.com"]
assert r.get_url() == "https://host:22/"
assert r.get_url(hostheader=True) == "https://foo.com:22/"
def test_path_components(self):
h = flow.ODictCaseless()
c = flow.ClientConnect(("addr", 2222))

39
test/test_fuzzing.py Normal file
View File

@@ -0,0 +1,39 @@
import tservers
"""
A collection of errors turned up by fuzzing. Errors are integrated here
after being fixed to check for regressions.
"""
class TestFuzzy(tservers.HTTPProxTest):
def test_idna_err(self):
req = r'get:"http://localhost:%s":i10,"\xc6"'
p = self.pathoc()
assert p.request(req%self.server.port).status_code == 400
def test_nullbytes(self):
req = r'get:"http://localhost:%s":i19,"\x00"'
p = self.pathoc()
assert p.request(req%self.server.port).status_code == 400
def test_invalid_ports(self):
req = 'get:"http://localhost:999999"'
p = self.pathoc()
assert p.request(req).status_code == 400
def test_invalid_ipv6_url(self):
req = 'get:"http://localhost:%s":i13,"["'
p = self.pathoc()
assert p.request(req%self.server.port).status_code == 400
def test_invalid_upstream(self):
req = r"get:'http://localhost:%s/p/200:i10,\'+\''"
p = self.pathoc()
assert p.request(req%self.server.port).status_code == 502
def test_upstream_disconnect(self):
req = r'200:d0:h"Date"="Sun, 03 Mar 2013 04:00:00 GMT"'
p = self.pathod(req)
assert p.status_code == 400

View File

@@ -1,4 +1,5 @@
from libmproxy import proxy, flow
import argparse
from libmproxy import proxy, flow, cmdline
import tutils
from libpathod import test
from netlib import http, tcp
@@ -22,7 +23,6 @@ def test_app_registry():
r.port = 81
assert not ar.get(r)
r = tutils.treq()
r.host = "domain2"
r.port = 80
@@ -59,3 +59,90 @@ class TestServerConnection:
sc.connection.close = mock.Mock(side_effect=IOError)
sc.terminate()
class MockParser:
def __init__(self):
self.err = None
def error(self, e):
self.err = e
def __repr__(self):
return "ParseError(%s)"%self.err
class TestProcessProxyOptions:
def p(self, *args):
parser = argparse.ArgumentParser()
cmdline.common_options(parser)
opts = parser.parse_args(args=args)
m = MockParser()
return m, proxy.process_proxy_options(m, opts)
def assert_err(self, err, *args):
m, p = self.p(*args)
assert err.lower() in m.err.lower()
def assert_noerr(self, *args):
m, p = self.p(*args)
assert p
return p
def test_simple(self):
assert self.p()
def test_cert(self):
self.assert_noerr("--cert", tutils.test_data.path("data/testkey.pem"))
self.assert_err("does not exist", "--cert", "nonexistent")
def test_confdir(self):
with tutils.tmpdir() as confdir:
self.assert_noerr("--confdir", confdir)
@mock.patch("libmproxy.platform.resolver", None)
def test_no_transparent(self):
self.assert_err("transparent mode not supported", "-T")
@mock.patch("libmproxy.platform.resolver")
def test_transparent_reverse(self, o):
self.assert_err("can't set both", "-P", "reverse", "-T")
self.assert_noerr("-T")
assert o.call_count == 1
self.assert_err("invalid reverse proxy", "-P", "reverse")
self.assert_noerr("-P", "http://localhost")
def test_certs(self):
with tutils.tmpdir() as confdir:
self.assert_noerr("--client-certs", confdir)
self.assert_err("directory does not exist", "--client-certs", "nonexistent")
self.assert_noerr("--dummy-certs", confdir)
self.assert_err("directory does not exist", "--dummy-certs", "nonexistent")
def test_auth(self):
p = self.assert_noerr("--nonanonymous")
assert p.authenticator
p = self.assert_noerr("--htpasswd", tutils.test_data.path("data/htpasswd"))
assert p.authenticator
self.assert_err("invalid htpasswd file", "--htpasswd", tutils.test_data.path("data/htpasswd.invalid"))
p = self.assert_noerr("--singleuser", "test:test")
assert p.authenticator
self.assert_err("invalid single-user specification", "--singleuser", "test")
class TestProxyServer:
def test_err(self):
parser = argparse.ArgumentParser()
cmdline.common_options(parser)
opts = parser.parse_args(args=[])
tutils.raises("error starting proxy server", proxy.ProxyServer, opts, 1)
class TestDummyServer:
def test_simple(self):
d = proxy.DummyServer(None)
d.start_slave()
d.shutdown()

View File

@@ -1,6 +1,6 @@
import socket, time
import mock
from netlib import tcp
from netlib import tcp, http_auth, http
from libpathod import pathoc
import tutils, tservers
from libmproxy import flow, proxy
@@ -13,11 +13,7 @@ from libmproxy import flow, proxy
for a 200 response.
"""
class SanityMixin:
def test_http(self):
assert self.pathod("304").status_code == 304
assert self.master.state.view
class CommonMixin:
def test_large(self):
assert len(self.pathod("200:b@50k").content) == 1024*50
@@ -40,27 +36,30 @@ class SanityMixin:
self.master.replay_request(l, block=True)
assert l.error
def test_http(self):
f = self.pathod("304")
assert f.status_code == 304
class TestHTTP(tservers.HTTPProxTest, SanityMixin):
def test_app(self):
p = self.pathoc()
ret = p.request("get:'http://testapp/'")
assert ret[1] == 200
assert ret[4] == "testapp"
def test_app_err(self):
p = self.pathoc()
ret = p.request("get:'http://errapp/'")
assert ret[1] == 500
assert "ValueError" in ret[4]
l = self.master.state.view[0]
assert l.request.client_conn.address
assert "host" in l.request.headers
assert l.response.code == 304
def test_invalid_http(self):
t = tcp.TCPClient("127.0.0.1", self.proxy.port)
t.connect()
t.wfile.write("invalid\n\n")
t.wfile.write("invalid\r\n\r\n")
t.wfile.flush()
assert "Bad Request" in t.rfile.readline()
class TestHTTP(tservers.HTTPProxTest, CommonMixin):
def test_app_err(self):
p = self.pathoc()
ret = p.request("get:'http://errapp/'")
assert ret.status_code == 500
assert "ValueError" in ret.content
def test_invalid_connect(self):
t = tcp.TCPClient("127.0.0.1", self.proxy.port)
t.connect()
@@ -71,16 +70,7 @@ class TestHTTP(tservers.HTTPProxTest, SanityMixin):
def test_upstream_ssl_error(self):
p = self.pathoc()
ret = p.request("get:'https://localhost:%s/'"%self.server.port)
assert ret[1] == 400
def test_http(self):
f = self.pathod("304")
assert f.status_code == 304
l = self.master.state.view[0]
assert l.request.client_conn.address
assert "host" in l.request.headers
assert l.response.code == 304
assert ret.status_code == 400
def test_connection_close(self):
# Add a body, so we have a content-length header, which combined with
@@ -116,7 +106,7 @@ class TestHTTP(tservers.HTTPProxTest, SanityMixin):
# within our read loop.
with mock.patch("libmproxy.proxy.ProxyHandler.read_request") as m:
m.side_effect = IOError("error!")
tutils.raises("empty reply", self.pathod, "304")
tutils.raises("server disconnect", self.pathod, "304")
def test_get_connection_switching(self):
def switched(l):
@@ -132,30 +122,101 @@ class TestHTTP(tservers.HTTPProxTest, SanityMixin):
def test_get_connection_err(self):
p = self.pathoc()
ret = p.request("get:'http://localhost:0'")
assert ret[1] == 502
assert ret.status_code == 502
def test_blank_leading_line(self):
p = self.pathoc()
req = "get:'%s/p/201':i0,'\r\n'"
assert p.request(req%self.server.urlbase).status_code == 201
def test_invalid_headers(self):
p = self.pathoc()
req = p.request("get:'http://foo':h':foo'='bar'")
assert req.status_code == 400
class TestHTTPS(tservers.HTTPProxTest, SanityMixin):
class TestHTTPAuth(tservers.HTTPProxTest):
authenticator = http_auth.BasicProxyAuth(http_auth.PassManSingleUser("test", "test"), "realm")
def test_auth(self):
assert self.pathod("202").status_code == 407
p = self.pathoc()
ret = p.request("""
get
'http://localhost:%s/p/202'
h'%s'='%s'
"""%(
self.server.port,
http_auth.BasicProxyAuth.AUTH_HEADER,
http.assemble_http_basic_auth("basic", "test", "test")
))
assert ret.status_code == 202
class TestHTTPConnectSSLError(tservers.HTTPProxTest):
certfile = True
def test_go(self):
p = self.pathoc()
req = "connect:'localhost:%s'"%self.proxy.port
assert p.request(req).status_code == 200
assert p.request(req).status_code == 400
class TestHTTPS(tservers.HTTPProxTest, CommonMixin):
ssl = True
clientcerts = True
def test_clientcert(self):
f = self.pathod("304")
assert f.status_code == 304
assert self.server.last_log()["request"]["clientcert"]["keyinfo"]
def test_sni(self):
f = self.pathod("304", sni="testserver.com")
assert f.status_code == 304
l = self.server.last_log()
assert self.server.last_log()["request"]["sni"] == "testserver.com"
class TestHTTPSCertfile(tservers.HTTPProxTest, SanityMixin):
def test_error_post_connect(self):
p = self.pathoc()
assert p.request("get:/:i0,'invalid\r\n\r\n'").status_code == 400
class TestHTTPSNoUpstream(tservers.HTTPProxTest, CommonMixin):
ssl = True
no_upstream_cert = True
def test_cert_gen_error(self):
f = self.pathoc_raw()
f.connect((u"foo..bar".encode("utf8"), 0))
f.request("get:/")
assert "dummy cert" in "".join(self.proxy.log)
class TestHTTPSCertfile(tservers.HTTPProxTest, CommonMixin):
ssl = True
certfile = True
def test_certfile(self):
assert self.pathod("304")
class TestReverse(tservers.ReverseProxTest, SanityMixin):
class TestReverse(tservers.ReverseProxTest, CommonMixin):
reverse = True
class TestTransparent(tservers.TransparentProxTest, SanityMixin):
transparent = True
class TestTransparent(tservers.TransparentProxTest, CommonMixin):
ssl = False
class TestTransparentSSL(tservers.TransparentProxTest, CommonMixin):
ssl = True
def test_sni(self):
f = self.pathod("304", sni="testserver.com")
assert f.status_code == 304
l = self.server.last_log()
assert self.server.last_log()["request"]["sni"] == "testserver.com"
def test_sslerr(self):
p = pathoc.Pathoc("localhost", self.proxy.port)
p.connect()
assert p.request("get:/").status_code == 400
class TestProxy(tservers.HTTPProxTest):
@@ -216,8 +277,7 @@ class MasterFakeResponse(tservers.TestMaster):
class TestFakeResponse(tservers.HTTPProxTest):
masterclass = MasterFakeResponse
def test_kill(self):
p = self.pathoc()
def test_fake(self):
f = self.pathod("200")
assert "header_response" in f.headers.keys()
@@ -231,8 +291,7 @@ class MasterKillRequest(tservers.TestMaster):
class TestKillRequest(tservers.HTTPProxTest):
masterclass = MasterKillRequest
def test_kill(self):
p = self.pathoc()
tutils.raises("empty reply", self.pathod, "200")
tutils.raises("server disconnect", self.pathod, "200")
# Nothing should have hit the server
assert not self.server.last_log()
@@ -245,8 +304,34 @@ class MasterKillResponse(tservers.TestMaster):
class TestKillResponse(tservers.HTTPProxTest):
masterclass = MasterKillResponse
def test_kill(self):
p = self.pathoc()
tutils.raises("empty reply", self.pathod, "200")
tutils.raises("server disconnect", self.pathod, "200")
# The server should have seen a request
assert self.server.last_log()
class EResolver(tservers.TResolver):
def original_addr(self, sock):
return None
class TestTransparentResolveError(tservers.TransparentProxTest):
resolver = EResolver
def test_resolve_error(self):
assert self.pathod("304").status_code == 502
class MasterIncomplete(tservers.TestMaster):
def handle_request(self, m):
resp = tutils.tresp()
resp.content = flow.CONTENT_MISSING
m.reply(resp)
class TestIncompleteResponse(tservers.HTTPProxTest):
masterclass = MasterIncomplete
def test_incomplete(self):
assert self.pathod("200").status_code == 502

View File

@@ -1,6 +1,5 @@
import threading, Queue
import flask
import human_curl as hurl
import libpathod.test, libpathod.pathoc
from libmproxy import proxy, flow, controller
import tutils
@@ -28,7 +27,7 @@ class TestMaster(flow.FlowMaster):
state = flow.State()
flow.FlowMaster.__init__(self, s, state)
self.testq = testq
self.log = []
self.clear_log()
def handle_request(self, m):
flow.FlowMaster.handle_request(self, m)
@@ -38,6 +37,9 @@ class TestMaster(flow.FlowMaster):
flow.FlowMaster.handle_response(self, m)
m.reply()
def clear_log(self):
self.log = []
def handle_log(self, l):
self.log.append(l.msg)
l.reply()
@@ -69,7 +71,8 @@ class ProxTestBase:
ssl = None
clientcerts = False
certfile = None
no_upstream_cert = False
authenticator = None
masterclass = TestMaster
@classmethod
def setupAll(cls):
@@ -78,7 +81,9 @@ class ProxTestBase:
cls.server2 = libpathod.test.Daemon(ssl=cls.ssl)
pconf = cls.get_proxy_config()
config = proxy.ProxyConfig(
no_upstream_cert = cls.no_upstream_cert,
cacert = tutils.test_data.path("data/serverkey.pem"),
authenticator = cls.authenticator,
**pconf
)
tmaster = cls.masterclass(cls.tqueue, config)
@@ -96,7 +101,10 @@ class ProxTestBase:
cls.server2.shutdown()
def setUp(self):
self.master.clear_log()
self.master.state.clear()
self.server.clear_log()
self.server2.clear_log()
@property
def scheme(self):
@@ -122,24 +130,31 @@ class ProxTestBase:
class HTTPProxTest(ProxTestBase):
def pathoc(self, connect_to = None):
def pathoc_raw(self):
return libpathod.pathoc.Pathoc("127.0.0.1", self.proxy.port)
def pathoc(self, sni=None):
"""
Returns a connected Pathoc instance.
"""
p = libpathod.pathoc.Pathoc("localhost", self.proxy.port)
p.connect(connect_to)
p = libpathod.pathoc.Pathoc("localhost", self.proxy.port, ssl=self.ssl, sni=sni)
if self.ssl:
p.connect(("127.0.0.1", self.server.port))
else:
p.connect()
return p
def pathod(self, spec):
def pathod(self, spec, sni=None):
"""
Constructs a pathod request, with the appropriate base and proxy.
Constructs a pathod GET request, with the appropriate base and proxy.
"""
return hurl.get(
self.server.urlbase + "/p/" + spec,
proxy=self.proxies,
validate_cert=False,
#debug=hurl.utils.stdout_debug
)
p = self.pathoc(sni=sni)
spec = spec.encode("string_escape")
if self.ssl:
q = "get:'/p/%s'"%spec
else:
q = "get:'%s/p/%s'"%(self.server.urlbase, spec)
return p.request(q)
class TResolver:
@@ -152,25 +167,39 @@ class TResolver:
class TransparentProxTest(ProxTestBase):
ssl = None
resolver = TResolver
@classmethod
def get_proxy_config(cls):
d = ProxTestBase.get_proxy_config()
if cls.ssl:
ports = [cls.server.port, cls.server2.port]
else:
ports = []
d["transparent_proxy"] = dict(
resolver = TResolver(cls.server.port),
sslports = []
resolver = cls.resolver(cls.server.port),
sslports = ports
)
return d
def pathod(self, spec):
def pathod(self, spec, sni=None):
"""
Constructs a pathod request, with the appropriate base and proxy.
Constructs a pathod GET request, with the appropriate base and proxy.
"""
r = hurl.get(
"http://127.0.0.1:%s"%self.proxy.port + "/p/" + spec,
validate_cert=False,
#debug=hurl.utils.stdout_debug
)
return r
if self.ssl:
p = self.pathoc(sni=sni)
q = "get:'/p/%s'"%spec
else:
p = self.pathoc()
q = "get:'/p/%s'"%spec
return p.request(q)
def pathoc(self, sni=None):
"""
Returns a connected Pathoc instance.
"""
p = libpathod.pathoc.Pathoc("localhost", self.proxy.port, ssl=self.ssl, sni=sni)
p.connect()
return p
class ReverseProxTest(ProxTestBase):
@@ -185,14 +214,23 @@ class ReverseProxTest(ProxTestBase):
)
return d
def pathod(self, spec):
def pathoc(self, sni=None):
"""
Constructs a pathod request, with the appropriate base and proxy.
Returns a connected Pathoc instance.
"""
r = hurl.get(
"http://127.0.0.1:%s"%self.proxy.port + "/p/" + spec,
validate_cert=False,
#debug=hurl.utils.stdout_debug
)
return r
p = libpathod.pathoc.Pathoc("localhost", self.proxy.port, ssl=self.ssl, sni=sni)
p.connect()
return p
def pathod(self, spec, sni=None):
"""
Constructs a pathod GET request, with the appropriate base and proxy.
"""
if self.ssl:
p = self.pathoc(sni=sni)
q = "get:'/p/%s'"%spec
else:
p = self.pathoc()
q = "get:'/p/%s'"%spec
return p.request(q)

24
todo
View File

@@ -1,24 +0,0 @@
This is a loose collection of todo items, in case someone else wants to start
hacking on mitmproxy. Drop me a line (aldo@corte.si) if you want to tackle any
of these and need some pointers.
Targeted for 0.9:
- White-background colorscheme
- Extra content view modules: CSS indenter, Flash SWF info extractor
- Upstream proxy support.
- Follow mode to keep most recent flow in view
- Verbose view to show timestamps
- Search within requests/responses
- Transparent proxy support
- Ordering a-la mutt's "o" shortcut
Future:
- Add some "workspace" features to mitmproxy:
- Flow comments
- Copying/duplicating flows
- Ordering by time, size, etc. a-la-mutt (o keyboard shorcut is reserved for this)
- Support HTTP Digest authentication through the stickyauth option. We'll
have to save the server nonce, and recalculate the hashes for each request.
- Chunked encoding support for requests (we already support it for responses).
- A progress indicator for large files