pax_global_header 0000666 0000000 0000000 00000000064 13374230531 0014513 g ustar 00root root 0000000 0000000 52 comment=b13ddc928326c62e25a88ac2390bcbe9c2ac4db8
.gitignore 0000664 0000000 0000000 00000000044 13374230531 0013045 0 ustar 00root root 0000000 0000000 __pycache__
aiosasl.egg-info
.local
.travis.yml 0000664 0000000 0000000 00000000441 13374230531 0013167 0 ustar 00root root 0000000 0000000 language: python
cache:
pip: true
python:
- "3.4"
- "3.5"
- "3.6"
- "3.7-dev"
install:
- pip install nose coveralls pyOpenSSL
- pip install .
script:
- nosetests --with-cover --cover-package aiosasl tests
after_success:
- if [[ "$TRAVIS_PYTHON_VERSION" == '3.6' ]]; then coveralls; fi
COPYING.LESSER 0000664 0000000 0000000 00000016743 13374230531 0013121 0 ustar 00root root 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
COPYING.gpl3 0000664 0000000 0000000 00000104513 13374230531 0012762 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
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.
Copyright (C)
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 .
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:
Copyright (C)
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
.
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
.
LICENSES 0000664 0000000 0000000 00000000241 13374230531 0012204 0 ustar 00root root 0000000 0000000 License
=======
The whole ``aiosasl`` package is distributed under the LGPLv3. See ``COPYING.gpl3`` together with ``COPYING.LESSER`` for the full license text.
MANIFEST.in 0000664 0000000 0000000 00000000075 13374230531 0012617 0 ustar 00root root 0000000 0000000 include COPYING.gpl3
include COPYING.LESSER
include LICENSES
Makefile 0000664 0000000 0000000 00000000273 13374230531 0012521 0 ustar 00root root 0000000 0000000 SPHINXBUILD ?= sphinx-build-3
docs-html:
cd docs; $(MAKE) SPHINXBUILD=$(SPHINXBUILD) html
docs-view-html: docs-html
xdg-open docs/sphinx-data/build/html/index.html
.PHONY: docs-html
README.rst 0000664 0000000 0000000 00000002615 13374230531 0012552 0 ustar 00root root 0000000 0000000 ``aiosasl``, pure python generic asyncio SASL library
#####################################################
.. image:: https://travis-ci.org/horazont/aiosasl.svg?branch=devel
:target: https://travis-ci.org/horazont/aiosasl
.. image:: https://coveralls.io/repos/github/horazont/aiosasl/badge.svg?branch=devel
:target: https://coveralls.io/github/horazont/aiosasl?branch=devel
``aiosasl`` provides a generic, asyncio-based SASL library. It can be used with
any protocol, provided the neccessary interface code is provided by the
application or protocol implementation.
Dependencies
------------
* Python ≥ 3.4 (or Python = 3.3 with tulip)
Supported SASL mechanisms
-------------------------
* ``PLAIN``: authenticate with plaintext password (RFC 4616)
* ``ANONYMOUS``: anonymous "authentication" (RFC 4505)
* ``SCRAM-SHA-1``, ``SCRAM-SHA-224``, , ``SCRAM-SHA-512``, ``SCRAM-SHA-384``,
and ``SCRAM-SHA-256``: Salted Challenge Response Authentication (RFC 5802),
(and the ``-PLUS`` variants with channel binding).
Documentation
-------------
Official documentation can be built with sphinx and is available online
`on our servers `_.
Supported channel binding methods
---------------------------------
* ``tls-unique`` and ``tls-server-end-point`` with a pyOpenSSL connection
* all methods supported by the Python standard library when using the
``ssl`` module
aiosasl/ 0000775 0000000 0000000 00000000000 13374230531 0012512 5 ustar 00root root 0000000 0000000 aiosasl/__init__.py 0000664 0000000 0000000 00000077141 13374230531 0014635 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: __init__.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
"""
Using SASL in a protocol
========================
To make use of SASL over an existing protocol, you first need to subclass and
implement :class:`SASLInterface`.
The usable mechanisms need to be detected by your application using the
protocol over which to implement SASL. This is generally protocol-specific. For
example, XMPP uses stream features to announce which SASL mechanisms are
supported by the server.
When a set of SASL mechanism strings has been obtained by the server (let us
call a set with the mechanism strings ``sasl_mechanisms``), the mechanisms
supported by your application (a list of :class:`SASLMechanism` subclass
instances, let us call it ``mechanism_impls``) can be queried for support::
# intf =
for impl in mechanism_impl:
token = impl.any_supported(sasl_mechanisms)
if token is not None:
sm = aiosasl.SASLStateMachine(intf)
try:
yield from impl.authenticate(sm, token)
except aiosasl.AuthenticationFailure:
# handle authentication failure
# it is generally not sensible to re-try with other mechanisms
except aiosasl.SASLFailure:
# this is a protocol problem, it is sensible to re-try other
# mechanisms
else:
# authentication was successful!
The instances for the mechanisms can be re-used; they do not save any state,
the state is held by :class:`SASLStateMachine` instead. The different
mechanisms require different arguments (the password-based mechanisms generally
require a callback which provides credentials).
The mechanisms which are currently supported by :mod:`aiosasl` are summarised
below:
.. autosummary::
PLAIN
SCRAM
SCRAMPLUS
Interface for protocols using SASL
==================================
To implement SASL on an existing protocol, you need to subclass
:class:`SASLInterface` and implement the abstract methods:
.. autoclass:: SASLInterface
.. autoclass:: SASLState
SASL mechansims
===============
.. autoclass:: PLAIN
.. autoclass:: SCRAM(credential_provider, *[, after_scram_plus=False][, enforce_minimum_iteration_count=True])
.. autoclass:: SCRAMPLUS(credential_provider, cb_provider, *[, enforce_minimum_iteration_count=True])
.. autoclass:: ANONYMOUS
Base class
----------
.. autoclass:: SASLMechanism
A note for implementers
-----------------------
The :class:`SASLStateMachine` unwraps `(SASLState.SUCCESS, payload)` messages
passed in from a :class:`SASLInterface` to the equivalent sequence
`(SASLState.CHALLENGE, payload)` (requiring the empty string as response) and
`(SASLState.SUCCESS, None)`. The two forms are equivalent as per the SASL
specification and this unwrapping allows uniform treatment of both
forms by the :class:`SASLMechanism` implementations.
SASL state machine
==================
.. autoclass:: SASLStateMachine
Exception classes
=================
.. autoclass:: SASLError
.. autoclass:: SASLFailure
.. autoclass:: AuthenticationFailure
Version information
===================
.. autodata:: __version__
.. autodata:: version_info
"""
import abc
import asyncio
import base64
import collections
import enum
import functools
import hashlib
import hmac
import logging
import random
import time
from aiosasl.stringprep import saslprep, trace
from aiosasl.utils import xor_bytes
from .version import version, __version__, version_info # NOQA
logger = logging.getLogger(__name__)
#: The imported :mod:`aiosasl` version as a tuple.
#:
#: The components of the tuple are, in order: `major version`, `minor version`,
#: `patch level`, and `pre-release identifier`.
version_info = version_info
#: The imported :mod:`aiosasl` version as a string.
#:
#: The version number is dot-separated; in pre-release or development versions,
#: the version number is followed by a hypen-separated pre-release identifier.
__version__ = __version__
_system_random = random.SystemRandom()
try:
from hashlib import pbkdf2_hmac as pbkdf2
except ImportError:
# this is untested if you have pbkdf2_hmac
def pbkdf2(hashfun_name, input_data, salt, iterations, dklen=None):
"""
Derivate a key from a password. `input_data` is taken as the bytes
object resembling the password (or other input). `hashfun` must be a
callable returning a :mod:`hashlib`-compatible hash function. `salt` is
the salt to be used in the PBKDF2 run, `iterations` the count of
iterations. `dklen` is the length in bytes of the key to be derived.
Return the derived key as :class:`bytes` object.
"""
if dklen is not None and dklen <= 0:
raise ValueError("Invalid length for derived key: {}".format(
dklen))
hashfun = lambda: hashlib.new(hashfun_name)
hlen = hashfun().digest_size
if dklen is None:
dklen = hlen
block_count = (dklen + (hlen - 1)) // hlen
mac_base = hmac.new(input_data, None, hashfun)
def do_hmac(data):
mac = mac_base.copy()
mac.update(data)
return mac.digest()
def calc_block(i):
u_prev = do_hmac(salt + i.to_bytes(4, "big"))
u_accum = u_prev
for k in range(1, iterations):
u_curr = do_hmac(u_prev)
u_accum = xor_bytes(u_accum, u_curr)
u_prev = u_curr
return u_accum
result = b"".join(
calc_block(i)
for i in range(1, block_count + 1))
return result[:dklen]
class SASLError(Exception):
"""
Base class for a SASL related error. `opaque_error` may be anything but
:data:`None` which helps your application re-identify the error at the
outer layers. `kind` is a string which helps identifying the class of the
error; this is set implicitly by the constructors of :class:`SASLFailure`
and :class:`AuthenticationFailure`, which you are encouraged to use.
`text` may be a human-readable string describing the error condition in
more detail.
`opaque_error` is set to :data:`None` by :class:`SASLMechanism`
implementations to indicate errors which originate from the local mechanism
implementation.
.. attribute:: opaque_error
The value passed to the respective constructor argument.
.. attribute:: text
The value passed to the respective constructor argument.
"""
def __init__(self, opaque_error, kind, text=None):
msg = "{}: {}".format(opaque_error, kind)
if text:
msg += ": {}".format(text)
super().__init__(msg)
self.opaque_error = opaque_error
self.text = text
class SASLFailure(SASLError):
"""
A SASL protocol failure which is unrelated to the credentials passed. This
may be raised by :class:`SASLInterface` methods.
"""
def __init__(self, opaque_error, text=None):
super().__init__(opaque_error, "SASL failure", text=text)
def promote_to_authentication_failure(self):
return AuthenticationFailure(
self.opaque_error,
self.text)
class AuthenticationFailure(SASLError):
"""
A SASL error which indicates that the provided credentials are
invalid. This may be raised by :class:`SASLInterface` methods.
"""
def __init__(self, opaque_error, text=None):
super().__init__(opaque_error, "authentication failed", text=text)
class SASLState(enum.Enum):
"""
The states of the SASL state machine.
.. attribute:: CHALLENGE
the server sent a SASL challenge
.. attribute:: SUCCESS
the authentication was successful
.. attribute:: FAILURE
the authentication failed
Internal states used by the state machine:
.. attribute:: INITIAL
the state of the state machine before the
authentication is started
.. attribute:: SUCCESS_SIMULATE_CHALLENGE
used to unwrap success replies that carry final data
These internal states *must not* be returned by the
:class:`SASLInterface` methods as first component of the result
tuple.
The following method is used to process replies returned
by the :class:`SASLInterface` methods:
.. method:: from_reply
"""
INITIAL = "initial"
CHALLENGE = "challenge"
SUCCESS = "success"
FAILURE = "failure"
SUCCESS_SIMULATE_CHALLENGE = "success-simulate-challenge"
@classmethod
def from_reply(cls, state):
"""
Comptaibility layer for old :class:`SASLInterface`
implementations.
Accepts the follwing set of :class:`SASLState` or strings and
maps the strings to :class:`SASLState` elements as follows:
``"challenge"``
:member:`SASLState.CHALLENGE`
``"failue"``
:member:`SASLState.FAILURE`
``"success"``
:member:`SASLState.SUCCESS`
"""
if state in (SASLState.FAILURE, SASLState.SUCCESS,
SASLState.CHALLENGE):
return state
if state in ("failure", "success", "challenge"):
return SASLState(state)
else:
raise RuntimeError("invalid SASL state", state)
class SASLInterface(metaclass=abc.ABCMeta):
"""
This class serves as an abstract base class for interfaces for use with
:class:`SASLStateMachine`. Specific protocols using SASL (such as XMPP,
IMAP or SMTP) can subclass this interface to implement SASL on top of the
existing protocol.
The interface class does not need to implement any state checking. State
checking is done by the :class:`SASLStateMachine`. The following interface
must be implemented by subclasses.
The return values of the methods below are tuples of the following form:
* ``(SASLState.SUCCESS, payload)`` -- After successful
authentication, success is returned. Depending on the mechanism,
a payload (as :class:`bytes` object) may be attached to the
result, otherwise, ``payload`` is :data:`None`.
* ``(SASLState.CHALLENGE, payload)`` -- A challenge was sent by
the server in reply to the previous command.
* ``(SASLState.FAILURE, None)`` -- This is only ever returned by
:meth:`abort`. All other methods **must** raise errors as
:class:`SASLFailure`.
.. versionchanged:: 0.4
The first element of the returned tuples are now elements of
:class:`SASLState`. For compatibility with previous versions of
``aiosasl`` the first elements of the string may be one of the
strings ``"success"``, ``"failure"`` or "``challenge``". For
more information see :meth:`SASLState.from_reply`.
.. automethod:: initiate
.. automethod:: respond
.. automethod:: abort
"""
@abc.abstractmethod
@asyncio.coroutine
def initiate(self, mechanism, payload=None):
"""
Send a SASL initiation request for the given `mechanism`. Depending on
the `mechanism`, an initial `payload` *may* be given. The `payload` is
then a :class:`bytes` object which needs to be passed as initial
payload during the initiation request.
Wait for a reply by the peer and return the reply as a next-state tuple
in the format documented at :class:`SASLInterface`.
"""
@abc.abstractmethod
@asyncio.coroutine
def respond(self, payload):
"""
Send a response to a challenge. The `payload` is a :class:`bytes`
object which is to be sent as response.
Wait for a reply by the peer and return the reply as a next-state tuple
in the format documented at :class:`SASLInterface`.
"""
@abc.abstractmethod
@asyncio.coroutine
def abort(self):
"""
Abort the authentication. The result is either the failure tuple
(``(SASLState.FAILURE, None)``) or a :class:`SASLFailure` exception if
the response from the peer did not indicate abortion (e.g. another
error was returned by the peer or the peer indicated success).
"""
class SASLStateMachine:
"""
A state machine to reduce code duplication during SASL handshake.
The state methods change the state and return the next client state of the
SASL handshake, optionally with server-supplied payload.
Note that, with the notable exception of :meth:`abort`, ``failure`` states
are never returned but thrown as :class:`SASLFailure` instead.
The initial state is never returned.
"""
def __init__(self, interface):
super().__init__()
self.interface = interface
self._state = SASLState.INITIAL
@asyncio.coroutine
def initiate(self, mechanism, payload=None):
"""
Initiate the SASL handshake and advertise the use of the given
`mechanism`. If `payload` is not :data:`None`, it will be base64
encoded and sent as initial client response along with the ````
element.
Return the next state of the state machine as tuple (see
:class:`SASLStateMachine` for details).
"""
if self._state != SASLState.INITIAL:
raise RuntimeError("initiate has already been called")
try:
next_state, payload = yield from self.interface.initiate(
mechanism,
payload=payload)
except SASLFailure:
self._state = SASLState.FAILURE
raise
next_state = SASLState.from_reply(next_state)
self._state = next_state
return next_state, payload
@asyncio.coroutine
def response(self, payload):
"""
Send a response to the previously received challenge, with the given
`payload`. The payload is encoded using base64 and transmitted to the
server.
Return the next state of the state machine as tuple (see
:class:`SASLStateMachine` for details).
"""
if self._state == SASLState.SUCCESS_SIMULATE_CHALLENGE:
if payload != b"":
# XXX: either our mechanism is buggy or the server
# sent SASLState.SUCCESS before all challenge-response
# messages defined by the mechanism were sent
self._state = SASLState.FAILURE
raise SASLFailure(
None,
"protocol violation: mechanism did not"
" respond with an empty response to a"
" challenge with final data – this suggests"
" a protocol-violating early success from the server."
)
self._state = SASLState.SUCCESS
return SASLState.SUCCESS, None
if self._state != SASLState.CHALLENGE:
raise RuntimeError(
"no challenge has been made or negotiation failed")
try:
next_state, payload = yield from self.interface.respond(payload)
except SASLFailure:
self._state = SASLState.FAILURE
raise
next_state = SASLState.from_reply(next_state)
# unfold the (SASLState.SUCCESS, payload) to a sequence of
# (SASLState.CHALLENGE, payload), (SASLState.SUCCESS, None) for the SASLMethod
# to allow uniform treatment of both cases
if next_state == SASLState.SUCCESS and payload is not None:
self._state = SASLState.SUCCESS_SIMULATE_CHALLENGE
return SASLState.CHALLENGE, payload
self._state = next_state
return next_state, payload
@asyncio.coroutine
def abort(self):
"""
Abort an initiated SASL authentication process. The expected result
state is ``failure``.
"""
if self._state == SASLState.INITIAL:
raise RuntimeError("SASL authentication hasn't started yet")
if self._state == SASLState.SUCCESS_SIMULATE_CHALLENGE:
raise RuntimeError("SASL message exchange already over")
try:
return (yield from self.interface.abort())
finally:
self._state = SASLState.FAILURE
class SASLMechanism(metaclass=abc.ABCMeta):
"""
Implementation of a SASL mechanism. Two methods must be implemented by
subclasses:
.. automethod:: any_supported
.. automethod:: authenticate
.. note:: Administrative note
Patches for new SASL mechanisms are welcome!
"""
@abc.abstractclassmethod
def any_supported(cls, mechanisms):
"""
Determine whether this class can perform any SASL mechanism in the set
of strings ``mechanisms``.
If the class cannot perform any of the SASL mechanisms in
``mechanisms``, it must return :data:`None`.
Otherwise, it must return a non-:data:`None` value. Applications must
not assign any meaning to any value (except that :data:`None` is a sure
indicator that the class cannot perform any of the listed mechanisms)
and must not alter any value returned by this function. Note that even
:data:`False` indicates success!
The return value must be passed as second argument to
:meth:`authenticate`. :meth:`authenticate` must not be called with a
:data:`None` value.
"""
@asyncio.coroutine
@abc.abstractmethod
def authenticate(self, sm, token):
"""
Execute the mechanism identified by `token` (the non-:data:`None` value
which has been returned by :meth:`any_supported` before) using the
given :class:`SASLStateMachine` `sm`.
If authentication fails, an appropriate exception is raised
(:class:`AuthenticationFailure`). If the authentication fails for a
reason unrelated to credentials, :class:`SASLFailure` is raised.
"""
class PLAIN(SASLMechanism):
"""
The password-based ``PLAIN`` SASL mechanism (see :rfc:`4616`).
.. warning::
This is generally unsafe over unencrypted connections and should not be
used there. Exclusion of the ``PLAIN`` mechanism over unsafe connections
is out of scope for :mod:`aiosasl` and needs to be handled by the
protocol implementation!
`credential_provider` must be coroutine which returns a ``(user,
password)`` tuple.
"""
def __init__(self, credential_provider):
super().__init__()
self._credential_provider = credential_provider
@classmethod
def any_supported(cls, mechanisms):
if "PLAIN" in mechanisms:
return "PLAIN"
return None
@asyncio.coroutine
def authenticate(self, sm, mechanism):
logger.info("attempting PLAIN mechanism")
username, password = yield from self._credential_provider()
username = saslprep(username).encode("utf8")
password = saslprep(password).encode("utf8")
state, _ = yield from sm.initiate(
mechanism="PLAIN",
payload=b"\0" + username + b"\0" + password)
if state != SASLState.SUCCESS:
raise SASLFailure(
None,
text="SASL protocol violation")
return True
SCRAMHashInfo = collections.namedtuple(
"SCRAMHashInfo",
[
"hashfun_name",
"quality",
"minimum_iteration_count",
]
)
class SCRAMBase:
"""
Shared implementation of SCRAM and SCRAMPLUS.
"""
def __init__(self, credential_provider, *, nonce_length=15,
enforce_minimum_iteration_count=True):
super().__init__()
self._credential_provider = credential_provider
self.nonce_length = nonce_length
self.enforce_minimum_iteration_count = enforce_minimum_iteration_count
_supported_hashalgos = {
# the second argument is for preference ordering (highest first)
# if anyone has a better hash ordering suggestion, I’m open for it
# a value of 1 is added if the -PLUS variant is used
# -- JSC
# the minimum iteration count is obtained from
#
"SHA-1": SCRAMHashInfo("sha1", 1, 4096),
"SHA-256": SCRAMHashInfo("sha256", 256, 4096),
}
@classmethod
def any_supported(cls, mechanisms):
supported = []
for mechanism in mechanisms:
if not mechanism.startswith("SCRAM-"):
continue
hashfun_key = mechanism[6:]
if cls._channel_binding:
if not mechanism.endswith("-PLUS"):
continue
hashfun_key = hashfun_key[:-5]
else:
if mechanism.endswith("-PLUS"):
continue
try:
info = cls._supported_hashalgos[hashfun_key]
except KeyError:
continue
supported.append(((1, info.quality), (mechanism, info,)))
if not supported:
return None
supported.sort()
return supported.pop()[1]
@classmethod
def parse_message(cls, msg):
parts = (
part
for part in msg.split(b",")
if part)
for part in parts:
key, _, value = part.partition(b"=")
if len(key) > 1 or key == b"m":
raise Exception("SCRAM protocol violation / unknown "
"future extension")
if key == b"n" or key == b"a":
value = value.replace(b"=2C", b",").replace(b"=3D", b"=")
yield key, value
@asyncio.coroutine
def authenticate(self, sm, token):
mechanism, info, = token
logger.info("attempting %s mechanism (using %s hashfun)",
mechanism,
info)
# this is pretty much a verbatim implementation of RFC 5802.
hashfun_factory = functools.partial(hashlib.new, info.hashfun_name)
gs2_header = self._get_gs2_header()
username, password = yield from self._credential_provider()
username = saslprep(username).encode("utf8")
password = saslprep(password).encode("utf8")
our_nonce = base64.b64encode(_system_random.getrandbits(
self.nonce_length * 8
).to_bytes(
self.nonce_length, "little"
))
auth_message = b"n=" + username + b",r=" + our_nonce
state, payload = yield from sm.initiate(
mechanism,
gs2_header + auth_message)
if state != SASLState.CHALLENGE or payload is None:
yield from sm.abort()
raise SASLFailure(
None,
text="protocol violation: expected challenge with payload")
auth_message += b"," + payload
payload = dict(self.parse_message(payload))
try:
iteration_count = int(payload[b"i"])
nonce = payload[b"r"]
salt = base64.b64decode(payload[b"s"])
except (ValueError, KeyError):
yield from sm.abort()
raise SASLFailure(
None,
text="malformed server message: {!r}".format(payload))
if not nonce.startswith(our_nonce):
yield from sm.abort()
raise SASLFailure(
None,
text="server nonce doesn't fit our nonce")
if (self.enforce_minimum_iteration_count and
iteration_count < info.minimum_iteration_count):
raise SASLFailure(
None,
text="minimum iteration count for {} violated "
"({} is less than {})".format(
mechanism,
iteration_count,
info.minimum_iteration_count,
)
)
t0 = time.time()
salted_password = pbkdf2(
info.hashfun_name,
password,
salt,
iteration_count)
logger.debug("pbkdf2 timing: %f seconds", time.time() - t0)
client_key = hmac.new(
salted_password,
b"Client Key",
hashfun_factory).digest()
stored_key = hashfun_factory(client_key).digest()
reply = b"c=" + base64.b64encode(self._get_cb_data()) + b",r=" + nonce
auth_message += b"," + reply
client_proof = xor_bytes(
hmac.new(
stored_key,
auth_message,
hashfun_factory).digest(),
client_key)
logger.debug("response generation time: %f seconds", time.time() - t0)
try:
state, payload = yield from sm.response(
reply + b",p=" + base64.b64encode(client_proof)
)
except SASLFailure as err:
raise err.promote_to_authentication_failure() from None
# this is the pseudo-challenge for the server signature
# we have to reply with the empty string!
if state != SASLState.CHALLENGE:
raise SASLFailure(
"malformed-request",
text="SCRAM protocol violation")
state, dummy_payload = yield from sm.response(b"")
if state != SASLState.SUCCESS or dummy_payload is not None:
raise SASLFailure(
None,
"SASL protocol violation")
server_signature = hmac.new(
hmac.new(
salted_password,
b"Server Key",
hashfun_factory).digest(),
auth_message,
hashfun_factory).digest()
payload = dict(self.parse_message(payload))
if base64.b64decode(payload[b"v"]) != server_signature:
raise SASLFailure(
None,
"authentication successful, but server signature invalid")
return True
class SCRAM(SCRAMBase, SASLMechanism):
"""
The password-based SCRAM (non-PLUS) SASL mechanism (see :rfc:`5802`).
:param credential_provider: A coroutine function which returns credentials.
:param after_scram_plus: Flag to indicate that SCRAM-PLUS *is* supported by
your implementation.
:type after_scram_plus: :class:`bool`
:param enforce_minimum_iteration_count: Enforce the minimum iteration
count specified by the SCRAM specifications.
:type enforce_minimum_iteration_count: :class:`bool`
.. note::
As "non-PLUS" suggests, this does not support channel binding.
Use :class:`SCRAMPLUS` if you want channel binding.
`credential_provider` must be coroutine function which returns a ``(user,
password)`` tuple.
If this is used after :class:`SCRAMPLUS` in a method list, the
keyword argument `after_scram_plus` should be set to
:data:`True`. Then we will use the gs2 header ``y,,`` to prevent
down-grade attacks by a man-in-the-middle attacker.
`enforce_minimum_iteration_count` controls the enforcement of the specified
minimum iteration count for the key derivation function used in SCRAM. By
default, this enforcement is enabled, and you are strongly advised to not
disable it: it can be used to make the exchange weaker.
Disabling `enforce_minimum_iteration_count` only makes sense if the
authentication exchange would otherwise fall back to using :class:`PLAIN`
or a similarly weak authentication mechanism.
.. versionchanged:: 0.4
The `enforce_minimum_iteration_count` argument and the behaviour to
enforce the minimum iteration count by default was added.
"""
_channel_binding = False
def __init__(self, credential_provider, *, after_scram_plus=False,
**kwargs):
super().__init__(credential_provider, **kwargs)
self._after_scram_plus = after_scram_plus
def _get_gs2_header(self):
if self._after_scram_plus:
return b"y,,"
else:
return b"n,,"
def _get_cb_data(self):
return self._get_gs2_header()
class ChannelBindingProvider(metaclass=abc.ABCMeta):
"""
Interface for a channel binding method.
The needed external information is supplied to the constructors of
the specific instances.
"""
@abc.abstractproperty
def cb_name(self):
"""
Return the name of the channel-binding mechanism.
:rtype: :class:`bytes`
"""
raise NotImplementedError
@abc.abstractmethod
def extract_cb_data(self):
"""
Return the channel binding data.
:returns: the channel binding data
:rtype: :class:`bytes`
"""
raise NotImplementedError
class SCRAMPLUS(SCRAMBase, SASLMechanism):
"""
The password-based SCRAM-PLUS SASL mechanism (see :rfc:`5802`).
:param credential_provider: A coroutine function which returns credentials.
:param cb_provider: Object which provides channel binding data and
information.
:type cb_provider: :class:`ChannelBindingProvider`
:param after_scram_plus: Flag to indicate that SCRAM-PLUS *is* supported by
your implementation.
:type after_scram_plus: :class:`bool`
:param enforce_minimum_iteration_count: Enforce the minimum iteration
count specified by the SCRAM specifications.
:type enforce_minimum_iteration_count: :class:`bool`
`credential_provider` must be coroutine which returns a ``(user,
password)`` tuple.
`cb_provider` must be an instance of
:class:`ChannelBindingProvider`, which specifies and implements
the channel binding type to use.
`enforce_minimum_iteration_count` controls the enforcement of the specified
minimum iteration count for the key derivation function used in SCRAM. By
default, this enforcement is enabled, and you are strongly advised to not
disable it: it can be used to make the exchange weaker.
.. seealso::
:class:`SCRAM` for more information on
`enforce_minimum_iteration_count`.
.. versionchanged:: 0.4
The `enforce_minimum_iteration_count` argument and the behaviour to
enforce the minimum iteration count by default was added.
"""
_channel_binding = True
def __init__(self, credential_provider, cb_provider,
**kwargs):
super().__init__(credential_provider, **kwargs)
self._cb_provider = cb_provider
def _get_gs2_header(self):
return b"p=" + self._cb_provider.cb_name + b",,"
def _get_cb_data(self):
gs2_header = self._get_gs2_header()
cb_data = self._cb_provider.extract_cb_data()
return gs2_header + cb_data
class ANONYMOUS(SASLMechanism):
"""
The ANONYMOUS SASL mechanism (see :rfc:`4505`).
.. versionadded:: 0.3
"""
def __init__(self, token):
super().__init__()
self._token = trace(token).encode("utf-8")
@classmethod
def any_supported(self, mechanisms):
if "ANONYMOUS" in mechanisms:
return "ANONYMOUS"
return None
@asyncio.coroutine
def authenticate(self, sm, mechanism):
logger.info("attempting ANONYMOUS mechanism")
state, _ = yield from sm.initiate(
mechanism="ANONYMOUS",
payload=self._token
)
if state != SASLState.SUCCESS:
raise SASLFailure(
None,
text="SASL protocol violation")
return True
aiosasl/channel_binding_methods.py 0000664 0000000 0000000 00000006540 13374230531 0017716 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: channel_binding_methods.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
"""
Channel binding methods
=======================
The module :mod:`aiosasl.channel_binding_methods` provides
implementations of the :class:`~aiosasl.ChannelBindingProvider`
interface for use with :mod:`ssl` respective :mod:`OpenSSL`.
.. autoclass:: StdlibTLS
.. autoclass:: TLSUnique
.. autoclass:: TLSServerEndPoint
"""
import functools
from . import ChannelBindingProvider
class StdlibTLS(ChannelBindingProvider):
"""
Provider for channel binding for :mod:`ssl`.
:param connection: the SSL connection
:type connection: :class:`ssl.SSLSocket`
:param type_: the channel binding type
:type type_: :class:`str`
"""
def __init__(self, connection, type_):
super().__init__()
self._connection = connection
self._type = type_
@property
def cb_name(self):
return self._type.encode("us-ascii")
def extract_cb_data(self):
return self._connection.get_channel_binding(self._type)
class TLSUnique(ChannelBindingProvider):
"""
Provider for the channel binding ``tls-unique`` as specified by
:rfc:`5929` for :mod:`OpenSSL`.
.. warning::
This only supports connections that were not created by session
resumption.
:param connection: the SSL connection
:type connection: :class:`OpenSSL.SSL.Connection`
"""
def __init__(self, connection):
super().__init__()
self._connection = connection
@property
def cb_name(self):
return b"tls-unique"
def extract_cb_data(self):
return self._connection.get_finished()
def parse_openssl_digest(digest):
return bytes(map(functools.partial(int, base=16), digest.split(b":")))
class TLSServerEndPoint(ChannelBindingProvider):
"""
Provider for the channel binding ``tls-server-end-point`` as
specified by :rfc:`5929` for :mod:`OpenSSL`.
:param connection: the SSL connection
:type connection: :class:`OpenSSL.SSL.Connection`
"""
def __init__(self, connection):
super().__init__()
self._connection = connection
@property
def cb_name(self):
return b"tls-server-end-point"
def extract_cb_data(self):
cert = self._connection.get_peer_certificate()
algo, part, _ = cert.get_signature_algorithm().lower().partition(
b"with")
if not part:
raise NotImplementedError
if algo in (b"sha1", b"md5"):
algo = b"sha256"
return parse_openssl_digest(cert.digest(algo.decode("us-ascii")))
aiosasl/stringprep.py 0000664 0000000 0000000 00000013116 13374230531 0015263 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: stringprep.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
"""
Stringprep support
##################
This module implements the SASLprep (`RFC 4013`_) stringprep profile.
.. autofunction:: saslprep
.. _RFC 4013: https://tools.ietf.org/html/rfc4013
"""
import stringprep
from unicodedata import ucd_3_2_0 as unicodedata
_nodeprep_prohibited = frozenset("\"&'/:<>@")
def is_RandALCat(c):
return unicodedata.bidirectional(c) in ("R", "AL")
def is_LCat(c):
return unicodedata.bidirectional(c) == "L"
def check_against_tables(chars, tables):
"""
Perform a check against the table predicates in `tables`. `tables` must be
a reusable iterable containing characteristic functions of character sets,
that is, functions which return :data:`True` if the character is in the
table.
The function returns the first character occuring in any of the tables or
:data:`None` if no character matches.
"""
for c in chars:
if any(in_table(c) for in_table in tables):
return c
return None
def do_normalization(chars):
"""
Perform the stringprep normalization. Operates in-place on a list of
unicode characters provided in `chars`.
"""
chars[:] = list(unicodedata.normalize("NFKC", "".join(chars)))
def check_bidi(chars):
"""
Check proper bidirectionality as per stringprep. Operates on a list of
unicode characters provided in `chars`.
"""
# the empty string is valid, as it cannot violate the RandALCat constraints
if not chars:
return
# first_is_RorAL = unicodedata.bidirectional(chars[0]) in {"R", "AL"}
# if first_is_RorAL:
has_RandALCat = any(is_RandALCat(c) for c in chars)
if not has_RandALCat:
return
has_LCat = any(is_LCat(c) for c in chars)
if has_LCat:
raise ValueError("L and R/AL characters must not occur in the same"
" string")
if not is_RandALCat(chars[0]) or not is_RandALCat(chars[-1]):
raise ValueError("R/AL string must start and end with R/AL character.")
def check_prohibited_output(chars, bad_tables):
"""
Check against prohibited output, by checking whether any of the characters
from `chars` are in any of the `bad_tables`.
Operates in-place on a list of code points from `chars`.
"""
violator = check_against_tables(chars, bad_tables)
if violator is not None:
raise ValueError("Input contains invalid unicode codepoint: "
"U+{:04x}".format(ord(violator)))
def check_unassigned(chars, bad_tables):
"""
Check that `chars` does not contain any unassigned code points as per
the given list of `bad_tables`.
Operates on a list of unicode code points provided in `chars`.
"""
bad_tables = (
stringprep.in_table_a1,)
violator = check_against_tables(chars, bad_tables)
if violator is not None:
raise ValueError("Input contains unassigned code point: "
"U+{:04x}".format(ord(violator)))
def _saslprep_do_mapping(chars):
"""
Perform the stringprep mapping step of SASLprep. Operates in-place on a
list of unicode characters provided in `chars`.
"""
i = 0
while i < len(chars):
c = chars[i]
if stringprep.in_table_c12(c):
chars[i] = "\u0020"
elif stringprep.in_table_b1(c):
del chars[i]
continue
i += 1
def saslprep(string, allow_unassigned=False):
"""
Process the given `string` using the SASLprep profile. In the error cases
defined in `RFC 3454`_ (stringprep), a :class:`ValueError` is raised.
"""
chars = list(string)
_saslprep_do_mapping(chars)
do_normalization(chars)
check_prohibited_output(
chars,
(
stringprep.in_table_c12,
stringprep.in_table_c21,
stringprep.in_table_c22,
stringprep.in_table_c3,
stringprep.in_table_c4,
stringprep.in_table_c5,
stringprep.in_table_c6,
stringprep.in_table_c7,
stringprep.in_table_c8,
stringprep.in_table_c9
)
)
check_bidi(chars)
if not allow_unassigned:
check_unassigned(
chars,
(
stringprep.in_table_a1,
)
)
return "".join(chars)
def trace(string):
"""
Implement the ``trace`` profile specified in :rfc:`4505`.
"""
check_prohibited_output(
string,
(
stringprep.in_table_c21,
stringprep.in_table_c22,
stringprep.in_table_c3,
stringprep.in_table_c4,
stringprep.in_table_c5,
stringprep.in_table_c6,
stringprep.in_table_c8,
stringprep.in_table_c9,
)
)
check_bidi(string)
return string
aiosasl/utils.py 0000664 0000000 0000000 00000002106 13374230531 0014223 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: utils.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
import operator
def xor_bytes(a, b):
"""
Calculate the byte wise exclusive of of two :class:`bytes` objects
of the same length.
"""
assert len(a) == len(b)
return bytes(map(operator.xor, a, b))
aiosasl/version.py 0000664 0000000 0000000 00000002076 13374230531 0014556 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: version.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
version_info = (0, 4, 0, None)
__version__ = ".".join(map(str, version_info[:3])) + ("-"+version_info[3] if
version_info[3] else "")
version = __version__
docs/ 0000775 0000000 0000000 00000000000 13374230531 0012007 5 ustar 00root root 0000000 0000000 docs/.gitignore 0000664 0000000 0000000 00000000023 13374230531 0013772 0 ustar 00root root 0000000 0000000 sphinx-data/build/
docs/Makefile 0000664 0000000 0000000 00000015171 13374230531 0013454 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = sphinx-data/build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aiosasl.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aiosasl.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/aiosasl"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aiosasl"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
docs/conf.py 0000664 0000000 0000000 00000021434 13374230531 0013312 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# aiosasl documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 9 12:45:22 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import alabaster
import runpy
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.viewcode',
'sphinx.ext.autosummary',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['sphinx-data/templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'aiosasl'
copyright = '2015, Jonas Wielicki'
version_mod = runpy.run_path("../aiosasl/version.py")
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ".".join(map(str, version_mod["version_info"][:2]))
# The full version, including alpha/beta/rc tags.
release = version_mod["__version__"]
del version_mod
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['sphinx-data/build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme_path = [alabaster.get_path()]
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"github_button": "true",
"github_repo": "aiosasl",
"github_user": "horazont",
"font_size": "12pt",
}
html_sidebars = {
'**': [
'about.html',
'localtoc.html',
'relations.html',
'searchbox.html',
'donate.html',
]
}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['sphinx-data/static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'aiosasldoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'aiosasl.tex', 'aiosasl Documentation',
'Jonas Wielicki', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'aiosasl', 'aiosasl Documentation',
['Jonas Wielicki'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'aiosasl', 'aiosasl Documentation',
'Jonas Wielicki', 'aiosasl', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'https://docs.python.org/3/': None,
'https://pyopenssl.org/en/stable/': None,
}
docs/index.rst 0000664 0000000 0000000 00000001562 13374230531 0013654 0 ustar 00root root 0000000 0000000 .. aiosasl documentation master file, created by
sphinx-quickstart on Wed Dec 9 12:45:22 2015.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to aiosasl's documentation!
===================================
:mod:`aiosasl` is a generic SASL implementation for use with :mod:`asyncio`
protocols. It makes very few assumptions about the protocol which uses SASL,
making it usable in different contexts. The assumptions are:
* It uses SASL, i.e. you can perform SASL initiation, responses and abortions.
* Those actions can be encapsulated in :mod:`asyncio` coroutines which return
the server response.
API Reference
=============
.. automodule:: aiosasl
.. automodule:: aiosasl.channel_binding_methods
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
setup.py 0000664 0000000 0000000 00000002126 13374230531 0012572 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import os.path
import runpy
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = f.read()
version_mod = runpy.run_path("aiosasl/version.py")
setup(
name="aiosasl",
version=version_mod["__version__"],
description="Pure-python, protocol agnostic SASL library for asyncio",
long_description=long_description,
url="https://github.com/horazont/aiosasl",
author="Jonas Wielicki",
author_email="jonas@wielicki.name",
license="GPL",
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
],
keywords="asyncio sasl library",
packages=find_packages(exclude=["tests*"])
)
tests/ 0000775 0000000 0000000 00000000000 13374230531 0012221 5 ustar 00root root 0000000 0000000 tests/test_aiosasl.py 0000664 0000000 0000000 00000114234 13374230531 0015272 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: test_aiosasl.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
import asyncio
import base64
import hashlib
import hmac
import unittest
import unittest.mock
import aiosasl
from aiosasl.channel_binding_methods import TLSUnique
from aiosasl.utils import xor_bytes
def run_coroutine(coroutine, timeout=1.0, loop=None):
if not loop:
loop = asyncio.get_event_loop()
return loop.run_until_complete(
asyncio.wait_for(
coroutine,
timeout=timeout))
class CoroutineMock(unittest.mock.Mock):
delay = 0
@asyncio.coroutine
def __call__(self, *args, **kwargs):
result = super().__call__(*args, **kwargs)
yield from asyncio.sleep(self.delay)
return result
class SASLInterfaceMock(aiosasl.SASLInterface):
def __init__(self, testobj, action_sequence):
super().__init__()
self._testobj = testobj
self._action_sequence = action_sequence
def _check_action(self, action, payload):
try:
(next_action,
next_payload,
new_state,
result_payload) = self._action_sequence.pop(0)
except ValueError:
raise AssertionError(
"SASL action performed unexpectedly: "
"{} with payload {}".format(
action,
payload))
self._state = new_state
self._testobj.assertEqual(
action,
next_action,
"SASL action sequence violated")
self._testobj.assertEqual(
payload,
next_payload,
"SASL payload expectation violated")
if new_state == "failure" and action != "abort":
opaque_error, text = result_payload
raise aiosasl.SASLFailure(opaque_error, text=text)
if result_payload is not None:
result_payload = result_payload
return new_state, result_payload
@asyncio.coroutine
def initiate(self, mechanism, payload=None):
return self._check_action("auth;"+mechanism, payload)
@asyncio.coroutine
def respond(self, payload):
return self._check_action("response", payload)
@asyncio.coroutine
def abort(self):
return self._check_action("abort", None)
def finalize(self):
self._testobj.assertFalse(
self._action_sequence,
"Not all actions performed")
class TestSASLState(unittest.TestCase):
def test_from_reply(self):
self.assertEqual(
aiosasl.SASLState.from_reply("success"),
aiosasl.SASLState.SUCCESS
)
self.assertEqual(
aiosasl.SASLState.from_reply("failure"),
aiosasl.SASLState.FAILURE
)
self.assertEqual(
aiosasl.SASLState.from_reply("challenge"),
aiosasl.SASLState.CHALLENGE
)
self.assertEqual(
aiosasl.SASLState.from_reply(aiosasl.SASLState.SUCCESS),
aiosasl.SASLState.SUCCESS
)
self.assertEqual(
aiosasl.SASLState.from_reply(aiosasl.SASLState.FAILURE),
aiosasl.SASLState.FAILURE
)
self.assertEqual(
aiosasl.SASLState.from_reply(aiosasl.SASLState.CHALLENGE),
aiosasl.SASLState.CHALLENGE
)
with self.assertRaises(RuntimeError):
aiosasl.SASLState.from_reply("initial"),
with self.assertRaises(RuntimeError):
aiosasl.SASLState.from_reply("success-simulate-initial"),
with self.assertRaises(RuntimeError):
aiosasl.SASLState.from_reply(aiosasl.SASLState.INITIAL),
with self.assertRaises(RuntimeError):
aiosasl.SASLState.from_reply(
aiosasl.SASLState.SUCCESS_SIMULATE_CHALLENGE),
class TestSASLStateMachine(unittest.TestCase):
def setUp(self):
self.loop = asyncio.get_event_loop()
self.intf = unittest.mock.Mock()
self.intf.initiate = CoroutineMock()
self.intf.respond = CoroutineMock()
self.intf.abort = CoroutineMock()
self.sm = aiosasl.SASLStateMachine(self.intf)
self.intf.initiate.return_value = (aiosasl.SASLState.SUCCESS, None)
def test_initiate_calls_to_interface(self):
result = run_coroutine(
self.sm.initiate("foo", b"bar")
)
self.intf.initiate.assert_called_with(
"foo",
payload=b"bar")
self.assertEqual(
run_coroutine(self.intf.initiate()),
result
)
def test_reject_double_initiate(self):
run_coroutine(self.sm.initiate("foo", b"bar"))
with self.assertRaisesRegexp(RuntimeError,
"has already been called"):
run_coroutine(self.sm.initiate("foo"))
def test_reject_double_initiate_after_error(self):
opaque_error = object()
self.intf.initiate.side_effect = aiosasl.SASLFailure(
opaque_error
)
with self.assertRaises(aiosasl.SASLFailure):
run_coroutine(self.sm.initiate("foo", b"bar"))
with self.assertRaisesRegexp(RuntimeError,
"has already been called"):
run_coroutine(self.sm.initiate("foo"))
def test_reject_response_without_challenge(self):
with self.assertRaisesRegexp(RuntimeError,
"no challenge"):
run_coroutine(self.sm.response(b"bar"))
def test_response_calls_to_interface(self):
self.sm._state = aiosasl.SASLState.CHALLENGE
self.intf.respond.return_value = (aiosasl.SASLState.SUCCESS, None)
result = run_coroutine(
self.sm.response(b"bar")
)
self.intf.respond.assert_called_with(b"bar")
self.assertEqual(
run_coroutine(self.intf.initiate()),
result
)
def test_response_failure(self):
opaque_error = object()
self.sm._state = aiosasl.SASLState.CHALLENGE
self.intf.respond.side_effect = aiosasl.SASLFailure(
opaque_error
)
with self.assertRaises(aiosasl.SASLFailure):
run_coroutine(
self.sm.response(b"bar")
)
self.assertEqual(self.sm._state, aiosasl.SASLState.FAILURE)
def test_reject_abort_without_initiate(self):
with self.assertRaises(RuntimeError):
run_coroutine(self.sm.abort())
def test_abort_calls_to_interface(self):
self.sm._state = "challenge"
self.intf.abort.return_value = ("failure", None)
self.assertEqual(
("failure", None),
run_coroutine(self.sm.abort())
)
self.intf.abort.assert_called_with()
self.assertEqual(self.sm._state, aiosasl.SASLState.FAILURE)
def test_abort_set_to_failure_and_re_raise_exceptions(self):
exc = Exception()
self.sm._state = aiosasl.SASLState.CHALLENGE
self.intf.abort.side_effect = exc
with self.assertRaises(Exception) as ctx:
run_coroutine(self.sm.abort())
self.assertIs(ctx.exception, exc)
self.intf.abort.assert_called_with()
self.assertEqual(self.sm._state, aiosasl.SASLState.FAILURE)
def test_success_simulated_challenge(self):
self.sm._state = aiosasl.SASLState.CHALLENGE
self.intf.respond.return_value = ("success", b"payload")
state, payload = run_coroutine(self.sm.response(b"foobar"))
self.assertEqual(self.sm._state,
aiosasl.SASLState.SUCCESS_SIMULATE_CHALLENGE)
self.assertEqual(state, aiosasl.SASLState.CHALLENGE)
self.assertEqual(payload, b"payload")
state, payload = run_coroutine(self.sm.response(b""))
self.assertEqual(state, aiosasl.SASLState.SUCCESS)
self.assertEqual(payload, None)
def test_success_simulated_challenge_protocol_violation(self):
self.sm._state = aiosasl.SASLState.SUCCESS_SIMULATE_CHALLENGE
with self.assertRaises(aiosasl.SASLFailure):
run_coroutine(self.sm.response(b"not-empty"))
self.assertEqual(self.sm._state, aiosasl.SASLState.FAILURE)
def tearDown(self):
del self.sm
del self.intf
del self.loop
class TestPLAIN(unittest.TestCase):
def test_rfc(self):
user = "tim"
password = "tanstaaftanstaaf"
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;PLAIN",
b"\0tim\0tanstaaftanstaaf",
"success",
None)
]))
@asyncio.coroutine
def provide_credentials(*args):
return user, password
def run():
plain = aiosasl.PLAIN(provide_credentials)
result = yield from plain.authenticate(
smmock,
"PLAIN")
self.assertTrue(result)
asyncio.get_event_loop().run_until_complete(run())
smmock.interface.finalize()
def test_fail_on_protocol_violation(self):
user = "tim"
password = "tanstaaftanstaaf"
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;PLAIN",
b"\0tim\0tanstaaftanstaaf",
"challenge",
b"foo")
]))
@asyncio.coroutine
def provide_credentials(*args):
return user, password
def run():
plain = aiosasl.PLAIN(provide_credentials)
yield from plain.authenticate(
smmock,
"PLAIN")
with self.assertRaisesRegexp(aiosasl.SASLFailure,
"protocol violation") as ctx:
asyncio.get_event_loop().run_until_complete(run())
self.assertEqual(
None,
ctx.exception.opaque_error
)
smmock.interface.finalize()
def test_reject_NUL_bytes_in_username(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
]))
@asyncio.coroutine
def provide_credentials(*args):
return "\0", "foo"
with self.assertRaises(ValueError):
run_coroutine(
aiosasl.PLAIN(provide_credentials).authenticate(
smmock,
"PLAIN")
)
def test_reject_NUL_bytes_in_password(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
]))
@asyncio.coroutine
def provide_credentials(*args):
return "foo", "\0"
with self.assertRaises(ValueError):
run_coroutine(
aiosasl.PLAIN(provide_credentials).authenticate(smmock, "PLAIN")
)
def test_supports_PLAIN(self):
self.assertEqual(
"PLAIN",
aiosasl.PLAIN.any_supported(["PLAIN"])
)
def test_does_not_support_SCRAM(self):
self.assertIsNone(
aiosasl.PLAIN.any_supported(["SCRAM-SHA-1"])
)
class TestSCRAMNegotiation(unittest.TestCase):
def test_supports_SCRAM_famliy(self):
hashes = ["SHA-1", "SHA-256"]
for hashname in hashes:
mechanism = "SCRAM-{}".format(hashname)
self.assertEqual(
(mechanism, unittest.mock.ANY),
aiosasl.SCRAM.any_supported([mechanism])
)
def test_supports_SCRAMPLUS_famliy(self):
hashes = ["SHA-1", "SHA-256"]
for hashname in hashes:
mechanism = "SCRAM-{}-PLUS".format(hashname)
self.assertEqual(
(mechanism, unittest.mock.ANY),
aiosasl.SCRAMPLUS.any_supported([mechanism])
)
def test_pick_longest_hash_SCRAM(self):
self.assertEqual(
("SCRAM-SHA-256", unittest.mock.ANY),
aiosasl.SCRAM.any_supported([
"SCRAM-SHA-1",
"SCRAM-SHA-256",
"PLAIN",
])
)
def test_no_support_for_unregistered_functions(self):
self.assertEqual(
("SCRAM-SHA-256", unittest.mock.ANY),
aiosasl.SCRAM.any_supported([
"SCRAM-SHA-1",
"SCRAM-SHA-256",
"SCRAM-SHA-512",
"PLAIN",
])
)
def test_pick_longest_hash_SCRAMPLUS(self):
self.assertEqual(
("SCRAM-SHA-256-PLUS", unittest.mock.ANY),
aiosasl.SCRAMPLUS.any_supported([
"SCRAM-SHA-1-PLUS",
"SCRAM-SHA-256-PLUS",
"SCRAM-SHA-224-PLUS",
"PLAIN",
])
)
def test_reject_scram_plus_SCRAM(self):
hashes = ["SHA-1", "SHA-224", "SHA-256",
"SHA-512", "SHA-384", "SHA-256"]
for hashname in hashes:
mechanism = "SCRAM-{}-PLUS".format(hashname)
self.assertIsNone(
aiosasl.SCRAM.any_supported([mechanism])
)
def test_reject_scram_SCRAMPLUS(self):
hashes = ["SHA-1", "SHA-256"]
for hashname in hashes:
mechanism = "SCRAM-{}".format(hashname)
self.assertIsNone(
aiosasl.SCRAMPLUS.any_supported([mechanism])
)
def test_reject_md5_SCRAM(self):
self.assertIsNone(
aiosasl.SCRAM.any_supported(["SCRAM-MD5"])
)
def test_reject_md5_SCRAMPLUS(self):
self.assertIsNone(
aiosasl.SCRAMPLUS.any_supported(["SCRAM-MD5-PLUS"])
)
def test_reject_unknown_hash_functions_SCRAM(self):
self.assertIsNone(
aiosasl.SCRAM.any_supported(["SCRAM-FOOBAR"])
)
def test_reject_unknown_hash_functions_SCRAMPLUS(self):
self.assertIsNone(
aiosasl.SCRAM.any_supported(["SCRAM-FOOBAR-PLUS"])
)
def test_parse_message_reject_long_keys_SCRAM(self):
with self.assertRaisesRegexp(Exception, "protocol violation"):
list(aiosasl.SCRAM.parse_message(b"foo=bar"))
def test_parse_message_reject_long_keys_SCRAMPLUS(self):
with self.assertRaisesRegexp(Exception, "protocol violation"):
list(aiosasl.SCRAMPLUS.parse_message(b"foo=bar"))
def test_parse_message_reject_m_key_SCRAM(self):
with self.assertRaisesRegexp(Exception, "protocol violation"):
list(aiosasl.SCRAM.parse_message(b"m=bar"))
def test_parse_message_reject_m_key_SCRAMPLUS(self):
with self.assertRaisesRegexp(Exception, "protocol violation"):
list(aiosasl.SCRAMPLUS.parse_message(b"m=bar"))
def test_parse_message_unescape_n_and_a_payload_SCRAM(self):
data = list(aiosasl.SCRAM.parse_message(b"n=foo=2Cbar=3Dbaz,"
b"a=fnord=2Cfunky=3Dfunk"))
self.assertSequenceEqual(
[
(b"n", b"foo,bar=baz"),
(b"a", b"fnord,funky=funk")
],
data
)
def test_parse_message_unescape_n_and_a_payload_SCRAMPLUS(self):
data = list(aiosasl.SCRAMPLUS.parse_message(
b"n=foo=2Cbar=3Dbaz,a=fnord=2Cfunky=3Dfunk"))
self.assertSequenceEqual(
[
(b"n", b"foo,bar=baz"),
(b"a", b"fnord,funky=funk")
],
data
)
class TestSCRAMImpl:
def setUp(self):
self.hashfun_factory = hashlib.sha1
self.digest_size = self.hashfun_factory().digest_size
self.user = b"user"
self.password = b"pencil"
self.salt = b"QSXCR+Q6sek8bf92"
aiosasl._system_random = unittest.mock.MagicMock()
aiosasl._system_random.getrandbits.return_value = int.from_bytes(
b"foo",
"little")
self.salted_password = aiosasl.pbkdf2(
"sha1",
self.password,
self.salt,
4096,
self.digest_size)
self.salted_password_4000 = aiosasl.pbkdf2(
"sha1",
self.password,
self.salt,
4000,
self.digest_size)
self.salted_password_5000 = aiosasl.pbkdf2(
"sha1",
self.password,
self.salt,
5000,
self.digest_size)
self.client_key = hmac.new(
self.salted_password,
b"Client Key",
self.hashfun_factory).digest()
self.client_key_4000 = hmac.new(
self.salted_password_4000,
b"Client Key",
self.hashfun_factory).digest()
self.client_key_5000 = hmac.new(
self.salted_password_5000,
b"Client Key",
self.hashfun_factory).digest()
self.stored_key = self.hashfun_factory(
self.client_key).digest()
self.stored_key_4000 = self.hashfun_factory(
self.client_key_4000).digest()
self.stored_key_5000 = self.hashfun_factory(
self.client_key_5000).digest()
self.client_first_message_bare = b"n=user,r=Zm9vAAAAAAAAAAAAAAAA"
self.server_first_message = b"".join([
b"r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j,s=",
base64.b64encode(self.salt),
b",i=4096"
])
self.server_first_message_4000 = b"".join([
b"r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j,s=",
base64.b64encode(self.salt),
b",i=4000"
])
self.server_first_message_5000 = b"".join([
b"r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j,s=",
base64.b64encode(self.salt),
b",i=5000"
])
if self._scram_plus == 'no':
self.client_final_message_without_proof = (
b"c=biws,r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j")
elif self._scram_plus == 'supported':
self.client_final_message_without_proof = (
b"c=eSws,r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j")
elif self._scram_plus == 'active':
self.client_final_message_without_proof = (
b"c=cD10bHMtdW5pcXVlLCxjaGFubmVsIGJpbmRpbmcgZGF0YQ==,"
b"r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j")
else:
raise Exception("invalid scram mode")
self.auth_message = b",".join([
self.client_first_message_bare,
self.server_first_message,
self.client_final_message_without_proof
])
self.auth_message_4000 = b",".join([
self.client_first_message_bare,
self.server_first_message_4000,
self.client_final_message_without_proof
])
self.auth_message_5000 = b",".join([
self.client_first_message_bare,
self.server_first_message_5000,
self.client_final_message_without_proof
])
self.client_signature = hmac.new(
self.stored_key,
self.auth_message,
self.hashfun_factory).digest()
self.client_signature_4000 = hmac.new(
self.stored_key_4000,
self.auth_message_4000,
self.hashfun_factory).digest()
self.client_signature_5000 = hmac.new(
self.stored_key_5000,
self.auth_message_5000,
self.hashfun_factory).digest()
self.client_proof = xor_bytes(self.client_signature, self.client_key)
self.client_proof_4000 = xor_bytes(self.client_signature_4000,
self.client_key_4000)
self.client_proof_5000 = xor_bytes(self.client_signature_5000,
self.client_key_5000)
self.server_key = hmac.new(
self.salted_password,
b"Server Key",
self.hashfun_factory).digest()
self.server_key_4000 = hmac.new(
self.salted_password_4000,
b"Server Key",
self.hashfun_factory).digest()
self.server_key_5000 = hmac.new(
self.salted_password_5000,
b"Server Key",
self.hashfun_factory).digest()
self.server_signature = hmac.new(
self.server_key,
self.auth_message,
self.hashfun_factory).digest()
self.server_signature_4000 = hmac.new(
self.server_key_4000,
self.auth_message_4000,
self.hashfun_factory).digest()
self.server_signature_5000 = hmac.new(
self.server_key_5000,
self.auth_message_5000,
self.hashfun_factory).digest()
self._tls_connection = unittest.mock.Mock()
self._tls_connection.get_finished = unittest.mock.Mock()
self._tls_connection.get_finished.return_value = \
b'channel binding data'
@asyncio.coroutine
def _provide_credentials(self, *args):
return ("user", "pencil")
def _run(self, smmock, scram):
info = aiosasl.SCRAMBase._supported_hashalgos["SHA-1"]
if self._scram_plus in ('no', 'supported'):
token = ("SCRAM-SHA-1", info)
else:
token = ("SCRAM-SHA-1-PLUS", info)
result = asyncio.get_event_loop().run_until_complete(
scram.authenticate(smmock, token)
)
smmock.interface.finalize()
return result
def tearDown(self):
import random
aiosasl._system_random = random.SystemRandom()
class TestSCRAM(TestSCRAMImpl, unittest.TestCase):
_scram_plus = 'no'
def test_rfc(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"success",
b"v="+base64.b64encode(self.server_signature))
]))
self.assertTrue(self._run(
smmock,
aiosasl.SCRAM(self._provide_credentials)
))
def test_malformed_reply(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
b"s=hut,t=hefu,c=kup,d=onny"),
("abort", None,
"failure", ("aborted", None))
]))
with self.assertRaises(aiosasl.SASLFailure) as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertIn(
"malformed",
str(ctx.exception).lower()
)
def test_other_malformed_reply(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
b"i=sometext,s=ABC,r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j"),
("abort", None,
"failure", ("aborted", None))
]))
with self.assertRaises(aiosasl.SASLFailure) as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertIn(
"malformed",
str(ctx.exception).lower()
)
def test_incorrect_nonce(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
b"r=foobar,s="+base64.b64encode(self.salt)+b",i=4096"),
("abort", None,
"failure", ("aborted", None))
]))
with self.assertRaisesRegexp(aiosasl.SASLFailure, "nonce") as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertIsNone(ctx.exception.opaque_error)
def test_invalid_signature(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"success",
b"v="+base64.b64encode(b"fnord"))
]))
with self.assertRaises(aiosasl.SASLFailure) as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertIsNone(ctx.exception.opaque_error)
self.assertIn(
"signature",
str(ctx.exception).lower()
)
def test_promote_failure_to_authentication_failure(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"failure",
("credentials-expired", None))
]))
with self.assertRaises(aiosasl.AuthenticationFailure) as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertEqual(
"credentials-expired",
ctx.exception.opaque_error
)
def test_reject_protocol_violation_1(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"success",
None),
]))
with self.assertRaisesRegexp(aiosasl.SASLFailure,
"protocol violation") as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertEqual(
"malformed-request",
ctx.exception.opaque_error
)
def test_reject_protocol_violation_2(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"success", None),
("abort", None,
"failure", ("aborted", None)),
]))
with self.assertRaisesRegexp(aiosasl.SASLFailure,
"protocol violation") as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertEqual(
None,
ctx.exception.opaque_error
)
def test_too_low_iteration_count(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message.replace(b",i=4096", b",i=4095")),
("abort", None,
"failure", ("aborted", None)),
]))
with self.assertRaisesRegexp(
aiosasl.SASLFailure,
r"minimum iteration count for SCRAM-SHA-1 violated "
r"\(4095 is less than 4096\)") as ctx:
self._run(smmock, aiosasl.SCRAM(self._provide_credentials))
self.assertEqual(
None,
ctx.exception.opaque_error
)
def test_too_low_iteration_count_without_enforcement(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message_4000),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof_4000),
"success",
b"v="+base64.b64encode(self.server_signature_4000))
]))
self.assertTrue(self._run(
smmock,
aiosasl.SCRAM(
self._provide_credentials,
enforce_minimum_iteration_count=False,
)
))
def test_high_iteration_count(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"n,,"+self.client_first_message_bare,
"challenge",
self.server_first_message_5000),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof_5000),
"success",
b"v="+base64.b64encode(self.server_signature_5000))
]))
self.assertTrue(self._run(
smmock,
aiosasl.SCRAM(self._provide_credentials)
))
class TestSCRAMDowngradeProtection(TestSCRAMImpl, unittest.TestCase):
_scram_plus = 'supported'
def test_rfc_with_downgrade_protection(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1",
b"y,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"success",
b"v="+base64.b64encode(self.server_signature))
]))
self.assertTrue(self._run(
smmock,
aiosasl.SCRAM(self._provide_credentials, after_scram_plus=True)
))
class TestSCRAMPLUS(TestSCRAMImpl, unittest.TestCase):
_scram_plus = 'active'
def test_rfc(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"success",
b"v="+base64.b64encode(self.server_signature))
]))
self.assertTrue(self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
))
def test_malformed_reply(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
b"s=hut,t=hefu,c=kup,d=onny"),
("abort", None,
"failure", ("aborted", None))
]))
with self.assertRaises(aiosasl.SASLFailure) as ctx:
self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
)
self.assertIn(
"malformed",
str(ctx.exception).lower()
)
def test_other_malformed_reply(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
b"i=sometext,s=ABC,r=Zm9vAAAAAAAAAAAAAAAA3rfcNHYJY1ZVvWVs7j"),
("abort", None,
"failure", ("aborted", None))
]))
with self.assertRaises(aiosasl.SASLFailure) as ctx:
self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
)
self.assertIn(
"malformed",
str(ctx.exception).lower()
)
def test_incorrect_nonce(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
b"r=foobar,s="+base64.b64encode(self.salt)+b",i=4096"),
("abort", None,
"failure", ("aborted", None))
]))
with self.assertRaisesRegexp(aiosasl.SASLFailure, "nonce") as ctx:
self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
)
self.assertIsNone(ctx.exception.opaque_error)
def test_invalid_signature(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"success",
b"v="+base64.b64encode(b"fnord"))
]))
with self.assertRaises(aiosasl.SASLFailure) as ctx:
self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
)
self.assertIsNone(ctx.exception.opaque_error)
self.assertIn(
"signature",
str(ctx.exception).lower()
)
def test_promote_failure_to_authentication_failure(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"failure",
("credentials-expired", None))
]))
with self.assertRaises(aiosasl.AuthenticationFailure) as ctx:
self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
)
self.assertEqual(
"credentials-expired",
ctx.exception.opaque_error
)
def test_reject_protocol_violation(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;SCRAM-SHA-1-PLUS",
b"p=tls-unique,,"+self.client_first_message_bare,
"challenge",
self.server_first_message),
("response",
self.client_final_message_without_proof +
b",p="+base64.b64encode(self.client_proof),
"challenge",
b"foo"),
("response", b"", "success", b"bar")
]))
with self.assertRaisesRegexp(aiosasl.SASLFailure,
"protocol violation") as ctx:
self._run(
smmock,
aiosasl.SCRAMPLUS(
self._provide_credentials,
TLSUnique(self._tls_connection)
)
)
self.assertEqual(
None,
ctx.exception.opaque_error
)
class TestANONYMOUS(unittest.TestCase):
def test_accepts_ANONYMOUS(self):
self.assertIsNotNone(
aiosasl.ANONYMOUS.any_supported(["ANONYMOUS"])
)
def test_passes_token_through_trace(self):
with unittest.mock.patch("aiosasl.trace") as trace:
trace.return_value = "traced"
anon = aiosasl.ANONYMOUS(unittest.mock.sentinel.token)
trace.assert_called_with(unittest.mock.sentinel.token)
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;ANONYMOUS",
b"traced",
"success",
None)
]))
def run():
result = yield from anon.authenticate(
smmock,
"ANONYMOUS")
self.assertTrue(result)
asyncio.get_event_loop().run_until_complete(run())
smmock.interface.finalize()
def test_simply_sends_token(self):
smmock = aiosasl.SASLStateMachine(SASLInterfaceMock(
self,
[
("auth;ANONYMOUS",
b"sirhc",
"success",
None)
]))
def run():
anon = aiosasl.ANONYMOUS("sirhc")
result = yield from anon.authenticate(
smmock,
"ANONYMOUS")
self.assertTrue(result)
asyncio.get_event_loop().run_until_complete(run())
smmock.interface.finalize()
tests/test_channel_binding_methods.py 0000664 0000000 0000000 00000024035 13374230531 0020463 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: test_channel_binding_methods.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
import unittest
import unittest.mock
import OpenSSL
from aiosasl import ChannelBindingProvider
from aiosasl.channel_binding_methods import (
StdlibTLS,
TLSUnique,
TLSServerEndPoint,
parse_openssl_digest,
)
RAW_EXAMPLE_CERTS = [(b'0\x82\x01\xf90\x82\x01b\x02\x01\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x000C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0"\x18\x0f20000101000000Z\x18\x0f21000101000000Z0C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0\x81\x9f0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x81\x8d\x000\x81\x89\x02\x81\x81\x00\x9d\xce/J\x9b\x89Z{~g\xda\xd8\xbfCi%g:\x9f\xbb\xcb\xe6\x08\xd0\x9c\x0b\xec1\xda\xb8\xd1w\x14v\xc83\x8dI\xc7\xf1#qz\x97\xf7\xf27\xd2\x97\x91s\x1f/i\x06f\x1a\x1ejN\xfb\x13\xf1\xe1\x8a\'\xa6\xec\x03h\xdd+\xbe\xda\xde\xba\xfd\xe7\xc4h\xc6]5d\xe5k\x97\x15\xf1\xc4\xc0\xf1\xc8\xb7\xb4\xea\x0f\xbb\x15O\xc10 3\x8d\x9a \xa8Dg\xb1\x1c\xac\xa3\xe7pY\xdb\xb7\xb8Ze\x95^\x94\x1b\xfa\xed\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x04\x05\x00\x03\x81\x81\x00l77\x1c\x95/\xb41G\xe8l\xe6\x9e\x8aL\xbcs#?\x8diZwB\x942\xa0\x82\x1e\xa5\x08\xe5%\xd8\x93<\xae\xe7\x1fR\x03\xf7\xcfw\xf4\xf7Q\x99B\x9c\xbf\x80\xac\xd5{\r\xa7\xf2\xb1\xfa\x88\xd2\x14\xf4\xf9q(\xfa4\x17\xa9\x07V\xb4\xe8G\xb4\x93\x8b\x8b\x0b\xc7\x00\xc5/\x80\x8c\x1d\x85Uv\xd5\xa9\xe6\x17\xb1m@\xb7\x01\xd6.l\xe6\xa9/\x90\xea$NB\xfa\xa5\xe3\xe4\xf4I\xfcQ\x85\x06\xc7\xd3g\xb8\xe9\xf5i', b'0B:AA:BA:DD:CA:F4:7C:2F:5A:2A:12:67:16:B3:1C:AF:65:1F:D6:B0:BF:A2:B7:B9:9A:CD:83:F4:AB:B5:CE:CD'), (b'0\x82\x01\xf90\x82\x01b\x02\x01\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x05\x05\x000C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0"\x18\x0f20000101000000Z\x18\x0f21000101000000Z0C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0\x81\x9f0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x81\x8d\x000\x81\x89\x02\x81\x81\x00\x9d\xce/J\x9b\x89Z{~g\xda\xd8\xbfCi%g:\x9f\xbb\xcb\xe6\x08\xd0\x9c\x0b\xec1\xda\xb8\xd1w\x14v\xc83\x8dI\xc7\xf1#qz\x97\xf7\xf27\xd2\x97\x91s\x1f/i\x06f\x1a\x1ejN\xfb\x13\xf1\xe1\x8a\'\xa6\xec\x03h\xdd+\xbe\xda\xde\xba\xfd\xe7\xc4h\xc6]5d\xe5k\x97\x15\xf1\xc4\xc0\xf1\xc8\xb7\xb4\xea\x0f\xbb\x15O\xc10 3\x8d\x9a \xa8Dg\xb1\x1c\xac\xa3\xe7pY\xdb\xb7\xb8Ze\x95^\x94\x1b\xfa\xed\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x05\x05\x00\x03\x81\x81\x00\x92$\xfe\xc8\xeb~#\xd5\x0f#\x1c\xd9\xfeV\xa4z\x84\xcc\x83\xdd\xfd\xa47\xb5\xf7\xe4*\x9fJ\xd5My\x13UFT+\x95\'v\xa8\xb6\x95{2\xe4t\xbd#F\x08\xbf\xf3\xbei\xaf\x83M\xbb\x06FO\x1b\x9ew\xc81\r\xa0\xc3Z\xb8\xb7\x16\tS\xde\xe8\xe4\xdd\xed\x04\xfb\xe1\x1a(\xf0i}\x18\x10Q\x82\x10\x8eH\xe9x:\xcd\xaec]\x9c\xd9\xa7&\xf1\xa3:`\xa8(\x86+\xf05\n!\x82\xac\xfd\xd7\xe72T\x15.', b'79:45:47:63:08:2F:E0:21:E4:31:A5:99:EE:FE:34:D5:9E:1A:A9:A0:54:00:D6:FE:E8:89:62:27:A1:8E:5F:A7'), (b'0\x82\x01\xf90\x82\x01b\x02\x01\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x000C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0"\x18\x0f20000101000000Z\x18\x0f21000101000000Z0C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0\x81\x9f0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x81\x8d\x000\x81\x89\x02\x81\x81\x00\x9d\xce/J\x9b\x89Z{~g\xda\xd8\xbfCi%g:\x9f\xbb\xcb\xe6\x08\xd0\x9c\x0b\xec1\xda\xb8\xd1w\x14v\xc83\x8dI\xc7\xf1#qz\x97\xf7\xf27\xd2\x97\x91s\x1f/i\x06f\x1a\x1ejN\xfb\x13\xf1\xe1\x8a\'\xa6\xec\x03h\xdd+\xbe\xda\xde\xba\xfd\xe7\xc4h\xc6]5d\xe5k\x97\x15\xf1\xc4\xc0\xf1\xc8\xb7\xb4\xea\x0f\xbb\x15O\xc10 3\x8d\x9a \xa8Dg\xb1\x1c\xac\xa3\xe7pY\xdb\xb7\xb8Ze\x95^\x94\x1b\xfa\xed\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\x0b\x05\x00\x03\x81\x81\x000\xbfiz\x97\x90\xab\x8f\xca1\x1eH\xeb\xd6\xbd?\x87o\x07\xd3\xddi\xe9C\xa9\x97\x84\x87Xp&&\'\x0c\xbci\xc3\xb4?o\xfdOy\x1d\xf2\x9e\xe36\x8d(\xc2A\x0c\x106$}\xb3X;\xa7\xc3h\xd38D\xeb\x95\x8f>6\x17\xa1e\x1a\xc9\xfa\xbd\r\x00\x8c0\xa5T{n5\xe5\x9dp\x80%\x9eb\xb4\xd6\xd3;\xc7\x8c\n\x19\x9b\xaf\xab =IhK\xfc%*\xdbMkM\x8f\x1d\x05\xd8\xa9\xbd\x17RW\xfc{', b'0A:19:C9:73:FE:9C:F2:B9:DF:5D:27:CC:5A:FD:04:5E:19:97:05:99:4A:EB:91:16:FC:3F:CC:87:1B:D5:6E:2E'), (b'0\x82\x01\xf90\x82\x01b\x02\x01\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\r\x05\x000C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0"\x18\x0f20000101000000Z\x18\x0f21000101000000Z0C1\x0b0\t\x06\x03U\x04\x06\x13\x02FN1\x1c0\x1a\x06\x03U\x04\n\x0c\x13Example Association1\x160\x14\x06\x03U\x04\x03\x0c\raiosasl tests0\x81\x9f0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x81\x8d\x000\x81\x89\x02\x81\x81\x00\x9d\xce/J\x9b\x89Z{~g\xda\xd8\xbfCi%g:\x9f\xbb\xcb\xe6\x08\xd0\x9c\x0b\xec1\xda\xb8\xd1w\x14v\xc83\x8dI\xc7\xf1#qz\x97\xf7\xf27\xd2\x97\x91s\x1f/i\x06f\x1a\x1ejN\xfb\x13\xf1\xe1\x8a\'\xa6\xec\x03h\xdd+\xbe\xda\xde\xba\xfd\xe7\xc4h\xc6]5d\xe5k\x97\x15\xf1\xc4\xc0\xf1\xc8\xb7\xb4\xea\x0f\xbb\x15O\xc10 3\x8d\x9a \xa8Dg\xb1\x1c\xac\xa3\xe7pY\xdb\xb7\xb8Ze\x95^\x94\x1b\xfa\xed\x02\x03\x01\x00\x010\r\x06\t*\x86H\x86\xf7\r\x01\x01\r\x05\x00\x03\x81\x81\x00\x8cf\x94\xeet\xf4\x03\xe6Tj|\xee\x1dh?\xed\x9b4\xb4\xb1\xc0J\xa6\xe1\xb8$\xf9c)\xd0[5\xed\x8d\xa3 \x9f\xfb\xedm\x904\x9a(u\xbe\x0b\xa8\\)d\xb2\x8b\xd6\xf2^\x80\xa4Z\x10\x0b\x8aN\'f\xbb\x81\x95\xc2\x99v\x96\xb2\xb5_\xed\xcc\xc1\x9a\xc1\xa7\x85\x7f\xa3s\x17\xab\x98\x91o\xdd3\xd64{\x9c\xaft3t`\xa8\'\x9b\x7f\x13\x02.\xf2Vl=3\xd5#\x8e>L\x8c\xfe\xce\x1c\xb3\x7f\x04\xe8m\xad', b'B1:90:A4:38:8E:0E:63:F4:0E:3B:D3:21:8F:C5:33:2E:3B:96:F7:86:14:C1:E1:37:ED:AE:BE:B1:4C:96:37:7A:E7:13:83:4D:94:B6:E8:2C:D8:A6:E0:3C:DA:AA:79:07:2A:73:85:58:C9:D1:ED:CE:53:E0:A8:F7:B1:A0:DB:62')] # NOQA
EXAMPLE_CERTS = []
for cert, digest in RAW_EXAMPLE_CERTS:
EXAMPLE_CERTS.append((
OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert),
parse_openssl_digest(digest),
))
class TestStdlibTLS(unittest.TestCase):
def test_is_channel_binding_type(self):
self.assertTrue(issubclass(StdlibTLS, ChannelBindingProvider))
def test_cb_name(self):
for method in ("tls-unique", "tls-server-end-point"):
mock_socket = unittest.mock.Mock()
provider = StdlibTLS(mock_socket, method)
self.assertEqual(provider.cb_name, method.encode("us-ascii"))
mock_socket = unittest.mock.Mock()
provider = StdlibTLS(mock_socket, "tls-server-end-point")
self.assertEqual(provider.cb_name, b"tls-server-end-point")
def test_extract_cb_data(self):
for method in ("tls-unique", "tls-server-end-point"):
mock_socket = unittest.mock.Mock()
provider = StdlibTLS(mock_socket, method)
with unittest.mock.patch.object(
mock_socket,
"get_channel_binding") as get_channel_binding:
get_channel_binding.return_value = b"foobar"
cb_data = provider.extract_cb_data()
self.assertSequenceEqual(
get_channel_binding.mock_calls,
[
unittest.mock.call(method)
]
)
self.assertEqual(cb_data, b"foobar")
class TestTLSUnique(unittest.TestCase):
def test_is_channel_binding_type(self):
self.assertTrue(issubclass(TLSUnique, ChannelBindingProvider))
def test_cb_name(self):
mock_conn = unittest.mock.Mock()
provider = TLSUnique(mock_conn)
self.assertEqual(provider.cb_name, b"tls-unique")
def test_extract_cb_data(self):
mock_conn = unittest.mock.Mock()
provider = TLSUnique(mock_conn)
with unittest.mock.patch.object(
mock_conn,
"get_finished") as get_finished:
get_finished.return_value = b"foobar"
cb_data = provider.extract_cb_data()
self.assertSequenceEqual(
get_finished.mock_calls,
[
unittest.mock.call()
]
)
self.assertEqual(cb_data, b"foobar")
class TestTLSServerEndPoint(unittest.TestCase):
def test_is_channel_binding_type(self):
self.assertTrue(issubclass(TLSServerEndPoint, ChannelBindingProvider))
def test_cb_name(self):
mock_conn = unittest.mock.Mock()
provider = TLSServerEndPoint(mock_conn)
self.assertEqual(provider.cb_name, b"tls-server-end-point")
def test_extract_cb_data(self):
mock_conn = unittest.mock.Mock()
provider = TLSServerEndPoint(mock_conn)
for cert, hash_ in EXAMPLE_CERTS:
with unittest.mock.patch.object(
mock_conn,
"get_peer_certificate") as get_peer_cert:
get_peer_cert.return_value = cert
cb_data = provider.extract_cb_data()
self.assertSequenceEqual(
get_peer_cert.mock_calls,
[
unittest.mock.call()
]
)
self.assertEqual(cb_data, hash_)
tests/test_stringprep.py 0000664 0000000 0000000 00000012116 13374230531 0016030 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: test_stringprep.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
import unittest
from aiosasl.stringprep import (
saslprep,
check_bidi,
trace,
)
class Testcheck_bidi(unittest.TestCase):
# some test cases which are not covered by the other tests
def test_empty_string(self):
check_bidi("")
def test_L_RAL_violation(self):
with self.assertRaises(ValueError):
check_bidi("\u05be\u0041")
class TestSASLprep(unittest.TestCase):
def test_map_to_nothing_rfcx(self):
self.assertEqual(
"IX",
saslprep("I\u00ADX"),
"SASLprep requirement: map SOFT HYPHEN to nothing")
def test_map_to_space(self):
self.assertEqual(
"I X",
saslprep("I\u00A0X"),
"SASLprep requirement: map SOFT HYPHEN to nothing")
def test_identity_rfcx(self):
self.assertEqual(
"user",
saslprep("user"),
"SASLprep requirement: identity transform")
def test_case_preservation_rfcx(self):
self.assertEqual(
"USER",
saslprep("USER"),
"SASLprep requirement: preserve case")
def test_nfkc_rfcx(self):
self.assertEqual(
"a",
saslprep("\u00AA"),
"SASLprep requirement: NFKC")
self.assertEqual(
"IX",
saslprep("\u2168"),
"SASLprep requirement: NFKC")
def test_prohibited_character_rfcx(self):
with self.assertRaises(
ValueError,
msg="SASLprep requirement: prohibited character (C.2.1)"):
saslprep("\u0007")
with self.assertRaises(
ValueError,
msg="SASLprep requirement: prohibited character (C.8)"):
saslprep("\u200E")
def test_bidirectional_check_rfcx(self):
with self.assertRaises(
ValueError,
msg="SASLprep requirement: bidirectional check"):
saslprep("\u0627\u0031")
def test_unassigned(self):
with self.assertRaises(
ValueError,
msg="SASLprep requirement: unassigned"):
saslprep("\u0221", allow_unassigned=False)
with self.assertRaises(
ValueError,
msg="enforce no unassigned by default"):
saslprep("\u0221")
self.assertEqual(
"\u0221",
saslprep("\u0221", allow_unassigned=True))
class Testtrace(unittest.TestCase):
def test_identity_rfcx(self):
self.assertEqual(
"user",
trace("user"),
"trace requirement: identity transform")
def test_case_preservation_rfcx(self):
self.assertEqual(
"USER",
trace("USER"),
"trace requirement: preserve case")
def test_prohibited_character_rfcx(self):
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.2.1)"):
trace("\u0007")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.2.2)"):
trace("\u070F")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.3)"):
trace("\uE000")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.4)"):
trace("\uFDEF")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.5)"):
trace("\uD800")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.6)"):
trace("\uFFF9")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.8)"):
trace("\u0340")
with self.assertRaises(
ValueError,
msg="trace requirement: prohibited character (C.9)"):
trace("\U000E0001")
def test_bidirectional_check_rfcx(self):
with self.assertRaises(
ValueError,
msg="trace requirement: bidirectional check"):
trace("\u0627\u0031")
tests/test_unicode_version.py 0000664 0000000 0000000 00000002076 13374230531 0017032 0 ustar 00root root 0000000 0000000 ########################################################################
# File name: test_unicode_version.py
# This file is part of: aiosasl
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program. If not, see
# .
#
########################################################################
import unittest
from aiosasl import stringprep
class TestUnicodeVersion(unittest.TestCase):
def test_version(self):
self.assertEqual(stringprep.unicodedata.unidata_version, "3.2.0")
tools/ 0000775 0000000 0000000 00000000000 13374230531 0012217 5 ustar 00root root 0000000 0000000 tools/gen_example_keys.py 0000664 0000000 0000000 00000001525 13374230531 0016113 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import OpenSSL
key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 1024)
encoded_certs = []
for algo, digest_algo in (("MD5", "SHA256"),
("SHA1", "SHA256"),
("SHA256", "SHA256"),
("SHA512", "SHA512")):
cert = OpenSSL.crypto.X509()
cert.set_serial_number(1)
cert.set_notBefore(b"20000101000000Z")
cert.set_notAfter(b"21000101000000Z")
cert.set_pubkey(key)
cert.sign(key, algo)
cert.get_subject().C = b"FN"
cert.get_subject().O = b"Example Association"
cert.get_subject().CN = b"aiosasl tests"
cert.set_issuer(cert.get_subject())
encoded_certs.append((
OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, cert),
cert.digest(digest_algo)
))
print(encoded_certs)