pax_global_header 0000666 0000000 0000000 00000000064 14342136262 0014515 g ustar 00root root 0000000 0000000 52 comment=5d3b3ebd086a6607027a68e761c864abf7dad5c3
cepces-0.3.7/ 0000775 0000000 0000000 00000000000 14342136262 0012766 5 ustar 00root root 0000000 0000000 cepces-0.3.7/.github/ 0000775 0000000 0000000 00000000000 14342136262 0014326 5 ustar 00root root 0000000 0000000 cepces-0.3.7/.github/workflows/ 0000775 0000000 0000000 00000000000 14342136262 0016363 5 ustar 00root root 0000000 0000000 cepces-0.3.7/.github/workflows/ci.yml 0000664 0000000 0000000 00000001067 14342136262 0017505 0 ustar 00root root 0000000 0000000 name: Run Python Tests
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Python 3
uses: actions/setup-python@v1
with:
python-version: 3.8
- name: Install dependencies
run: |
sudo apt-get install libkrb5-dev
python3 -m pip install --upgrade pip
pip3 install -r requirements.txt
- name: Run tests
run: pushd tests; python3 runner.py; popd
cepces-0.3.7/.gitignore 0000664 0000000 0000000 00000000261 14342136262 0014755 0 ustar 00root root 0000000 0000000 # Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Distribution
*.egg-info/
dist/
# Local files
local/
# Configuration files
*.conf
.vscode/
.venv/
cepces-0.3.7/.pylintrc 0000664 0000000 0000000 00000000223 14342136262 0014630 0 ustar 00root root 0000000 0000000 [MESSAGES CONTROL]
# no-name-in-module (E0611) seems broken.
disable=no-name-in-module
[FORMAT]
max-line-length=80
[DESIGN]
min-public-methods=1
cepces-0.3.7/LICENSE 0000664 0000000 0000000 00000104513 14342136262 0013777 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
.
cepces-0.3.7/MANIFEST.in 0000664 0000000 0000000 00000000265 14342136262 0014527 0 ustar 00root root 0000000 0000000 # Include all tests
recursive-include tests *.py
include selinux/Makefile
include selinux/cepces.fc
include selinux/cepces.te
include selinux/cepces.if
include LICENSE
include *.rst cepces-0.3.7/README.rst 0000664 0000000 0000000 00000012141 14342136262 0014454 0 ustar 00root root 0000000 0000000 ==============================
CEP/CES Certificate Enrollment
==============================
``cepces`` is an application for enrolling certificates through CEP and CES. It
requires `certmonger`_ to operate.
Only simple deployments using Microsoft Active Directory Certificate Services
have been tested.
For more up-to-date information and further documentation, please visit the
project's home page at: https://github.com/openSUSE/cepces
Requirements
============
This application uses two SOAP endpoints over HTTPS provided by Microsoft
Active Directory Certificate Services. Currently, only Kerberos authentication
is supported. Therefore, the client has to be a Windows Domain Member with a
valid Kerberos keytab.
`cepces` is implemented in Python and requires at least Python 3.4 in order to
run, with all the required dependencies.
Installation
============
``cepces`` is currently supported on any system (well, not really) with:
* Python 3.4 or later
* Python dependencies specified in ``requirements.txt``
* `certmonger`_
If available, it is recommended to use a repository for installing the
application and all dependencies. Please consult the project's wiki for more
information on what distributions are supported and have repositories provided.
Download and unpack a release tarball and issue these commands from within the
extracted directory:
.. code-block:: bash
# pip3 install -r requirements.txt
# python3 setup.py install
Configuration
=============
Once installed, there is a configuration file that needs to be modified in
order for the certificate enrollment to function properly, possibly along with
some external modifications of system configuration files.
The configuration file should be available in the `/etc/cepces` directory,
possibly with a ".dist" extension. If that is the case drop the ".dist"
extension by either copying (or renaming) the file (i.e. ``cepces.conf.dist``
should be named ``cepces.conf``).
Alternatively, some configuration options can be specified from the command
line when adding a CA to `certmonger`_. For example:
.. code-block:: bash
getcert add-ca -c CA-name -e '/usr/libexec/certmonger/cepces-submit --server=ca-dns-name.suse.de --keytab=/etc/krb5.keytab --principals=MY-HOST$@SUSE.DE'
cepces.conf
-----------
This is the main configuration file. It is fairly small and only requires two
settings to be changed (`server` or `endpoint`, and `cas`).
`endpoint` should be set to the CEP endpoint, whereas `cas` should point to a
directory containing all CA certificates in your chain (if the version of the
`python-requests` package is recent enough), or preferably a bundle file
containing all CA certificates in the chain.
Usage
=====
`certmonger` should have a CA already configured after the packages were
installed:
.. code-block:: bash
# getcert list-cas
...
CA 'cepces':
is-default: no
ca-type: EXTERNAL
helper-location: /usr/libexec/certmonger/cepces-submit
Use this CA configuration as with any other. Please consult the official
`certmonger`_ documentation for instructions.
Example: Requesting a Machine Certificate
-----------------------------------------
If the current workstation is entitled to enroll "Workstation certificates" from
a CA (with the identifier ``Machine``), use the following command to issue and
track a new certificate:
.. code-block:: bash
# getcert request -c cepces -T Machine -I MachineCertificate -k /etc/pki/tls/private/machine.key -f /etc/pki/tls/certs/machine.crt
New signing request "MachineCertificate" added.
The certificate should now be submitted to the CA. Verify the progress with:
.. code-block:: bash
# getcert list
Number of certificates and requests being tracked: 1.
Request ID 'MachineCertificate':
status: SUBMITTING
stuck: no
key pair storage: type=FILE,location='/etc/pki/tls/private/machine.key'
certificate: type=FILE,location='/etc/pki/tls/certs/machine.crt'
CA: cepces
issuer:
subject:
expires: unknown
pre-save command:
post-save command:
track: yes
auto-renew: yes
After a few moments when the CA has successfully processed the request, the
certificate should be issued and monitored by certmonger:
.. code-block:: bash
# getcert list
Number of certificates and requests being tracked: 1.
Request ID 'MachineCertificate':
status: MONITORING
stuck: no
key pair storage: type=FILE,location='/etc/pki/tls/private/machine.key'
certificate: type=FILE,location='/etc/pki/tls/certs/machine.crt'
CA: cepces
issuer: CN=
subject: CN=
expires: 2017-08-15 17:37:02 UTC
dns:
key usage: digitalSignature,keyEncipherment
eku: id-kp-clientAuth,id-kp-serverAuth
certificate template/profile: Machine
pre-save command:
post-save command:
track: yes
auto-renew: yes
.. _certmonger: https://fedorahosted.org/certmonger/
cepces-0.3.7/bin/ 0000775 0000000 0000000 00000000000 14342136262 0013536 5 ustar 00root root 0000000 0000000 cepces-0.3.7/bin/cepces-submit 0000775 0000000 0000000 00000010243 14342136262 0016227 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=broad-except,invalid-name
"""This is a submission helper for certmonger."""
import logging
import os
import sys
import traceback
import argparse
import requests
from cepces.certmonger.core import Result
from cepces.certmonger.operation import Operation
from cepces.config import Configuration
from cepces.core import Service
from cepces.log import init_logging
def main(global_overrides, krb5_overrides):
"""Main function."""
# Initialize logging.
init_logging()
logger = logging.getLogger(__name__)
# A dictionary of all supported operations.
operations = {}
# Ensure there's any operation to call.
if 'CERTMONGER_OPERATION' not in os.environ:
logger.error('Missing environment variable: CERTMONGER_OPERATION')
sys.exit(Result.UNDERCONFIGURED)
# Find all supported certmonger operations.
for subclass in Operation.__subclasses__():
operations[subclass.name] = subclass
# Retrieve the operation name from the environment.
operation = os.environ['CERTMONGER_OPERATION']
result = Result.UNDERCONFIGURED
# If the operation is available, call it. Otherwise, return an error code.
if operation not in operations.keys():
result = Result.UNSUPPORTED
else:
try:
# Load the configuration and instantiate a service.
config = Configuration.load(global_overrides=global_overrides,
krb5_overrides=krb5_overrides)
if config.openssl_seclevel and config.openssl_seclevel.isnumeric():
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ALL:@SECLEVEL=%s' % config.openssl_seclevel
service = Service(config)
# Call the operation.
operation = operations[operation](service)
result = operation()
except Exception:
logger.error(traceback.format_exc())
sys.exit(result)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='cepces submission helper for certmonger')
parser.add_argument('--server',
help='Hostname of the issuing certification authority')
parser.add_argument('--auth',
help='Authentication mechanism used for connecting to the service',
choices=['Anonymous', 'Kerberos',
'UsernamePassword', 'Certificate'],
default='Kerberos')
parser.add_argument('--poll_interval',
help='Time in seconds before re-checking if the certificate has been issued')
parser.add_argument('--keytab', help='Use the specified keytab')
parser.add_argument('--principals',
help='A list of principals to try when requesting a ticket')
parser.add_argument('--openssl-seclevel', help='The openssl security level')
args = parser.parse_args()
g_overrides = {}
if args.server is not None:
g_overrides['server'] = args.server
g_overrides['auth'] = args.auth
endpoint = 'https://%s/ADPolicyProvider_CEP_%s/service.svc/CEP' % \
(args.server, args.auth)
g_overrides['endpoint'] = endpoint
if args.poll_interval is not None:
g_overrides['poll_interval'] = args.poll_interval
if args.openssl_seclevel is not None:
g_overrides['openssl_seclevel'] = args.openssl_seclevel
k_overrides = {}
if args.keytab is not None:
k_overrides['keytab'] = args.keytab
if args.principals is not None:
k_overrides['principals'] = args.principals
main(g_overrides, k_overrides)
cepces-0.3.7/cepces/ 0000775 0000000 0000000 00000000000 14342136262 0014230 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/__init__.py 0000664 0000000 0000000 00000003612 14342136262 0016343 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=too-few-public-methods
"""Main application package."""
import logging
__title__ = 'cepces'
__description__ = 'CEP/CES library.'
__url__ = 'https://github.com/openSUSE/cepces/'
__version__ = '0.3.7'
__author__ = 'Daniel Uvehag'
__author_email__ = 'daniel.uvehag@gmail.com'
__license__ = 'GPLv3'
__copyright__ = 'Copyright 2017 Daniel Uvehag'
class Base():
"""Base for most classes.
This class contains common behaviour for all classes used within the
project.
"""
def __init__(self, logger=None):
"""Initialize the instance.
The class uses either a supplied logger, or retrieves the default
logger for the instance.
:param logger: Optional logger.
"""
name = '{}.{}<0x{:02x}>'.format(
self.__module__,
self.__class__.__name__,
id(self),
)
self._logger = logger or logging.getLogger(name)
self._logger.debug('Initializing {0:s}.'
.format(name))
def __str__(self):
"""Returns a string representation of this instance.
:return: A string representation of this instance.
"""
return '{0}<{1}>'.format(self.__class__.__name__, hex(id(self)))
cepces-0.3.7/cepces/auth.py 0000664 0000000 0000000 00000011200 14342136262 0015535 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Module containing authentication type handlers."""
from abc import ABCMeta, abstractmethod
from cepces import Base
from cepces.krb5.functions import Error as KerberosError
from cepces.krb5.types import EncryptionType as KerberosEncryptionType
from cepces.soap import auth as SOAPAuth
def strtobool(value):
if str(value).lower() in ('t', 'true', 'y', 'yes', '1'):
return True
return False
class AuthenticationHandler(Base, metaclass=ABCMeta):
"""Base class for any authentication handled."""
def __init__(self, parser):
super().__init__()
self._parser = parser
@abstractmethod
def handle(self):
"""Constructs and returns a SOAPAuth authentication handler."""
class AnonymousAuthenticationHandler(AuthenticationHandler):
"""Constructs an anonymous authentication handler."""
def handle(self):
return SOAPAuth.AnonymousAuthentication()
class KerberosAuthenticationHandler(AuthenticationHandler):
"""Kerberos Authentication Handler"""
def handle(self):
parser = self._parser
# Ensure there's a kerberos section present.
if 'kerberos' not in parser:
raise RuntimeError('Missing "kerberos" section in configuration.')
section = parser['kerberos']
keytab = section.get('keytab', None)
realm = section.get('realm', None)
ccache = section.get('ccache', True)
principals = section.get('principals', '')
enctypes = section.get('enctypes', '')
delegate = strtobool(section.get('delegate', True))
# Decode all encryption types.
etypes = []
for enctype in enctypes.strip().split('\n'):
etype = "KRB5_ENCTYPE_{}".format(enctype.replace('-', '_').upper())
try:
etypes.append(KerberosEncryptionType[etype])
except KeyError as e:
raise RuntimeError(
'Unknown encryption type: {}'.format(enctype),
) from e
# Figure out which principal to use.
auth = None
for principal in principals.strip().split('\n'):
if realm:
principal = '{}@{}'.format(principal, realm)
try:
auth = SOAPAuth.TransportKerberosAuthentication(
principal_name=principal,
init_ccache=ccache,
keytab=keytab,
delegate=delegate,
)
except KerberosError:
# Ignore
pass
if auth:
return auth
else:
raise RuntimeError('No suitable key found in keytab.')
class UsernamePasswordAuthenticationHandler(AuthenticationHandler):
"""Handler for Username and Password based authentication."""
def handle(self):
parser = self._parser
# Ensure there's a usernamepassword section present.
if 'usernamepassword' not in parser:
raise RuntimeError(
'Missing "usernamepassword" section in configuration.',
)
section = parser['usernamepassword']
username = section.get('username', None)
password = section.get('password', None)
return SOAPAuth.MessageUsernamePasswordAuthentication(
username,
password,
)
class CertificateAuthenticationHandler(AuthenticationHandler):
"""Handler for Certificate based authentication."""
def handle(self):
"""Constructs and returns a SOAPAuth authentication handler."""
parser = self._parser
# Ensure there's a certificate section present.
if 'certificate' not in parser:
raise RuntimeError(
'Missing "certificate" section in configuration.',
)
section = parser['certificate']
certfile = section.get('certfile', None)
keyfile = section.get('keyfile', None)
return SOAPAuth.TransportCertificateAuthentication(
certfile,
keyfile,
)
cepces-0.3.7/cepces/certmonger/ 0000775 0000000 0000000 00000000000 14342136262 0016375 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/certmonger/__init__.py 0000664 0000000 0000000 00000001346 14342136262 0020512 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Package containing all certmonger integration components."""
cepces-0.3.7/cepces/certmonger/core.py 0000664 0000000 0000000 00000003233 14342136262 0017700 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""This module contains common shared certmonger classes."""
from enum import IntEnum
class Result(IntEnum):
"""This enumeration contains the result codes expected by certmonger."""
DEFAULT = 0
ISSUED = 0
WAIT = 1
REJECTED = 2
CONNECTERROR = 3
UNDERCONFIGURED = 4
WAITMORE = 5
UNSUPPORTED = 6
class MissingEnvironmentVariable(RuntimeError):
"""This error is raised when an expected environment variable is missing.
"""
def __init__(self, variable):
"""Initializes the error.
:param variable: the name of the missing environment variable.
"""
self._variable = variable
super().__init__(
'The mandatory environment variable {} is missing, '
'cannot proceed.'.format(variable)
)
@property
def variable(self):
"""Returns the name of the missing environment variable.
:return: the name of the missing environment variable.
"""
return self._variable
cepces-0.3.7/cepces/certmonger/operation.py 0000664 0000000 0000000 00000020512 14342136262 0020747 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=too-few-public-methods
"""This module contains all the supported certmonger operations."""
from abc import ABCMeta, abstractmethod
import os
import sys
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cepces import __title__, __version__
from cepces import Base
from cepces.core import PartialChainError
from cepces.certmonger.core import MissingEnvironmentVariable
from cepces.certmonger.core import Result as CertmongerResult
from cepces.soap.service import SOAPFault
class Operation(Base, metaclass=ABCMeta):
"""Abstract base class used by child classes mapping certmonger operations.
As certmonger calls the helper, all of the necessary data is available as
environment variables. Some of these variables may be required to perform
an action, whereas others are optional. This base class helps ensure
everything required is present, or fails otherwise.
Two class variables are used to define this behaviour:
* `required`: A list containing all required environment variables.
* `optional`: A list containing tuples of all optional environment
variables and their defaults (e.g., '("VAR", None)').
An extra class variable, `name`, is used to distinguish the mapped
certmonger operation.
"""
name = None
required = []
optional = []
def __init__(self, service, out=sys.stdout, logger=None):
"""Initializes an Operation.
All required and optional environment variables are verified, read and
stored in the instance as a dictionary.
:param service: the cepces service
:param out: default output stream (default: sys.stdout)
:raise MissingEnvironmentVariable: if a required environment variable
is not present.
"""
super().__init__(logger=logger)
self._service = service
self._out = out
self._vars = {}
# Verify that all required environment variables are present.
for var in self.__class__.required:
if var not in os.environ:
raise MissingEnvironmentVariable(var)
else:
self._vars[var] = os.environ[var]
# Get all optional variables and set their defaults if they're missing.
for var, default in self.__class__.optional:
if var not in os.environ:
self._vars[var] = default
else:
self._vars[var] = os.environ[var]
@abstractmethod
def __call__(self):
"""Calls the operation to let it performs its logic.
:return: the certmonger result code.
"""
class Submit(Operation):
"""Attempt to enroll a new certificate."""
name = 'SUBMIT'
required = ['CERTMONGER_CSR']
optional = [
('CERTMONGER_CERTIFICATE', None),
]
def __call__(self):
service = self._service
pem = self._vars['CERTMONGER_CSR'].strip()
csr = x509.load_pem_x509_csr(pem.encode(), default_backend())
self._logger.debug('Sending CSR: %s', pem)
try:
result = service.request(
csr,
renew=self._vars['CERTMONGER_CERTIFICATE'] is not None,
)
except SOAPFault as error:
print(error, file=self._out)
return CertmongerResult.REJECTED
self._logger.debug('Result is: %s', result)
# If we have a certificate, return it. Otherwise, ask certmonger to
# wait a bit.
if result.token:
self._logger.debug('Token is: %s', result.token)
pem = result.token.public_bytes(serialization.Encoding.PEM)
print(pem.decode().strip(), file=self._out)
return CertmongerResult.ISSUED
# Output a "cookie" that can be used to later poll the status.
print(
'{}\n{},{}'.format(
service._config.poll_interval,
result.request_id,
result.reference,
),
file=self._out,
)
return CertmongerResult.WAITMORE
class Poll(Operation):
"""Poll the status for a previous deferred request."""
name = 'POLL'
required = ['CERTMONGER_CA_COOKIE']
def __call__(self):
service = self._service
cookie = self._vars['CERTMONGER_CA_COOKIE']
request_id, reference = cookie.split(',', maxsplit=1)
try:
result = service.poll(int(request_id), reference)
except SOAPFault as error:
print(error, file=self._out)
return CertmongerResult.REJECTED
# If we have a certificate, return it. Otherwise, ask certmonger to
# wait a bit.
if result.token:
self._logger.debug('Token is: %s', result.token)
pem = result.token.public_bytes(serialization.Encoding.PEM)
print(pem.decode().strip(), file=self._out)
return CertmongerResult.ISSUED
# Output a "cookie" that can be used to later poll the status.
print(
'{}\n{},{}'.format(
service._config.poll_interval,
result.request_id,
result.reference,
),
file=self._out,
)
return CertmongerResult.WAITMORE
class Identify(Operation):
"""Outputs version information for this helper."""
name = 'IDENTIFY'
def __call__(self):
print('{} {}'.format(__title__, __version__), file=self._out)
return CertmongerResult.DEFAULT
class GetNewRequestRequirements(Operation):
"""Outputs a list of required environment variables for submission."""
name = 'GET-NEW-REQUEST-REQUIREMENTS'
def __call__(self):
# Output a list of required environment variables.
print('CERTMONGER_CA_PROFILE', file=self._out)
return CertmongerResult.DEFAULT
class GetRenewRequestRequirements(Operation):
"""Outputs a list of required environment variables for renewal."""
name = 'GET-RENEW-REQUEST-REQUIREMENTS'
def __call__(self):
# Output a list of required environment variables.
print('CERTMONGER_CA_PROFILE', file=self._out)
return CertmongerResult.DEFAULT
class GetSupportedTemplates(Operation):
"""Outputs a list of supported templates."""
name = 'GET-SUPPORTED-TEMPLATES'
def __call__(self):
templates = self._service.templates
if templates:
for template in templates:
print(template, file=self._out)
return CertmongerResult.DEFAULT
class GetDefaultTemplate(Operation):
"""Outputs the default template (which is nothing).
MS-XCEP doesn't specify a default template/policy, so this operation always
results in no output.
"""
name = 'GET-DEFAULT-TEMPLATE'
def __call__(self):
return CertmongerResult.DEFAULT
class FetchRoots(Operation):
"""Outputs suggested nick-names and certificates for all CAs."""
name = 'FETCH-ROOTS'
def __call__(self):
oid_cn = x509.oid.NameOID.COMMON_NAME
# Retrieve the certificate chain as far as possible.
try:
certs = list(self._service.certificate_chain or [])
except PartialChainError as error:
certs = error.result
output = []
for cert in certs:
names = cert.subject.get_attributes_for_oid(oid_cn)
pem = cert.public_bytes(serialization.Encoding.PEM)
output.append(
'{}\n{}'.format(
names[0].value,
pem.decode().strip(),
),
)
print('\n'.join(output), file=self._out)
return CertmongerResult.DEFAULT
cepces-0.3.7/cepces/config.py 0000664 0000000 0000000 00000014723 14342136262 0016056 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Module handling configuration loading."""
from configparser import ConfigParser, ExtendedInterpolation
from pathlib import Path
import logging
import socket
from cepces import Base
from cepces import auth as CoreAuth
from cepces.soap import auth as SOAPAuth
DEFAULT_CONFIG_FILES = [
'/etc/cepces/cepces.conf',
'/usr/local/etc/cepces/cepces.conf',
'conf/cepces.conf',
'cepces.conf',
]
DEFAULT_CONFIG_DIRS = [
'/etc/cepces/conf.d',
'/usr/local/etc/cepces/conf.d'
'conf/conf.d',
]
class Configuration(Base):
"""Base configuration class."""
AUTH_HANDLER_MAP = {
'Anonymous': CoreAuth.AnonymousAuthenticationHandler,
'Kerberos': CoreAuth.KerberosAuthenticationHandler,
'UsernamePassword': CoreAuth.UsernamePasswordAuthenticationHandler,
'Certificate': CoreAuth.CertificateAuthenticationHandler,
}
AUTH_MAP = {
'Anonymous': SOAPAuth.AnonymousAuthentication,
'Kerberos': SOAPAuth.TransportKerberosAuthentication,
'UsernamePassword': SOAPAuth.MessageUsernamePasswordAuthentication,
'Certificate': SOAPAuth.TransportCertificateAuthentication,
}
def __init__(self, endpoint, endpoint_type, cas, auth, poll_interval, openssl_seclevel):
super().__init__()
self._endpoint = endpoint
self._endpoint_type = endpoint_type
self._cas = cas
self._auth = auth
self._poll_interval = poll_interval
self._openssl_seclevel = openssl_seclevel
@property
def endpoint(self):
"""Return the endpoint."""
return self._endpoint
@property
def endpoint_type(self):
"""Return the endpoint."""
return self._endpoint_type
@property
def cas(self):
"""Return the CA path."""
return self._cas
@property
def auth(self):
"""Return the authentication method."""
return self._auth
@property
def poll_interval(self):
"""Return the poll interval."""
return self._poll_interval
@property
def openssl_seclevel(self):
"""Return the openssl security level."""
return self._openssl_seclevel
@classmethod
def load(cls, files=None, dirs=None, global_overrides=None,
krb5_overrides=None):
"""Load configuration files and directories and instantiate a new
Configuration."""
name = '{}.{}'.format(
cls.__module__,
cls.__name__,
)
logger = logging.getLogger(name)
logger.debug('Initializing application configuration.')
config = ConfigParser(interpolation=ExtendedInterpolation())
config.optionxform = str # Make options case sensitive.
# Add some defaults.
hostname = socket.gethostname().lower()
fqdn = socket.getfqdn()
shortname = hostname.split('.')[0]
config['DEFAULT']['hostname'] = hostname.lower()
config['DEFAULT']['HOSTNAME'] = hostname.upper()
config['DEFAULT']['fqdn'] = fqdn.lower()
config['DEFAULT']['FQDN'] = fqdn.upper()
config['DEFAULT']['shortname'] = shortname.lower()
config['DEFAULT']['SHORTNAME'] = shortname.upper()
if not config.has_section('global'):
config.add_section('global')
config['global']['openssl_seclevel'] = ''
if files is None:
files = DEFAULT_CONFIG_FILES
if dirs is None:
dirs = DEFAULT_CONFIG_DIRS
# Read all configuration files.
for path in [Path(x) for x in files]:
if path.is_file():
logger.debug('Reading: {0:s}'.format(path.__str__()))
config.read(path.__str__())
# Read all configuration directories.
for cdir in [Path(x) for x in dirs]:
if cdir.is_dir():
for path in sorted([x for x in cdir.iterdir() if x.is_file()]):
logger.debug('Reading: {0:s}'.format(path.__str__()))
config.read(path)
# Override globals set from the command line
if global_overrides is not None:
for key, val in global_overrides.items():
config['global'][key] = val
if krb5_overrides is not None:
for key, val in krb5_overrides.items():
config['kerberos'][key] = val
return Configuration.from_parser(config)
@classmethod
def from_parser(cls, parser):
"""Create a Configuration instance from a ConfigParser."""
# Ensure there's a global section present.
if 'global' not in parser:
raise RuntimeError('Missing "global" section in configuration.')
section = parser['global']
# Ensure certain required variables are present.
for var in ['endpoint', 'auth', 'type', 'poll_interval', 'openssl_seclevel']:
if var not in section:
raise RuntimeError(
'Missing "{}/{}" variable in configuration.'.format(
'global',
var,
),
)
# Verify that the chosen authentication method is valid.
if section['auth'] not in Configuration.AUTH_HANDLER_MAP.keys():
raise RuntimeError(
'No such authentication method: {}'.format(
section['auth'],
),
)
# Store the global configuration options.
endpoint = section.get('endpoint')
endpoint_type = section.get('type')
authn = Configuration.AUTH_HANDLER_MAP[section['auth']](parser)
cas = section.get('cas', True)
poll_interval = section.get('poll_interval')
openssl_seclevel = section.get('openssl_seclevel')
if cas == '':
cas = False
return Configuration(endpoint, endpoint_type, cas, authn.handle(), poll_interval, openssl_seclevel)
cepces-0.3.7/cepces/core.py 0000664 0000000 0000000 00000025643 14342136262 0015544 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=invalid-name,no-self-use
"""Module containing core classes and functionality."""
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
import requests
from cepces import Base
from cepces.config import Configuration
from cepces.xcep.service import Service as XCEPService
from cepces.wstep.service import Service as WSTEPService
class PartialChainError(RuntimeError):
"""Error raised when a complete certificate chain cannot be retreived."""
def __init__(self, msg, result):
super().__init__(msg)
self._result = result
@property
def result(self):
"""Return the result so far."""
return self._result
class Service(Base):
"""Main service."""
class Endpoint(Base):
"""Internal class representing potential endpoints."""
def __init__(self, url, priority, renewal_only):
super().__init__()
self._url = url
self._priority = priority
self._renewal_only = renewal_only
@property
def url(self):
"""Get the URL."""
return self._url
@property
def priority(self):
"""Get the priority."""
return self._priority
@property
def renewal_only(self):
"""Can this endpoint be used only for renewals?"""
return self._renewal_only
def __str__(self):
return self.url
def __init__(self, config):
super().__init__()
self._config = config
if config.endpoint_type == 'Policy':
self._xcep = XCEPService(
endpoint=config.endpoint,
auth=config.auth,
capath=config.cas,
)
# Eagerly load the policy response.
self._policies = self._xcep.get_policies()
elif config.endpoint_type == 'Enrollment':
self._xcep = None
self._ces = WSTEPService(
endpoint=config.endpoint,
auth=config.auth,
capath=config.cas,
)
@property
def templates(self):
"""Retrieve a list of available templates.
Returns None if no policy endpoint is used.
"""
if self._xcep is None:
return None
templates = []
for policy in self._policies.response.policies:
templates.append(policy.attributes.common_name)
return templates
@property
def endpoints(self):
"""Retrieves a list of WSTEP suitable endpoints.
Returns None if no policy endpoint is used.
"""
if self._xcep is None:
return None
config = self._config
endpoints = []
for ca in self._policies.cas:
for uri in [x for x in ca.uris if x.id in Configuration.AUTH_MAP]:
if isinstance(config.auth, Configuration.AUTH_MAP[uri.id]):
endpoints.append(
Service.Endpoint(
uri.uri,
uri.priority,
uri.renewal_only,
),
)
return sorted(endpoints, key=lambda x: x.priority)
@property
def certificate_chain(self, index=0):
"""Get the complete certification authority chain.
This retreives the certificate from the issuing endpoint service, and
then uses the AIA information to retreive the rest of the chain.
This is only implemented for Policy endpoints. Returns None otherwise.
:raise PartialChainError: if no AIA is found, or the complete chain
cannot be retreived. The exception contains
the partial result.
"""
if self._xcep is None:
return None
# Get the first certificate. Since is (or at least always should) be
# securely retreived over a secure channel, only verify subsequent
# certificates.
data = self._policies.cas[index].certificate
return reversed(self._resolve_chain(data))
def _request_ces(self, csr):
"""Request a certificate with a CSR from a CES endpoint."""
csr_bytes = csr.public_bytes(serialization.Encoding.PEM)
csr_raw = csr_bytes.decode('utf-8').strip()
response = self._ces.request(csr_raw)
# There should only be one response, as we only send one request.
if response:
# Convert to proper certificate, if possible.
r = response[0]
if r.token:
pem = r.token.encode()
cert = x509.load_pem_x509_certificate(pem, default_backend())
r.token = cert
return r
return None
def _request_cep(self, csr, renew=False):
"""Request a certificate with a CSR through a CEP endpoint."""
endpoint = None
for candidate in self.endpoints:
# If not renewing and the endpoint only supports renewal, ignore
# it.
if renew and candidate.renewal_only or not candidate.renewal_only:
endpoint = candidate
break
# No endpoint found.
if not endpoint:
return None
self._ces = WSTEPService(
endpoint=str(endpoint),
auth=self._config.auth,
capath=self._config.cas,
)
return self._request_ces(csr)
def request(self, csr, renew=False):
"""Request a certificate with a CSR."""
if self._xcep:
return self._request_cep(csr, renew)
else:
return self._request_ces(csr)
def poll(self, request_id, uri):
"""Poll the status of a previous request."""
ces = WSTEPService(
endpoint=uri,
auth=self._config.auth,
capath=self._config.cas,
)
response = ces.poll(request_id)
# There should only be one response, as we only send one request.
if response:
# Convert to proper certificate, if possible.
r = response[0]
if r.token:
pem = r.token.encode()
cert = x509.load_pem_x509_certificate(pem, default_backend())
r.token = cert
return r
return None
def _verify_certificate_signature(self, cert, issuer):
"""Verify that the certificate is signed.
:param cert: the certificate to verify
:param issuer: the certificate's issuer certificate
:raise InvalidSignature: if the signature cannot be verified
:return: True on successful verification
"""
sig_hash_alg = cert.signature_hash_algorithm
sig_bytes = cert.signature
issuer_public_key = issuer.public_key()
# Check the type of public key
if isinstance(issuer_public_key, rsa.RSAPublicKey):
verifier = issuer_public_key.verifier(
sig_bytes, padding.PKCS1v15(), sig_hash_alg,
)
elif isinstance(issuer_public_key, ec.EllipticCurvePublicKey):
verifier = issuer_public_key.verifier(
sig_bytes, ec.ECDSA(sig_hash_alg),
)
else:
verifier = issuer_public_key.verifier(
sig_bytes, sig_hash_alg,
)
verifier.update(cert.tbs_certificate_bytes)
verifier.verify()
return True
def _resolve_chain(self, data, child=None):
"""Recursive method for resolving a certificate. This starts with the
data for a certificate, and a possible child certificate that needs to
be validated. This is a reversed approach as the process is to start
with a issued certificate and validate it upwards, until the root
CA is reached.
:param data: PEM encoded certificate to resolve.
:param child: Optional child to validate.
:raise PartialChainError: if no AIA is found, or the complete chain
cannot be retreived. The exception contains
the partial result.
"""
result = []
extension = x509.AuthorityInformationAccess
oid = x509.oid.AuthorityInformationAccessOID
# Load the certificate.
cert = x509.load_pem_x509_certificate(
data.encode(),
default_backend(),
)
# If no child is present, this is the first cert and thus cannot be
# verified yet.
# If there is a child, verify the signature.
if not child:
result.append(cert)
elif self._verify_certificate_signature(child, cert):
result.append(cert)
else:
raise PartialChainError(
'Could not verify certificate chain '
'({} not signed by {})'.format(
child.subject,
cert.subject,
),
result,
)
# If the issuer and subject are the same, this is a root certificate.
# break here.
if cert.subject == cert.issuer:
return result
try:
# Get all AIA extensions from the certificate.
aias = cert.extensions.get_extension_for_class(extension)
for aia in aias.value:
# Ignore anything but issuers.
if aia.access_method == oid.CA_ISSUERS:
uri = aia.access_location.value
# Try to fetch the certificate.
r = requests.get(uri)
r.raise_for_status()
parent = self._resolve_chain(r.text, cert)
if parent:
result.extend(parent)
except x509.ExtensionNotFound as e:
raise PartialChainError('Missing AIA', result) from e
except requests.exceptions.RequestException as e:
raise PartialChainError(e, result) from e
except InvalidSignature as e:
raise PartialChainError(e, result) from e
return result
cepces-0.3.7/cepces/krb5/ 0000775 0000000 0000000 00000000000 14342136262 0015073 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/krb5/__init__.py 0000664 0000000 0000000 00000001335 14342136262 0017206 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""This package contains all Kerberos related logic."""
cepces-0.3.7/cepces/krb5/core.py 0000664 0000000 0000000 00000027025 14342136262 0016403 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=too-many-arguments
"""This module contains wrapper classes for the Kerberos integration."""
import ctypes
import re
from cepces import Base as CoreBase
from cepces.krb5 import types as ktypes
from cepces.krb5 import functions as kfuncs
# Regular expressions for matching against keytab and principal names.
NAME_EX = r'^(?:(?P[A-Z]+):)?(?P.+)$'
PRINCIPAL_EX = r'^(?P[^/]+)(?:/(?P.+))?@(?P.+)$'
class Base(CoreBase):
"""Base class for any Kerberos wrapper class."""
def __init__(self, handle):
super().__init__()
self._logger.debug("Handle %s", handle)
self._handle = handle
@property
def handle(self):
"""Get the Kerberos context handle."""
if hasattr(self, '_handle'):
return self._handle
return None
class Context(Base):
"""Represents the Kerberos context."""
def __init__(self):
super().__init__(ktypes.krb5_context())
kfuncs.init_context(self.handle)
def __del__(self):
if self.handle:
# self._logger.debug("Freeing context {}".format(self.handle))
kfuncs.free_context(self.handle)
class KeytabName(Base):
"""Represents the name of the keytab.
MIT Kerberos represents this as 'TYPE:RESIDUAL' (e.g.,
'FILE:/etc/krb5.keytab'). Heimdall on the other hand, retreiving the
name of the keytab only returns the residual (e.g.,
'/etc/krb5.keytab').
Setting normalize to True constructs a 'TYPE:RESIDUAL' name, even if
the native call to krb5_kt_get_name only returns the residual part.
"""
def __init__(self, name=None, context=None, keytab=None, normalize=True):
super().__init__(None)
if name and context and keytab:
raise RuntimeError("Only specify name OR context and keytab.")
elif name:
self._init_name(name)
elif context and keytab:
self._init_keytab(context, keytab, normalize)
else:
# Raise an error.
raise RuntimeError("Missing name OR context and keytab.")
def __str__(self):
return self._name
def _init_name(self, name):
parts = name.split(':', maxsplit=1)
if not len(parts) == 2:
raise RuntimeError("Name has to equal \"TYPE:RESIDUAL\".")
self._name = name
self._type = parts[0]
self._residual = parts[1]
def _init_keytab(self, context, keytab, normalize):
buffer = ctypes.create_string_buffer(ktypes.LINE_MAX)
kfuncs.kt_get_name(
context.handle,
keytab.handle,
buffer,
ktypes.LINE_MAX,
)
name = buffer.value.decode('utf-8')
match = re.match(NAME_EX, name)
self._type = match.group('type')
self._residual = match.group('residual')
if not self._type:
buffer = kfuncs.kt_get_type(
context.handle,
keytab.handle,
)
# If type is still None, assume that it's 'FILE'.
if buffer:
self._type = buffer.decode('utf-8')
else:
self._type = 'FILE'
if normalize:
self._name = '{}:{}'.format(self._type, self._residual)
else:
self._name = self._residual
else:
self._name = name
@property
def type(self):
"""Get the type of the keytab name."""
return self._type
@property
def residual(self):
"""Get the residual of the keytab name."""
return self._residual
@staticmethod
def default(context):
"""Get the default Keytab name."""
buffer = ctypes.create_string_buffer(ktypes.LINE_MAX)
kfuncs.kt_default_name(
context.handle,
buffer,
ktypes.LINE_MAX,
)
return buffer.value.decode('utf-8')
class Keytab(Base):
"""Wrapper class for a keytab."""
def __init__(self, context, keytab=None):
super().__init__(ktypes.krb5_keytab())
self._context = context
self._keytab = keytab
if self._keytab:
kfuncs.kt_resolve(
self._context.handle,
self._keytab.encode('utf-8'),
self.handle,
)
else:
kfuncs.kt_default(
self._context.handle,
self.handle,
)
self._name = KeytabName(context=self._context, keytab=self)
def __del__(self):
if self.handle:
# self._logger.debug("Closing keytab {}".format(self.handle))
kfuncs.kt_close(self._context.handle, self.handle)
def __str__(self):
return str(self._name)
@property
def type(self):
"""Get the type of the keytab."""
return self._name.type
@property
def residual(self):
"""Get the residual of the keytab."""
return self._name.residual
class PrincipalName(Base):
"""Representation of a Kerberos Principal Name.
It consists of one or more principal name components, separated by slashes,
optionally followed by the @ character and a realm name. If the realm name
is not specified, the local realm is used.
"""
def __init__(self, principal, name, context, host, service, service_type):
super().__init__(None)
if name:
kfuncs.parse_name(
context.handle,
name.encode('utf-8'),
principal.handle,
)
else:
kfuncs.sname_to_principal(
context.handle,
host,
service,
service_type,
principal.handle,
)
# Unparse the recently acquired principal to retrieve the different
# components.
buffer = ctypes.c_char_p()
kfuncs.unparse_name(context.handle, principal.handle, buffer)
name = buffer.value.decode('utf-8')
kfuncs.free_unparsed_name(context.handle, buffer)
match = re.match(PRINCIPAL_EX, name)
self._primary = match.group('primary')
self._instance = match.group('instance')
self._realm = match.group('realm')
@property
def primary(self):
"""Get the primary component of the name."""
return self._primary
@property
def instance(self):
"""Get the instance component of the name."""
return self._instance
@property
def realm(self):
"""Get the realm component of the name."""
return self._realm
class Principal(Base):
"""Representation of a Kerberos Principal."""
def __init__(self, context, name=None, host=None, service=None,
service_type=ktypes.PrincipalType.KRB5_NT_SRV_HST):
super().__init__(ktypes.krb5_principal())
self._context = context
self._name = PrincipalName(
self,
name,
context,
host,
service,
service_type,
)
def __del__(self):
if self.handle:
# self._logger.debug("Freeing principal {}".format(self.handle))
kfuncs.free_principal(self._context.handle, self.handle)
@property
def primary(self):
"""Get the primary component of the name."""
return self._name.primary
@property
def instance(self):
"""Get the instance component of the name."""
return self._name.instance
@property
def realm(self):
"""Get the realm component of the name."""
return self._name.realm
class CredentialOptions(Base):
"""Represents a Kerberos Credential Options structure."""
def __init__(self, context):
super().__init__(ktypes.krb5_get_init_creds_opt_p())
self._context = context
self._forwardable = False
self._encryption_types = []
kfuncs.get_init_creds_opt_alloc(
self._context.handle,
self.handle,
)
def __del__(self):
if self.handle:
# self._logger.debug("Freeing credential options {}".format(
# self.handle))
kfuncs.get_init_creds_opt_free(self._context.handle, self.handle)
@property
def forwardable(self):
"""Returns whether or not the credentials are forwardable."""
return self._forwardable
@forwardable.setter
def forwardable(self, value):
kfuncs.get_init_creds_opt_set_forwardable(
self.handle,
int(value is True)
)
self._forwardable = value
@property
def encryption_types(self):
"""Returns a list of encryption types."""
return self._encryption_types
@encryption_types.setter
def encryption_types(self, types):
if not types:
return
etypes = (ktypes.krb5_enctype * len(types))(*types)
kfuncs.get_init_creds_opt_set_etype_list(
self.handle,
ctypes.cast(etypes, ctypes.POINTER(ktypes.krb5_enctype)),
len(types),
)
self._encryption_types = types
class Credentials(Base):
"""Representation of a set of Kerberos Credentials."""
def __init__(self, context, client, keytab, start_time, tkt_service,
options):
super().__init__(ktypes.krb5_creds())
self._context = context
self._client = client
self._keytab = keytab
self._start_time = start_time
self._tkt_service = tkt_service
self._options = options
self._init()
def _init(self):
kfuncs.get_init_creds_keytab(
self._context.handle,
self.handle,
self._client.handle,
self._keytab.handle,
self._start_time,
self._tkt_service.encode('utf-8'),
self._options.handle,
)
def __del__(self):
if self.handle:
# self._logger.debug("Freeing credentials {}".format(
# self.handle))
kfuncs.free_cred_contents(self._context.handle, self.handle)
class CredentialCache(Base):
"""Representation of a Credential Cache."""
def __init__(self, context, name, client, credentials):
super().__init__(ktypes.krb5_ccache())
self._context = context
self._name = name
self._client = client
self._credentials = credentials
kfuncs.cc_resolve(
self._context.handle,
self._name.encode('utf-8'),
self.handle,
)
kfuncs.cc_initialize(
self._context.handle,
self.handle,
self._client.handle,
)
kfuncs.cc_store_cred(
self._context.handle,
self.handle,
self._credentials.handle,
)
def __del__(self):
if self.handle:
# self._logger.debug("Closing credential cache {}".format(
# self.handle))
kfuncs.krb5_cc_close(self._context.handle, self.handle)
cepces-0.3.7/cepces/krb5/functions.py 0000664 0000000 0000000 00000025626 14342136262 0017470 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=invalid-name
"""This module contains all the Kerberos functions."""
import ctypes
import functools
from cepces.krb5 import types as ktypes
from cepces.krb5.lib import _shlib
class Error(RuntimeError):
"""Generic error class, representing a runtime error from Kerberos."""
def __init__(self, context, code):
message_p = get_error_message(context, code)
self._code = code
self._message = message_p.value.decode('utf-8')
super().__init__(self._message)
free_error_message(context, message_p)
@property
def code(self):
"""Get the error code."""
return self._code
def __str__(self):
return self._message
def error_decorator(func):
"""Decorator for wrapping a function that raises errors on failed
Kerberos calls."""
if func.restype is not ktypes.krb5_error_code:
return func
@functools.wraps(func)
def wrapper(context, *args):
"""Wrapper function."""
result = func(context, *args)
# If the function call failed, raise an error.
if result:
raise Error(context, result)
return result
return wrapper
# krb5_error_code krb5_cc_close(krb5_context context, krb5_ccache cache)
krb5_cc_close = _shlib.krb5_cc_close
krb5_cc_close.restype = ktypes.krb5_error_code
krb5_cc_close.argtypes = [
ktypes.krb5_context,
ktypes.krb5_ccache,
]
cc_close = error_decorator(krb5_cc_close)
# krb5_error_code krb5_cc_initialize(krb5_context context, krb5_ccache cache,
# krb5_principal principal)
krb5_cc_initialize = _shlib.krb5_cc_initialize
krb5_cc_initialize.restype = ktypes.krb5_error_code
krb5_cc_initialize.argtypes = [
ktypes.krb5_context,
ktypes.krb5_ccache,
ktypes.krb5_principal,
]
cc_initialize = error_decorator(krb5_cc_initialize)
# krb5_error_code krb5_cc_resolve(krb5_context context, const char * name,
# krb5_ccache * cache)
krb5_cc_resolve = _shlib.krb5_cc_resolve
krb5_cc_resolve.restype = ktypes.krb5_error_code
krb5_cc_resolve.argtypes = [
ktypes.krb5_context,
ctypes.c_char_p,
ctypes.POINTER(ktypes.krb5_ccache),
]
cc_resolve = error_decorator(krb5_cc_resolve)
# krb5_error_code krb5_cc_store_cred(krb5_context context, krb5_ccache cache,
# krb5_creds * creds)
krb5_cc_store_cred = _shlib.krb5_cc_store_cred
krb5_cc_store_cred.restype = ktypes.krb5_error_code
krb5_cc_store_cred.argtypes = [
ktypes.krb5_context,
ktypes.krb5_ccache,
ctypes.POINTER(ktypes.krb5_creds),
]
cc_store_cred = error_decorator(krb5_cc_store_cred)
# void krb5_free_context(krb5_context context)
krb5_free_context = _shlib.krb5_free_context
krb5_free_context.restype = None
krb5_free_context.argtypes = [
ktypes.krb5_context,
]
free_context = error_decorator(krb5_free_context)
# void krb5_free_cred_contents(krb5_context context, krb5_creds * val)
krb5_free_cred_contents = _shlib.krb5_free_cred_contents
krb5_free_cred_contents.restype = None
krb5_free_cred_contents.argtypes = [
ktypes.krb5_context,
ctypes.POINTER(ktypes.krb5_creds),
]
free_cred_contents = error_decorator(krb5_free_cred_contents)
# void krb5_free_error_message(krb5_context ctx, const char * msg)
krb5_free_error_message = _shlib.krb5_free_error_message
krb5_free_error_message.restype = None
krb5_free_error_message.argtypes = [
ktypes.krb5_context,
ktypes.c_char_p_n,
]
free_error_message = error_decorator(krb5_free_error_message)
# void krb5_free_principal(krb5_context context, krb5_principal val)
krb5_free_principal = _shlib.krb5_free_principal
krb5_free_principal.restype = None
krb5_free_principal.argtypes = [
ktypes.krb5_context,
ktypes.krb5_principal,
]
free_principal = error_decorator(krb5_free_principal)
# void krb5_free_unparsed_name(krb5_context context, char * val)
krb5_free_unparsed_name = _shlib.krb5_free_unparsed_name
krb5_free_unparsed_name.restype = None
krb5_free_unparsed_name.argtypes = [
ktypes.krb5_context,
ctypes.c_char_p,
]
free_unparsed_name = error_decorator(krb5_free_unparsed_name)
# const char * krb5_get_error_message(krb5_context ctx, krb5_error_code code)
krb5_get_error_message = _shlib.krb5_get_error_message
krb5_get_error_message.restype = ktypes.c_char_p_n
krb5_get_error_message.argtypes = [
ktypes.krb5_context,
ktypes.krb5_error_code,
]
get_error_message = error_decorator(krb5_get_error_message)
# krb5_error_code krb5_get_init_creds_keytab(krb5_context context,
# krb5_creds * creds, krb5_principal client, krb5_keytab arg_keytab,
# krb5_deltat start_time, const char * in_tkt_service,
# krb5_get_init_creds_opt * k5_gic_options)
krb5_get_init_creds_keytab = _shlib.krb5_get_init_creds_keytab
krb5_get_init_creds_keytab.restype = ktypes.krb5_error_code
krb5_get_init_creds_keytab.argtypes = [
ktypes.krb5_context,
ctypes.POINTER(ktypes.krb5_creds),
ktypes.krb5_principal,
ktypes.krb5_keytab,
ktypes.krb5_deltat,
ctypes.c_char_p,
ctypes.POINTER(ktypes.krb5_get_init_creds_opt),
]
get_init_creds_keytab = error_decorator(krb5_get_init_creds_keytab)
# krb5_error_code krb5_get_init_creds_opt_alloc(krb5_context context,
# krb5_get_init_creds_opt ** opt)
krb5_get_init_creds_opt_alloc = _shlib.krb5_get_init_creds_opt_alloc
krb5_get_init_creds_opt_alloc.restype = ktypes.krb5_error_code
krb5_get_init_creds_opt_alloc.argtypes = [
ktypes.krb5_context,
ctypes.POINTER(ctypes.POINTER(ktypes.krb5_get_init_creds_opt)),
]
get_init_creds_opt_alloc = error_decorator(krb5_get_init_creds_opt_alloc)
# void krb5_get_init_creds_opt_free(krb5_context context,
# krb5_get_init_creds_opt * opt)
krb5_get_init_creds_opt_free = _shlib.krb5_get_init_creds_opt_free
krb5_get_init_creds_opt_free.restype = None
krb5_get_init_creds_opt_free.argtypes = [
ktypes.krb5_context,
ctypes.POINTER(ktypes.krb5_get_init_creds_opt),
]
get_init_creds_opt_free = error_decorator(krb5_get_init_creds_opt_free)
# void krb5_get_init_creds_opt_set_etype_list(krb5_get_init_creds_opt * opt,
# krb5_enctype * etype_list, int etype_list_length)
krb5_get_init_creds_opt_set_etype_list = \
_shlib.krb5_get_init_creds_opt_set_etype_list
krb5_get_init_creds_opt_set_etype_list.restype = None
krb5_get_init_creds_opt_set_etype_list.argtypes = [
ctypes.POINTER(ktypes.krb5_get_init_creds_opt),
ctypes.POINTER(ktypes.krb5_enctype),
ctypes.c_int,
]
get_init_creds_opt_set_etype_list = \
error_decorator(krb5_get_init_creds_opt_set_etype_list)
# void krb5_get_init_creds_opt_set_forwardable(krb5_get_init_creds_opt * opt,
# int forwardable)
krb5_get_init_creds_opt_set_forwardable = \
_shlib.krb5_get_init_creds_opt_set_forwardable
krb5_get_init_creds_opt_set_forwardable.restype = None
krb5_get_init_creds_opt_set_forwardable.argtypes = [
ctypes.POINTER(ktypes.krb5_get_init_creds_opt),
ctypes.c_int,
]
get_init_creds_opt_set_forwardable = \
error_decorator(krb5_get_init_creds_opt_set_forwardable)
# krb5_error_code krb5_init_context(krb5_context * context)
krb5_init_context = _shlib.krb5_init_context
krb5_init_context.restype = ktypes.krb5_error_code
krb5_init_context.argtypes = [
ctypes.POINTER(ktypes.krb5_context),
]
init_context = error_decorator(krb5_init_context)
# krb5_error_code krb5_kt_close(krb5_context context, krb5_keytab keytab)
krb5_kt_close = _shlib.krb5_kt_close
krb5_kt_close.restype = ktypes.krb5_error_code
krb5_kt_close.argtypes = [
ktypes.krb5_context,
ktypes.krb5_keytab,
]
kt_close = error_decorator(krb5_kt_close)
# krb5_error_code krb5_kt_default(krb5_context context, krb5_keytab * id)
krb5_kt_default = _shlib.krb5_kt_default
krb5_kt_default.restype = ktypes.krb5_error_code
krb5_kt_default.argtypes = [
ktypes.krb5_context,
ctypes.POINTER(ktypes.krb5_keytab),
]
kt_default = error_decorator(krb5_kt_default)
# krb5_error_code krb5_kt_default_name(krb5_context context, char * name,
# int name_size)
krb5_kt_default_name = _shlib.krb5_kt_default_name
krb5_kt_default_name.restype = ktypes.krb5_error_code
krb5_kt_default_name.argtypes = [
ktypes.krb5_context,
ctypes.POINTER(ctypes.c_char),
ctypes.c_uint,
]
kt_default_name = error_decorator(krb5_kt_default_name)
# krb5_error_code krb5_kt_get_name(krb5_context context, krb5_keytab keytab,
# char * name, unsigned int namelen)
krb5_kt_get_name = _shlib.krb5_kt_get_name
krb5_kt_get_name.restype = ktypes.krb5_error_code
krb5_kt_get_name.argtypes = [
ktypes.krb5_context,
ktypes.krb5_keytab,
ctypes.POINTER(ctypes.c_char),
ctypes.c_uint,
]
kt_get_name = error_decorator(krb5_kt_get_name)
# const char * krb5_kt_get_type(krb5_context context, krb5_keytab keytab)
krb5_kt_get_type = _shlib.krb5_kt_get_type
krb5_kt_get_type.restype = ctypes.c_char_p
krb5_kt_get_type.argtypes = [
ktypes.krb5_context,
ktypes.krb5_keytab,
]
kt_get_type = error_decorator(krb5_kt_get_type)
# krb5_error_code krb5_kt_resolve(krb5_context context, const char * name,
# krb5_keytab * ktid)
krb5_kt_resolve = _shlib.krb5_kt_resolve
krb5_kt_resolve.restype = ktypes.krb5_error_code
krb5_kt_resolve.argtypes = [
ktypes.krb5_context,
ctypes.c_char_p,
ctypes.POINTER(ktypes.krb5_keytab),
]
kt_resolve = error_decorator(krb5_kt_resolve)
# krb5_error_code krb5_kt_default(krb5_context context, krb5_keytab * id)
krb5_parse_name = _shlib.krb5_parse_name
krb5_parse_name.restype = ktypes.krb5_error_code
krb5_parse_name.argtypes = [
ktypes.krb5_context,
ctypes.c_char_p,
ctypes.POINTER(ktypes.krb5_principal),
]
parse_name = error_decorator(krb5_parse_name)
# krb5_error_code krb5_sname_to_principal(krb5_context context,
# const char * hostname, const char * sname, krb5_int32 type,
# krb5_principal * ret_princ)
krb5_sname_to_principal = _shlib.krb5_sname_to_principal
krb5_sname_to_principal.restype = ktypes.krb5_error_code
krb5_sname_to_principal.argtypes = [
ktypes.krb5_context,
ctypes.c_char_p,
ctypes.c_char_p,
ktypes.krb5_int32,
ctypes.POINTER(ktypes.krb5_principal),
]
sname_to_principal = error_decorator(krb5_sname_to_principal)
# krb5_error_code krb5_unparse_name(krb5_context context,
# krb5_const_principal principal, register char ** name)
krb5_unparse_name = _shlib.krb5_unparse_name
krb5_unparse_name.restype = ktypes.krb5_error_code
krb5_unparse_name.argtypes = [
ktypes.krb5_context,
ktypes.krb5_const_principal,
ctypes.POINTER(ctypes.c_char_p),
]
unparse_name = error_decorator(krb5_unparse_name)
cepces-0.3.7/cepces/krb5/lib.py 0000664 0000000 0000000 00000002405 14342136262 0016214 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=invalid-name
"""This module tries to load the shared library for Kerberos."""
import ctypes
# Try to load the Kerberos5 library dynamically. Naïvely try to load everything
# in the list until successful.
_shlib = None
_libs = [
'libgssapi_krb5.so',
'libgssapi_krb5.so.2',
'libgssapi_krb5.dylib',
]
for lib in _libs:
if _shlib is not None:
break
else:
try:
_shlib = ctypes.CDLL(lib)
except OSError:
pass
# If no library was found, fail.
if _shlib is None:
raise RuntimeError("Could not load any Kerberos library.")
cepces-0.3.7/cepces/krb5/types.py 0000664 0000000 0000000 00000012167 14342136262 0016620 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=invalid-name,too-few-public-methods
"""This module contains all Kerberos specific types and structures."""
import ctypes
from enum import IntEnum
LINE_MAX = 2048
# The name of the Kerberos ticket granting service
KRB5_TGS_NAME = 'krbtgt'
krb5_int32 = ctypes.c_int32
krb5_enctype = krb5_int32
krb5_deltat = krb5_int32
krb5_error_code = krb5_int32
class PrincipalType(IntEnum):
"""Enumeration for all possible principal types."""
# Name type not known
KRB5_NT_UNKNOWN = 0
# Just the name of the principal as in DCE, or for users
KRB5_NT_PRINCIPAL = 1
# Service and other unique instance (krbtgt)
KRB5_NT_SRV_INST = 2
# Service with host name as instance (telnet, rcommands)
KRB5_NT_SRV_HST = 3
# Service with host as remaining components
KRB5_NT_SRV_XHST = 4
# Unique ID
KRB5_NT_UID = 5
# PKINIT
KRB5_NT_X500_PRINCIPAL = 6
# Name in form of SMTP email name
KRB5_NT_SMTP_NAME = 7
# Windows 2000 UPN
KRB5_NT_ENTERPRISE_PRINCIPAL = 10
# Well-known (special) principal
KRB5_NT_WELLKNOWN = 11
# Domain based service with host name as instance (RFC5179)
KRB5_NT_SRV_HST_DOMAIN = 12
# Windows 2000 UPN and SID
KRB5_NT_MS_PRINCIPAL = -128
# NT 4 style name
KRB5_NT_MS_PRINCIPAL_AND_ID = -129
# NT 4 style name and SID
KRB5_NT_ENT_PRINCIPAL_AND_ID = -130
# NTLM name, realm is domain
KRB5_NT_NTLM = -1200
# x509 general name (base64 encoded)
KRB5_NT_X509_GENERAL_NAME = -1201
# name is actually a uuid pointing to ccache, use client name in cache
KRB5_NT_CACHE_UUID = -1203
class EncryptionType(IntEnum):
"""Enumeration for all possible encryption types."""
KRB5_ENCTYPE_NULL = 0
KRB5_ENCTYPE_DES_CBC_CRC = 1
KRB5_ENCTYPE_DES_CBC_MD4 = 2
KRB5_ENCTYPE_DES_CBC_MD5 = 3
KRB5_ENCTYPE_DES_CBC_RAW = 4
KRB5_ENCTYPE_DES3_CBC_SHA = 5
KRB5_ENCTYPE_DES3_CBC_RAW = 6
KRB5_ENCTYPE_OLD_DES3_CBC_SHA1 = 7
KRB5_ENCTYPE_DES_HMAC_SHA1 = 8
KRB5_ENCTYPE_DSA_SHA1_CMS = 9
KRB5_ENCTYPE_MD5_RSA_CMS = 10
KRB5_ENCTYPE_SHA1_RSA_CMS = 11
KRB5_ENCTYPE_RC2_CBC_ENV = 12
KRB5_ENCTYPE_RSA_ENV = 13
KRB5_ENCTYPE_RSA_ES_OAEP_ENV = 14
KRB5_ENCTYPE_DES3_CBC_ENV = 15
KRB5_ENCTYPE_DES3_CBC_SHA1 = 16
KRB5_ENCTYPE_AES128_CTS_HMAC_SHA1_96 = 17
KRB5_ENCTYPE_AES256_CTS_HMAC_SHA1_96 = 18
KRB5_ENCTYPE_AES128_CTS_HMAC_SHA256_128 = 19
KRB5_ENCTYPE_AES256_CTS_HMAC_SHA384_192 = 20
KRB5_ENCTYPE_ARCFOUR_HMAC = 23
KRB5_ENCTYPE_ARCFOUR_HMAC_EXP = 24
KRB5_ENCTYPE_CAMELLIA128_CTS_CMAC = 25
KRB5_ENCTYPE_CAMELLIA256_CTS_CMAC = 26
KRB5_ENCTYPE_UNKNOWN = 511
# ctypes converts c_char_p and then throws away the pointer. This child class
# prevents that behaviour.
class c_char_p_n(ctypes.c_char_p):
"""Opaque class for a character pointer."""
class _krb5_context(ctypes.Structure):
"""Opaque structure for a Kerberos context."""
krb5_context = ctypes.POINTER(_krb5_context)
class _krb5_kt(ctypes.Structure):
"""Opaque structure for a Kerberos keytab."""
krb5_keytab = ctypes.POINTER(_krb5_kt)
class krb5_principal_data(ctypes.Structure):
"""Opaque structure for a Kerberos principal data."""
krb5_principal = ctypes.POINTER(krb5_principal_data)
krb5_const_principal = ctypes.POINTER(krb5_principal_data)
class _krb5_get_init_creds_opt(ctypes.Structure):
"""Structure for Kerberos credential options."""
_fields_ = [
('flags', krb5_int32),
('tkt_life', krb5_deltat),
('renew_life', krb5_deltat),
('forwardable', ctypes.c_int),
('proxiable', ctypes.c_int),
('etype_list', ctypes.POINTER(krb5_enctype)),
('etype_list_length', ctypes.c_int),
('address_list', ctypes.POINTER(ctypes.c_void_p)),
('preauth_list', ctypes.POINTER(krb5_int32)),
('preauth_list_length', ctypes.c_int),
('salt', ctypes.c_void_p),
]
krb5_get_init_creds_opt = _krb5_get_init_creds_opt
krb5_get_init_creds_opt_p = ctypes.POINTER(krb5_get_init_creds_opt)
class _krb5_creds(ctypes.Structure):
"""An opaque structure representing _krb5_creds.
Since different Kerberos implementations have different structures,
generate a "large enough" struct that can be filled by the Kerberos
library.
"""
_fields_ = [
('data', ctypes.c_byte * 256),
]
krb5_creds = _krb5_creds
class _krb5_ccache(ctypes.Structure):
"""Opaque structure for a Kerberos credential cache."""
krb5_ccache = ctypes.POINTER(_krb5_ccache)
cepces-0.3.7/cepces/log.py 0000664 0000000 0000000 00000002352 14342136262 0015365 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""This module contains logging configuration."""
from pathlib import Path
import logging.config
from cepces import __title__
# Load logging configuration settings properly.
LOGGING_CONFIG_FILES = [
'{}/logging.conf'.format(__title__),
'/etc/{}/logging.conf'.format(__title__),
'/usr/local/etc/{}/logging.conf'.format(__title__),
]
def init_logging():
"""Initialize logging by reading all (possible) configuration files."""
for path in [Path(x) for x in LOGGING_CONFIG_FILES]:
if path.is_file():
logging.config.fileConfig(path.__str__())
cepces-0.3.7/cepces/soap/ 0000775 0000000 0000000 00000000000 14342136262 0015172 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/soap/__init__.py 0000664 0000000 0000000 00000001763 14342136262 0017312 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Package for very rudimentary SOAP handling."""
from xml.etree.ElementTree import QName
NS_SOAP = 'http://www.w3.org/2003/05/soap-envelope'
NS_ADDRESSING = 'http://www.w3.org/2005/08/addressing'
# ACTION_FAULT = 'http://www.w3.org/2005/08/addressing/fault'
QNAME_FAULT = QName('http://www.w3.org/2003/05/soap-envelope', 'Fault')
cepces-0.3.7/cepces/soap/auth.py 0000664 0000000 0000000 00000012525 14342136262 0016512 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# This module contains SOAP related classes, implementing a loose subset of the
# specification, just enough to be able to communicate a service.
#
"""This module contains SOAP related authentication."""
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import gssapi
from requests_gssapi import HTTPSPNEGOAuth
from cepces import Base
from cepces.krb5 import types as ktypes
from cepces.krb5.core import Context, Keytab, Principal
from cepces.krb5.core import CredentialOptions, Credentials, CredentialCache
class Authentication(Base, metaclass=ABCMeta):
"""Base class for handling authentication of SOAP endpoints."""
@abstractproperty
def transport(self):
"""Property containing authentication mechanism for the transport layer
(i.e. requests)."""
@abstractproperty
def clientcertificate(self):
"""Property containing TLS client certificate Ãnformation for the transport layer
(i.e. requests)."""
@abstractmethod
def post_process(self, envelope):
"""Method for securing (post processing) a SOAP envelope."""
class AnonymousAuthentication(Authentication):
"""A simple pass-through authentication method."""
@property
def transport(self):
"""Property containing authentication mechanism for the transport layer
(i.e. requests)."""
return None
def post_process(self, envelope):
# Nothing to be done here.
return envelope
class TransportKerberosAuthentication(Authentication):
"""Kerberos authentication on the transport level."""
def __init__(self, principal_name=None, init_ccache=True, keytab=None,
enctypes=None, delegate=True):
super().__init__()
self._config = {}
self._config['name'] = principal_name
self._config['init_ccache'] = init_ccache
self._config['keytab'] = keytab
self._config['enctypes'] = enctypes
self._config['delegate'] = delegate
# Only initialize a credential cache if requested. Otherwise, rely on
# a credential cache already being available.
if self._config['init_ccache']:
self._init_ccache()
self._init_transport()
def _init_ccache(self):
start_time = 0
context = Context()
keytab = Keytab(context, keytab=self._config['keytab'])
principal = Principal(
context,
name=self._config['name'],
service_type=ktypes.PrincipalType.KRB5_NT_SRV_HST,
)
credential_options = CredentialOptions(context)
credential_options.forwardable = True
credential_options.encryption_types = self._config['enctypes']
tkt_service = '{service}/{host}@{realm}'.format(
service=ktypes.KRB5_TGS_NAME,
host=principal.realm,
realm=principal.realm,
)
credentials = Credentials(
context,
principal,
keytab,
start_time,
tkt_service,
credential_options,
)
ccache_name = "MEMORY:cepces"
self._ccache = CredentialCache(
context,
ccache_name,
principal,
credentials,
)
os.environ["KRB5CCNAME"] = ccache_name
def _init_transport(self):
name = gssapi.Name(self._config['name'], gssapi.NameType.user)
creds = gssapi.Credentials(name=name, usage="initiate")
self._transport = HTTPSPNEGOAuth(creds=creds, delegate=self._config['delegate'])
@property
def transport(self):
return self._transport
@property
def clientcertificate(self):
return None
def post_process(self, envelope):
# Nothing to be done here.
return envelope
class MessageUsernamePasswordAuthentication(Authentication):
"""Message authentication using a username and a password."""
def __init__(self, username, password):
super().__init__()
self._username = username
self._password = password
@property
def transport(self):
return None
@property
def clientcertificate(self):
return None
def post_process(self, envelope):
raise NotImplementedError()
class TransportCertificateAuthentication(Authentication):
"""Transport authentication using a client certificate."""
def __init__(self, certfile, keyfile):
super().__init__()
self._certfile = certfile
self._keyfile = keyfile
@property
def transport(self):
return None
@property
def clientcertificate(self):
return ( self._certfile, self._keyfile )
def post_process(self, envelope):
# Nothing to be done here.
return envelope
cepces-0.3.7/cepces/soap/service.py 0000664 0000000 0000000 00000007752 14342136262 0017217 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# This module contains SOAP related classes, implementing a loose subset of the
# specification, just enough to be able to communicate a service.
#
"""This module contains SOAP service related logic."""
from xml.etree import ElementTree
import requests
from cepces import Base
from cepces.soap import QNAME_FAULT
from cepces.soap.types import Envelope, Fault
class SOAPFault(Exception):
"""Runtime error representing a SOAP fault."""
def __init__(self, fault):
self._code = fault.code.value
self._reason = fault.reason.text
if fault.code.subcode:
self._subcode = fault.code.subcode.value
else:
self._subcode = None
msg = "{} (Code: {}; Subcode: {})".format(
self._reason,
self._code,
self._subcode,
)
super().__init__(msg)
class Service(Base):
"""Base class for a SOAP service endpoint."""
def __init__(self, endpoint, auth=None, capath=True):
super().__init__()
self._logger.debug(
"Initializing service (endpoint: %s, auth: %s)",
endpoint,
auth,
)
self._endpoint = endpoint
self._auth = auth
self._capath = capath
def send(self, message):
"""Send a message to the remote SOAP service."""
headers = {'Content-Type': 'application/soap+xml; charset=utf-8'}
data = ElementTree.tostring(message.element)
self._logger.debug("Sending message:")
self._logger.debug(" -endpoint: %s", self._endpoint)
self._logger.debug(" -headers: %s", headers)
self._logger.debug(" -verify: %s", self._capath)
self._logger.debug(" -auth: %s", self._auth)
self._logger.debug(" -data: %s", data)
# Post process the envelope.
if self._auth:
message = self._auth.post_process(message)
data = ElementTree.tostring(message.element)
self._logger.debug(" -data after post-processing: %s", data)
# Post the envelope and raise an error if necessary.
req = requests.post(url=self._endpoint,
data=data,
headers=headers,
verify=self._capath,
cert=self._auth.clientcertificate,
auth=self._auth.transport)
# If we get an internal server error (code 500), there's a chance that
# we get a SOAP Envelope back containing a SOAP Fault.
# if not r.status_code == requests.codes.internal_server_error:
if not req.status_code == 500:
req.raise_for_status()
# Convert the response.
element = ElementTree.fromstring(req.text)
envelope = Envelope(element)
self._logger.debug(
"Received message: %s",
ElementTree.tostring(envelope.element),
)
# Throw a SOAP fault if one was received. Otherwise, raise a generic
# exception from requests.
# if r.status_code == requests.codes.internal_server_error and \
# envelope.body.payload.tag == QNAME_FAULT:
if req.status_code == 500 and envelope.body.payload.tag == QNAME_FAULT:
fault = Fault(envelope.body.payload)
raise SOAPFault(fault)
else:
req.raise_for_status()
return envelope
cepces-0.3.7/cepces/soap/types.py 0000664 0000000 0000000 00000011615 14342136262 0016714 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# This module contains SOAP related classes, implementing a loose subset of the
# specification, just enough to be able to communicate a service.
#
# pylint: disable=invalid-name
"""This module contains common SOAP types."""
from xml.etree.ElementTree import Element, QName
from cepces.soap import NS_ADDRESSING, NS_SOAP
from cepces.xml import NS_XSI
from cepces.xml.binding import XMLElement, XMLNode, XMLValue
from cepces.xml.converter import StringConverter
class FaultSubcode(XMLNode):
"""SOAP Fault Subcode."""
value = XMLValue('Value',
converter=StringConverter,
namespace=NS_SOAP)
@staticmethod
def create():
element = Element(QName(NS_SOAP, 'Subcode'))
value = Element(QName(NS_SOAP, 'Value'))
element.append(value)
return element
class FaultCode(XMLNode):
"""SOAP Fault Code."""
value = XMLValue('Value',
converter=StringConverter,
namespace=NS_SOAP)
subcode = XMLElement('Subcode',
binder=FaultSubcode,
namespace=NS_SOAP)
@staticmethod
def create():
element = Element(QName(NS_SOAP, 'Code'))
value = Element(QName(NS_SOAP, 'Value'))
element.append(value)
element.append(FaultSubcode.create())
return element
class FaultReason(XMLNode):
"""SOAP Fault Reason."""
text = XMLValue('Text',
converter=StringConverter,
namespace=NS_SOAP)
@staticmethod
def create():
element = Element(QName(NS_SOAP, 'Reason'))
value = Element(QName(NS_SOAP, 'Text'))
element.append(value)
return element
class Fault(XMLNode):
"""SOAP Fault."""
code = XMLElement('Code',
binder=FaultCode,
namespace=NS_SOAP)
reason = XMLElement('Reason',
binder=FaultReason,
namespace=NS_SOAP)
@staticmethod
def create():
element = Element(QName(NS_SOAP, 'Fault'))
element.append(FaultCode.create())
element.append(FaultReason.create())
return element
class Header(XMLNode):
"""SOAP Header."""
action = XMLValue('Action',
converter=StringConverter,
namespace=NS_ADDRESSING,
nillable=True)
message_id = XMLValue('MessageID',
converter=StringConverter,
namespace=NS_ADDRESSING,
nillable=True)
to = XMLValue('To',
converter=StringConverter,
namespace=NS_ADDRESSING,
nillable=True)
relates_to = XMLValue('RelatesTo',
converter=StringConverter,
namespace=NS_ADDRESSING,
nillable=True)
@staticmethod
def create():
header = Element(QName(NS_SOAP, 'Header'))
action = Element(QName(NS_ADDRESSING, 'Action'))
action.attrib[QName(NS_SOAP, 'mustUnderstand')] = '1'
action.attrib[QName(NS_XSI, 'nil')] = 'true'
header.append(action)
message_id = Element(QName(NS_ADDRESSING, 'MessageID'))
message_id.attrib[QName(NS_XSI, 'nil')] = 'true'
header.append(message_id)
to = Element(QName(NS_ADDRESSING, 'To'))
to.attrib[QName(NS_SOAP, 'mustUnderstand')] = '1'
to.attrib[QName(NS_XSI, 'nil')] = 'true'
header.append(to)
return header
class Body(XMLNode):
"""SOAP Body."""
payload = XMLElement('*',
binder=None,
required=False)
@staticmethod
def create():
body = Element(QName(NS_SOAP, 'Body'))
return body
class Envelope(XMLNode):
"""SOAP Envelope."""
header = XMLElement('Header',
binder=Header,
namespace=NS_SOAP)
body = XMLElement('Body',
binder=Body,
namespace=NS_SOAP)
@staticmethod
def create():
envelope = Element(QName(NS_SOAP, 'Envelope'))
envelope.append(Header.create())
envelope.append(Body.create())
return envelope
cepces-0.3.7/cepces/wstep/ 0000775 0000000 0000000 00000000000 14342136262 0015372 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/wstep/__init__.py 0000664 0000000 0000000 00000003010 14342136262 0017475 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""This package contains WSTEP related logic."""
NS_WST = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512'
NS_WST_SECEXT = 'http://docs.oasis-open.org/wss/2004/01/' \
'oasis-200401-wss-wssecurity-secext-1.0.xsd'
NS_ENROLLMENT = 'http://schemas.microsoft.com/windows/pki/2009/01/enrollment'
TOKEN_TYPE = 'http://docs.oasis-open.org/wss/2004/01/' \
'oasis-200401-wss-x509-token-profile-1.0#X509v3'
ISSUE_REQUEST_TYPE = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue'
QUERY_REQUEST_TYPE = 'http://schemas.microsoft.com/windows/pki/2009/01/' \
'enrollment/QueryTokenStatus'
VALUE_TYPE = 'http://schemas.microsoft.com/windows/pki/2009/01/' \
'enrollment#PKCS10'
ENCODING_TYPE = 'http://docs.oasis-open.org/wss/2004/01/' \
'oasis-200401-wss-wssecurity-secext-1.0.xsd#base64binary'
cepces-0.3.7/cepces/wstep/service.py 0000664 0000000 0000000 00000013500 14342136262 0017403 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=protected-access
"""Module for WSTEP SOAP service logic."""
from xml.etree import ElementTree
import uuid
import re
from cepces import Base
from cepces.soap.service import Service as SOAPService
from cepces.soap.types import Envelope
from cepces.wstep import QUERY_REQUEST_TYPE, NS_ENROLLMENT
from cepces.wstep.types import SecurityTokenRequest
from cepces.wstep.types import SecurityTokenResponseCollection
ACTION = 'http://schemas.microsoft.com/windows/pki/2009/01/enrollment/' \
'RST/wstep'
class Service(SOAPService):
"""WSTEP Service proxy."""
class Response(Base):
"""Inner class for a service response."""
def __init__(self, request_id, token=None, reference=None):
super().__init__()
self._request_id = request_id
self._token = token
self._reference = reference
@property
def request_id(self):
"""Returns the request ID."""
return self._request_id
@property
def token(self):
"""Returns the response token."""
return self._token
@token.setter
def token(self, value):
"""Sets the response token."""
self._token = value
@property
def reference(self):
"""Returns the response reference."""
return self._reference
def _get_envelope(self, payload):
envelope = Envelope()
envelope.header.action = ACTION
envelope.header.message_id = "urn:uuid:{0:s}".format(str(uuid.uuid4()))
envelope.header.to = self._endpoint
envelope.body.payload = payload._element
self._logger.debug(
"Preparing message %s to %s with payload: %s",
envelope.header.message_id,
envelope.header.to,
ElementTree.tostring(payload._element),
)
return envelope
def request(self, csr):
"""Request a certificate using a certificate signing request."""
match = re.search(r'^\-{5}BEGIN (?:NEW )?CERTIFICATE REQUEST\-{5}\n'
r'(.*)\n'
r'\-{5}END (?:NEW )?CERTIFICATE REQUEST\-{5}\s*$',
csr,
flags=re.DOTALL)
if not match:
raise LookupError("Invalid CSR.")
token = SecurityTokenRequest()
token.token = match.group(1)
envelope = self._get_envelope(token)
response = self.send(envelope)
result = SecurityTokenResponseCollection(response.body.payload)
# All responses has to be processed before hand, since they need to be
# curated of any (possible) extra Microsoft-added line endings.
results = []
for response in result.responses:
self._logger.debug('Got response: %s', str(response))
token = response.requested_token
if token.text:
token.text = token.text.replace('
', '')
results.append(
Service.Response(
request_id=response.request_id,
token=token.text,
),
)
else:
results.append(
Service.Response(
request_id=response.request_id,
reference=response.requested_token.token_reference.reference.uri,
),
)
self._logger.debug('Returning curated responses: %s', results)
return results
def poll(self, request_id):
"""Poll the service endpoint for the status of a previous request."""
self._logger.debug('Sending info for previous request %s', request_id)
token = SecurityTokenRequest()
token.request_type = QUERY_REQUEST_TYPE
# Improve this handling since we're manually inserting an element here.
qname = ElementTree.QName(NS_ENROLLMENT, 'RequestID')
element = ElementTree.Element(qname)
token._element.append(element)
token.request_id = request_id
envelope = self._get_envelope(token)
response = self.send(envelope)
result = SecurityTokenResponseCollection(response.body.payload)
# All responses has to be processed before hand, since they need to be
# curated of any (possible) extra Microsoft-added line endings.
results = []
for response in result.responses:
self._logger.debug('Got response: %s', response)
token = response.requested_token
if token.text:
token.text = token.text.replace('
', '')
results.append(
Service.Response(
request_id=response.request_id,
token=token.text,
),
)
else:
results.append(
Service.Response(
request_id=response.request_id,
reference=response.requested_token.token_reference.reference.uri,
),
)
self._logger.debug('Returning curated responses: %s', results)
return results
cepces-0.3.7/cepces/wstep/types.py 0000664 0000000 0000000 00000011644 14342136262 0017116 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""WSTEP Types."""
from xml.etree.ElementTree import Element, QName
from cepces.soap import NS_ADDRESSING
from cepces.wstep import NS_WST, NS_WST_SECEXT, NS_ENROLLMENT
from cepces.wstep import TOKEN_TYPE, VALUE_TYPE, ENCODING_TYPE
from cepces.wstep import ISSUE_REQUEST_TYPE
from cepces.xml.binding import XMLAttribute
from cepces.xml.binding import XMLElement, XMLElementList
from cepces.xml.binding import XMLNode, XMLValue
from cepces.xml.converter import CertificateConverter
from cepces.xml.converter import StringConverter, UnsignedIntegerConverter
class SecurityTokenRequest(XMLNode):
"""Security Token Request"""
#
token_type = XMLValue('TokenType',
converter=StringConverter,
namespace=NS_WST,
required=False)
request_type = XMLValue('RequestType',
converter=StringConverter,
namespace=NS_WST)
request_id = XMLValue('RequestID',
converter=UnsignedIntegerConverter,
namespace=NS_ENROLLMENT)
token = XMLValue('BinarySecurityToken',
converter=StringConverter,
namespace=NS_WST_SECEXT)
@staticmethod
def create():
element = Element(QName(NS_WST, 'RequestSecurityToken'))
token_type = Element(QName(NS_WST, 'TokenType'))
token_type.text = TOKEN_TYPE
element.append(token_type)
request_type = Element(QName(NS_WST, 'RequestType'))
request_type.text = ISSUE_REQUEST_TYPE
element.append(request_type)
token = Element(QName(NS_WST_SECEXT, 'BinarySecurityToken'))
token.set(QName(NS_WST_SECEXT, 'ValueType'), VALUE_TYPE)
token.set(QName(NS_WST_SECEXT, 'EncodingType'), ENCODING_TYPE)
token.set(QName(NS_ADDRESSING, 'Id'), '')
element.append(token)
return element
class Reference(XMLNode):
"""Reference"""
uri = XMLAttribute('URI',
converter=StringConverter)
@staticmethod
def create():
return None
class SecurityTokenReference(XMLNode):
"""Security Token Reference"""
reference = XMLElement('Reference',
binder=Reference,
namespace=NS_WST_SECEXT,
required=False)
@staticmethod
def create():
return None
class RequestedToken(XMLNode):
"""Requested Token"""
text = XMLValue('BinarySecurityToken',
converter=CertificateConverter,
namespace=NS_WST_SECEXT)
token_reference = XMLElement('SecurityTokenReference',
binder=SecurityTokenReference,
namespace=NS_WST_SECEXT,
required=False)
@staticmethod
def create():
return None
class SecurityTokenResponse(XMLNode):
"""Security Token Response"""
#
token_type = XMLValue('TokenType',
converter=StringConverter,
namespace=NS_WST,
required=False)
disposition_message = XMLValue('DispositionMessage',
converter=StringConverter,
namespace=NS_ENROLLMENT)
token = XMLValue('BinarySecurityToken',
converter=StringConverter,
namespace=NS_WST_SECEXT)
requested_token = XMLElement('RequestedSecurityToken',
binder=RequestedToken,
namespace=NS_WST)
request_id = XMLValue('RequestID',
converter=UnsignedIntegerConverter,
namespace=NS_ENROLLMENT)
@staticmethod
def create():
return None
class SecurityTokenResponseCollection(XMLNode):
"""Security Token Response Collection"""
responses = XMLElementList('.',
child_name='RequestSecurityTokenResponse',
binder=SecurityTokenResponse,
child_namespace=NS_WST)
@staticmethod
def create():
return None
cepces-0.3.7/cepces/xcep/ 0000775 0000000 0000000 00000000000 14342136262 0015167 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/xcep/__init__.py 0000664 0000000 0000000 00000001363 14342136262 0017303 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
NS_CEP = 'http://schemas.microsoft.com/windows/pki/2009/01/enrollmentpolicy'
cepces-0.3.7/cepces/xcep/converter.py 0000664 0000000 0000000 00000005072 14342136262 0017554 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Module containing XCEP related type converters."""
from cepces.xml.converter import IntegerConverter
class ClientAuthenticationConverter(IntegerConverter):
"""Converts to and from allowed authentication methods (int <-> str)."""
MAP = [
(1, 'Anonymous'),
(2, 'Kerberos'),
(4, 'UsernamePassword'),
(8, 'Certificate')
]
@staticmethod
def from_string(value):
"""Converts the stringified integer key to its string value
:param value: the stringified integer to convert, or None
:raise TypeError: if the input is not a string
:raise ValueError: if the input cannot be resolved
:return: the input as a string value, or None if value is None
"""
values = [v[0] for v in ClientAuthenticationConverter.MAP]
if value is None:
return value
elif not isinstance(value, str):
raise TypeError('Unsupported type.')
elif int(value) not in values:
raise ValueError('Unsupported value.')
else:
index = values.index(int(value))
return ClientAuthenticationConverter.MAP[index][1]
@staticmethod
def to_string(value):
"""Converts the string value its stringified integer
:param value: the string to convert, or None
:raise TypeError: if the input is not a string
:raise ValueError: if the input cannot be resolved
:return: the input as a string value, or None if value is None
"""
values = [v[1] for v in ClientAuthenticationConverter.MAP]
if value is None:
return None
elif not isinstance(value, str):
raise TypeError('Unsupported type.')
elif value not in values:
raise ValueError('Unsupported value.')
else:
index = values.index(value)
return str(ClientAuthenticationConverter.MAP[index][0])
cepces-0.3.7/cepces/xcep/service.py 0000664 0000000 0000000 00000004100 14342136262 0017174 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=protected-access
"""Module for XCEP SOAP service logic."""
from xml.etree import ElementTree
import uuid
from cepces.soap.service import Service as SOAPService
from cepces.soap.types import Envelope
from cepces.xcep.types import GetPolicies as GetPoliciesMessage
from cepces.xcep.types import GetPoliciesResponse as GetPoliciesResponseMessage
ACTION = 'http://schemas.microsoft.com/windows/pki/2009/01/enrollmentpolicy/' \
'IPolicy/GetPolicies'
class Service(SOAPService):
"""XCEP Service proxy."""
def _get_envelope(self, payload):
envelope = Envelope()
envelope.header.action = ACTION
envelope.header.message_id = 'urn:uuid:{0:s}'.format(str(uuid.uuid4()))
envelope.header.to = self._endpoint
envelope.body.payload = payload._element
self._logger.debug(
"Preparing message %s to %s with payload: %s",
envelope.header.message_id,
envelope.header.to,
ElementTree.tostring(payload._element),
)
return envelope
def get_policies(self):
"""Get a list of available policies."""
envelope = self._get_envelope(GetPoliciesMessage())
response = self.send(envelope)
self._logger.debug(
"Received message: %s",
ElementTree.tostring(response.body.payload),
)
return GetPoliciesResponseMessage(response.body.payload)
cepces-0.3.7/cepces/xcep/types.py 0000664 0000000 0000000 00000035041 14342136262 0016710 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=invalid-name
"""XCEP Types."""
from xml.etree.ElementTree import Element, QName
from cepces.xml.binding import ATTR_NIL
from cepces.xml.binding import XMLElement, XMLElementList
from cepces.xml.binding import XMLNode
from cepces.xml.binding import XMLValue, XMLValueList
from cepces.xml.converter import BooleanConverter, CertificateConverter
from cepces.xml.converter import DateTimeConverter, IntegerConverter
from cepces.xml.converter import SignedIntegerConverter, StringConverter
from cepces.xml.converter import UnsignedIntegerConverter
from cepces.xcep import NS_CEP
from cepces.xcep.converter import ClientAuthenticationConverter
class Client(XMLNode):
"""The `Client` node contains information about the client's current state
and preferences."""
last_update = XMLValue('lastUpdate',
converter=DateTimeConverter,
namespace=NS_CEP,
nillable=True)
# This should probably use a LanguageConverter for proper validation.
preferred_language = XMLValue('preferredLanguage',
converter=StringConverter,
namespace=NS_CEP,
nillable=True)
@staticmethod
def create():
client = Element(QName(NS_CEP, 'client'))
last_update = Element(QName(NS_CEP, 'lastUpdate'))
last_update.attrib[ATTR_NIL] = 'true'
client.append(last_update)
preferred_language = Element(QName(NS_CEP, 'preferredLanguage'))
preferred_language.attrib[ATTR_NIL] = 'true'
client.append(preferred_language)
return client
class RequestFilter(XMLNode):
"""The `RequestFilter` node is provided in a request and used by the
server to filter the `GetPoliciesResponse` to contain only
`CertificateEnrollmentPolicy` objects that satisfy the filter."""
policy_oids = XMLValueList('policyOIDs',
child_name='oid',
converter=StringConverter,
namespace=NS_CEP,
child_namespace=NS_CEP,
nillable=True)
client_version = XMLValue('clientVersion',
converter=SignedIntegerConverter,
namespace=NS_CEP,
nillable=True)
server_version = XMLValue('serverVersion',
converter=SignedIntegerConverter,
namespace=NS_CEP,
nillable=True, required=False)
@staticmethod
def create():
element = Element(QName(NS_CEP, 'requestFilter'))
policy_oids = Element(QName(NS_CEP, 'policyOIDs'))
policy_oids.attrib[ATTR_NIL] = 'true'
element.append(policy_oids)
client_version = Element(QName(NS_CEP, 'clientVersion'))
client_version.attrib[ATTR_NIL] = 'true'
element.append(client_version)
server_version = Element(QName(NS_CEP, 'serverVersion'))
server_version.attrib[ATTR_NIL] = 'true'
element.append(server_version)
return element
class GetPolicies(XMLNode):
"""The `GetPolicies` node contains the client request."""
client = XMLElement('client',
binder=Client,
namespace=NS_CEP)
request_filter = XMLElement('requestFilter',
binder=RequestFilter,
namespace=NS_CEP,
nillable=True)
@staticmethod
def create():
element = Element(QName(NS_CEP, 'GetPolicies'))
element.append(Client.create())
element.append(RequestFilter.create())
return element
class CertificateAuthorityURI(XMLNode):
"""Certificate Authority URI"""
# The element is used to define the supported
# authentication type for the element of this CAURI object. The
# element is an unsigned integer that MUST have one
# of the following values.
#
# 1: Anonymous Authentication
# 2: Transport Kerberos Authentication
# 4: Message Username and Password Authentication
# 8: Message X.509 Certificate Authentication
#
#
id = XMLValue('clientAuthentication',
converter=ClientAuthenticationConverter,
namespace=NS_CEP)
# The element is used to store a Uniform Resource Identifier (URI)
# entry for a CA (section 3.1.4.1.3.2) object.
#
#
uri = XMLValue('uri',
converter=StringConverter,
namespace=NS_CEP)
# The element is an integer value that represents the priority
# value for the URI. The element value is used as a relative
# indicator against other CAURI objects. The lower the integer value, the
# higher the priority. Two CAURI objects have the same priority if the
# integer values of each element are the same. A CAURI object
# is considered to have a lower priority if the element integer
# value is more than the integer value of the element of an
# alternate CAURI object.
#
#
priority = XMLValue('priority',
converter=UnsignedIntegerConverter,
namespace=NS_CEP,
nillable=True)
# The element is an xs:boolean value that identifies whether
# the corresponding CAURI object can accept all types of requests, or only
# renewal requests. If the value is true, the server that is addressed by
# the CAURI object only accepts renewal requests. If the value is false,
# other request types are supported.
renewal_only = XMLValue('renewalOnly',
converter=BooleanConverter,
namespace=NS_CEP,
nillable=True)
@staticmethod
def create():
return None
class CertificateAuthority(XMLNode):
"""Certificate Authority"""
# An instance of a CAURICollection object as defined in section
# 3.1.4.1.3.6, which contains the list of URI values for a certificate
# authority.
#
#
#
uris = XMLElementList('uris',
child_name='cAURI',
binder=CertificateAuthorityURI,
namespace=NS_CEP,
child_namespace=NS_CEP)
# The element contains the xs:base64Binary representation of
# the Abstract Syntax Notation One (ASN.1) encoded certificate authority
# signing certificate. The value for the element MUST never
# be an empty string.
certificate = XMLValue('certificate',
converter=CertificateConverter,
namespace=NS_CEP)
# The element contains an xs:boolean value that
# indicates whether or not the requestor has permission to submit
# enrollment requests to the server represented by the corresponding CA
# object. It MUST be true or false. If the element is
# true, the requestor has enroll permissions and can submit requests. If
# the element is false, the requestor does not have
# permission.
enroll_permission = XMLValue('enrollPermission',
converter=BooleanConverter,
namespace=NS_CEP)
# Each instance of a CA object in a GetPoliciesResponse message MUST have a
# unique . The is an unsigned integer value
# used as an index for referencing the corresponding CA object within the
# scope of a GetPoliciesResponse message.
#
#
id = XMLValue('cAReferenceID',
converter=SignedIntegerConverter,
namespace=NS_CEP)
@staticmethod
def create():
return None
class Attributes(XMLNode):
"""Attributes"""
# A string value of the common name (CN) of a CertificateEnrollmentPolicy
# object. The element MUST be unique in the scope of a
# GetPoliciesResponse (section 3.1.4.1.1.2) message.
#
#
#
common_name = XMLValue('commonName',
converter=StringConverter,
namespace=NS_CEP)
@staticmethod
def create():
return None
class CertificateEnrollmentPolicy(XMLNode):
"""Certificate Enrollment Policy"""
# A element is used to represent an instance of a
# CAReferenceCollection object as defined in section 3.1.4.1.3.4, which is
# used to reference the issuers for this CertificateEnrollmentPolicy
# object.
#
#
cas = XMLValueList('cAs',
child_name='cAReference',
converter=IntegerConverter,
namespace=NS_CEP,
child_namespace=NS_CEP,
nillable=True)
# attributes: A element is used to represent an instance of an
# Attributes object as defined in section 3.1.4.1.3.1.
#
#
attributes = XMLElement('attributes',
binder=Attributes,
namespace=NS_CEP,
nillable=True)
@staticmethod
def create():
return None
class Response(XMLNode):
"""Response"""
# A unique identifier for the certificate enrollment policy. Two or more
# servers can respond with the same element in a
# GetPoliciesResponse message if, and only if, they are configured to
# return the same Response object to the same requestor. The
# element is not intended to be a human-readable property.
#
#
id = XMLValue('policyID',
converter=StringConverter,
namespace=NS_CEP)
# A human readable friendly name for the certificate enrollment policy.
#
#
name = XMLValue('policyFriendlyName',
converter=StringConverter,
namespace=NS_CEP,
nillable=True)
# An integer representing the number of hours that the server recommends
# the client wait before submitting another GetPolicies message. If the
# element is present and not nil, the
# element value MUST be a positive nonzero integer.
#
#
next_update = XMLValue('nextUpdateHours',
converter=UnsignedIntegerConverter,
namespace=NS_CEP,
nillable=True)
# Used to indicate to the requestor whether the policies have changed since
# the requestor specified in the GetPolicies request
# message as described in section 3.1.4.1.3.9. If the value of the
# element is true, the policy has not changed since
# the value in the GetPolicies message. If the
# element is false or nil, the policy has changed
# since the requestor specified .
#
#
policies_not_changed = XMLValue('policiesNotChanged',
converter=UnsignedIntegerConverter,
namespace=NS_CEP,
nillable=True)
# A list of policies.
#
#
#
policies = XMLElementList('policies',
child_name='policy',
binder=CertificateEnrollmentPolicy,
namespace=NS_CEP,
child_namespace=NS_CEP,
nillable=True)
@staticmethod
def create():
return None
class GetPoliciesResponse(XMLNode):
"""Get Policies Response"""
# The element is an instance of the Response object as
# defined in section 3.1.4.1.3.23 that contains the certificate enrollment
# policies.
#
#
response = XMLElement('response',
binder=Response,
namespace=NS_CEP,
nillable=True)
# The element is an instance of a CACollection object as defined
# in section 3.1.4.1.3.3 that contains the issuers for the certificate
# enrollment policies.
#
#
#
cas = XMLElementList('cAs',
child_name='cA',
binder=CertificateAuthority,
namespace=NS_CEP,
child_namespace=NS_CEP,
nillable=True)
@staticmethod
def create():
return None
cepces-0.3.7/cepces/xml/ 0000775 0000000 0000000 00000000000 14342136262 0015030 5 ustar 00root root 0000000 0000000 cepces-0.3.7/cepces/xml/__init__.py 0000664 0000000 0000000 00000001510 14342136262 0017136 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Package containing XML utilities."""
from cepces.xml import util
NS_XSI = 'http://www.w3.org/2001/XMLSchema-instance'
ATTR_NIL = util.to_clark('nil', NS_XSI)
cepces-0.3.7/cepces/xml/binding.py 0000664 0000000 0000000 00000036721 14342136262 0017025 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=protected-access,too-few-public-methods,too-many-arguments
# pylint: disable=too-many-ancestors
"""Module containing XML bindings."""
from collections.abc import MutableSequence
from xml.etree import ElementTree
import inspect
from abc import ABCMeta, abstractmethod
from cepces.xml import ATTR_NIL, NS_XSI, util
from cepces.xml.converter import StringConverter
class XMLDescriptor(metaclass=ABCMeta):
"""Abstract base class for all XML descriptors.
This class maintains a static index used for ordering all declared XML
descriptors in an subclass. It is automatically incremented as needed.
"""
_index = 0
def __init__(self, name, namespace=None):
"""Initializes a new `XMLDescriptor`.
When initializing a new XMLDescriptor object, the name (and possibly
namespace) is used to construct an internal Qualified Name using
Clark's notation.
:param name: The name of the element to bind with.
:param namespace: An optional namespace.
"""
# Assign and increase the descriptor index.
self._index = XMLDescriptor._index
XMLDescriptor._index += 1
self._name = name
self._namespace = namespace
if namespace:
# Convert to Clark's notation.
self._qname = util.to_clark(name, namespace)
else:
self._qname = name
@abstractmethod
def __get__(self, instance, _owner=None):
pass
@abstractmethod
def __set__(self, instance, value):
pass
@abstractmethod
def __delete__(self, instance):
pass
class ListingMeta(type):
"""A meta class for ordered XML Descriptor attributes.
This meta class adds an extra property, `__listing__`, which includes all
`XMLDescriptor` properties in their declared order.
"""
def __new__(cls, name, bases, class_dict):
def is_member(member):
"""Checks if a member is an XMLDescriptor."""
# Only return members that are instances of XMLDescriptor.
result = isinstance(member, XMLDescriptor)
return result
# Create a new class.
klass = type.__new__(cls, name, bases, class_dict)
members = inspect.getmembers(klass, is_member)
klass.__listing__ = sorted(members, key=lambda i: i[1]._index)
return klass
class XMLAttribute(XMLDescriptor):
"""This class binds to an attribute of an element."""
def __init__(self, name, namespace=None, converter=None):
"""Initializes a new `XMLAttribute`.
:param name: The name of the element to bind with.
:param namespace: An optional namespace.
:param converter: An optional data type converter.
"""
super().__init__(name, namespace)
# Use a StringConverter if None is given.
if converter is None:
converter = StringConverter
self._converter = converter
def __get__(self, instance, _owner=None):
attribute = instance._element.get(self._qname)
return self._converter.from_string(attribute)
def __set__(self, instance, value):
instance._element.set(self._qname, self._converter.to_string(value))
def __delete__(self, instance):
del instance._element.attrib[self._qname]
class XMLNode(metaclass=ListingMeta):
"""Base class for all binding nodes."""
def __init__(self, element=None):
"""Initializes a new `XMLNode`.
If no base element is provided, the instance is instructed to create a
new element (and possibly child elements).
Args:
element (Element): The root Element on which to bind.
Raises:
TypeError: If `element` is of the wrong type.
"""
if element is None:
element = self.create()
elif not isinstance(element, ElementTree.Element):
raise TypeError('Expected {0:s}, got {1:s}'.format(
ElementTree.__name__,
element.__class__.__name__))
self._element = element
self._bindings = {}
@property
def element(self):
"""Get the backing XML element."""
return self._element
@staticmethod
@abstractmethod
def create():
"""Create a new XML element for the node."""
raise NotImplementedError()
class XMLElement(XMLDescriptor):
"""Map an element to an XMLNode instance."""
def __init__(self, name, binder=None, namespace=None,
required=True, nillable=False):
super().__init__(name, namespace)
if binder is None:
def func(value):
"""Simple pass-through function."""
return value
binder = func
self._binder = binder
self._required = required
self._nillable = nillable
def index(self, instance):
"""Returns the element index of this descriptor for a given class.
"""
if not isinstance(type(instance), ListingMeta):
raise TypeError('Expected type ListingMeta, got {0:s}'.format(
str(type(instance))))
# Get the index of the descriptor.
descriptors = [e[1] for e in instance.__listing__]
attr_index = descriptors.index(self)
# Find the first non-empty predecessor sibling element.
for index in reversed(list(range(0, attr_index))):
predecessor = descriptors[index]
if predecessor._element is not None:
attr_index = index
break
return attr_index
def __get__(self, instance, _owner=None):
if instance is None:
return self
# Get any previous binder.
if hash(self) in instance._bindings:
return instance._bindings[hash(self)]
# No previous binder found. Get the element, if it exists, and
# instantiate a new one.
element = instance._element.find(self._qname)
if element is None:
# No element exists. It must have been removed.
return None
# Create a new binder for the existing element.
binder = self._binder(element)
instance._bindings[hash(self)] = binder
return binder
def __set__(self, instance, value):
# If there is a previous value assigned, (try to) delete it first.
if hash(self) in instance._bindings:
del instance._bindings[hash(self)]
# If the value is None, set it to a new element. The binder is expected
# to understand how to create a new, empty element.
if value is None:
value = self._binder.create()
# Create a new binder based on the specified element.
binder = self._binder(value)
instance._bindings[hash(self)] = binder
# Add the element to the parent
index = self.index(instance)
instance._element.insert(index, value)
def __delete__(self, instance):
"""Deletes an element."""
if self._required:
raise AttributeError("Element is required, cannot delete.")
elif hash(self) in instance._bindings:
del instance._bindings[hash(self)]
element = instance._element.find(self._qname)
if element is not None:
instance._element.remove(element)
class XMLElementList(XMLElement):
"""XML Element List"""
class List(MutableSequence):
"""Internal list."""
def __init__(self, parent, element, binder, qname):
super().__init__()
self._list = list()
self._parent = parent
self._element = element
self._binder = binder
self._qname = qname
children = self._element.findall(qname)
for child in children:
self._list.append(self._binder(child))
def __len__(self):
return len(self._list)
def __getitem__(self, key):
return self._list[key]
def __delitem__(self, key):
item = self._list[key]
if isinstance(item, XMLNode):
item = item._element
self._element.remove(item)
del self._list[key]
if self._parent._nillable:
if not self._list:
self._element.set(ATTR_NIL, 'true')
self._element.text = None
def __setitem__(self, key, value):
# Value has to be of the same type as the binder.
if not isinstance(value, self._binder):
raise TypeError('Expected value of {0:s}'
.format(str(type(self._binder))))
# If there is a previous value assigned, remove it.
old = self._list[key]
if old is not None:
self._element.remove(old._element)
self._element.insert(key, value._element)
self._list[key] = value
# pylint: disable=arguments-differ
def insert(self, key, value):
self._element.insert(key, value._element)
self._list.insert(key, value)
# Check if nillable.
if self._parent._nillable:
if ATTR_NIL in self._element.attrib:
del self._element.attrib[ATTR_NIL]
def __str__(self):
return str(self._list)
def __init__(self, name, child_name, binder, namespace=None,
child_namespace=None, required=True, nillable=False):
super().__init__(name=name,
binder=None,
namespace=namespace,
required=required,
nillable=nillable)
self._child_binder = binder
self._child_name = child_name
self._child_namespace = child_namespace
if child_namespace:
# Convert to Clark's notation.
self._child_qname = util.to_clark(child_name, child_namespace)
else:
self._child_qname = child_name
def __get__(self, instance, _owner=None):
binder = super().__get__(instance, _owner)
if binder is self:
return binder
elif not isinstance(binder, XMLElementList.List):
binder = XMLElementList.List(parent=self,
element=binder,
binder=self._child_binder,
qname=self._child_qname)
instance._bindings[hash(self)] = binder
return binder
class XMLValue(XMLElement):
"""XML Value"""
def __init__(self, name, converter, namespace=None,
required=True, nillable=False):
super().__init__(name,
binder=None,
namespace=namespace,
required=required,
nillable=nillable)
self._converter = converter
def __get__(self, instance, _owner=None):
element = super().__get__(instance, _owner)
if element is None:
return None
elif element is self:
return self
# Check if nillable.
if self._nillable:
if hasattr(element, 'attrib') and ATTR_NIL in element.attrib:
if element.get(ATTR_NIL) == 'true':
# Since nil=true, return None regardless of any text.
return None
if hasattr(element, 'text'):
return self._converter.from_string(element.text)
return self._converter.from_string('')
def __set__(self, instance, value):
element = super().__get__(instance, None)
if element is None:
element = ElementTree.Element(self._qname)
super().__set__(instance, element)
if self._nillable:
attr = '{{{0:s}}}{1:s}'.format(NS_XSI, 'nil')
if value is None:
element.attrib[attr] = 'true'
else:
if attr in element.attrib:
del element.attrib[attr]
elif value is None:
raise ValueError('Element not nillable.')
element.text = self._converter.to_string(value)
class XMLValueList(XMLElement):
"""XML Value List"""
class List(MutableSequence):
"""Internal list"""
def __init__(self, parent, element, converter, qname):
super().__init__()
self._list = list()
self._parent = parent
self._element = element
self._converter = converter
self._qname = qname
children = self._element.findall(qname)
for child in children:
self._list.append(child)
def __len__(self):
return len(self._list)
def __getitem__(self, key):
return self._converter.from_string(self._list[key].text)
def __delitem__(self, key):
item = self._list[key]
self._element.remove(item)
del self._list[key]
if self._parent._nillable:
if not self._list:
self._element.set(ATTR_NIL, 'true')
self._element.text = None
def __setitem__(self, key, value):
self._list[key].text = self._converter.to_string(value)
# pylint: disable=arguments-differ
def insert(self, key, value):
element = ElementTree.Element(self._qname)
element.text = self._converter.to_string(value)
self._element.insert(key, element)
self._list.insert(key, element)
# Check if nillable.
if self._parent._nillable:
if ATTR_NIL in self._element.attrib:
del self._element.attrib[ATTR_NIL]
def __str__(self):
return str(self._list)
def __init__(self, name, child_name, converter, namespace=None,
child_namespace=None, required=True, nillable=False):
super().__init__(name=name,
binder=None,
namespace=namespace,
required=required,
nillable=nillable)
self._converter = converter
self._child_name = child_name
self._child_namespace = child_namespace
if child_namespace:
# Convert to Clark's notation.
self._child_qname = util.to_clark(child_name, child_namespace)
else:
self._child_qname = child_name
def __get__(self, instance, _owner=None):
binder = super().__get__(instance, _owner)
if binder is self:
return binder
elif not isinstance(binder, XMLValueList.List):
binder = XMLValueList.List(parent=self,
element=binder,
converter=self._converter,
qname=self._child_qname)
instance._bindings[hash(self)] = binder
return binder
return None
cepces-0.3.7/cepces/xml/converter.py 0000664 0000000 0000000 00000033531 14342136262 0017416 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
# pylint: disable=arguments-differ
"""This module contains converters for common XML data types."""
from datetime import datetime, timedelta, tzinfo
import re
import textwrap
class Converter():
"""A base class for any value converter.
It is responsible for converting an arbitrary input to and from a string
for use within an XML document.
"""
@staticmethod
def from_string(value, value_type=str):
"""Parse a string and convert it to a suitable type or format.
:param value: the string to parse, or None
:param value_type: the desired type
:raise TypeError: if the input is of an invalid type
:return: the input as a suitable type or format, or None if value is
None
"""
if value is None:
return None
elif not isinstance(value, value_type):
raise TypeError(
"Unsupported type (got '{}', expected '{}')".format(
type(value),
value_type,
)
)
else:
return value
@staticmethod
def to_string(value, value_type=str):
"""Convert a value to an explicit string.
:param value: the value to convert, or None
:param value_type: the desired type
:raise TypeError: if the input is of an invalid type
:return: the input as a string, or None if value is None
"""
if value is None:
return None
elif not isinstance(value, value_type):
raise TypeError(
"Unsupported type (got '{}', expected '{}')".format(
type(value),
value_type,
)
)
else:
return str(value)
# Make StringConverter as an alias to Converter, as it defaults to the string
# type.
StringConverter = Converter
class BooleanConverter():
"""Boolean Converter"""
MAP = {
'true': True,
'false': False,
'1': True,
'0': False,
}
"""Converts to and from booleans."""
@staticmethod
def from_string(value):
"""Converts the input value to a boolean
:param value: the value to convert, or None
:raise TypeError: if the input is not a boolean
:raise ValueError: if the input cannot be parsed as a boolean
:return: the input as a boolean, or None if value is None
"""
result = Converter.from_string(value)
if not result:
return result
elif result not in BooleanConverter.MAP:
raise ValueError('Unsupported value: "{}"'.format(result))
else:
return BooleanConverter.MAP[result]
@staticmethod
def to_string(value):
"""Converts a boolean to a string
:param value: the boolean to convert, or None
:raise TypeError: if the input is not a boolean
:raise ValueError: if the input cannot be parsed as a boolean
:return: the input as a string, or None if value is None
"""
if value is not None:
return Converter.to_string(value, bool).lower()
return None
class IntegerConverter():
"""Converts to and from integers."""
@staticmethod
def from_string(value):
"""Converts the input value to an integer
:param value: the value to convert, or None
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer
:return: the input as a string, or None if value is None
"""
result = Converter.from_string(value)
if not result:
return result
return int(result)
@staticmethod
def to_string(value):
"""Converts the an integer to a string
:param value: the integer to convert, or None
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer
:return: the input as a string, or None if value is None
"""
return Converter.to_string(value, int)
class RangedIntegerConverter():
"""Converts to and from integers with a range constraint."""
@staticmethod
def range_check(value, lower, upper):
"""Check that the given value is within the inclusive range.
:param value: the integer to check
:param lower: the lower (inclusive) bound
:param upper: the upper (inclusive) bound
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
"""
if value is None:
return None
elif not isinstance(value, int):
raise TypeError('Unsupported type')
elif int(value) < int(lower) or int(value) > int(upper):
raise ValueError(
'{0:d} outside allowed range ({1:d}, {2:d})'.format(
value,
lower,
upper,
)
)
return value
@staticmethod
def from_string(value, lower, upper):
"""Converts the input value to an integer within the allowed range.
:param value: the integer to check
:param lower: the lower (inclusive) bound
:param upper: the upper (inclusive) bound
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
:return: the input, if within the allowed range
"""
result = IntegerConverter.from_string(value)
return RangedIntegerConverter.range_check(result, lower, upper)
@staticmethod
def to_string(value, lower, upper):
"""Converts the an integer to a string
:param value: the integer to convert, or None
:param lower: the lower (inclusive) bound
:param upper: the upper (inclusive) bound
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
:return: the input as a string, or None if value is None
"""
result = RangedIntegerConverter.range_check(value, lower, upper)
return IntegerConverter.to_string(result)
class SignedIntegerConverter(Converter):
"""Converts to and from signed (32-bit) integers.
All values has to be within the allowed range -2,147,483,648 and
2,147,483,647.
"""
@staticmethod
def from_string(value):
"""Converts the input value to an integer, checking that it is within
the allowed range.
:param value: the value to convert, or None
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
:return: the input as a string, or None if value is None
"""
return RangedIntegerConverter.from_string(value, -2 ** 31, 2 ** 31 - 1)
@staticmethod
def to_string(value):
"""Converts the an integer to a string
:param value: the integer to convert, or None
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
:return: the input as a string, or None if value is None
"""
return RangedIntegerConverter.to_string(value, -2 ** 31, 2 ** 31 - 1)
class UnsignedIntegerConverter(Converter):
"""Converts to and from signed (32-bit) integers.
All values has to be within the allowed range 0 and 4,294,967,295.
"""
@staticmethod
def from_string(value):
"""Converts the input value to an integer, checking that it is within
the allowed range.
:param value: the value to convert, or None
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
:return: the input as a string, or None if value is None
"""
return RangedIntegerConverter.from_string(value, 0, 2 ** 32 - 1)
@staticmethod
def to_string(value):
"""Converts the an integer to a string
:param value: the integer to convert, or None
:raise TypeError: if the input is not an integer
:raise ValueError: if the input cannot be parsed as an integer, or if
the input is outside the allowed range.
:return: the input as a string, or None if value is None
"""
return RangedIntegerConverter.to_string(value, 0, 2 ** 32 - 1)
class DateTimeConverter(Converter):
"""Converts the date time datatype.
This datatype describes instances identified by the combination of a date
and a time. Its value space is described as a combination of date and time
of day in Chapter 5.4 of ISO 8601. Its lexical space is the extended
format:
[-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
The time zone may be specified as Z (UTC) or (+|-)hh:mm. Time zones that
aren't specified are considered undetermined.
Python has a built in limitation preventing years before 1900 from being
used. Therefore, the initial [-] is meaningless.
"""
class FixedOffset(tzinfo):
"""Internal class representing a fixed Time Zone."""
def __init__(self, offset, name=None):
self._offset = timedelta(minutes=offset)
self._name = name
def utcoffset(self, _dt):
return self._offset
def tzname(self, _dt):
return self._name
def dst(self, _dt):
return timedelta(0)
@staticmethod
def from_string(value):
match = re.search(
r'^'
r'(?P\d{4})-'
r'(?P\d{2})-'
r'(?P\d{2})'
r'T'
r'(?P\d{2}):'
r'(?P\d{2}):'
r'(?P\d{2})'
r'(?PZ|'
r'(?P[+-])'
r'(?P\d{2}):'
r'(?P\d{2}))'
r'$',
value,
)
if match.group('tz') == 'Z':
timezone = DateTimeConverter.FixedOffset(0, 'UTC')
else:
tz_hour = int(match.group('tz_hour'))
tz_minute = int(match.group('tz_minute'))
tz_sign = match.group('tz_sign')
offset = 60 * tz_hour + tz_minute
timezone = DateTimeConverter.FixedOffset(
int(
'{0:s}{1:d}'.format(
tz_sign,
offset,
)
),
'UTC',
)
return datetime(
year=int(match.group('year')),
month=int(match.group('month')),
day=int(match.group('day')),
hour=int(match.group('hour')),
minute=int(match.group('minute')),
second=int(match.group('second')),
tzinfo=timezone,
)
@staticmethod
def to_string(value):
# Allow None value.
if value is None:
return value
# Check the value type.
if not isinstance(value, datetime):
raise TypeError(
'{0:s} expected, got {1:s}'.format(
datetime.__class__,
type(value).__class__,
),
)
# If no timezone is set, default to 'Z'.
if value.tzinfo is None:
timezone = 'Z'
else:
offset = int(value.utcoffset().total_seconds() / 60)
timezone = '{0:0=+3d}:{1:0=2d}'.format(
offset / 60,
abs(offset % 60),
)
result = '{0:0=2d}-{1:0=2d}-{2:0=2d}T{3:0=2d}:{4:0=2d}:{5:0=2d}{6:s}'
return result.format(
value.year,
value.month,
value.day,
value.hour,
value.minute,
value.second,
timezone,
)
class CertificateConverter():
"""Converts to and from PEM certificates."""
@staticmethod
def from_string(value):
"""Converts the input value to a proper PEM certificate
:param value: the value to convert, or None
:return: the input as a string, or None if value is None
"""
template = '{}\n{}\n{}'
return template.format(
'-----BEGIN CERTIFICATE-----',
textwrap.fill(Converter.from_string(value), 64),
'-----END CERTIFICATE-----',
)
@staticmethod
def to_string(value):
"""Converts the certificate to a plain string
:param value: the certificate to convert, or None
:return: the input as a string, or None if value is None
"""
match = re.search(
'-----BEGIN CERTIFICATE-----'
'((?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?)'
'-----END CERTIFICATE-----',
''.join(value.splitlines()),
)
return Converter.to_string(match.group(1), str)
cepces-0.3.7/cepces/xml/util.py 0000664 0000000 0000000 00000003123 14342136262 0016356 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
"""Module containing XML utilities."""
import re
def to_clark(name, namespace=None):
"""Returns an element name in Clark's Notation.
:param name: the element name
:param namespace: an optional namespace
:return: the name in Clark's notation
"""
if namespace:
return '{{{1:s}}}{0:s}'.format(name, namespace)
return str(name)
def from_clark(string):
"""Returns a (name, namespace) tuple from an element name following Clark's
notation.
Note that the URI is not checked whether it is well-formed or not.
Raises ValueError on malformed input.
:param string: the string to match against
:return: a (name, namespace) tuple
"""
match = re.search(r'^(?:{(?P.+)})?(?P[^{}]+)$', string)
if not match:
raise ValueError('Invalid input, expected Clark\'s notation')
name, namespace = match.group('name', 'namespace')
return name, namespace
cepces-0.3.7/conf/ 0000775 0000000 0000000 00000000000 14342136262 0013713 5 ustar 00root root 0000000 0000000 cepces-0.3.7/conf/cepces.conf.dist 0000664 0000000 0000000 00000007203 14342136262 0016770 0 ustar 00root root 0000000 0000000 [global]
# Hostname of the Certificate Enrollment Policy (CEP) Server.
# Used to construct the URL to the CEP endpoint.
#
# Default: ca
server=ca
# This is the endpoint type. It can be either "Policy" where the server
# endpoint specified later will be used to look up enrollment endpoints, or it
# can be "Enrollment" to specify a direct endpoint (bypassing XCEP
# altogether.)
type=Policy
# This is the authentication mechanism used for connecting to the service
# endpoint. The following options are available:
#
# * Anonymous
# Anonymous authentication (i.e. no authentication at all.) This
# is discouraged and untested. It is only included for completness
# as defined in the MS-XCEP specification.
# * Kerberos
# Transport level authentication. This is the default where the
# authentication is performed in the HTTP(s) layer.
# * UsernamePassword
# Message level authentication. The credentials are used in the
# message header for authentication.
# * Certificate
# Transport level authentication. A client certificate is used
# for TLS client authentication in the HTTPS layer.
#
# Default: Kerberos
auth=Kerberos
# This is the final URL of the Policy Provider endpoint.
#
# Default: https://${server}/ADPolicyProvider_CEP_${auth}/service.svc/CEP
endpoint=https://${server}/ADPolicyProvider_CEP_${auth}/service.svc/CEP
# Path to a CA bundle or directory containing certificates. If not specified,
# the system default is used. If set to an empty value, verification is
# bypassed. This is strongly discouraged.
#
# Please note that directories are supported starting with python-requests 2.9.
#
# Default:
#cas=
# Time in seconds before re-checking if the certificate has been issued
poll_interval=3600
# This is the openssl security level. The latest openssl sets the default to
# level 2, which disables some less secure ciphers. You may encounter an error
# of '[SSL: DH_KEY_TOO_SMALL] dh key too small' if this level is set to high
# for your server. If this happens, you can work around this issue by setting
# openssl_seclevel to 1.
#
# Default: 2
#openssl_seclevel=2
[kerberos]
# Use the specified keytab. If unspecified, the system default is used.
#
# Default:
#keytab=
# An optional explicit realm to use. If unspecified, the default system realm
# is used.
#
# Default:
#realm=
# Initialize a credential cache. If this is disabled, a valid credential cache
# is required prior launching the application. If enabled, a temporary
# in-memory cache is created, and released when the application ends.
#
# Default: True
ccache=True
# A list of principals to try when requesting a ticket.
#
# Default:
principals=
${shortname}$$
${SHORTNAME}$$
host/${SHORTNAME}
host/${fqdn}
# A list of encryption types to use.
#
# Default:
enctypes=
des-cbc-crc
des-cbc-md5
arcfour-hmac
aes128-cts-hmac-sha1-96
aes256-cts-hmac-sha1-96
# When the webenrollment services and the CA aren't installed on the same
# machine you will get a access denied error if kerberos delegation is
# disabled. This is enabled by default.
#
# Default: True
delegate=True
[certificate]
# Use the following client certificate,
# given as OpenSSL format certificate file.
# The issuer CA certificate of this client certificate must be included
# in the AD NTAuth container.
#
# Default:
#certfile = /path/to/openssl-certfile.pem
# Use the following client certificate key,
# given as OpenSSL format private key file without passphrase protection.
#
# Default:
#keyfile = /path/to/openssl-keyfile.pem
cepces-0.3.7/conf/logging.conf.dist 0000664 0000000 0000000 00000000732 14342136262 0017154 0 ustar 00root root 0000000 0000000 [loggers]
keys=root
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=defaultFormatter
[logger_root]
level=INFO
handlers=consoleHandler,fileHandler
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=defaultFormatter
args=(sys.stderr,)
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=defaultFormatter
args=('/var/log/cepces/cepces.log',)
[formatter_defaultFormatter]
format=%(asctime)s %(name)s:%(levelname)s:%(message)s
datefmt=
cepces-0.3.7/requirements.txt 0000664 0000000 0000000 00000000062 14342136262 0016250 0 ustar 00root root 0000000 0000000 cryptography>=1.2
requests
requests_gssapi>=1.2.2
cepces-0.3.7/selinux/ 0000775 0000000 0000000 00000000000 14342136262 0014455 5 ustar 00root root 0000000 0000000 cepces-0.3.7/selinux/.gitignore 0000664 0000000 0000000 00000000021 14342136262 0016436 0 ustar 00root root 0000000 0000000 /cepces.pp
/tmp/
cepces-0.3.7/selinux/Makefile 0000664 0000000 0000000 00000000253 14342136262 0016115 0 ustar 00root root 0000000 0000000 TARGETS?=cepces
MODULES?=${TARGETS:=.pp}
all: ${TARGETS:=.pp}
%.pp: %.te %.fc %.if
make -f /usr/share/selinux/devel/Makefile $@
clean:
rm -f *~ *.tc *.pp
rm -rf tmp
cepces-0.3.7/selinux/cepces.fc 0000664 0000000 0000000 00000000117 14342136262 0016230 0 ustar 00root root 0000000 0000000 /var/log/cepces(/.*)? gen_context(system_u:object_r:cepces_log_t,s0)
cepces-0.3.7/selinux/cepces.if 0000664 0000000 0000000 00000002251 14342136262 0016237 0 ustar 00root root 0000000 0000000 ## policy for cepces########################################
##
## Read cepces's log files.
##
##
##
## Domain allowed access.
##
##
##
#
interface(`cepces_read_log',`
gen_require(`
type cepces_log_t;
')
logging_search_logs($1)
read_files_pattern($1, cepces_log_t, cepces_log_t)
')
########################################
##
## Append to cepces log files.
##
##
##
## Domain allowed access.
##
##
#
interface(`cepces_append_log',`
gen_require(`
type cepces_log_t;
')
logging_search_logs($1)
append_files_pattern($1, cepces_log_t, cepces_log_t)
')
########################################
##
## Manage cepces log files
##
##
##
## Domain allowed access.
##
##
#
interface(`cepces_manage_log',`
gen_require(`
type cepces_log_t;
')
logging_search_logs($1)
manage_dirs_pattern($1, cepces_log_t, cepces_log_t)
manage_files_pattern($1, cepces_log_t, cepces_log_t)
manage_lnk_files_pattern($1, cepces_log_t, cepces_log_t)
')
cepces-0.3.7/selinux/cepces.te 0000664 0000000 0000000 00000000633 14342136262 0016253 0 ustar 00root root 0000000 0000000 policy_module(cepces, 0.3.7)
require {
type certmonger_t;
type kernel_t;
type ldconfig_exec_t;
}
type cepces_log_t;
logging_log_file(cepces_log_t)
allow certmonger_t cepces_log_t:dir { add_name search write };
allow certmonger_t cepces_log_t:file { create open };
allow certmonger_t kernel_t:system module_request;
allow certmonger_t ldconfig_exec_t:file { read execute open execute_no_trans };
cepces-0.3.7/setup.py 0000775 0000000 0000000 00000004063 14342136262 0014506 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from codecs import open as copen
from os import path
from setuptools import setup
import cepces
HERE = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with copen(path.join(HERE, 'README.rst'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(
name=cepces.__title__,
version=cepces.__version__,
description=cepces.__description__,
long_description=LONG_DESCRIPTION,
url=cepces.__url__,
author=cepces.__author__,
author_email=cepces.__author_email__,
license=cepces.__license__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: System Administrators',
'Topic :: System :: Systems Administration',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
],
keywords='certificate ca cep ces adcs wstep xcep',
packages=[
'cepces',
'cepces.certmonger',
'cepces.krb5',
'cepces.soap',
'cepces.wstep',
'cepces.xcep',
'cepces.xml',
],
data_files=[
('libexec/certmonger', ['bin/cepces-submit']),
],
install_requires=[],
test_suite='tests',
)
cepces-0.3.7/tests/ 0000775 0000000 0000000 00000000000 14342136262 0014130 5 ustar 00root root 0000000 0000000 cepces-0.3.7/tests/__init__.py 0000664 0000000 0000000 00000001245 14342136262 0016243 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
cepces-0.3.7/tests/cepces_test/ 0000775 0000000 0000000 00000000000 14342136262 0016431 5 ustar 00root root 0000000 0000000 cepces-0.3.7/tests/cepces_test/__init__.py 0000664 0000000 0000000 00000001346 14342136262 0020546 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from .certmonger import *
from .xcep import *
from .xml import *
cepces-0.3.7/tests/cepces_test/certmonger/ 0000775 0000000 0000000 00000000000 14342136262 0020576 5 ustar 00root root 0000000 0000000 cepces-0.3.7/tests/cepces_test/certmonger/__init__.py 0000664 0000000 0000000 00000001276 14342136262 0022715 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from .operation import *
cepces-0.3.7/tests/cepces_test/certmonger/operation.py 0000664 0000000 0000000 00000002633 14342136262 0023154 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from cepces import __title__, __version__
import unittest
import cepces.certmonger.operation as CertmongerOperations
import io
class TestGetDefaultTemplate(unittest.TestCase):
"""Tests the GetDefaultTemplate operation"""
def testCall(self):
out = io.StringIO()
operation = CertmongerOperations.GetDefaultTemplate(None, out=out)
operation()
self.assertEqual(out.getvalue(), '')
class TestIdentify(unittest.TestCase):
"""Tests the Identity operation"""
def testCall(self):
out = io.StringIO()
operation = CertmongerOperations.Identify(None, out=out)
operation()
self.assertEqual(
out.getvalue(),
'{} {}\n'.format(__title__, __version__),
)
cepces-0.3.7/tests/cepces_test/core.py 0000664 0000000 0000000 00000002234 14342136262 0017734 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
import unittest
import logging
from cepces import Base
class TestBase(unittest.TestCase):
"""Tests the Base class"""
def testDefaultLogger(self):
"""Test with default logger"""
base = Base()
self.assertIsNotNone(base._logger)
def testSuppliedLogger(self):
"""Test with supplied logger"""
logger = logging.getLogger('Test')
base = Base(logger=logger)
self.assertIsNotNone(base._logger)
self.assertIs(base._logger, logger)
cepces-0.3.7/tests/cepces_test/xcep/ 0000775 0000000 0000000 00000000000 14342136262 0017370 5 ustar 00root root 0000000 0000000 cepces-0.3.7/tests/cepces_test/xcep/__init__.py 0000664 0000000 0000000 00000001276 14342136262 0021507 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from .converter import *
cepces-0.3.7/tests/cepces_test/xcep/converter.py 0000664 0000000 0000000 00000004503 14342136262 0021753 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from unittest import TestCase
import cepces.xcep.converter as converter
class TestClientAuthenticationConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
c = converter.ClientAuthenticationConverter
self.assertIsNone(c.from_string(input))
def testFromString(self):
"""Valid input integer strings should return the correct string"""
c = converter.ClientAuthenticationConverter
for i in range(len(converter.ClientAuthenticationConverter.MAP)):
result = c.from_string(str(1 << i))
self.assertEqual(
converter.ClientAuthenticationConverter.MAP[i][1],
result,
msg="{} should return {}".format(
str(i),
converter.ClientAuthenticationConverter.MAP[i][1],
),
)
self.assertIs(
type(result),
str,
msg="{} should be of type str".format(str(i)),
)
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.IntegerConverter.to_string(input)
self.assertIsNone(result)
def testToString(self):
"""A valid string should yield the correct stringified integer"""
c = converter.ClientAuthenticationConverter
for i in range(len(converter.ClientAuthenticationConverter.MAP)):
value = converter.ClientAuthenticationConverter.MAP[i]
result = c.to_string(value[1])
self.assertEqual(type(result), str)
self.assertEqual(result, str(value[0]))
cepces-0.3.7/tests/cepces_test/xml/ 0000775 0000000 0000000 00000000000 14342136262 0017231 5 ustar 00root root 0000000 0000000 cepces-0.3.7/tests/cepces_test/xml/__init__.py 0000664 0000000 0000000 00000001351 14342136262 0021342 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from .binding import *
from .converter import *
from .util import *
cepces-0.3.7/tests/cepces_test/xml/binding.py 0000664 0000000 0000000 00000006161 14342136262 0021221 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
import unittest
from cepces.xml.binding import ListingMeta
from cepces.xml.binding import XMLDescriptor
class MockXMLDescriptor(XMLDescriptor):
def __get__(self, instance, _owner=None):
return instance._test_value
def __set__(self, instance, value):
instance._test_value = value
def __delete__(self, instance):
pass
class TestXMLDescriptor(unittest.TestCase):
def testOnlyName(self):
"""Qualified name should be equal to name"""
descriptor = MockXMLDescriptor('name')
self.assertEqual(descriptor._name, 'name')
self.assertEqual(descriptor._namespace, None)
self.assertEqual(descriptor._qname, 'name')
def testNameAndNameSpace(self):
"""Qualified name should be in Clark's notation"""
descriptor = MockXMLDescriptor('name', 'namespace')
self.assertEqual(descriptor._name, 'name')
self.assertEqual(descriptor._namespace, 'namespace')
self.assertEqual(descriptor._qname, '{namespace}name')
def testIndexIncrement(self):
"""Static index should increase accordingly"""
index = XMLDescriptor._index
# Create three descriptors..
first = MockXMLDescriptor('first')
second = MockXMLDescriptor('second')
third = MockXMLDescriptor('third')
self.assertEqual(first._index, index)
self.assertEqual(second._index, index + 1)
self.assertEqual(third._index, index + 2)
self.assertEqual(XMLDescriptor._index, index + 3)
class TestListingMeta(unittest.TestCase):
def setUp(self):
super().setUp()
# Create a dummy class.
class MockClass(metaclass=ListingMeta):
first = MockXMLDescriptor('first')
second = MockXMLDescriptor('second')
third = MockXMLDescriptor('third')
self._dummy = MockClass
def testListingAttribute(self):
self.assertTrue(hasattr(self._dummy, '__listing__'))
def testOrderedListing(self):
dummy = self._dummy
listing = dummy.__listing__
self.assertEqual(listing[0][0], 'first')
self.assertEqual(listing[1][0], 'second')
self.assertEqual(listing[2][0], 'third')
self.assertEqual(listing[0][1], dummy.__dict__[listing[0][0]])
self.assertEqual(listing[1][1], dummy.__dict__[listing[1][0]])
self.assertEqual(listing[2][1], dummy.__dict__[listing[2][0]])
def tearDown(self):
super().tearDown()
self._dummy = None
cepces-0.3.7/tests/cepces_test/xml/converter.py 0000664 0000000 0000000 00000015205 14342136262 0021615 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from unittest import TestCase
import cepces.xml.converter as converter
class TestStringConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
result = converter.StringConverter.from_string(input)
self.assertIsNone(result)
def testFromString(self):
"""A string as input should return an equal string"""
input = 'TestString'
result = converter.StringConverter.from_string(input)
self.assertEqual(input, result)
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.StringConverter.to_string(input)
self.assertIsNone(result)
def testToString(self):
"""A string as input should return an equal string"""
input = 'TestString'
result = converter.StringConverter.to_string(input)
self.assertEqual(str(input), result)
class TestBooleanConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
result = converter.BooleanConverter.from_string(input)
self.assertIsNone(result)
def testFromString(self):
"""Boolean strings as input should return a boolean"""
c = converter.BooleanConverter
self.assertEqual(True, c.from_string('true'))
self.assertEqual(True, c.from_string('1'))
self.assertEqual(False, c.from_string('false'))
self.assertEqual(False, c.from_string('0'))
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.BooleanConverter.to_string(input)
self.assertIsNone(result)
def testToString(self):
"""A boolean as input should return an equal boolean (lower) string"""
c = converter.BooleanConverter
self.assertEqual('true', c.to_string(True))
self.assertEqual('false', c.to_string(False))
class TestIntegerConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
result = converter.IntegerConverter.from_string(input)
self.assertIsNone(result)
def testFromString(self):
"""An integer string as input should return an integer"""
input = 4711
result = converter.IntegerConverter.from_string(str(input))
self.assertEqual(input, result)
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.IntegerConverter.to_string(input)
self.assertIsNone(result)
def testToString(self):
"""An integer as input should return an equal integer string"""
input = 4711
result = converter.IntegerConverter.to_string(input)
self.assertEqual(str(input), result)
class TestRangedIntegerConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
result = converter.RangedIntegerConverter.from_string(input, 0, 1)
self.assertIsNone(result)
def testFromString(self):
"""An integer string as input should return a valid integer"""
f = converter.RangedIntegerConverter.from_string
self.assertEqual(10, f(str(10), 0, 20))
self.assertRaises(ValueError, f, str(-1), 0, 20)
self.assertRaises(ValueError, f, str(21), 0, 20)
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.RangedIntegerConverter.to_string(input, 0, 1)
self.assertIsNone(result)
def testToString(self):
"""An integer as input should return an equal integer string"""
f = converter.RangedIntegerConverter.to_string
self.assertEqual(str(10), f(10, 0, 20))
self.assertRaises(ValueError, f, -1, 0, 20)
self.assertRaises(ValueError, f, 21, 0, 20)
class TestSignedIntegerConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
result = converter.SignedIntegerConverter.from_string(input)
self.assertIsNone(result)
def testFromString(self):
"""An integer string as input should return a valid integer"""
f = converter.SignedIntegerConverter.from_string
self.assertEqual(10, f(str(10)))
self.assertRaises(ValueError, f, str(-2 ** 31 - 1))
self.assertRaises(ValueError, f, str(2 ** 31))
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.SignedIntegerConverter.to_string(input)
self.assertIsNone(result)
def testToString(self):
"""An integer as input should return an equal integer string"""
f = converter.SignedIntegerConverter.to_string
self.assertEqual(str(10), f(10))
self.assertRaises(ValueError, f, -2 ** 31 - 1)
self.assertRaises(ValueError, f, 2 ** 31)
class TestUnsignedIntegerConverter(TestCase):
def testFromNone(self):
"""None as input should return None"""
input = None
result = converter.UnsignedIntegerConverter.from_string(input)
self.assertIsNone(result)
def testFromString(self):
"""An integer string as input should return a valid integer"""
f = converter.UnsignedIntegerConverter.from_string
self.assertEqual(10, f(str(10)))
self.assertRaises(ValueError, f, str(-1))
self.assertRaises(ValueError, f, str(2 ** 32))
def testToNone(self):
"""None as input should return None"""
input = None
result = converter.UnsignedIntegerConverter.to_string(input)
self.assertIsNone(result)
def testToString(self):
"""An integer as input should return an equal integer string"""
f = converter.UnsignedIntegerConverter.to_string
self.assertEqual(str(10), f(10))
self.assertRaises(ValueError, f, -1)
self.assertRaises(ValueError, f, 2 ** 32)
class TestDateTimeConverter(TestCase):
# TODO
pass
cepces-0.3.7/tests/cepces_test/xml/util.py 0000664 0000000 0000000 00000004324 14342136262 0020563 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is part of cepces.
#
# cepces 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.
#
# cepces 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 cepces. If not, see .
#
from cepces.xml import util
import unittest
class TestToClarkNotation(unittest.TestCase):
def testName(self):
"""Name should not be changed when namespace is None"""
name = 'TestName'
self.assertEqual(util.to_clark(name), name)
def testNameAndNamespace(self):
"""Result should follow Clarks's notation"""
name = 'TestName'
namespace = 'TestNameSpace'
self.assertEqual(
util.to_clark(name, namespace),
'{{{1:s}}}{0:s}'.format(name, namespace)
)
def testNamespace(self):
"""Only specifying the namespace should fail"""
namespace = 'TestNameSpace'
with self.assertRaises(TypeError):
util.to_clark(None, namespace)
class TestFromClarkNotation(unittest.TestCase):
def testOnlyName(self):
"""Input should be returned unaltered"""
name = 'TestName'
rname, rnamespace = util.from_clark(name)
self.assertEqual(rname, name)
self.assertEqual(rnamespace, None)
def testNameAndNamespace(self):
"""(name, namsepace) tuple should be returned"""
name = 'TestName'
namespace = 'TestNamespace'
clarke = util.to_clark(name, namespace)
rname, rnamespace = util.from_clark(clarke)
self.assertEqual(name, rname)
self.assertEqual(namespace, rnamespace)
def testOnlyNamespace(self):
"""Having only a namespace should fail"""
string = '{TestNamespace}'
with self.assertRaises(ValueError):
util.from_clark(string)
cepces-0.3.7/tests/runner.py 0000775 0000000 0000000 00000000734 14342136262 0016022 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
import unittest
import sys
sys.path.insert(0, '../')
import cepces_test
if __name__ == "__main__":
loader = unittest.TestLoader()
suite = unittest.TestSuite()
suite.addTests(loader.loadTestsFromModule(cepces_test.certmonger))
suite.addTests(loader.loadTestsFromModule(cepces_test.xcep))
suite.addTests(loader.loadTestsFromModule(cepces_test.xml))
runner = unittest.TextTestRunner(verbosity=3, failfast=True)
runner.run(suite)