Imported Upstream version 1.0 debian upstream upstream/1.0
authorDevon Kearns <dookie@kali.org>
Wed, 26 Dec 2012 20:48:50 +0000 (13:48 -0700)
committerDevon Kearns <dookie@kali.org>
Wed, 26 Dec 2012 20:48:50 +0000 (13:48 -0700)
108 files changed:
.idea/.name [new file with mode: 0644]
.idea/encodings.xml [new file with mode: 0644]
.idea/inspectionProfiles/profiles_settings.xml [new file with mode: 0644]
.idea/misc.xml [new file with mode: 0644]
.idea/modules.xml [new file with mode: 0644]
.idea/scopes/scope_settings.xml [new file with mode: 0644]
.idea/sslcaudit.iml [new file with mode: 0644]
.idea/vcs.xml [new file with mode: 0644]
COPYING.HEADER [new file with mode: 0644]
COPYING.TXT [new file with mode: 0644]
README [new file with mode: 0644]
doc/example3-client-openssl.sh [new file with mode: 0755]
doc/example3-server.sh [new file with mode: 0755]
doc/example4-client-curl.sh [new file with mode: 0755]
doc/example4-server.sh [new file with mode: 0755]
doc/matrix.ods [new file with mode: 0644]
doc/notes.txt [new file with mode: 0644]
doc/sslcaudit-guide-20120501.pdf [new file with mode: 0644]
doc/sslcaudit-user-guide-1.0.odt [new file with mode: 0644]
doc/sslcaudit-user-guide-1.0.pdf [new file with mode: 0644]
misc/clean.sh [new file with mode: 0755]
misc/kill.sh [new file with mode: 0755]
misc/prepend_file.sh [new file with mode: 0755]
optparse-gui/CHANGELOG [new file with mode: 0644]
optparse-gui/COPYRIGHT [new file with mode: 0644]
optparse-gui/README [new file with mode: 0644]
optparse-gui/TODO [new file with mode: 0644]
optparse-gui/ez_setup.py [new file with mode: 0644]
optparse-gui/optparse_gui/__init__.py [new file with mode: 0644]
optparse-gui/setup.py [new file with mode: 0644]
optparse-gui/tests/__init__.py [new file with mode: 0644]
optparse-gui/tests/test.py [new file with mode: 0644]
src/__init__.py [new file with mode: 0644]
src/__init__.pyc [new file with mode: 0644]
src/core/BaseClientAuditController.py [new file with mode: 0644]
src/core/BaseClientAuditController.pyc [new file with mode: 0644]
src/core/CertFactory.py [new file with mode: 0644]
src/core/CertFactory.pyc [new file with mode: 0644]
src/core/ClientAuditorServer.py [new file with mode: 0644]
src/core/ClientAuditorServer.pyc [new file with mode: 0644]
src/core/ClientConnection.py [new file with mode: 0644]
src/core/ClientConnection.pyc [new file with mode: 0644]
src/core/ClientConnectionAuditEvent.py [new file with mode: 0644]
src/core/ClientConnectionAuditEvent.pyc [new file with mode: 0644]
src/core/ClientHandler.py [new file with mode: 0644]
src/core/ClientHandler.pyc [new file with mode: 0644]
src/core/ConfigError.py [new file with mode: 0644]
src/core/ConfigError.pyc [new file with mode: 0644]
src/core/FileBag.py [new file with mode: 0644]
src/core/FileBag.pyc [new file with mode: 0644]
src/core/SSLCAuditCLI.py [new file with mode: 0644]
src/core/SSLCAuditCLI.pyc [new file with mode: 0644]
src/core/Utils.py [new file with mode: 0644]
src/core/Utils.pyc [new file with mode: 0644]
src/core/__init__.py [new file with mode: 0644]
src/core/__init__.pyc [new file with mode: 0644]
src/modules/__init__.py [new file with mode: 0644]
src/modules/__init__.pyc [new file with mode: 0644]
src/modules/base/BaseProfileFactory.py [new file with mode: 0644]
src/modules/base/BaseProfileFactory.pyc [new file with mode: 0644]
src/modules/base/BaseServerHandler.py [new file with mode: 0644]
src/modules/base/BaseServerHandler.pyc [new file with mode: 0644]
src/modules/base/__init__.py [new file with mode: 0644]
src/modules/base/__init__.pyc [new file with mode: 0644]
src/modules/dummy/ProfileFactory.py [new file with mode: 0644]
src/modules/dummy/__init__.py [new file with mode: 0644]
src/modules/sslcert/ProfileFactory.py [new file with mode: 0644]
src/modules/sslcert/ProfileFactory.pyc [new file with mode: 0644]
src/modules/sslcert/SSLServerHandler.py [new file with mode: 0644]
src/modules/sslcert/SSLServerHandler.pyc [new file with mode: 0644]
src/modules/sslcert/__init__.py [new file with mode: 0644]
src/modules/sslcert/__init__.pyc [new file with mode: 0644]
src/profile/__init__.py [new file with mode: 0644]
src/test/ConnectionHammer.py [new file with mode: 0644]
src/test/ConnectionHammer.pyc [new file with mode: 0644]
src/test/ExternalCommandHammer.py [new file with mode: 0644]
src/test/ExternalCommandHammer.pyc [new file with mode: 0644]
src/test/Hammer.py [new file with mode: 0644]
src/test/Hammer.pyc [new file with mode: 0644]
src/test/SSLConnectionHammer.py [new file with mode: 0644]
src/test/SSLConnectionHammer.pyc [new file with mode: 0644]
src/test/TCPConnectionHammer.py [new file with mode: 0644]
src/test/TCPConnectionHammer.pyc [new file with mode: 0644]
src/test/TestConfig.py [new file with mode: 0644]
src/test/__init__.py [new file with mode: 0644]
src/test/__init__.pyc [new file with mode: 0644]
sslcaudit [new file with mode: 0755]
test-sslcaudit [new file with mode: 0755]
test/TestCertFactory.py [new file with mode: 0644]
test/TestDummyModule.py [new file with mode: 0644]
test/TestFileBag.py [new file with mode: 0644]
test/TestSSLCertModule.py [new file with mode: 0644]
test/_SimpleX509create.py [new file with mode: 0644]
test/_TestM2CryptoBug.py [new file with mode: 0644]
test/__init__.py [new file with mode: 0644]
test/certs/test-ca-cacert.pem [new file with mode: 0644]
test/certs/test-ca-cakey.pem [new file with mode: 0644]
test/certs/test-client-cert.pem [new file with mode: 0644]
test/certs/test-client-key.pem [new file with mode: 0644]
test/certs/www.example.com-cert.pem [new file with mode: 0644]
test/certs/www.example.com-key.pem [new file with mode: 0644]
test/client-cert-verify--client.sh [new file with mode: 0755]
test/client-cert-verify--server.sh [new file with mode: 0755]
test/client.sh [new file with mode: 0755]
test/exthammer.sh [new file with mode: 0755]
test/exthammer.sh_socat [new file with mode: 0755]
test/ssl-client.py [new file with mode: 0644]
test/sslcaudit-selftest-all.sh [new file with mode: 0755]

diff --git a/.idea/.name b/.idea/.name
new file mode 100644 (file)
index 0000000..608a00f
--- /dev/null
@@ -0,0 +1 @@
+sslcaudit
\ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
new file mode 100644 (file)
index 0000000..e206d70
--- /dev/null
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
+</project>
+
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644 (file)
index 0000000..c60c33b
--- /dev/null
@@ -0,0 +1,7 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="PROJECT_PROFILE" />
+    <option name="USE_PROJECT_PROFILE" value="false" />
+    <version value="1.0" />
+  </settings>
+</component>
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644 (file)
index 0000000..4284862
--- /dev/null
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 2.7.1+ (/usr/bin/python2.7)" project-jdk-type="Python SDK" />
+</project>
+
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644 (file)
index 0000000..49577b1
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/sslcaudit.iml" filepath="$PROJECT_DIR$/.idea/sslcaudit.iml" />
+    </modules>
+  </component>
+</project>
+
diff --git a/.idea/scopes/scope_settings.xml b/.idea/scopes/scope_settings.xml
new file mode 100644 (file)
index 0000000..922003b
--- /dev/null
@@ -0,0 +1,5 @@
+<component name="DependencyValidationManager">
+  <state>
+    <option name="SKIP_IMPORT_STATEMENTS" value="false" />
+  </state>
+</component>
\ No newline at end of file
diff --git a/.idea/sslcaudit.iml b/.idea/sslcaudit.iml
new file mode 100644 (file)
index 0000000..a34a857
--- /dev/null
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
+
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644 (file)
index 0000000..c80f219
--- /dev/null
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>
+
diff --git a/COPYING.HEADER b/COPYING.HEADER
new file mode 100644 (file)
index 0000000..9583d2c
--- /dev/null
@@ -0,0 +1,6 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
diff --git a/COPYING.TXT b/COPYING.TXT
new file mode 100644 (file)
index 0000000..10926e8
--- /dev/null
@@ -0,0 +1,675 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    <program>  Copyright (C) <year>  <name of author>
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..36126ad
--- /dev/null
+++ b/README
@@ -0,0 +1,31 @@
+INTRODUCTION
+
+The goal of sslcaudit project is to develop a utility to automate testing SSL/TLS
+clients for resistance against MITM attacks. It might be useful for testing a thick
+client, a mobile application, an appliance, pretty much anything communicating over
+SSL/TLS over TCP.
+
+INSTALLATION
+
+There is no proper installation procedure yet (Debian package and distutils-based
+Python installer are coming soon). For now just fetch the release from GIT repository:
+
+       $ git clone -b release_1_0 https://github.com/grwl/sslcaudit.git
+       Cloning into sslcaudit...
+
+Then find sslcaudit in the top level directory and run it with -h option. PDF
+user-guide is available at doc/sslcaudit-user-guide-1.0.pdf.
+
+Sslcaudit uses M2Crypto Python library. On Debian system M2Crypto library can be
+installed with the following command:
+
+       $ sudo apt-get install python-m2crypto
+
+MORE INFORMATION
+
+See the user guide for more information or run 'sslcaudit -h'.
+
+LICENSING
+
+GPLv3, see COPYING.TXT
+
diff --git a/doc/example3-client-openssl.sh b/doc/example3-client-openssl.sh
new file mode 100755 (executable)
index 0000000..b02087f
--- /dev/null
@@ -0,0 +1,2 @@
+#!/bin/sh -x
+for _ in `seq 1 4` ; do socat - OPENSSL:localhost:8443,cafile=/home/abb/certs/sslcaudit-test-cacert.pem ; done
diff --git a/doc/example3-server.sh b/doc/example3-server.sh
new file mode 100755 (executable)
index 0000000..9eb7787
--- /dev/null
@@ -0,0 +1,5 @@
+#!/bin/sh -x
+./sslcaudit --user-ca-cert \
+       ~/certs/sslcaudit-test-cacert.pem \
+       --user-ca-key ~/certs/sslcaudit-test-cakey.pem \
+       --server 62.213.200.252:443
diff --git a/doc/example4-client-curl.sh b/doc/example4-client-curl.sh
new file mode 100755 (executable)
index 0000000..c8101e5
--- /dev/null
@@ -0,0 +1,2 @@
+#!/bin/sh -x
+for _ in `seq 1 4` ; do curl --cacert /home/abb/certs/sslcaudit-test-cacert.pem https://brufeprd1.hackingmachines.com:8443/ ; done
diff --git a/doc/example4-server.sh b/doc/example4-server.sh
new file mode 100755 (executable)
index 0000000..9eb7787
--- /dev/null
@@ -0,0 +1,5 @@
+#!/bin/sh -x
+./sslcaudit --user-ca-cert \
+       ~/certs/sslcaudit-test-cacert.pem \
+       --user-ca-key ~/certs/sslcaudit-test-cakey.pem \
+       --server 62.213.200.252:443
diff --git a/doc/matrix.ods b/doc/matrix.ods
new file mode 100644 (file)
index 0000000..34cc134
Binary files /dev/null and b/doc/matrix.ods differ
diff --git a/doc/notes.txt b/doc/notes.txt
new file mode 100644 (file)
index 0000000..28eb230
--- /dev/null
@@ -0,0 +1 @@
+git svn clone -s http://optparse-gui.googlecode.com/svn optparse-gui
diff --git a/doc/sslcaudit-guide-20120501.pdf b/doc/sslcaudit-guide-20120501.pdf
new file mode 100644 (file)
index 0000000..4d9a2b2
Binary files /dev/null and b/doc/sslcaudit-guide-20120501.pdf differ
diff --git a/doc/sslcaudit-user-guide-1.0.odt b/doc/sslcaudit-user-guide-1.0.odt
new file mode 100644 (file)
index 0000000..76c0b03
Binary files /dev/null and b/doc/sslcaudit-user-guide-1.0.odt differ
diff --git a/doc/sslcaudit-user-guide-1.0.pdf b/doc/sslcaudit-user-guide-1.0.pdf
new file mode 100644 (file)
index 0000000..fca3db1
Binary files /dev/null and b/doc/sslcaudit-user-guide-1.0.pdf differ
diff --git a/misc/clean.sh b/misc/clean.sh
new file mode 100755 (executable)
index 0000000..2deaac7
--- /dev/null
@@ -0,0 +1,6 @@
+#!/bin/sh -xe
+
+rm -rf sslcaudit.*
+rm -rf test/sslcaudit.*
+rm -rf test/testfilebag.*
+
diff --git a/misc/kill.sh b/misc/kill.sh
new file mode 100755 (executable)
index 0000000..ec89fa8
--- /dev/null
@@ -0,0 +1,16 @@
+#!/bin/sh -e
+
+# ----------------------------------------------------------------------------
+# SSLCAUDIT - a tool for automating security audit of SSL clients
+# Released under terms of GPLv3, see COPYING.TXT
+# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+# ----------------------------------------------------------------------------
+
+pid=`ps ax|grep sslcaudit| grep -v grep | awk '{print $1}'`
+if [ -n "$pid" ] ; then
+       kill $pid
+       echo "killed $pid"
+else
+       echo "nothinig to kill"
+fi
+
diff --git a/misc/prepend_file.sh b/misc/prepend_file.sh
new file mode 100755 (executable)
index 0000000..4f91cd8
--- /dev/null
@@ -0,0 +1,18 @@
+#!/bin/sh -xe
+
+# ----------------------------------------------------------------------------
+# SSLCAUDIT - a tool for automating security audit of SSL clients
+# Released under terms of GPLv3, see COPYING.TXT 
+# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+# ----------------------------------------------------------------------------
+
+# After execution of "./prepend.sh F1 F2" file F2 will contain F2 + F1"
+# Example:
+#  find . -name \*.py | xargs -n1 -IF ./prepend_file.sh F COPYING.HEADER
+
+[ $# -eq 2 ]
+
+mv "$1" "$1.orig"
+cat "$2" "$1.orig" > "$1"
+rm "$1.orig"
+
diff --git a/optparse-gui/CHANGELOG b/optparse-gui/CHANGELOG
new file mode 100644 (file)
index 0000000..7d33ca1
--- /dev/null
@@ -0,0 +1,9 @@
+= optparse_gui 0.1 =\r
+\r
+First release of optparse_gui.\r
+Dynamically generated a wx-based dialog with controls the match the option's\r
+type:\r
+ * CheckBox for boolean options\r
+ * ComboBox for "choice" options\r
+ * TextCtrl for all other options\r
+ * An extra TextCtrl for entering non-option command line arguments\r
diff --git a/optparse-gui/COPYRIGHT b/optparse-gui/COPYRIGHT
new file mode 100644 (file)
index 0000000..aff9294
--- /dev/null
@@ -0,0 +1,11 @@
+Copyright (c) 2008, slider fry\r
+All rights reserved.\r
+\r
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r
+\r
+    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\r
+    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\r
+    * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\r
+\r
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
+\r
diff --git a/optparse-gui/README b/optparse-gui/README
new file mode 100644 (file)
index 0000000..b3e74f9
--- /dev/null
@@ -0,0 +1,59 @@
+Welcome to optparse_gui!\r
\r
+= What is *_optparse_gui_*? = \r
+\r
+In a single sentence: import *_optparse_gui_* as _optparse_\r
+\r
+_optparse_ is a great built-in python module for parsing command line arguments.\r
+see http://docs.python.org/lib/module-optparse.html for more info.\r
+\r
+*_optparse_gui_* is a drop-in replacement for _optparse_.\r
+It allows entering command line arguments in a dynamically generated wx-based dialog.\r
+*_optparse_gui_* generates the dialog depending on the provided _optparse_ options:\r
+ * CheckBox for boolean options\r
+ * ComboBox for "choice" options\r
+ * TextCtrl for all other options\r
+ * An extra TextCtrl for entering non-option command line arguments\r
+Also, the dialog contains context-sensitive help for every control.\r
+\r
+Ever wanted to transparently add a GUI to your command-line driven python scripts? \r
+This is the module for you.\r
+\r
+= Installing =\r
+\r
+In order to install, simply run "setup.py install" from the command line.\r
+On windows - you can also use the provided installer.\r
+\r
+= Using =\r
+\r
+Like the title says - simply "import *_optparse_gui_* as _optparse_"\r
+\r
+A more elaborate use case might be to use *_optparse_gui_* when the application\r
+is ran with no command line arguments ( i.e. a double-click on the module's icon ),\r
+but use the original _optparse_ to handle the command line arguments if they are\r
+given.\r
+That way, a user can drive your app using a GUI, and yet - the app can\r
+be automated by passing command line arguments.\r
+A sample for this might be as follows ( also included in test\test.py ):\r
+\r
+{{{\r
+import sys\r
+import optparse\r
+import optparse_gui\r
+\r
+def main():\r
+       if 1 == len( sys.argv ):\r
+               optparser_class = optparse.OptionParser\r
+       else:\r
+               optparser_class = optparse_gui.OptionParser\r
+\r
+       parser = optparser_class.OptionParser()\r
+       parser.add_option( ... )\r
+       parser.add_option( ... )\r
+       parser.add_option( ... )\r
+\r
+       option, args = parser.parse_args()\r
+\r
+       do_usefull_stuff( options, args )\r
+}}}\r
+\r
diff --git a/optparse-gui/TODO b/optparse-gui/TODO
new file mode 100644 (file)
index 0000000..97d64c0
--- /dev/null
@@ -0,0 +1,3 @@
+* Magically guess that an option is a filename or directory and provide\r
+  a "browse" button.\r
+* Make the options dialog resizable\r
diff --git a/optparse-gui/ez_setup.py b/optparse-gui/ez_setup.py
new file mode 100644 (file)
index 0000000..89cf056
--- /dev/null
@@ -0,0 +1,272 @@
+#!python
+"""Bootstrap setuptools installation
+
+If you want to use setuptools in your package's setup.py, just include this
+file in the same directory with it, and add this to the top of your setup.py::
+
+    from ez_setup import use_setuptools
+    use_setuptools()
+
+If you want to require a specific version of setuptools, set a download
+mirror, or use an alternate download directory, you can do so by supplying
+the appropriate options to ``use_setuptools()``.
+
+This file can also be run as a script to install or upgrade setuptools.
+"""
+import sys
+DEFAULT_VERSION = "0.6c8"
+DEFAULT_URL     = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3]
+
+md5_data = {
+    'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',
+    'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',
+    'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',
+    'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',
+    'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',
+    'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',
+    'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5',
+    'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4',
+    'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c',
+    'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b',
+    'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27',
+    'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277',
+    'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa',
+    'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e',
+    'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e',
+    'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f',
+    'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2',
+    'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc',
+    'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167',
+    'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64',
+    'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d',
+    'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20',
+    'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab',
+    'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53',
+    'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2',
+    'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e',
+    'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372',
+    'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902',
+    'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de',
+    'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b',
+}
+
+import sys, os
+
+def _validate_md5(egg_name, data):
+    if egg_name in md5_data:
+        from md5 import md5
+        digest = md5(data).hexdigest()
+        if digest != md5_data[egg_name]:
+            print >>sys.stderr, (
+                "md5 validation of %s failed!  (Possible download problem?)"
+                % egg_name
+            )
+            sys.exit(2)
+    return data
+
+
+def use_setuptools(
+    version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+    download_delay=15
+):
+    """Automatically find/download setuptools and make it available on sys.path
+
+    `version` should be a valid setuptools version number that is available
+    as an egg for download under the `download_base` URL (which should end with
+    a '/').  `to_dir` is the directory where setuptools will be downloaded, if
+    it is not already available.  If `download_delay` is specified, it should
+    be the number of seconds that will be paused before initiating a download,
+    should one be required.  If an older version of setuptools is installed,
+    this routine will print a message to ``sys.stderr`` and raise SystemExit in
+    an attempt to abort the calling script.
+    """
+    was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules
+    def do_download():
+        egg = download_setuptools(version, download_base, to_dir, download_delay)
+        sys.path.insert(0, egg)
+        import setuptools; setuptools.bootstrap_install_from = egg
+    try:
+        import pkg_resources
+    except ImportError:
+        return do_download()       
+    try:
+        pkg_resources.require("setuptools>="+version); return
+    except pkg_resources.VersionConflict, e:
+        if was_imported:
+            print >>sys.stderr, (
+            "The required version of setuptools (>=%s) is not available, and\n"
+            "can't be installed while this script is running. Please install\n"
+            " a more recent version first, using 'easy_install -U setuptools'."
+            "\n\n(Currently using %r)"
+            ) % (version, e.args[0])
+            sys.exit(2)
+        else:
+            del pkg_resources, sys.modules['pkg_resources']    # reload ok
+            return do_download()
+    except pkg_resources.DistributionNotFound:
+        return do_download()
+
+def download_setuptools(
+    version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,
+    delay = 15
+):
+    """Download setuptools from a specified location and return its filename
+
+    `version` should be a valid setuptools version number that is available
+    as an egg for download under the `download_base` URL (which should end
+    with a '/'). `to_dir` is the directory where the egg will be downloaded.
+    `delay` is the number of seconds to pause before an actual download attempt.
+    """
+    import urllib2, shutil
+    egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])
+    url = download_base + egg_name
+    saveto = os.path.join(to_dir, egg_name)
+    src = dst = None
+    if not os.path.exists(saveto):  # Avoid repeated downloads
+        try:
+            from distutils import log
+            if delay:
+                log.warn("""
+---------------------------------------------------------------------------
+This script requires setuptools version %s to run (even to display
+help).  I will attempt to download it for you (from
+%s), but
+you may need to enable firewall access for this script first.
+I will start the download in %d seconds.
+
+(Note: if this machine does not have network access, please obtain the file
+
+   %s
+
+and place it in this directory before rerunning this script.)
+---------------------------------------------------------------------------""",
+                    version, download_base, delay, url
+                ); from time import sleep; sleep(delay)
+            log.warn("Downloading %s", url)
+            src = urllib2.urlopen(url)
+            # Read/write all in one block, so we don't create a corrupt file
+            # if the download is interrupted.
+            data = _validate_md5(egg_name, src.read())
+            dst = open(saveto,"wb"); dst.write(data)
+        finally:
+            if src: src.close()
+            if dst: dst.close()
+    return os.path.realpath(saveto)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+def main(argv, version=DEFAULT_VERSION):
+    """Install or upgrade setuptools and EasyInstall"""
+    try:
+        import setuptools
+    except ImportError:
+        egg = None
+        try:
+            egg = download_setuptools(version, delay=0)
+            sys.path.insert(0,egg)
+            from setuptools.command.easy_install import main
+            return main(list(argv)+[egg])   # we're done here
+        finally:
+            if egg and os.path.exists(egg):
+                os.unlink(egg)
+    else:
+        if setuptools.__version__ == '0.0.1':
+            print >>sys.stderr, (
+            "You have an obsolete version of setuptools installed.  Please\n"
+            "remove it from your system entirely before rerunning this script."
+            )
+            sys.exit(2)
+
+    req = "setuptools>="+version
+    import pkg_resources
+    try:
+        pkg_resources.require(req)
+    except pkg_resources.VersionConflict:
+        try:
+            from setuptools.command.easy_install import main
+        except ImportError:
+            from easy_install import main
+        main(list(argv)+[download_setuptools(delay=0)])
+        sys.exit(0) # try to force an exit
+    else:
+        if argv:
+            from setuptools.command.easy_install import main
+            main(argv)
+        else:
+            print "Setuptools version",version,"or greater has been installed."
+            print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
+
+def update_md5(filenames):
+    """Update our built-in md5 registry"""
+
+    import re
+    from md5 import md5
+
+    for name in filenames:
+        base = os.path.basename(name)
+        f = open(name,'rb')
+        md5_data[base] = md5(f.read()).hexdigest()
+        f.close()
+
+    data = ["    %r: %r,\n" % it for it in md5_data.items()]
+    data.sort()
+    repl = "".join(data)
+
+    import inspect
+    srcfile = inspect.getsourcefile(sys.modules[__name__])
+    f = open(srcfile, 'rb'); src = f.read(); f.close()
+
+    match = re.search("\nmd5_data = {\n([^}]+)}", src)
+    if not match:
+        print >>sys.stderr, "Internal error!"
+        sys.exit(2)
+
+    src = src[:match.start(1)] + repl + src[match.end(1):]
+    f = open(srcfile,'w')
+    f.write(src)
+    f.close()
+
+
+if __name__=='__main__':
+    if len(sys.argv)>2 and sys.argv[1]=='--md5update':
+        update_md5(sys.argv[2:])
+    else:
+        main(sys.argv[1:])
+
+
+
+
+
diff --git a/optparse-gui/optparse_gui/__init__.py b/optparse-gui/optparse_gui/__init__.py
new file mode 100644 (file)
index 0000000..b3b91e3
--- /dev/null
@@ -0,0 +1,312 @@
+'''
+A drop-in replacement for optparse ( "import optparse_gui as optparse" )
+Provides an identical interface to optparse(.OptionParser),
+But displays an automatically generated wx dialog in order to enter the
+options/args, instead of parsing command line arguments
+'''
+
+import os
+import sys
+import re
+import optparse
+
+import wx
+
+__version__ = 0.1
+__revision__ = '$Id$'
+
+class OptparseDialog( wx.Dialog ):
+    '''The dialog presented to the user with dynamically generated controls,
+    to fill in the required options.
+    Based on the wx.Dialog sample from wx Docs & Demos'''
+    def __init__(
+            self,
+            option_parser, #The OptionParser object
+            parent = None,
+            ID = 0,
+            title = 'Optparse Dialog',
+            pos=wx.DefaultPosition,
+            size=wx.DefaultSize,
+            style=wx.DEFAULT_DIALOG_STYLE,
+            name = 'OptparseDialog',
+        ):
+
+        provider = wx.SimpleHelpProvider()
+        wx.HelpProvider_Set(provider)
+
+        pre = wx.PreDialog()
+        pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
+        pre.Create(parent, ID, title, pos, size, style)
+
+        self.PostCreate(pre)
+
+        sizer = wx.BoxSizer(wx.VERTICAL)
+
+        self.option_controls = {}
+
+        top_label_text = '%s %s' % ( option_parser.get_prog_name(),
+                                     option_parser.get_version() )
+        label = wx.StaticText(self, -1, top_label_text)
+        sizer.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
+
+        self.browse_option_map = {}
+
+        # Add controls for all the options
+        for option in option_parser.option_list:
+            if option.dest is None:
+                continue
+
+            if option.help is None:
+                option.help = u''
+
+            box = wx.BoxSizer(wx.HORIZONTAL)
+            if 'store' == option.action:
+                label = wx.StaticText(self, -1, option.dest )
+                label.SetHelpText( option.help )
+                box.Add( label, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
+
+                if 'choice' == option.type:
+                    if optparse.NO_DEFAULT == option.default:
+                        option.default = option.choices[0]
+                    ctrl = wx.ComboBox(
+                        self, -1, choices = option.choices,
+                        value = option.default,
+                        style = wx.CB_DROPDOWN | wx.CB_READONLY | wx.CB_SORT
+                    )
+                else:
+                    if 'MULTILINE' in option.help:
+                        ctrl = wx.TextCtrl( self, -1, "", size=(300,100), style = wx.TE_MULTILINE|wx.TE_PROCESS_ENTER )
+                    else:
+                        ctrl = wx.TextCtrl( self, -1, "", size=(300,-1) )
+
+                    if ( option.default != optparse.NO_DEFAULT ) and \
+                       ( option.default is not None ):
+                        ctrl.Value = unicode( option.default )
+
+                box.Add( ctrl, 1, wx.ALIGN_CENTRE|wx.ALL, 5 )
+
+                if option.type in ['file', 'directory']:
+                    browse = wx.Button(self, label='...')
+                    browse.SetHelpText( 'Click to open %s browser' % (option.type) )
+                    self.browse_option_map[browse.GetId()] = option, ctrl
+                    wx.EVT_BUTTON(self, browse.GetId(), self.OnSelectPath)
+                    box.Add( browse, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
+
+            elif option.action in ( 'store_true', 'store_false' ):
+                ctrl = wx.CheckBox( self, -1, option.dest, size = ( 300, -1 ) )
+                box.Add( ctrl, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )
+            else:
+                raise NotImplementedError ( 'Unknown option action: %s' % repr( option.action ) )
+
+            ctrl.SetHelpText( option.help )
+            sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
+
+            self.option_controls[ option ] = ctrl
+
+        # Add a text control for entering args
+        box = wx.BoxSizer( wx.HORIZONTAL )
+        label = wx.StaticText(self, -1, 'args' )
+        label.SetHelpText( 'This is the place to enter the args' )
+
+        self.args_ctrl = wx.TextCtrl( self, -1, '', size = ( -1, 100 ),
+                            style=wx.TE_MULTILINE | wx.TE_PROCESS_ENTER )
+        self.args_ctrl.SetHelpText(
+'''Args can either be separated by a space or a newline
+Args the contain spaces must be entered like so: "arg with sapce"
+'''
+        )
+        box.Add( label, 0, wx.ALIGN_CENTRE | wx.ALL, 5 )
+        box.Add( self.args_ctrl, 1, wx.ALIGN_CENTRE | wx.ALL, 5 )
+
+        sizer.Add( box , 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)
+
+        line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
+        sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)
+
+        btnsizer = wx.StdDialogButtonSizer()
+
+        if wx.Platform != "__WXMSW__":
+            btn = wx.ContextHelpButton(self)
+            btnsizer.AddButton(btn)
+
+        btn = wx.Button(self, wx.ID_OK)
+        btn.SetHelpText("The OK button completes the dialog")
+        btn.SetDefault()
+        btnsizer.AddButton(btn)
+
+        btn = wx.Button(self, wx.ID_CANCEL)
+        btn.SetHelpText("The Cancel button cancels the dialog. (Cool, huh?)")
+        btnsizer.AddButton(btn)
+        btnsizer.Realize()
+
+        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
+
+        self.SetSizer(sizer)
+        sizer.Fit(self)
+
+    def OnSelectPath(self, event):
+        option, ctrl = self.browse_option_map[event.GetId()]
+        path = os.path.abspath(ctrl.Value)
+        if option.type == 'file':
+            dlg = wx.FileDialog(self,
+                                message = 'Select file for %s' % (option.dest),
+                                defaultDir = os.path.dirname(path),
+                                defaultFile = path)
+        elif option.type == 'directory':
+            if os.path.isfile (path):
+                path = os.path.dirname (path)
+            dlg = wx.DirDialog(self,
+                               message = 'Select directory for %s' % (option.dest),
+                               defaultPath = path)
+        else:
+            raise NotImplementedError(`option.type`)
+        dlg_result = dlg.ShowModal()
+        if wx.ID_OK != dlg_result:
+            return
+        ctrl.Value = dlg.GetPath()
+##        import open_py_shell;open_py_shell.open_py_shell( locals() )
+
+    def _getOptions( self ):
+        option_values = {}
+        for option, ctrl in self.option_controls.iteritems():
+            option_values[option] = ctrl.Value
+
+        return option_values
+
+    def _getArgs( self ):
+        args_buff = self.args_ctrl.Value
+        args = re.findall( r'(?:((?:(?:\w|\d)+)|".*?"))\s*', args_buff )
+        return args
+
+    def getOptionsAndArgs( self ):
+        '''Returns the tuple ( options, args )
+        options -  a dictionary of option names and values
+        args - a sequence of args'''
+
+        option_values = self._getOptions()
+        args = self._getArgs()
+        return option_values, args
+
+class UserCancelledError( Exception ):
+    pass
+
+class Option (optparse.Option):
+    SUPER = optparse.Option
+    TYPES = SUPER.TYPES + ('file', 'directory')
+
+class OptionParser( optparse.OptionParser ):
+    SUPER = optparse.OptionParser
+
+    def __init__( self, *args, **kwargs ):
+        if wx.GetApp() is None:
+            self.app = wx.App( False )
+
+        if 'option_class' not in kwargs:
+            kwargs['option_class'] = Option
+        self.SUPER.__init__( self, *args, **kwargs )
+
+    def parse_args( self, args = None, values = None ):
+        '''
+        This is the heart of it all - overrides optparse.OptionParser.parse_args
+        @param arg is irrelevant and thus ignored,
+               it's here only for interface compatibility
+        '''
+        # preprocess command line arguments and set to defaults
+        option_values, args = self.SUPER.parse_args(self, args, values)
+        for option in self.option_list:
+            if option.dest and hasattr(option_values, option.dest):
+                default = getattr(option_values, option.dest)
+                if default is not None:
+                    option.default = default
+
+        dlg = OptparseDialog( option_parser = self )
+
+        if args:
+            dlg.args_ctrl.Value = ' '.join(args)
+
+        dlg_result = dlg.ShowModal()
+        if wx.ID_OK != dlg_result:
+            raise UserCancelledError( 'User has canceled' )
+
+        if values is None:
+            values = self.get_default_values()
+
+        option_values, args = dlg.getOptionsAndArgs()
+
+        for option, value in option_values.iteritems():
+            if ( 'store_true' == option.action ) and ( value is False ):
+                setattr( values, option.dest, False )
+                continue
+            if ( 'store_false' == option.action ) and ( value is True ):
+                setattr( values, option.dest, False )
+                continue
+
+            if option.takes_value() is False:
+                value = None
+
+            option.process( option, value, values, self )
+
+        return values, args
+
+    def error( self, msg ):
+        wx.MessageDialog( None, msg, 'Error!', wx.ICON_ERROR ).ShowModal()
+        return self.SUPER.error( self, msg )
+
+
+################################################################################
+
+def sample_parse_args():
+    usage = "usage: %prog [options] args"
+    if 1 == len( sys.argv ):
+        option_parser_class = OptionParser
+    else:
+        option_parser_class = optparse.OptionParser
+
+    parser = option_parser_class( usage = usage, version='0.1' )
+    parser.add_option("-f", "--file", dest="filename", default = r'c:\1.txt',
+                      help="read data from FILENAME")
+    parser.add_option("-t", "--text", dest="text", default = r'c:\1.txt',
+                      help="MULTILINE text field")
+    parser.add_option("-a", "--action", dest="action",
+                      choices = ['delete', 'copy', 'move'],
+                      help="Which action do you wish to take?!")
+    parser.add_option("-n", "--number", dest="number", default = 23,
+                      type = 'int',
+                      help="Just a number")
+    parser.add_option("-v", "--verbose",
+                      action="store_true", dest="verbose",
+                      help = 'To be or not to be? ( verbose )' )
+
+    (options, args) = parser.parse_args()
+    return options, args
+
+def sample_parse_args_issue1():
+    usage = "usage: %prog [options] args"
+    option_parser_class = OptionParser
+
+    parser = option_parser_class( usage = usage, version='0.1' )
+    parser.add_option("-f", "--file", dest="filename", default = r'c:\1.txt',
+                      type = 'file',
+                      help="read data from FILENAME")
+    parser.add_option("-t", "--text", dest="text", default = r'c:\1.txt',
+                      help="MULTILINE text field")
+    parser.add_option("-a", "--action", dest="action",
+                      choices = ['delete', 'copy', 'move'],
+                      help="Which action do you wish to take?!")
+    parser.add_option("-n", "--number", dest="number", default = 23,
+                      type = 'int',
+                      help="Just a number")
+    parser.add_option("-v", "--verbose",
+                      action="store_true", dest="verbose",
+                      help = 'To be or not to be? ( verbose )' )
+
+    (options, args) = parser.parse_args()
+    return options, args
+
+def main():
+    options, args = sample_parse_args_issue1()
+    print 'args: %s' % repr( args )
+    print 'options: %s' % repr( options )
+
+if '__main__' == __name__:
+    main()
diff --git a/optparse-gui/setup.py b/optparse-gui/setup.py
new file mode 100644 (file)
index 0000000..fc52cf5
--- /dev/null
@@ -0,0 +1,40 @@
+from optparse_gui import __version__
+
+import ez_setup
+ez_setup.use_setuptools()
+
+from setuptools import setup, find_packages
+
+setup(
+    name = "optparse_gui",
+    version = str( __version__ ),
+    packages = find_packages(exclude=["tests"]),
+
+    author = "slider fry",
+    author_email = "slider.fry@gmail.com",
+    description = "import optparse_gui as optparse - wx gui frontend for optparse",
+    license = "BSD",
+    keywords = "python gui wx commandline optparse",
+    url = "http://optparse-gui.googlecode.com",
+    zip_safe = True,
+    #install_requires = [ 'wxPython' ],
+    classifiers = [
+        'Development Status :: 3 - Alpha',
+        'Environment :: Win32 (MS Windows)',
+        'Environment :: X11 Applications',
+        'Intended Audience :: Developers',
+        'License :: OSI Approved :: BSD License',
+        'Operating System :: Microsoft :: Windows',
+        'Operating System :: POSIX',
+        'Operating System :: OS Independent',
+        'Operating System :: MacOS',
+        'Programming Language :: Python',
+        'Topic :: Software Development'
+    ],
+    long_description = \
+'''
+**optparse_gui** is a drop-in replacement for *optparse*.
+It allows entering command line arguments in a dynamically generated wx-based dialog.
+''',
+    download_url = r'http://optparse-gui.googlecode.com/files/optparse_gui-%s.zip' % __version__
+)
\ No newline at end of file
diff --git a/optparse-gui/tests/__init__.py b/optparse-gui/tests/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/optparse-gui/tests/test.py b/optparse-gui/tests/test.py
new file mode 100644 (file)
index 0000000..a5767d4
--- /dev/null
@@ -0,0 +1,31 @@
+import sys
+import optparse
+import optparse_gui
+
+def main():
+    usage = "usage: %prog [options] args"
+    if 1 == len( sys.argv ):
+        option_parser_class = optparse_gui.OptionParser
+    else:
+        option_parser_class = optparse.OptionParser
+        
+    parser = option_parser_class( usage = usage, version='0.1' )
+    parser.add_option("-f", "--file", dest="filename", default = r'c:\sample.txt',
+                      help="read data from FILENAME")
+    parser.add_option("-a", "--action", dest="action",
+                      choices = ['delete', 'copy', 'move'],
+                      help="Which action do you wish to take?!")
+    parser.add_option("-n", "--number", dest="number", default = 23,
+                      type = 'int',
+                      help="Just a number")
+    parser.add_option("-v", "--verbose",
+                      action="store_true", dest="verbose",
+                      help = 'To be or not to be? ( verbose )')
+    
+    options, args = parser.parse_args()
+
+    print 'args: %s' % args
+    print 'options: %s' % options
+
+if '__main__' == __name__:
+    main()
diff --git a/src/__init__.py b/src/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/__init__.pyc b/src/__init__.pyc
new file mode 100644 (file)
index 0000000..ec63200
Binary files /dev/null and b/src/__init__.pyc differ
diff --git a/src/core/BaseClientAuditController.py b/src/core/BaseClientAuditController.py
new file mode 100644 (file)
index 0000000..3c035df
--- /dev/null
@@ -0,0 +1,128 @@
+from Queue import Empty
+from exceptions import Exception
+import logging
+import sys
+from threading import Thread
+from src.core.ClientAuditorServer import ClientAuditorServer
+from src.core.ClientConnectionAuditEvent import ClientAuditResult
+from src.core.ConfigError import ConfigError
+from src.core.FileBag import FileBag
+from src.test.ExternalCommandHammer import CurlHammer
+from src.test.SSLConnectionHammer import ChainVerifyingSSLConnectionHammer, CNVerifyingSSLConnectionHammer
+from src.test.TCPConnectionHammer import TCPConnectionHammer
+
+HOST_ADDR_ANY = '0.0.0.0'
+
+MODULE_MODULE_NAME_PREFIX = 'src.modules'
+PROFILE_FACTORY_MODULE_NAME = 'ProfileFactory'
+PROFILE_FACTORY_CLASS_NAME = 'ProfileFactory'
+
+PROG_NAME = 'sslcaudit'
+PROG_VERSION = '1.0'
+
+class BaseClientAuditController(Thread):
+    logger = logging.getLogger('BaseClientAuditController')
+
+    def __init__(self, options):
+        Thread.__init__(self, target=self.run)
+        self.options = options
+        self.queue_read_timeout = 0.1
+
+        if self.options.debug_level > 0:
+            logging.getLogger().setLevel(logging.DEBUG)
+
+        self.file_bag = FileBag(self.options.test_name)
+
+        self.init_profile_factories()
+
+        self.server = ClientAuditorServer(self.options.listen_on, self.profile_factories)
+        self.res_queue = self.server.res_queue
+
+        #self.logger.info('initialized with options %s' % str(self.options))
+
+        self.init_self_tests()
+
+    def init_profile_factories(self):
+        self.profile_factories = []
+
+        for module_name in self.options.modules.split(','):
+            # load the module from under MODULE_NAME_PREFIX
+            module_name = MODULE_MODULE_NAME_PREFIX + "." + module_name + '.' + PROFILE_FACTORY_MODULE_NAME
+            try:
+                __import__(module_name, fromlist=[])
+            except Exception as ex:
+                raise ConfigError("cannot load module %s, exception: %s" % (module_name, ex))
+
+            # find and instantiate the profile factory class
+            profile_factory_class = sys.modules[module_name].__dict__[PROFILE_FACTORY_CLASS_NAME]
+            self.profile_factories.append(profile_factory_class(self.file_bag, self.options))
+
+        # there must be some profile factories in the list, otherwise we die right here
+        if len(self.profile_factories) == 0:
+            raise ConfigError("no single profile factory configured, nothing to do")
+
+    def start(self):
+        self.do_stop = False
+        self.server.start()
+        Thread.start(self)
+
+        if self.selftest_hammer is not None:
+            self.selftest_hammer.start()
+
+    def stop(self):
+        # signal the controller thread to stop
+        self.do_stop = True
+
+    def run(self):
+        '''
+        SSLCAuditCLI loop function. Will run until the desired number of clients is handled.
+        '''
+        nresults = 0
+
+        # loop until get all desired results, quit if stopped
+        while nresults < self.options.nclients and not self.do_stop:
+            try:
+                # wait for a message blocking for short intervals, check stop flag frequently
+                res = self.server.res_queue.get(True, self.queue_read_timeout)
+                self.logger.debug("got result %s", res)
+                self.handle_result(res)
+
+                if isinstance(res, ClientAuditResult):
+                    nresults = nresults + 1
+            except Empty:
+                pass
+
+    def handle_result(self, res):
+        raise NotImplemented('subclasses must override this method')
+
+    def init_self_tests(self):
+        # determine where to connect to
+        if self.options.listen_on[0] == HOST_ADDR_ANY:
+            peer_host = 'localhost'
+        else:
+            peer_host = self.options.listen_on[0]
+        peer = (peer_host, self.options.listen_on[1])
+
+        # instantiate hammer class
+        if self.options.self_test is None:
+            self.selftest_hammer = None
+        else:
+            if self.options.self_test == 0:
+                self.selftest_hammer = TCPConnectionHammer(-1)
+
+            elif self.options.self_test == 1:
+                if self.options.user_cn is not None:
+                    self.selftest_hammer = CNVerifyingSSLConnectionHammer(-1, 'hello')
+                else:
+                    raise ConfigError('test mode 1 requires --user-cn')
+
+            elif self.options.self_test == 2:
+                if self.options.user_ca_cert_file is not None:
+                    self.selftest_hammer = CurlHammer(-1, self.options.user_ca_cert_file)
+                else:
+                    raise ConfigError('test mode 2 requires --user-ca-cert/--user-ca-key')
+            else:
+                raise ConfigError('invalid selftest number %d' % self.options.self_test)
+
+            # set the peer for the hammer
+            self.selftest_hammer.set_peer(peer)
diff --git a/src/core/BaseClientAuditController.pyc b/src/core/BaseClientAuditController.pyc
new file mode 100644 (file)
index 0000000..627351f
Binary files /dev/null and b/src/core/BaseClientAuditController.pyc differ
diff --git a/src/core/CertFactory.py b/src/core/CertFactory.py
new file mode 100644 (file)
index 0000000..30f205f
--- /dev/null
@@ -0,0 +1,234 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import socket
+
+from M2Crypto import X509, ASN1, RSA, EVP, util, SSL
+import M2Crypto
+from M2Crypto.SSL import SSLError
+from src.core.ConfigError import ConfigError
+
+DEFAULT_X509_C = 'BE'
+DEFAULT_X509_ORG = 'Gremwell bvba'
+SELFSIGNED = 'SELF'
+BITS=1024
+
+CERT_FILE_SUFFIX = '-cert.pem'
+KEY_FILE_SUFFIX = '-key.pem'
+
+class CertAndKey(object):
+    '''
+    This class holds:
+     * object name
+     * X509 certificate object
+     * path to the cert file
+     * path to the key file
+    '''
+
+    def __init__(self, name, cert_filename, key_filename, cert, pkey):
+        self.name = name
+        self.cert = cert
+        self.cert_filename = cert_filename
+        self.key_filename = key_filename
+
+        if cert == None:
+            self.cert = X509.load_cert(self.cert_filename)
+        else:
+            self.cert = cert
+
+        if pkey == None:
+            self.pkey = EVP.load_key(self.key_filename)
+        else:
+            self.pkey = pkey
+
+    def __repr__(self):
+        return "CertAndKey%s" % self.__dict__
+
+    def __str__(self):
+        return str(self.name)
+
+
+DEFAULT_BITS = 1024
+
+class CertFactory(object):
+    '''
+    This class provides methods to generate new X509 certificates and corresponding
+    keys, encapsulated into CertAndKey objects.
+    '''
+
+    def __init__(self, file_bag):
+        self.file_bag = file_bag
+
+    def load_certnkey_files(self, cert_file, key_file):
+        '''
+        This function loads the content of the certificate file
+        and initializes paths to the certificate and the key.
+           '''
+        try:
+            cert = X509.load_cert(cert_file)
+        except M2Crypto.X509.X509Error as ex:
+            raise ConfigError('failed to parse cert file %s, exception: %s' % (cert_file, ex))
+
+        try:
+            pkey = EVP.load_key(key_file)
+        except M2Crypto.EVP.EVPError as ex:
+            raise ConfigError('failed to parse key file %s, exception: %s' % (key_file, ex))
+
+        return CertAndKey(cert.get_subject().CN, cert_file, key_file, cert, pkey)
+
+    def mk_certreq_n_keys(self, cn, v3_exts=[]):
+        '''
+        This function creates a certificate request with following attributes:
+         * given common name, organization, and country
+         * maximum validity period
+         * given extensions
+        Returns the certificate request and the keys as a tuple (X509, EVP, RSA)
+        '''
+        bits = DEFAULT_BITS
+
+        # subject
+        subj = X509.X509_Name()
+        subj.CN = cn
+        subj.C = DEFAULT_X509_C
+        subj.O = DEFAULT_X509_ORG
+
+        # maximum possible validity time frame
+        not_before = ASN1.ASN1_UTCTIME()
+        not_before.set_time(0)
+        not_after = ASN1.ASN1_UTCTIME()
+        not_after.set_time(2 ** 31 - 1)
+
+        return self.dododo(bits, subj, not_before, not_after, v3_exts)
+
+    def dododo(self, bits, subj, not_before, not_after, v3_exts, version=3):
+        # create a new keypair
+        rsa_keypair = RSA.gen_key(bits, 65537, util.no_passphrase_callback)
+        pkey = EVP.PKey()
+        pkey.assign_rsa(rsa_keypair, capture=False)
+
+        # create certificate request
+        cert_req = X509.X509()
+        cert_req.set_version(version)
+        cert_req.set_subject(subj)
+        cert_req.set_pubkey(pkey)
+        cert_req.set_not_before(not_before)
+        cert_req.set_not_after(not_after)
+
+        for ext in v3_exts:
+            cert_req.add_ext(ext)
+
+        return (cert_req, pkey, rsa_keypair)
+
+    def sign_cert_req(self, certreq_n_keys, ca_certnkey):
+        '''
+        This function signs the certificate request.
+        Expects a tuple (X509, EVP, RSA) as returned by mk_certreq_n_keys().
+        Returns CertAndKey() object.
+        '''
+        (cert_req, pkey, rsa_keypair) = certreq_n_keys
+
+        # hardcoded parameters
+        md = 'sha1'
+
+        # XXX
+        cert_req.set_serial_number(1)
+
+        # set issuer
+        if ca_certnkey != None:
+            cert_req.set_issuer(ca_certnkey.cert.get_subject())
+        else:
+            cert_req.set_issuer(cert_req.get_subject())
+
+        # sign
+        if ca_certnkey != None:
+            cert_req.sign(ca_certnkey.pkey, md)
+            signed_by = ca_certnkey.name
+        else:
+            cert_req.sign(pkey, md)
+            signed_by = SELFSIGNED
+
+        # save the certificate in a file
+        (cert_file, key_file) = self.file_bag.mk_two_files(suffix1=CERT_FILE_SUFFIX, suffix2=KEY_FILE_SUFFIX)
+        cert_file.write(cert_req.as_text())
+        cert_file.write(cert_req.as_pem())
+        if ca_certnkey != None:
+            cert_file.write(ca_certnkey.cert.as_text())
+            cert_file.write(ca_certnkey.cert.as_pem())
+        cert_file.close()
+
+        # save the private key in a file
+        rsa_keypair.save_key(key_file.name, None)
+        key_file.close()
+
+        return CertAndKey((cert_req.get_subject().CN, signed_by), cert_file.name, key_file.name, cert_req, pkey)
+
+    def grab_server_x509_cert(self, server, protocol):
+        '''
+        This function connects to the specified server and grabs its certificate.
+        Expects (server, port) tuple as input.
+        '''
+        # create context
+        ctx = SSL.Context(protocol=protocol)
+        ctx.set_allow_unknown_ca(True)
+        ctx.set_verify(SSL.verify_none, 0)
+
+        # establish TCP connection to the server
+        sock = socket.create_connection(server)
+
+        # prepare SSL context
+        sslsock = SSL.Connection(ctx, sock=sock)
+        sslsock.set_post_connection_check_callback(None)
+        sslsock.setup_ssl()
+        sslsock.set_connect_state()
+
+        # try to establish SSL connection
+        try:
+            sslsock.connect_ssl()
+            ssl_connect_ex = None
+        except SSLError as ex:
+            # this exception is not necessarily a deal breaker
+            # save it until we check if server certificate is available
+            ssl_connect_ex = ex
+
+        # grab server certificate and shut the connection
+        server_cert = sslsock.get_peer_cert()
+        sslsock.close()
+
+        if server_cert is None:
+            # failed to grab the certificate, rethrow the exception
+            raise ssl_connect_ex
+
+        return server_cert
+
+    def mk_replica_certreq_n_keys(self, orig_cert):
+        '''
+        This function creates a certificate request replicating given certificate. It returns a tuple of certificate and
+        Most of the fields of the original certificates are replicated:
+         * key length
+         * subject
+         * validity dates
+         * serial number
+         * version
+         * extensions
+        Couple parameters don't get replicated (because I don't know where to find them in M2Crypto.X509 object):
+         * public key exponent which is fixed to 65537,
+         * signature algorithm which is fixed to sha1WithRSAEncryption.
+        '''
+
+        # copy certificate attributes
+        public_key = orig_cert.get_pubkey()
+
+        bits = public_key.get_rsa().__len__()
+        subj = orig_cert.get_subject()
+        not_before = orig_cert.get_not_before()
+        not_after = orig_cert.get_not_after()
+        version = orig_cert.get_version()
+
+        v3_exts = []
+        for i in range(orig_cert.get_ext_count()):
+            v3_exts.append(orig_cert.get_ext_at(i))
+
+        return self.dododo(bits, subj, not_before, not_after, v3_exts, version)
diff --git a/src/core/CertFactory.pyc b/src/core/CertFactory.pyc
new file mode 100644 (file)
index 0000000..97dca66
Binary files /dev/null and b/src/core/CertFactory.pyc differ
diff --git a/src/core/ClientAuditorServer.py b/src/core/ClientAuditorServer.py
new file mode 100644 (file)
index 0000000..11818d4
--- /dev/null
@@ -0,0 +1,83 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import  logging
+from SocketServer import TCPServer
+import socket
+from threading import Thread
+from Queue import Queue
+from src.core.ClientConnection import ClientConnection
+from src.core.ClientHandler import ClientHandler
+
+logger = logging.getLogger('ClientAuditorTCPServer')
+
+#class ClientAuditorTCPServer(ThreadingMixIn, TCPServer):
+class ClientAuditorTCPServer(TCPServer):
+    '''
+    This class extends TCPServer to enforce address reuse, enforce daemon threads, and allow threading.
+    '''
+
+    def __init__(self, listen_on):
+        TCPServer.__init__(self, listen_on, None, bind_and_activate=False)
+        self.daemon_threads = True
+        # make sure SO_REUSE_ADDR socket option is set
+        self.allow_reuse_address = True
+
+        try:
+            self.server_bind()
+        except socket.error as ex:
+            raise RuntimeError('failed to bind to %s, exception: %s' % (listen_on, ex))
+
+        self.server_activate()
+
+
+class ClientAuditorServer(Thread):
+    '''
+    This class with specification of listen port, a list of profiles, and result queue.
+    It works in a separate Thread and uses ClientAuditorTCPServer server to receive connections from clients under test.
+    It distinguishes between different clients by their IP addresses. It creates an instance of ClientHandler class
+    for each individual client and calls ClientHandler.handle() for each incoming connection.
+    By itself this class does not interpret the content of 'profiles' in any way, just passes it to the constructor of
+    ClientHandler. If res_queue is None, this class will create its own Queue and make accessible to users of this class
+    via ClientAuditorServer res_queue.
+    '''
+
+    def __init__(self, listen_on, profiles, res_queue=None):
+        Thread.__init__(self, target=self.run)
+        self.daemon = True
+
+        self.listen_on = listen_on
+        self.clients = {}
+        self.profiles = profiles
+
+        # create a local result queue unless one is already provided
+        if res_queue == None:
+            self.res_queue = Queue()
+        else:
+            self.res_queue = res_queue
+
+        # create TCP server and make it use our method to handle the requests
+        self.tcp_server = ClientAuditorTCPServer(self.listen_on)
+        self.tcp_server.finish_request = self.finish_request
+
+    def finish_request(self, sock, client_address):
+        # this method overrides TCPServer implementation and actually handles new connections
+
+        # create new conn object and obtain client id
+        conn = ClientConnection(sock, client_address)
+        client_id = conn.get_client_id()
+
+        # find or create a session handler
+        if not self.clients.has_key(client_id):
+            logger.debug('new client %s [id %s]', conn, client_id)
+            self.clients[client_id] = ClientHandler(client_id, self.profiles, self.res_queue)
+
+        # handle the request
+        self.clients[client_id].handle(conn)
+
+    def run(self):
+        logger.debug('running %s, listen_on %s, profiles %s', self, self.listen_on, self.profiles)
+        self.tcp_server.serve_forever()
diff --git a/src/core/ClientAuditorServer.pyc b/src/core/ClientAuditorServer.pyc
new file mode 100644 (file)
index 0000000..6f6fdf2
Binary files /dev/null and b/src/core/ClientAuditorServer.pyc differ
diff --git a/src/core/ClientConnection.py b/src/core/ClientConnection.py
new file mode 100644 (file)
index 0000000..d28bd21
--- /dev/null
@@ -0,0 +1,21 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+class ClientConnection(object):
+    def __init__(self, sock, client_address):
+        self.sock = sock
+        self.client_address = client_address
+        self.sockname = self.sock.getsockname()
+
+    def get_client_id(self):
+        '''
+        This function returns a key is used to distinguish between different clients under test.
+        In the current implementation we use client IP address as a key.
+        '''
+        return self.client_address[0]
+
+    def __str__(self):
+        return "%s [%s->%s]" % (self.get_client_id(), self.client_address, self.sockname)
diff --git a/src/core/ClientConnection.pyc b/src/core/ClientConnection.pyc
new file mode 100644 (file)
index 0000000..fba310a
Binary files /dev/null and b/src/core/ClientConnection.pyc differ
diff --git a/src/core/ClientConnectionAuditEvent.py b/src/core/ClientConnectionAuditEvent.py
new file mode 100644 (file)
index 0000000..e9a6924
--- /dev/null
@@ -0,0 +1,56 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+class ClientConnectionAuditEvent(object):
+    '''
+    This is a base class for events produced while auditing client connections.
+    '''
+    def __init__(self, conn, profile):
+        self.profile = profile
+        self.conn = conn
+
+    def __eq__(self, other):
+        return (self.__class__ == other.__class__) and (self.__dict__ == other.__dict__)
+
+
+class ClientConnectionAuditResult(ClientConnectionAuditEvent):
+    '''
+    This class contains audit results returned by handle() method of subclasses of BaseServerHandler. It
+    contains the results of the audit of a single connection.
+    '''
+
+    def __init__(self, conn, profile, res):
+        ClientConnectionAuditEvent.__init__(self, conn, profile)
+        self.res = res
+
+    def __str__(self):
+        return ' CCAR(%s[%s], %s)' % (self.profile, self.profile.certnkey.cert_filename, self.res)
+
+class ClientAuditStartEvent(ClientConnectionAuditEvent):
+    '''
+    This event is generated by ClientHandler on very first connection.
+    '''
+    pass
+
+
+class ClientAuditEndEvent(ClientConnectionAuditEvent):
+    '''
+    This event is generated by ClientHandler after very last connection.
+    '''
+    pass
+
+class ClientAuditResult(object):
+    '''
+    This event is generated by ClientHandler after very last connection, after ClientAuditEndEvent. It contains results
+    produced by handle() methods of all client connection auditors, for a single client.
+    '''
+
+    def __init__(self, client_id):
+        self.client_id = client_id
+        self.results = []
+
+    def add(self, res):
+        self.results.append(res)
diff --git a/src/core/ClientConnectionAuditEvent.pyc b/src/core/ClientConnectionAuditEvent.pyc
new file mode 100644 (file)
index 0000000..be0ae41
Binary files /dev/null and b/src/core/ClientConnectionAuditEvent.pyc differ
diff --git a/src/core/ClientHandler.py b/src/core/ClientHandler.py
new file mode 100644 (file)
index 0000000..5d900d6
--- /dev/null
@@ -0,0 +1,96 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import logging, itertools
+from exceptions import StopIteration
+from src.core.ClientConnectionAuditEvent import ClientAuditStartEvent, ClientAuditEndEvent, ClientAuditResult
+
+def try_iterator_length(iter):
+    '''
+    Tries to traverse the iterator and returns sequence length
+    '''
+    length = 0
+    while True:
+        try:
+            iter.next()
+            length += 1
+        except StopIteration:
+            return length
+
+class ClientHandler(object):
+    '''
+    Instances of this class hold information about the progress and the results of an audit of a single client.
+    Normally it gets instantiated on the very first connection from a client and same instance handles all subsequent
+    connections from the same client. For each connection it fetches a next auditor object from the predefined
+    auditor set and uses that auditor to test the connection. It sends ClientAuditStartEvent event on first client
+    connection. After each connection is handled, it pushes the result returned by the auditor, which normally is
+    ClientConnectionAuditResult or another subclass of ClientConnectionAuditEvent. After the last auditor has
+    finished its work it pushes ClientAuditEndEvent and ClientAuditResult into the queue.
+
+    Object states:
+        right after initialization: next_auditor = None, done = False
+        after first and subsequent connection: next_auditor = something, done = False
+        after set of auditors is exhausted: next_auditor = None, done = True
+
+    XXX race condition XXX
+    '''
+    logger = logging.getLogger('ClientHandler')
+
+    def __init__(self, client_id, profiles, res_queue):
+        self.client_id = client_id
+        self.result = ClientAuditResult(self.client_id)
+        self.res_queue = res_queue
+
+        self.nprofiles = try_iterator_length(itertools.chain.from_iterable(profiles))
+        self.profiles_iterator = itertools.chain.from_iterable(profiles)
+        self.profiles_count = 0
+
+        self.next_profile = None
+
+        self.done = False
+
+    def handle(self, conn):
+        '''
+        This method is invoked when a new connection arrives.
+        '''
+        if self.done:
+            self.logger.debug('no more profiles for connection %s', conn)
+            return
+
+        if self.next_profile == None:
+            # this is a very first connection
+            try:
+                self.next_profile = self.profiles_iterator.next()
+                self.profiles_count = self.profiles_count + 1
+                self.res_queue.put(ClientAuditStartEvent(self.next_profile, self.client_id))
+            except StopIteration:
+                self.logger.debug('no profiles for connection %s (the iterator was empty)', conn)
+                self.res_queue.put(self.result)
+                self.done = True
+                return
+
+        # handle this connection
+        handler = self.next_profile.get_handler()
+        res = handler.handle(conn, self.next_profile)
+        self.logger.debug('connection from %s using %s (%d/%d) resulted in %s',
+            conn, self.next_profile, self.profiles_count, self.nprofiles, res)
+
+        # log and record the results of the test
+        #self.logger.debug('testing client conn %s using %s resulted in %s', conn, self.next_auditor, res)
+        self.logger.debug('testing connection %s using %s resulted in %s', conn, self.next_profile, res)
+        self.result.add(res)
+        self.res_queue.put(res)
+
+        # prefetch next auditor from the iterator, to check if this was the last one
+        try:
+            self.next_profile = self.profiles_iterator.next()
+            self.profiles_count = self.profiles_count + 1
+        except StopIteration:
+            # it was the last auditor in the set
+            self.logger.debug('no more tests for client conn %s', conn)
+            self.res_queue.put(ClientAuditEndEvent(self.next_profile, self.client_id))
+            self.res_queue.put(self.result)
+            self.done = True
diff --git a/src/core/ClientHandler.pyc b/src/core/ClientHandler.pyc
new file mode 100644 (file)
index 0000000..fef245f
Binary files /dev/null and b/src/core/ClientHandler.pyc differ
diff --git a/src/core/ConfigError.py b/src/core/ConfigError.py
new file mode 100644 (file)
index 0000000..395c7fe
--- /dev/null
@@ -0,0 +1,11 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+class ConfigError(Exception):
+    '''
+    The code has to throw this exception if it has a problem with input
+    parameters. Should only be thrown during startup.
+    '''
diff --git a/src/core/ConfigError.pyc b/src/core/ConfigError.pyc
new file mode 100644 (file)
index 0000000..7447c31
Binary files /dev/null and b/src/core/ConfigError.pyc differ
diff --git a/src/core/FileBag.py b/src/core/FileBag.py
new file mode 100644 (file)
index 0000000..971ce21
--- /dev/null
@@ -0,0 +1,73 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import os
+from tempfile import NamedTemporaryFile
+import errno
+import tempfile
+
+DEFAULT_BASENAME = 'sslcaudit'
+MAX_REV = 1000000
+DEFAULT_TMPDIR_PREFIX = 'filebag'
+
+class FileBag(object):
+    '''
+    This class
+    '''
+    def __init__(self, basename, use_tempdir=False):
+        if basename == None:
+            basename = DEFAULT_BASENAME
+
+        if use_tempdir:
+            basename = os.path.join(tempfile.mkdtemp(prefix=DEFAULT_TMPDIR_PREFIX), basename)
+
+        for rev in range(0, MAX_REV):
+            # create a path based on the base name and revision number
+            path = '%s.%d' % (basename, rev)
+
+            # try to create the directory, if already exist, retry with another revision number
+            try:
+                os.mkdir(path)
+            except OSError as ex:
+                if ex.errno != errno.EEXIST:
+                    raise ex
+                else:
+                    continue
+
+            # created
+            self.base_dir = path
+            return
+
+        # was unable to create any directory
+        raise RuntimeError("can't find a free numeric suffix for basename %s" % basename)
+
+    def mk_file(self, suffix='', prefix=tempfile.template):
+        return NamedTemporaryFile(dir=self.base_dir, prefix=prefix, suffix=suffix, delete=False)
+
+    def mk_two_files(self, suffix1, suffix2, prefix=tempfile.template):
+        while True:
+            # create the first file
+            f1 = NamedTemporaryFile(dir=self.base_dir, prefix=prefix, suffix=suffix1, delete=False)
+            # the name of the second file is the same as the first one, but with different suffix
+            f2name = f1.name[:-len(suffix1)] + suffix2
+
+            if os.path.exists(f2name):
+                # a file with a name matching desired f2 name already exists
+                try:
+                    # remove the first file
+                    os.unlink(f1)
+                except:
+                    # XXX
+                    pass
+
+                # try from the beginning
+                continue
+            else:
+                # create the second file
+                # XXX race condition here, but rather unlikely to happen
+                f2 = open(f2name, 'w')
+
+                return (f1, f2)
diff --git a/src/core/FileBag.pyc b/src/core/FileBag.pyc
new file mode 100644 (file)
index 0000000..022e92b
Binary files /dev/null and b/src/core/FileBag.pyc differ
diff --git a/src/core/SSLCAuditCLI.py b/src/core/SSLCAuditCLI.py
new file mode 100644 (file)
index 0000000..ec969b4
--- /dev/null
@@ -0,0 +1,110 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import logging
+from optparse import OptionParser
+from src.core import Utils
+from src.core.BaseClientAuditController import BaseClientAuditController, PROG_NAME, PROG_VERSION, HOST_ADDR_ANY
+from src.core.ClientConnectionAuditEvent import ClientConnectionAuditResult
+from src.core.ConfigError import ConfigError
+
+FORMAT = '%(asctime)s %(name)s %(levelname)s   %(message)s'
+logging.basicConfig(level=logging.INFO, format=FORMAT)
+
+logger = logging.getLogger('SSLCAuditCLI')
+
+DEFAULT_HOST = HOST_ADDR_ANY
+DEFAULT_PORT = 8443
+DEFAULT_MODULES = 'sslcert'
+DEFAULT_LISTEN_ON = '%s:%d' % (DEFAULT_HOST, DEFAULT_PORT)
+OUTPUT_FIELD_SEPARATOR = ' '
+
+class SSLCAuditCLI(BaseClientAuditController):
+    def __init__(self, argv):
+        BaseClientAuditController.__init__(self, self.parse_options(argv))
+
+    def parse_options(self, argv):
+        parser = OptionParser(usage=('%s [OPTIONS]' % PROG_NAME), version=("%s %s" % (PROG_NAME, PROG_VERSION)))
+        parser.add_option("-l", dest="listen_on", default=DEFAULT_LISTEN_ON,
+            help='Specify IP address and TCP PORT to listen on, in format of HOST:PORT. '
+            + 'Default is %s' % DEFAULT_LISTEN_ON)
+        parser.add_option("-m", dest="modules", default=DEFAULT_MODULES,
+            help="Launch specific modules. For now the only functional module is 'sslcert'. "
+                 + "There is also 'dummy' module used for internal testing or as a template code for "
+            + "new modules. Default is %s" % DEFAULT_MODULES)
+        parser.add_option("-v", dest="verbose", default=0,
+            help="Increase verbosity level. Default is 0. Try 1.")
+        parser.add_option("-d", dest="debug_level", default=0,
+            help="Set debug level. Default is 0, which disables debugging output. Try 1 to enable it.")
+        parser.add_option("-c", dest="nclients", default=1,
+            help="Number of clients to handle before quitting. By default sslcaudit will quit as soon as "
+            + "it gets one client fully processed.")
+        parser.add_option("-N", dest="test_name",
+            help="Set the name of the test. If specified will appear in the leftmost column in the output.")
+        parser.add_option('-T', type='int', dest='self_test',
+            help='Launch self-test. 0 - plain TCP client, 1 - CN verifying client, 2 - curl.')
+
+        parser.add_option("--user-cn", dest="user_cn",
+            help="Set user-specified CN.")
+        parser.add_option("--server", dest="server",
+            help="Where to fetch the server certificate from, in HOST:PORT format.")
+        parser.add_option("--user-cert", dest="user_cert_file",
+            help="Set path to file containing the user-supplied certificate.")
+        parser.add_option("--user-key", dest="user_key_file",
+            help="Set path to file containing the user-supplied key.")
+        parser.add_option("--user-ca-cert", dest="user_ca_cert_file",
+            help="Set path to file containing certificate for user-supplied CA.")
+        parser.add_option("--user-ca-key", dest="user_ca_key_file",
+            help="Set path to file containing key for user-supplied CA.")
+
+        parser.add_option("--no-default-cn", action="store_true", default=False, dest="no_default_cn",
+            help=("Do not use default CN"))
+        parser.add_option("--no-self-signed", action="store_true", default=False, dest="no_self_signed",
+            help="Don't try self-signed certificates")
+        parser.add_option("--no-user-cert-signed", action="store_true", default=False, dest="no_user_cert_signed",
+            help="Do not sign server certificates with user-supplied one")
+
+        (options, args) = parser.parse_args(argv)
+        if len(args) > 0:
+            raise ConfigError("unexpected arguments: %s" % args)
+
+        # transform listen_on string into a tuple
+        try:
+            options.listen_on = Utils.parse_hostport(options.listen_on)
+        except ValueError as ex:
+            raise ConfigError("invalid value for -l parameter, exception: %s" % ex)
+
+        # transform server string into a tuple
+        if options.server is not None:
+            try:
+                options.server = Utils.parse_hostport(options.server)
+            except ValueError as ex:
+                raise ConfigError("invalid value for --server parameter, exception: %s" % ex)
+
+        return options
+
+    def run(self):
+        '''
+        Print config info to the console before running the controller
+        '''
+        if self.options.verbose > 0:
+            print '# filebag location: %s' % str(self.file_bag.base_dir)
+        BaseClientAuditController.run(self)
+
+    def handle_result(self, res):
+        if isinstance(res, ClientConnectionAuditResult):
+            # dump:
+            # * filebag path (only in verbose mode),
+            # * client address and port,
+            # * server profile
+            # * result
+            # all in one line, in fixed width columns
+            fields = []
+            client_address = '%s:%d' % (res.conn.client_address)
+            fields.append('%-16s' % client_address)
+            fields.append('%-60s' % (res.profile))
+            fields.append(str(res.res))
+            print OUTPUT_FIELD_SEPARATOR.join(fields)
diff --git a/src/core/SSLCAuditCLI.pyc b/src/core/SSLCAuditCLI.pyc
new file mode 100644 (file)
index 0000000..697b076
Binary files /dev/null and b/src/core/SSLCAuditCLI.pyc differ
diff --git a/src/core/Utils.py b/src/core/Utils.py
new file mode 100644 (file)
index 0000000..3dda85d
--- /dev/null
@@ -0,0 +1,34 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import re
+import socket
+
+def parse_hostport(hostport):
+    '''
+    This function receives HOST:PORT string specification (PORT is integer or a service name)
+    and converts it to (HOST, INTPORT) tuple, where INTPORT is a numeric value. Almost no
+    validation is done for the host name.
+    '''
+    match = re.match('^([\w\.\:\-]+):([\w\-]+)$', hostport)
+
+    if match is None:
+        raise ValueError('invalid HOST:PORT specification (bad format): %s' % hostport)
+
+    try:
+        # convert port to integer
+        port = int(match.group(2))
+        return (match.group(1), port)
+    except ValueError:
+        pass
+
+    try:
+        # try to lookup the port by TCP service name
+        port = socket.getservbyname(match.group(2), 'tcp')
+        return (match.group(1), port)
+    except socket.error:
+        raise ValueError('invalid HOST:PORT specification (unknown service): %s' % hostport)
+
diff --git a/src/core/Utils.pyc b/src/core/Utils.pyc
new file mode 100644 (file)
index 0000000..b30e9c4
Binary files /dev/null and b/src/core/Utils.pyc differ
diff --git a/src/core/__init__.py b/src/core/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/core/__init__.pyc b/src/core/__init__.pyc
new file mode 100644 (file)
index 0000000..e3141b7
Binary files /dev/null and b/src/core/__init__.pyc differ
diff --git a/src/modules/__init__.py b/src/modules/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/modules/__init__.pyc b/src/modules/__init__.pyc
new file mode 100644 (file)
index 0000000..1f55eab
Binary files /dev/null and b/src/modules/__init__.pyc differ
diff --git a/src/modules/base/BaseProfileFactory.py b/src/modules/base/BaseProfileFactory.py
new file mode 100644 (file)
index 0000000..9dd7322
--- /dev/null
@@ -0,0 +1,43 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+class BaseProfileSpec(object):
+    def __eq__(self, other):
+        return self.__class__ == other.__class__ and self.__dict__ == other.__dict__
+
+class BaseProfile(object):
+    '''
+    Base object for all profiles.
+    Can return its specification.
+    Can return a suitable handler.
+    '''
+
+    def get_spec(self):
+        raise NotImplemented('subclasses must override this method')
+
+    def get_handler(self):
+        raise NotImplemented('subclasses must override this method')
+
+
+class BaseProfileFactory(object):
+    '''
+    This class contains a list of profiles (subclasses of BaseProfile class). Each module is
+    expected to contain a subclass of this class named ProfileFactory. Single instance of that subclass will be created
+    when module gets loaded during program startup. Its constructor will receive a dictionary of command-line options
+    and is expected to populate the list of profiles by invoking add_profile() method. The objects added into
+    this list should extend BaseProfile class.
+    '''
+
+    def __init__(self, file_bag, options):
+        self.file_bag = file_bag
+        self.options = options
+        self.profiles_ = []
+
+    def add_profile(self, profile):
+        self.profiles_.append(profile)
+
+    def __iter__(self):
+        return self.profiles_.__iter__()
diff --git a/src/modules/base/BaseProfileFactory.pyc b/src/modules/base/BaseProfileFactory.pyc
new file mode 100644 (file)
index 0000000..d036b4b
Binary files /dev/null and b/src/modules/base/BaseProfileFactory.pyc differ
diff --git a/src/modules/base/BaseServerHandler.py b/src/modules/base/BaseServerHandler.py
new file mode 100644 (file)
index 0000000..e5bba9f
--- /dev/null
@@ -0,0 +1,24 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+class BaseServerHandler(object):
+    '''
+    This is an abstract class for a server handler. Each client testing module is expected to at least one
+    subclass of this class. An instance that subclass are normally contained in a subclass of BaseProfileFactory,
+    created when the module gets loaded during program startup.
+
+    Subclasses of this class contain module-specific behavior and functionality to test incoming connections using
+    module-specific profiles.
+    '''
+
+    def handle(self, conn, profile):
+        '''
+        This method will be invoked by ClientHandler when new client connection arrives. It is expected to treat given
+        connection using given profile and return ClientConnectionAuditResult describing the outcome. This method gets
+        invoked multiple times, for different client connections, for different profiles, so it must not change the
+        state of the object itself and be thread-safe.
+        '''
+        raise NotImplementedError('subclasses must override this method')
diff --git a/src/modules/base/BaseServerHandler.pyc b/src/modules/base/BaseServerHandler.pyc
new file mode 100644 (file)
index 0000000..4e65fc7
Binary files /dev/null and b/src/modules/base/BaseServerHandler.pyc differ
diff --git a/src/modules/base/__init__.py b/src/modules/base/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/modules/base/__init__.pyc b/src/modules/base/__init__.pyc
new file mode 100644 (file)
index 0000000..7487689
Binary files /dev/null and b/src/modules/base/__init__.pyc differ
diff --git a/src/modules/dummy/ProfileFactory.py b/src/modules/dummy/ProfileFactory.py
new file mode 100644 (file)
index 0000000..bb3d45c
--- /dev/null
@@ -0,0 +1,48 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+from src.modules.base.BaseProfileFactory import BaseProfileFactory
+from src.core.ClientConnectionAuditEvent import ClientConnectionAuditResult
+from src.modules.base.BaseServerHandler import BaseServerHandler
+
+class DummyServerProfile(object):
+    '''
+    This dummy profile contains one value only
+    '''
+
+    def __init__(self, value):
+        self.value = value
+
+    def __str__(self):
+        return 'dummy(%s)' % (value)
+
+    def get_handler(self):
+        return dummy_server_handler
+
+
+class DummyServerHandler(BaseServerHandler):
+    '''
+    This dummy server handler does nothing, but returns a value from the profile.
+    '''
+
+    def handle(self, conn, profile):
+        # do nothing with client connection
+        # just return a value from the profile as a result
+        return ClientConnectionAuditResult(conn, profile, profile.value)
+
+
+class ProfileFactory(BaseProfileFactory):
+    '''
+    This profile factory contains two dummy profiles and a dummy handler.
+    '''
+
+    def __init__(self, file_bag, options):
+        BaseProfileFactory.__init__(self, file_bag, options)
+
+        self.add_profile(DummyServerProfile(False))
+        self.add_profile(DummyServerProfile(True))
+
+dummy_server_handler = DummyServerHandler()
diff --git a/src/modules/dummy/__init__.py b/src/modules/dummy/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/modules/sslcert/ProfileFactory.py b/src/modules/sslcert/ProfileFactory.py
new file mode 100644 (file)
index 0000000..f1f6f29
--- /dev/null
@@ -0,0 +1,214 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+import socket
+from M2Crypto import X509
+import M2Crypto
+from src.core import Utils
+
+from src.core.ConfigError import ConfigError
+from src.core.CertFactory import CertFactory
+from src.modules.base.BaseProfileFactory import BaseProfileFactory, BaseProfile, BaseProfileSpec
+from src.modules.sslcert.SSLServerHandler import SSLServerHandler
+
+DEFAULT_CN = 'www.example.com'
+IM_CA_NONE_CN = 'ca-none'
+IM_CA_FALSE_CN = 'ca-false'
+IM_CA_TRUE_CN = 'ca-true'
+
+sslcert_server_handler = SSLServerHandler('sslv23')
+
+class SSLProfileSpec_SelfSigned(BaseProfileSpec):
+    def __init__(self, cn):
+        self.cn = cn
+
+    def __str__(self):
+        return "selfsigned(%s)" % self.cn
+
+class SSLProfileSpec_Signed(BaseProfileSpec):
+    def __init__(self, cn, ca_cn):
+        self.cn = cn
+        self.ca_cn = ca_cn
+
+    def __str__(self):
+        return "signed1(%s, %s)" % (self.cn, self.ca_cn)
+
+class SSLProfileSpec_IMCA_Signed(BaseProfileSpec):
+    def __init__(self, cn, im_ca_cn, ca_cn):
+        self.cn = cn
+        self.im_ca_cn = im_ca_cn
+        self.ca_cn = ca_cn
+
+    def __str__(self):
+        return "signed2(%s, %s, %s)" % (self.cn, self.im_ca_cn, self.ca_cn)
+
+class SSLProfileSpec_UserSupplied(BaseProfileSpec):
+    def __init__(self, cn):
+        self.cn = cn
+
+    def __str__(self):
+        return "user-supplied(%s)" % (self.cn)
+
+class SSLServerCertProfile(BaseProfile):
+    def __init__(self, profile_spec, certnkey):
+        self.profile_spec = profile_spec
+        self.certnkey = certnkey
+
+    def get_spec(self):
+        return self.profile_spec
+
+    def get_handler(self):
+        return sslcert_server_handler
+
+    def __str__(self):
+        return str(self.profile_spec)
+
+class ProfileFactory(BaseProfileFactory):
+    def __init__(self, file_bag, options, protocol='sslv23'):
+        BaseProfileFactory.__init__(self, file_bag, options)
+
+        self.protocol = protocol
+        self.cert_factory = CertFactory(self.file_bag)
+
+        self.init_options()
+
+        self.init_cert_requests()
+        self.add_profiles()
+
+    def init_options(self):
+        # handle --server= option
+        if self.options.server != None:
+            # fetch X.509 certificate from user-specified server
+            try:
+                self.server_x509_cert = self.cert_factory.grab_server_x509_cert(self.options.server, protocol=self.protocol)
+            except socket.error as ex:
+                raise RuntimeError('failed to fetch certificate from server %s, exception: %s' % (self.options.server, ex))
+        else:
+            self.server_x509_cert = None
+
+        # handle --user-cert and --user-key options
+        self.user_certnkey = self.load_certnkey(
+            '--user-cert', self.options.user_cert_file,
+            '--user-key', self.options.user_key_file)
+
+        # handle --user-ca-cert and --user-ca-key options
+        self.user_ca_certnkey = self.load_certnkey(
+            '--user-ca-cert', self.options.user_ca_cert_file,
+            '--user-ca-key', self.options.user_ca_key_file)
+
+    # ----------------------------------------------------------------------------------------------
+
+    def init_cert_requests(self):
+        self.certreq_n_keyss = []
+
+        if not self.options.no_default_cn:
+            req1 = self.cert_factory.mk_certreq_n_keys(cn=DEFAULT_CN)
+            self.certreq_n_keyss.append(req1)
+
+        if self.options.user_cn != None:
+            req2 = self.cert_factory.mk_certreq_n_keys(cn=self.options.user_cn)
+            self.certreq_n_keyss.append(req2)
+
+        if self.server_x509_cert != None:
+            cert_req3 = self.cert_factory.mk_replica_certreq_n_keys(self.server_x509_cert)
+            self.certreq_n_keyss.append(cert_req3)
+
+    def add_profiles(self):
+        if self.user_certnkey != None:
+            self.add_raw_user_certnkey_profile()
+
+        if not self.options.no_self_signed:
+            self.add_signed_profiles(ca_certnkey=None)
+
+        if self.user_certnkey != None:
+            self.add_signed_profiles(ca_certnkey=self.user_certnkey)
+
+        if self.user_ca_certnkey != None:
+            self.add_signed_profiles(ca_certnkey=self.user_ca_certnkey)
+            self.add_im_basic_constraints_profiles()
+
+    def add_raw_user_certnkey_profile(self):
+        spec = SSLProfileSpec_UserSupplied(self.user_certnkey.cert.get_subject().CN)
+        self.add_profile(SSLServerCertProfile(spec, self.user_certnkey))
+
+    def add_im_basic_constraints_profiles(self):
+        '''
+        This method initializes auditors testing for basicConstraints violations
+        '''
+
+        for cert_req in self.certreq_n_keyss:
+            self.add_im_basic_constraints_profile(cert_req, basicConstraint_CA=None)
+            self.add_im_basic_constraints_profile(cert_req, basicConstraint_CA=False)
+            self.add_im_basic_constraints_profile(cert_req, basicConstraint_CA=True)
+
+        # XXX if no user-cn and defalt-cn is disabled the test will be not performed silently
+
+    # ----------------------------------------------------------------------------------------------
+
+    def add_signed_profiles(self, ca_certnkey):
+        for certreq_n_keys in self.certreq_n_keyss:
+            cn = certreq_n_keys[0].get_subject().CN
+            if ca_certnkey == None:
+                cert_spec = SSLProfileSpec_SelfSigned(cn)
+            else:
+                ca_cn = ca_certnkey.cert.get_subject().CN
+                cert_spec = SSLProfileSpec_Signed(cn, ca_cn)
+
+            self.add_signed_profile(cert_spec, certreq_n_keys, ca_certnkey)
+
+    def add_signed_profile(self, cert_spec, certreq_n_keys, ca_certnkey):
+        certnkey = self.cert_factory.sign_cert_req(certreq_n_keys=certreq_n_keys, ca_certnkey=ca_certnkey)
+        self.add_profile(SSLServerCertProfile(cert_spec, certnkey))
+
+    def add_im_basic_constraints_profile(self, cert_req, basicConstraint_CA):
+        ca_certnkey = self.user_ca_certnkey
+
+        # create an intermediate authority, signed by user-supplied CA, possibly with proper constraints
+        if basicConstraint_CA != None:
+            if basicConstraint_CA:
+                ext_value="CA:TRUE"
+                im_ca_cn = IM_CA_TRUE_CN
+            else:
+                ext_value = "CA:FALSE"
+                im_ca_cn = IM_CA_FALSE_CN
+            ca_ext = X509.new_extension("basicConstraints", ext_value)
+            ca_ext.set_critical()
+            v3_exts=[ca_ext]
+        else:
+            v3_exts=[]
+            im_ca_cn = IM_CA_NONE_CN
+
+        # create the intermediate CA
+        im_ca_cert_req = self.cert_factory.mk_certreq_n_keys(cn=im_ca_cn, v3_exts=v3_exts)
+        im_ca_certnkey = self.cert_factory.sign_cert_req(im_ca_cert_req, ca_certnkey=ca_certnkey)
+
+        # create server certificate, signed by that authority
+        certnkey = self.cert_factory.sign_cert_req(cert_req, ca_certnkey=im_ca_certnkey)
+
+        # create auditor using that certificate
+        cn = certnkey.cert.get_subject().CN
+        ca_cn = ca_certnkey.cert.get_subject().CN
+        spec = SSLProfileSpec_IMCA_Signed(cn, im_ca_cn, ca_cn)
+        self.add_profile(SSLServerCertProfile(spec, certnkey))
+
+    def load_certnkey(self, cert_param, cert_file, key_param, key_file):
+        '''
+        This function loads X509 certificate from files and returns CertAndKey object.
+        It throws a sensible ConfigErrorException in case of parameter error or problems
+        with the input files.
+        '''
+        if (cert_file == None) and (key_file == None):
+            return None
+
+        if key_file == None:
+            raise ConfigError("if %s is set, %s must be set too" % (cert_param, key_param))
+
+        if cert_file == None:
+            raise ConfigError("if %s is set, %s must be set too" % (key_param, cert_param))
+
+        try:
+            return self.cert_factory.load_certnkey_files(cert_file, key_file)
+        except IOError as ex:
+            raise ConfigError('failed to load cert/key file, exception: %s' % ex)
diff --git a/src/modules/sslcert/ProfileFactory.pyc b/src/modules/sslcert/ProfileFactory.pyc
new file mode 100644 (file)
index 0000000..481aab3
Binary files /dev/null and b/src/modules/sslcert/ProfileFactory.pyc differ
diff --git a/src/modules/sslcert/SSLServerHandler.py b/src/modules/sslcert/SSLServerHandler.py
new file mode 100644 (file)
index 0000000..3db56e7
--- /dev/null
@@ -0,0 +1,143 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import M2Crypto, logging
+from time import time
+from M2Crypto.SSL.timeout import timeout
+from src.core.ClientConnectionAuditEvent import ClientConnectionAuditResult
+from src.modules.base.BaseServerHandler import BaseServerHandler
+
+DEFAULT_SOCK_READ_TIMEOUT = 3.0
+MAX_SIZE = 1024
+
+# --- some classes and constants here should be moved elsewhere, to be shared between different modules
+
+UNEXPECTED_EOF = 'unexpected eof'
+ALERT_UNKNOWN_CA = 'tlsv1 alert unknown ca'
+ALERT_CERT_UNKNOWN = 'sslv3 alert certificate unknown'
+
+class Connected(object): pass
+
+class ConnectedGotEOFBeforeTimeout(Connected):
+    def __init__(self, dt=None):
+        self.dt = dt
+
+    def __str__(self):
+        if self.dt != None:
+            dt_str = " (in %.3fs)" % self.dt
+        else:
+            dt_str = ''
+        return "connected, EOF before timeout%s" % dt_str
+
+    def __eq__(self, other):
+        # NB: ignore actual DT
+        return self.__class__ == other.__class__
+
+
+class ConnectedReadTimeout(Connected):
+    def __init__(self, dt=None):
+        self.dt = dt
+
+    def __str__(self):
+        if self.dt != None:
+            dt_str = " (in %.1fs)" % self.dt
+        else:
+            dt_str = ''
+        return "connected, read timeout%s" % dt_str
+
+    def __eq__(self, other):
+        # NB: ignore actual DT
+        return self.__class__ == other.__class__
+
+
+class ConnectedGotRequest(Connected):
+    def __init__(self, req=None, dt=None):
+        self.req = req
+        self.dt = dt
+
+    def __eq__(self, other):
+        # NB: ignore actual DT
+        if self.__class__ != other.__class__: return False
+
+        return self.req == None or self.req == other.req
+
+    def __str__(self):
+        if self.dt != None:
+            dt_str = '%.1fs' % self.dt
+        else:
+            dt_str = '?s'
+        if self.req != None:
+            noctets_str = '%d' % len(self.req)
+        else:
+            noctets_str = '?'
+        return 'connected, got %s octets in %s' % (noctets_str, dt_str)
+
+# ------------------
+
+class SSLServerHandler(BaseServerHandler):
+    '''
+    This class implements SSL/TLS server. Its handle() method tries to perform SSL/TLS handshake using provided
+    certificate and a key. If connection is successful, it waits for the client to send some data. In some cases
+    even if SSL session is set up a client terminates the connection right away (for example if it realises CN does
+    not match the expected value).
+    '''
+    logger = logging.getLogger('SSLServerHandler')
+
+    sock_read_timeout = DEFAULT_SOCK_READ_TIMEOUT
+
+    def __init__(self, proto):
+        BaseServerHandler.__init__(self)
+
+        self.proto = proto
+
+    def handle(self, conn, profile):
+        ctx = M2Crypto.SSL.Context(self.proto)
+        ctx.load_cert_chain(certchainfile=profile.certnkey.cert_filename, keyfile=profile.certnkey.key_filename)
+
+        self.logger.debug('trying to accept SSL connection %s with profile %s', conn, profile)
+        try:
+            # try to accept SSL connection
+            ssl_conn = M2Crypto.SSL.Connection(ctx=ctx, sock=conn.sock)
+            ssl_conn.set_socket_read_timeout(timeout(self.sock_read_timeout))
+            ssl_conn.setup_ssl()
+            ssl_conn_res = ssl_conn.accept_ssl()
+            if ssl_conn_res == 1:
+                self.logger.debug('SSL connection accepted')
+            else:
+                self.logger.debug('SSL handshake failed: %s', ssl_conn.ssl_get_error(ssl_conn_res))
+                res = ssl_conn.ssl_get_error(ssl_conn_res)
+                return ClientConnectionAuditResult(conn, profile, res)
+
+            # try to read something from the client
+            start_time = time()
+            client_req = ssl_conn.read(size=MAX_SIZE)
+            end_time = time()
+            dt = end_time - start_time
+
+            if client_req == None:
+                # read timeout
+                res = ConnectedReadTimeout(dt)
+            else:
+                if len(client_req) == 0:
+                    # EOF or timeout? XXX
+                    if dt < self.sock_read_timeout:
+                        res = ConnectedGotEOFBeforeTimeout(dt)
+                    else:
+
+                        res = ConnectedReadTimeout(dt)
+                else:
+                    # got data
+                    res = ConnectedGotRequest(client_req, dt)
+        except Exception as ex:
+            res = ex.message
+            self.logger.debug('SSL accept failed: %s', ex)
+
+        # report the result
+
+        return ClientConnectionAuditResult(conn, profile, res)
+
+    def __repr__(self):
+        return "SSLServerHandler%s" % self.__dict__
diff --git a/src/modules/sslcert/SSLServerHandler.pyc b/src/modules/sslcert/SSLServerHandler.pyc
new file mode 100644 (file)
index 0000000..3556742
Binary files /dev/null and b/src/modules/sslcert/SSLServerHandler.pyc differ
diff --git a/src/modules/sslcert/__init__.py b/src/modules/sslcert/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/modules/sslcert/__init__.pyc b/src/modules/sslcert/__init__.pyc
new file mode 100644 (file)
index 0000000..17f1e71
Binary files /dev/null and b/src/modules/sslcert/__init__.pyc differ
diff --git a/src/profile/__init__.py b/src/profile/__init__.py
new file mode 100644 (file)
index 0000000..fe13404
--- /dev/null
@@ -0,0 +1 @@
+__author__ = 'abb'
diff --git a/src/test/ConnectionHammer.py b/src/test/ConnectionHammer.py
new file mode 100644 (file)
index 0000000..6fde0a1
--- /dev/null
@@ -0,0 +1,20 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+from src.test.Hammer import Hammer
+
+DEFAULT_DELAY_BEFORE_CLOSE = 1
+
+class ConnectionHammer(Hammer):
+    def __init__(self, nattempts):
+        Hammer.__init__(self, nattempts)
+        self.peer = None
+        self.delay_before_close = DEFAULT_DELAY_BEFORE_CLOSE
+
+    def set_peer(self, peer):
+        self.peer = peer
+        self.logger.info('initialized with peer %s' % str(self.peer))
+
diff --git a/src/test/ConnectionHammer.pyc b/src/test/ConnectionHammer.pyc
new file mode 100644 (file)
index 0000000..ac62936
Binary files /dev/null and b/src/test/ConnectionHammer.pyc differ
diff --git a/src/test/ExternalCommandHammer.py b/src/test/ExternalCommandHammer.py
new file mode 100644 (file)
index 0000000..63cbe54
--- /dev/null
@@ -0,0 +1,38 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+import logging
+import os
+from src.test.ConnectionHammer import ConnectionHammer
+from subprocess import call
+
+class ExternalCommandHammer(ConnectionHammer):
+    logger = logging.getLogger('ConnectionHammer')
+
+    def __init__(self, nattempts, ca_cert_file):
+        ConnectionHammer.__init__(self, nattempts)
+        self.ca_cert_file = ca_cert_file
+
+    def get_command(self):
+        raise NotImplemented('subclasses must override this method')
+
+    def hammer(self, _round):
+        cmd = self.get_command()
+
+        # run the command discarding stdout and stderr
+        devnull = open(os.devnull, 'w')
+        try:
+            self.logger.debug('calling %s', str(cmd))
+            res = call(cmd, stdout = devnull, stderr = devnull)
+            self.logger.debug('exit code %d', res)
+        finally:
+            devnull.close()
+
+class CurlHammer(ExternalCommandHammer):
+    logger = logging.getLogger('CurlHammer')
+
+    def get_command(self):
+        server = 'https://%s:%d' % (self.peer[0], self.peer[1])
+        return ['curl', '--cacert', self.ca_cert_file, server]
diff --git a/src/test/ExternalCommandHammer.pyc b/src/test/ExternalCommandHammer.pyc
new file mode 100644 (file)
index 0000000..947c419
Binary files /dev/null and b/src/test/ExternalCommandHammer.pyc differ
diff --git a/src/test/Hammer.py b/src/test/Hammer.py
new file mode 100644 (file)
index 0000000..9138cef
--- /dev/null
@@ -0,0 +1,53 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import logging, time
+from threading import Thread
+
+class Hammer(Thread):
+    '''
+    This is an abstract class for hammering, normally used for unit tests only.
+    '''
+    logger = logging.getLogger('Hammer')
+
+    HAMMERING_DELAY = 0.5
+
+    def __init__(self, nattempts):
+        Thread.__init__(self, target=self.run)
+        self.nattempts = nattempts
+
+        self.daemon = True
+        self.should_stop = False
+
+    def run(self):
+        self.logger.debug("running %s", self)
+
+        i = 0
+        while (self.nattempts == -1 or i < self.nattempts) and not self.should_stop:
+            # connect to the peer, do something, disconnect
+            try:
+                self.logger.debug("start hammering round %d to target %s", i, self.peer)
+                self.hammer(i)
+                self.logger.debug("stopped hammering round %d to target %s", i, self.peer)
+            except Exception as ex:
+                self.logger.error('error hammering round %d target %s: %s', i, self.peer, ex)
+
+            # wait a little while before repeating
+            time.sleep(self.HAMMERING_DELAY)
+
+            i += 1
+        self.logger.debug("exiting %s", self)
+
+    def hammer(self, round):
+        '''
+        This method can be overridden by subclasses to do something useful. Round parameter contains a sequence
+        number of the invocation of this method.
+        '''
+        raise NotImplemented('subclasses must override this method')
+
+    def stop(self):
+        self.logger.debug("stopping %s", self)
+        self.should_stop = True
diff --git a/src/test/Hammer.pyc b/src/test/Hammer.pyc
new file mode 100644 (file)
index 0000000..59e2248
Binary files /dev/null and b/src/test/Hammer.pyc differ
diff --git a/src/test/SSLConnectionHammer.py b/src/test/SSLConnectionHammer.py
new file mode 100644 (file)
index 0000000..0a517bf
--- /dev/null
@@ -0,0 +1,68 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import time, logging, M2Crypto
+from M2Crypto.SSL.Checker import  SSLVerificationError
+from src.test.ConnectionHammer import ConnectionHammer
+
+class CNVerifyingSSLConnectionHammer(ConnectionHammer):
+    '''
+    This client only matches CN
+    '''
+    logger = logging.getLogger('CNVerifyingSSLConnectionHammer')
+
+    def __init__(self, nattempts, hello):
+        ConnectionHammer.__init__(self, nattempts)
+        self.hello = hello
+
+        # create a context
+        self.ctx = M2Crypto.SSL.Context()
+        self.ctx.set_allow_unknown_ca(True)
+        self.ctx.set_verify(M2Crypto.SSL.verify_none, 9)
+
+    def hammer(self, i):
+        self.logger.debug('starting SSL handshake')
+        conn = M2Crypto.SSL.Connection(self.ctx)
+
+        try:
+            res = conn.connect(self.peer)
+            if res == 1:
+                conn.write(self.hello)
+                self.logger.debug('SSL handshake complete for connection %d to %s, hello sent, waiting for %.1fs before closing',
+                    i, self.peer, self.delay_before_close)
+                time.sleep(self.delay_before_close)
+                conn.close()
+                self.logger.debug('SSL connection %d to %s closed', i, self.peer)
+                return True
+            else:
+                self.logger.debug('SSL handshake failed: %s', ssl_conn.ssl_get_error(res))
+                return False
+        except SSLVerificationError as ex:
+            self.logger.debug('SSL handshake SSLVerificationError: %s', ex)
+            return False
+
+class ChainVerifyingSSLConnectionHammer(CNVerifyingSSLConnectionHammer):
+    '''
+    This client only matches CN and verifies the chain of trust
+    '''
+    logger = logging.getLogger('ChainVerifyingSSLConnectionHammer')
+
+    def __init__(self, nattempts, hello, ca_cert_file):
+        CNVerifyingSSLConnectionHammer.__init__(self, nattempts, hello)
+        self.ca_cert_file = ca_cert_file
+
+        #self.ctx.set_allow_unknown_ca(True)
+        self.ctx.load_verify_locations(self.ca_cert_file)
+        self.ctx.set_verify(
+            mode=M2Crypto.SSL.verify_peer | M2Crypto.SSL.verify_fail_if_no_peer_cert,
+            depth=9,
+            callback=self.verify_callback)
+
+        self.logger.info('initialized with ca_cert_file %s' % self.ca_cert_file)
+
+    def verify_callback(self):
+        #self.logger.info('*** verify_callback called ***')
+        pass
diff --git a/src/test/SSLConnectionHammer.pyc b/src/test/SSLConnectionHammer.pyc
new file mode 100644 (file)
index 0000000..82f481e
Binary files /dev/null and b/src/test/SSLConnectionHammer.pyc differ
diff --git a/src/test/TCPConnectionHammer.py b/src/test/TCPConnectionHammer.py
new file mode 100644 (file)
index 0000000..f6fb677
--- /dev/null
@@ -0,0 +1,33 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import logging, time
+from socket import socket
+from src.test.ConnectionHammer import ConnectionHammer
+
+class TCPConnectionHammer(ConnectionHammer):
+    '''
+    This class continuously tries to connect to the specified host and port.
+    After connection is established, it immediately closes it.
+    Normally used for unit tests only.
+    '''
+    logger = logging.getLogger('TCPConnectionHammer')
+
+    def hammer(self, i):
+        # connect to the peer, do something, disconnect
+        sock = socket()
+        try:
+            self.logger.debug("opening connection %d to %s ...", i, self.peer)
+            sock.connect(self.peer)
+            self.logger.debug("connection %d to %s established, waiting for %.1fs before closing",
+                i, self.peer, self.delay_before_close)
+            time.sleep(self.delay_before_close)
+
+        except IOError as ex:
+            self.logger.error('connection %d failed: %s', i, ex)
+        finally:
+            sock.close()
+            self.logger.debug("connection %d with %s closed", i, self.peer)
diff --git a/src/test/TCPConnectionHammer.pyc b/src/test/TCPConnectionHammer.pyc
new file mode 100644 (file)
index 0000000..4dc3961
Binary files /dev/null and b/src/test/TCPConnectionHammer.pyc differ
diff --git a/src/test/TestConfig.py b/src/test/TestConfig.py
new file mode 100644 (file)
index 0000000..9375afc
--- /dev/null
@@ -0,0 +1,43 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import os
+
+TEST_MAIN_JOIN_TIMEOUT = 60
+
+TEST_USER_CN = 'user-cn.example.com'
+
+TEST_SERVER_HOST = '62.213.200.252'
+TEST_SERVER_PORT = 443
+TEST_SERVER = '%s:%d' % (TEST_SERVER_HOST, TEST_SERVER_PORT)
+TEST_SERVER_CN = 'brufeprd1.hackingmachines.com'
+
+TEST_LISTENER_ADDR = 'localhost'
+TEST_LISTENER_BASEPORT = 10000
+
+## figure out path to test/certs directory
+if os.path.exists(os.path.join('test', 'certs')): TEST_CERT_DIR = os.path.join('test', 'certs')
+elif os.path.exists('certs'): TEST_CERT_DIR = 'certs'
+else: raise RuntimeError('cannot find test/certs or certs/ directory')
+TEST_CERT_DIR += os.sep
+
+TEST_USER_CERT_CN = 'www.example.com'
+TEST_USER_CERT_FILE = TEST_CERT_DIR + 'www.example.com-cert.pem'
+TEST_USER_KEY_FILE = TEST_CERT_DIR + 'www.example.com-key.pem'
+
+TEST_USER_CA_CN = 'test-ca'
+TEST_USER_CA_CERT_FILE = TEST_CERT_DIR + 'test-ca-cacert.pem'
+TEST_USER_CA_KEY_FILE = TEST_CERT_DIR + 'test-ca-cakey.pem'
+
+def get_next_listener_port():
+    '''
+    This method used to allocate ports the test server will listen on
+    '''
+    global TEST_LISTENER_BASEPORT
+    TEST_LISTENER_BASEPORT = TEST_LISTENER_BASEPORT + 1
+    return TEST_LISTENER_BASEPORT
+
+
diff --git a/src/test/__init__.py b/src/test/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/src/test/__init__.pyc b/src/test/__init__.pyc
new file mode 100644 (file)
index 0000000..6b3d484
Binary files /dev/null and b/src/test/__init__.pyc differ
diff --git a/sslcaudit b/sslcaudit
new file mode 100755 (executable)
index 0000000..23dd7c9
--- /dev/null
+++ b/sslcaudit
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+
+# ----------------------------------------------------------------------
+# SSLCAUDIT - a tool for automating security audit of SSL clients
+# Released under terms of GPLv3, see COPYING.TXT
+# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+# ----------------------------------------------------------------------
+# Code handling keyboard interrupts contributed by Raf Somers (raf.somers@telenet.be)
+# ----------------------------------------------------------------------
+
+
+import sys, logging
+from src.core.ConfigError import ConfigError
+from src.core.SSLCAuditCLI import SSLCAuditCLI
+
+def check_dependencies():
+    # make sure M2Crypto is installed
+    try:
+        import M2Crypto
+        return True
+    except ImportError as ex:
+        print 'Failed to load M2Crypto: %s' % ex
+        print
+        print 'Sslcaudit requires M2Crypto library. Please install your OS package or see'
+        print 'website http://chandlerproject.org/bin/view/Projects/MeTooCrypto.'
+        return False
+
+def init_controller(argv):
+    # initialize the controller
+    try:
+        controller = SSLCAuditCLI(argv[1:])
+        controller.start()
+        return controller
+    except KeyboardInterrupt as ex:
+        print 'Got KeyboardInterrupt exception before controller loop started, exiting'
+        return None
+    except ConfigError as ex:
+        print 'Configuration error: %s' % ex
+        return None
+    except RuntimeError as ex:
+        print 'Runtime error: %s' % ex
+        return None
+
+def run(controller):
+    # wait for the main thread to finish, handle Ctrl-C if any
+    interrupted_by_user = False
+    while controller.isAlive():
+        try:
+            controller.join(1)
+        except KeyboardInterrupt:
+            print 'Got KeyboardInterrupt exception, aborting the program ...'
+            controller.stop() # graceful death
+            interrupted_by_user = True
+    # if the program is aborted by the user, return exitcode 1
+    if interrupted_by_user:
+        return 1
+    else:
+        return 0
+
+def main(argv):
+    if not check_dependencies():
+        return 1
+    c = init_controller(argv)
+    if c is None:
+        return 1
+    return run(c)
+
+if __name__ == "__main__":
+    logging.basicConfig()
+    sys.exit(main(sys.argv))
+
diff --git a/test-sslcaudit b/test-sslcaudit
new file mode 100755 (executable)
index 0000000..4c04a1f
--- /dev/null
@@ -0,0 +1,23 @@
+#!/usr/bin/env python
+
+# ----------------------------------------------------------------------
+# SSLCAUDIT - a tool for automating security audit of SSL clients
+# Released under terms of GPLv3, see COPYING.TXT
+# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+# ----------------------------------------------------------------------
+
+import sys
+#sys.path.insert(0, 'test')
+
+import unittest
+
+from test.TestCertFactory import TestCertFactory
+from test.TestDummyModule import TestDummyModule
+from test.TestSSLCertModule import TestSSLCertModule
+
+if __name__ == '__main__':
+    suite = unittest.TestSuite()
+    suite.addTest(unittest.makeSuite(TestCertFactory))
+    suite.addTest(unittest.makeSuite(TestDummyModule))
+    suite.addTest(unittest.makeSuite(TestSSLCertModule))
+    unittest.TextTestRunner(verbosity=2).run(suite)
diff --git a/test/TestCertFactory.py b/test/TestCertFactory.py
new file mode 100644 (file)
index 0000000..1001ce2
--- /dev/null
@@ -0,0 +1,79 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+import tempfile
+
+import unittest
+from src.core.CertFactory import *
+from src.core.FileBag import FileBag
+from src.test.TestConfig import *
+
+SSL_PROTO = 'sslv23'
+
+class TestCertFactory(unittest.TestCase):
+    def setUp(self):
+        self.file_bag = FileBag('testcertfactory', use_tempdir=True)
+        self.cert_factory = CertFactory(self.file_bag)
+
+    def test__mk_certreq_n_keys(self):
+        certreq = self.cert_factory.mk_certreq_n_keys(TEST_USER_CN)
+        # check subject
+        good_subj = 'CN=%s, C=%s, O=%s' % (TEST_USER_CN, DEFAULT_X509_C, DEFAULT_X509_ORG)
+        self.assertEqual(good_subj, certreq[0].get_subject().as_text())
+
+    def test__load_certnkey_files(self):
+        ca_certnkey = self.cert_factory.load_certnkey_files(TEST_USER_CA_CERT_FILE, TEST_USER_CA_KEY_FILE)
+        # check CN of loaded certificate
+        self.assertEqual(TEST_USER_CA_CN, ca_certnkey.cert.get_subject().CN)
+
+    def test_create_selfsigned(self):
+        certreq = self.cert_factory.mk_certreq_n_keys(TEST_USER_CN)
+        certnkey = self.cert_factory.sign_cert_req(certreq, None)
+        # check subject and issuer of self-signed certificate
+        good_subj = 'CN=%s, C=%s, O=%s' % (TEST_USER_CN, DEFAULT_X509_C, DEFAULT_X509_ORG)
+        self.assertEqual(good_subj, certnkey.cert.get_subject().as_text())
+        self.assertEqual(good_subj, certnkey.cert.get_issuer().as_text())
+
+    def test_create_signed(self):
+        # create signed certificate
+        certreq = self.cert_factory.mk_certreq_n_keys(TEST_USER_CN)
+        ca_certnkey = self.cert_factory.load_certnkey_files(TEST_USER_CA_CERT_FILE, TEST_USER_CA_KEY_FILE)
+        certnkey = self.cert_factory.sign_cert_req(certreq, ca_certnkey)
+        # check subject and issuer of signed certificate
+        good_subj = 'CN=%s, C=%s, O=%s' % (TEST_USER_CN, DEFAULT_X509_C, DEFAULT_X509_ORG)
+        self.assertEqual(good_subj, certnkey.cert.get_subject().as_text())
+        self.assertEqual(certnkey.cert.get_issuer().as_text(), ca_certnkey.cert.get_subject().as_text())
+
+    def test__mk_signed_server_replica_cert(self):
+        # grab server certificate and make its replica
+        server_cert = self.cert_factory.grab_server_x509_cert((TEST_SERVER_HOST, TEST_SERVER_PORT), SSL_PROTO)
+        ss_replica_cert_req = self.cert_factory.mk_replica_certreq_n_keys(server_cert)
+
+        # check that CN is right
+        self.assertEqual(
+            TEST_SERVER_CN,
+            ss_replica_cert_req[0].get_subject().CN)
+
+        # load CA and sign the replica
+        ca_certnkey = self.cert_factory.load_certnkey_files(TEST_USER_CA_CERT_FILE, TEST_USER_CA_KEY_FILE)
+        ss_replica_certnkey = self.cert_factory.sign_cert_req(ss_replica_cert_req, ca_certnkey)
+
+        # check that CN is still right
+        self.assertEqual(
+            server_cert.get_subject().as_text(),
+            ss_replica_certnkey.cert.get_subject().as_text())
+
+        # check issuer
+        self.assertEqual(
+            ca_certnkey.cert.get_subject().as_text(),
+            ss_replica_certnkey.cert.get_issuer().as_text())
+
+    def test__grab_server_x509_cert(self):
+        server_cert = self.cert_factory.grab_server_x509_cert((TEST_SERVER_HOST, TEST_SERVER_PORT), SSL_PROTO)
+        # check CN of server certificate
+        self.assertEqual(server_cert.get_subject().CN, TEST_SERVER_CN)
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/test/TestDummyModule.py b/test/TestDummyModule.py
new file mode 100644 (file)
index 0000000..67b1c02
--- /dev/null
@@ -0,0 +1,82 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import logging
+import unittest
+from src.core.SSLCAuditCLI import SSLCAuditCLI
+from src.core.ClientConnectionAuditEvent import ClientAuditStartEvent, ClientAuditEndEvent, ClientConnectionAuditResult
+from src.core.ClientHandler import ClientAuditResult
+from src.test.TCPConnectionHammer import TCPConnectionHammer
+from src.test.TestConfig import get_next_listener_port, TEST_LISTENER_ADDR
+
+class TestDummyModule(unittest.TestCase):
+    '''
+    test dummy client / auditor, no SSL whatsoever
+    '''
+    logger = logging.getLogger('TestDummyModule')
+    MAIN_JOIN_TIMEOUT = 5
+    HAMMER_ATTEMPTS = 3
+
+    def test_dummy(self):
+        '''
+        This test establishes a bunch of plain TCP connections against dummy auditor.
+        The dummy auditor just acknowledges the fact of connection happening.
+        '''
+        # these variables will be updated from a hook function invoked from main
+        self.got_result_start = 0
+        self.got_result = 0
+        self.got_result_end = 0
+        self.got_bulk_result = 0
+        self.nstray = 0
+
+        # the hook function
+        def main__handle_result(res):
+            '''
+            This function overrides main.handle_result() and updates our counters
+            '''
+            if isinstance(res, ClientAuditStartEvent):
+                self.got_result_start = self.got_result_start + 1
+            elif isinstance(res, ClientAuditEndEvent):
+                self.got_result_end = self.got_result_end + 1
+            elif isinstance(res, ClientConnectionAuditResult):
+                self.got_result = self.got_result + 1
+            elif isinstance(res, ClientAuditResult):
+                self.got_bulk_result = self.got_bulk_result + 1
+            else:
+                self.nstray = self.nstray + 1
+
+        # allocate port
+        port = get_next_listener_port()
+
+        # create a client hammering our test listener
+        self.hammer = TCPConnectionHammer(self.HAMMER_ATTEMPTS)
+
+        # create main, the target of the test
+        self.main = SSLCAuditCLI(['-m', 'dummy', '-l', ("%s:%d" % (TEST_LISTENER_ADDR, port))])
+        self.main.handle_result = main__handle_result
+
+        # tell the hammer how many attempts to make exactly
+        self.hammer.set_peer((TEST_LISTENER_ADDR, port))
+
+        # start server and client
+        self.main.start()
+        self.hammer.start()
+
+        self.main.join(timeout=5)
+        self.hammer.stop()
+        self.main.stop()
+
+        # make sure we have received expected number of results
+        self.assertEquals(self.got_result_start, 1)
+        self.assertEquals(self.got_result, 2)
+        self.assertEquals(self.got_result_end, 1)
+        self.assertEquals(self.got_bulk_result, 1)
+        self.assertEquals(self.nstray, 0)
+
+
+if __name__ == '__main__':
+    unittest.main()
+
diff --git a/test/TestFileBag.py b/test/TestFileBag.py
new file mode 100644 (file)
index 0000000..5f55743
--- /dev/null
@@ -0,0 +1,29 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import unittest, tempfile
+from src.core.FileBag import FileBag
+
+class TestFileBag(unittest.TestCase):
+    def setUp(self):
+        self.file_bag = FileBag('testfilebag', use_tempdir=True)
+
+    def test__mk_file(self):
+        f = self.file_bag.mk_file(suffix='.bar', prefix='foo')
+        f.write('blah')
+        f.close()
+
+    def test__mk_file2(self):
+        (f1, f2) = self.file_bag.mk_two_files(suffix1='.bar1', suffix2='.bar2', prefix='foo')
+
+        f1.write('blah1')
+        f1.close()
+
+        f2.write('blah2')
+        f2.close()
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/test/TestSSLCertModule.py b/test/TestSSLCertModule.py
new file mode 100644 (file)
index 0000000..084c265
--- /dev/null
@@ -0,0 +1,275 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import logging, unittest
+from src.core.SSLCAuditCLI import SSLCAuditCLI
+
+from src.core.ClientConnectionAuditEvent import ClientConnectionAuditResult
+from src.modules.sslcert.ProfileFactory import DEFAULT_CN, SSLProfileSpec_SelfSigned, SSLProfileSpec_IMCA_Signed, SSLProfileSpec_Signed, IM_CA_FALSE_CN, IM_CA_TRUE_CN, IM_CA_NONE_CN, SSLProfileSpec_UserSupplied
+from src.modules.sslcert.SSLServerHandler import     UNEXPECTED_EOF, ALERT_UNKNOWN_CA, ConnectedGotEOFBeforeTimeout, ConnectedGotRequest
+from src.test import TestConfig
+from src.test.SSLConnectionHammer import CNVerifyingSSLConnectionHammer
+from src.test.TCPConnectionHammer import TCPConnectionHammer
+from src.test.TestConfig import *
+from src.test.ExternalCommandHammer import CurlHammer
+
+LOCALHOST = 'localhost'
+HAMMER_HELLO = 'hello'
+
+def get_full_test_args(user_cn=TEST_USER_CN):
+    return [
+        '--user-cn', user_cn,
+        '--user-cert', TEST_USER_CERT_FILE,
+        '--server', TEST_SERVER,
+        '--user-key', TEST_USER_KEY_FILE,
+        '--user-ca-cert', TEST_USER_CA_CERT_FILE,
+        '--user-ca-key', TEST_USER_CA_KEY_FILE
+    ]
+
+
+class ECCAR(object):
+    def __init__(self, profile_spec, expected_res):
+        self.profile_spec = profile_spec
+        self.expected_result = expected_res
+
+    def matches(self, actual_res):
+        '''
+        Given an actual audit result instance (ClientConnectionAuditResult) checks if it matches our expectations.
+        '''
+        if not (self.profile_spec == actual_res.profile.get_spec()):
+            return False
+
+        if self.expected_result == actual_res.res:
+            return True
+        else:
+            return False
+
+    def __str__(self):
+        return "ECCAR(%s, %s)" % (self.profile_spec, self.expected_result)
+
+
+class TestSSLCertModule(unittest.TestCase):
+    '''
+    Unittests for SSLCert.
+    '''
+    logger = logging.getLogger('TestSSLCertModule')
+
+    def test_plain_tcp_client(self):
+        # Plain TCP client causes unexpected UNEXPECTED_EOF.
+        eccars = [
+            # user-supplied certificate
+            ECCAR(SSLProfileSpec_UserSupplied(TEST_USER_CERT_CN), UNEXPECTED_EOF),
+
+            # self-signed certificates
+            ECCAR(SSLProfileSpec_SelfSigned(DEFAULT_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_SelfSigned(TEST_USER_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_SelfSigned(TEST_SERVER_CN), UNEXPECTED_EOF),
+
+            # signed by user-supplied certificate
+            ECCAR(SSLProfileSpec_Signed(DEFAULT_CN, TEST_USER_CERT_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_Signed(TEST_USER_CN, TEST_USER_CERT_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_Signed(TEST_SERVER_CN, TEST_USER_CERT_CN), UNEXPECTED_EOF),
+
+            # signed by user-supplied CA
+            ECCAR(SSLProfileSpec_Signed(DEFAULT_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_Signed(TEST_USER_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_Signed(TEST_SERVER_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+
+            # default CN, signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_NONE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+
+            # user-supplied CN signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_USER_CN, IM_CA_NONE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_USER_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_USER_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+
+            # replica of server certificate signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_NONE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN), UNEXPECTED_EOF)
+        ]
+        self._main_test(
+            get_full_test_args(),
+            TCPConnectionHammer(len(eccars)),
+            eccars
+        )
+
+    def test_cn_verifying_client(self):
+        # CN verifying client only cares about getting a correct CN
+        eccars = [
+            # user-supplied certificate
+            ECCAR(SSLProfileSpec_UserSupplied(TEST_USER_CERT_CN), ConnectedGotEOFBeforeTimeout()),
+
+            # self-signed certificates
+            ECCAR(SSLProfileSpec_SelfSigned(DEFAULT_CN), ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_SelfSigned(LOCALHOST), ConnectedGotRequest(HAMMER_HELLO)),
+            ECCAR(SSLProfileSpec_SelfSigned(TEST_SERVER_CN), ConnectedGotEOFBeforeTimeout()),
+
+            # signed by user-supplied certificate
+            ECCAR(SSLProfileSpec_Signed(DEFAULT_CN, TEST_USER_CERT_CN), ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_Signed(LOCALHOST, TEST_USER_CERT_CN), ConnectedGotRequest(HAMMER_HELLO)),
+            ECCAR(SSLProfileSpec_Signed(TEST_SERVER_CN, TEST_USER_CERT_CN), ConnectedGotEOFBeforeTimeout()),
+
+            # signed by user-supplied CA
+            ECCAR(SSLProfileSpec_Signed(DEFAULT_CN, TEST_USER_CA_CN), ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_Signed(LOCALHOST, TEST_USER_CA_CN), ConnectedGotRequest(HAMMER_HELLO)),
+            ECCAR(SSLProfileSpec_Signed(TEST_SERVER_CN, TEST_USER_CA_CN), ConnectedGotEOFBeforeTimeout()),
+
+            # default CN, signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_NONE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+
+            # user-supplied CN signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(LOCALHOST, IM_CA_NONE_CN, TEST_USER_CA_CN),
+                ConnectedGotRequest(HAMMER_HELLO)),
+            ECCAR(SSLProfileSpec_IMCA_Signed(LOCALHOST, IM_CA_FALSE_CN, TEST_USER_CA_CN),
+                ConnectedGotRequest(HAMMER_HELLO)),
+            ECCAR(SSLProfileSpec_IMCA_Signed(LOCALHOST, IM_CA_TRUE_CN, TEST_USER_CA_CN),
+                ConnectedGotRequest(HAMMER_HELLO)),
+
+            # replica of server certificate signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_NONE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+            ]
+
+        self._main_test(
+            get_full_test_args(user_cn=LOCALHOST),
+            CNVerifyingSSLConnectionHammer(len(eccars), HAMMER_HELLO),
+            eccars)
+
+    def test_curl(self):
+        # curl does all the checks
+        eccars = [
+            # user-supplied certificate
+            ECCAR(SSLProfileSpec_UserSupplied(TEST_USER_CERT_CN), ConnectedGotEOFBeforeTimeout()),
+
+            # self-signed certificates
+            ECCAR(SSLProfileSpec_SelfSigned(DEFAULT_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_SelfSigned(LOCALHOST), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_SelfSigned(TEST_SERVER_CN), ALERT_UNKNOWN_CA),
+
+            # signed by user-supplied certificate
+            ECCAR(SSLProfileSpec_Signed(DEFAULT_CN, TEST_USER_CERT_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_Signed(LOCALHOST, TEST_USER_CERT_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_Signed(TEST_SERVER_CN, TEST_USER_CERT_CN), ALERT_UNKNOWN_CA),
+
+            # signed by user-supplied CA
+            ECCAR(SSLProfileSpec_Signed(DEFAULT_CN, TEST_USER_CA_CN), ConnectedGotEOFBeforeTimeout()),
+            ECCAR(SSLProfileSpec_Signed(LOCALHOST, TEST_USER_CA_CN), ConnectedGotRequest()),
+            ECCAR(SSLProfileSpec_Signed(TEST_SERVER_CN, TEST_USER_CA_CN), ConnectedGotEOFBeforeTimeout()),
+
+            # default CN, signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_NONE_CN, TEST_USER_CA_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_IMCA_Signed(DEFAULT_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+
+            # user-supplied CN signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(LOCALHOST, IM_CA_NONE_CN, TEST_USER_CA_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_IMCA_Signed(LOCALHOST, IM_CA_FALSE_CN, TEST_USER_CA_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_IMCA_Signed(LOCALHOST, IM_CA_TRUE_CN, TEST_USER_CA_CN), ConnectedGotRequest()),
+
+            # replica of server certificate signed by user-supplied CA, with an intermediate CA
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_NONE_CN, TEST_USER_CA_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_FALSE_CN, TEST_USER_CA_CN), ALERT_UNKNOWN_CA),
+            ECCAR(SSLProfileSpec_IMCA_Signed(TEST_SERVER_CN, IM_CA_TRUE_CN, TEST_USER_CA_CN),
+                ConnectedGotEOFBeforeTimeout()),
+            ]
+
+        self._main_test(
+            get_full_test_args(user_cn=LOCALHOST),
+            CurlHammer(len(eccars), TEST_USER_CA_CERT_FILE),
+            eccars
+        )
+
+    def tearDown(self):
+        if self.main != None:
+            self.main.stop()
+
+    def _main_test(self, main_args, hammer, expected_results):
+        '''
+        This is a main worker function. It allocates external resources and launches threads,
+        to make sure they are freed this function was to be called exactly once per test method,
+        to allow tearDown() method to cleanup properly.
+        '''
+        self._main_test_init(main_args, hammer)
+        self._main_test_do(expected_results)
+
+    def _main_test_init(self, args, hammer):
+        # allocate port
+        port = TestConfig.get_next_listener_port()
+
+        # create main, the target of the test
+        test_name = "%s %s" % (hammer, args)
+        main_args = ['-l', '%s:%d' % (TestConfig.TEST_LISTENER_ADDR, port)]
+        main_args.extend(args)
+        self.main = SSLCAuditCLI(main_args)
+
+        # collect classes of observed audit results
+        self.actual_results = []
+        self.orig_main__handle_result = self.main.handle_result
+
+        def main__handle_result(res):
+            self.orig_main__handle_result(res)
+            if isinstance(res, ClientConnectionAuditResult):
+                self.actual_results.append(res)
+            else:
+                pass # ignore events print res
+
+        self.main.handle_result = main__handle_result
+
+        self.hammer = hammer
+        if self.hammer != None:
+            self.hammer.set_peer((TestConfig.TEST_LISTENER_ADDR, port))
+
+    def _main_test_do(self, expected_results):
+        # run the server
+        self.main.start()
+
+        # start the hammer if any
+        if self.hammer != None:
+            self.hammer.start()
+
+        # wait for main to finish its job
+        self.main.join(timeout=TestConfig.TEST_MAIN_JOIN_TIMEOUT)
+        # on timeout throws exception, which we let propagate after we shut the hammer and the main thread
+
+        self.assertFalse(self.main.is_alive(), 'main thread is still alive')
+
+        # stop the hammer if any
+        if self.hammer != None:    self.hammer.stop()
+
+        # stop the server
+        self.main.stop()
+
+        # check if the actual results match expected ones
+        if len(expected_results) != len(self.actual_results):
+            mismatch = True
+            print "! length mismatch len(er)=%d, len(ar)=%d" % (len(expected_results), len(self.actual_results))
+            for er in expected_results: print "er=%s" % er
+            for ar in self.actual_results: print "ar=%s" % ar
+        else:
+            mismatch = False
+            for i in range(len(expected_results)):
+                er = expected_results[i]
+                ar = self.actual_results[i]
+                if not er.matches(ar):
+                    print "! mismatch\n\ter=%s\n\tar=%s" % (er, ar)
+                    mismatch = True
+        self.assertFalse(mismatch)
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/test/_SimpleX509create.py b/test/_SimpleX509create.py
new file mode 100644 (file)
index 0000000..9eb3d67
--- /dev/null
@@ -0,0 +1,184 @@
+#!/usr/bin/env python
+#
+#vim: ts=4 sw=4 nowrap
+#
+
+"""PKI demo by Peter Teniz <peter.teniz@inverisa.net>"""
+
+import M2Crypto
+
+
+MBSTRING_FLAG = 0x1000
+MBSTRING_ASC = MBSTRING_FLAG | 1
+MBSTRING_BMP = MBSTRING_FLAG | 2
+
+
+class Cert:
+    def __init__( self ):
+        self.RsaKey = {'KeyLength': 1024,
+                       'PubExponent': 0x10001, # -> 65537
+                       'keygen_callback': self.callback
+        }
+
+        self.KeyPair = None
+        self.PKey = None
+
+        self.X509Request = None
+        self.X509Certificate = None
+
+    def callback( self, *args ):
+        return 'p'
+
+
+    def CreatePKey( self ):
+        self.KeyPair = M2Crypto.RSA.gen_key(self.RsaKey['KeyLength'], self.RsaKey['PubExponent'],
+            self.RsaKey['keygen_callback'])
+        #PubKey = M2Crypto.RSA.new_pub_key( self.KeyPair.pub () )
+
+        self.KeyPair.save_key('KeyPair.pem', cipher='des_ede3_cbc', callback=self.callback)
+
+        self.PKey = M2Crypto.EVP.PKey(md='sha1')
+        self.PKey.assign_rsa(self.KeyPair)
+
+
+    def CreateX509Request( self ):
+        #
+        # X509 REQUEST
+        #
+
+        self.X509Request = M2Crypto.X509.Request()
+
+        #
+        # subject
+        #
+
+        X509Name = M2Crypto.X509.X509_Name()
+
+        X509Name.add_entry_by_txt(field='C', type=MBSTRING_ASC, entry='austria', len=-1, loc=-1,
+            set=0)    # country name
+        X509Name.add_entry_by_txt(field='SP', type=MBSTRING_ASC, entry='kernten', len=-1, loc=-1,
+            set=0)    # state of province name
+        X509Name.add_entry_by_txt(field='L', type=MBSTRING_ASC, entry='stgallen', len=-1, loc=-1,
+            set=0)    # locality name
+        X509Name.add_entry_by_txt(field='O', type=MBSTRING_ASC, entry='labor', len=-1, loc=-1,
+            set=0)    # organization name
+        X509Name.add_entry_by_txt(field='OU', type=MBSTRING_ASC, entry='it-department', len=-1, loc=-1,
+            set=0)    # organizational unit name
+        X509Name.add_entry_by_txt(field='CN', type=MBSTRING_ASC, entry='Certificate client', len=-1, loc=-1,
+            set=0)    # common name
+        X509Name.add_entry_by_txt(field='Email', type=MBSTRING_ASC, entry='user@localhost', len=-1, loc=-1,
+            set=0)    # pkcs9 email address
+        X509Name.add_entry_by_txt(field='emailAddress', type=MBSTRING_ASC, entry='user@localhost', len=-1, loc=-1,
+            set=0)    # pkcs9 email address
+
+        self.X509Request.set_subject_name(X509Name)
+
+        #
+        # publickey
+        #
+
+        self.X509Request.set_pubkey(pkey=self.PKey)
+        self.X509Request.sign(pkey=self.PKey, md='sha1')
+
+    #print X509Request.as_text ()
+
+
+
+
+
+
+    def CreateX509Certificate( self ):
+        #
+        # X509 CERTIFICATE
+        #
+
+        self.X509Certificate = M2Crypto.X509.X509()
+
+        #
+        # version
+        #
+
+        self.X509Certificate.set_version(0)
+
+        #
+        # time notBefore
+        #
+
+        ASN1 = M2Crypto.ASN1.ASN1_UTCTIME()
+        ASN1.set_time(500)
+        self.X509Certificate.set_not_before(ASN1)
+
+        #
+        # time notAfter
+        #
+
+        ASN1 = M2Crypto.ASN1.ASN1_UTCTIME()
+        ASN1.set_time(500)
+        self.X509Certificate.set_not_after(ASN1)
+
+        #
+        # public key
+        #
+
+        self.X509Certificate.set_pubkey(pkey=self.PKey)
+
+        #
+        # subject
+        #
+
+        X509Name = self.X509Request.get_subject()
+
+        #print X509Name.entry_count ()
+        #print X509Name.as_text ()
+
+        self.X509Certificate.set_subject_name(X509Name)
+
+        #
+        # issuer
+        #
+
+        X509Name = M2Crypto.X509.X509_Name(M2Crypto.m2.x509_name_new())
+
+        X509Name.add_entry_by_txt(field='C', type=MBSTRING_ASC, entry='germany', len=-1, loc=-1,
+            set=0)    # country name
+        X509Name.add_entry_by_txt(field='SP', type=MBSTRING_ASC, entry='bavaria', len=-1, loc=-1,
+            set=0)    # state of province name
+        X509Name.add_entry_by_txt(field='L', type=MBSTRING_ASC, entry='munich', len=-1, loc=-1,
+            set=0)    # locality name
+        X509Name.add_entry_by_txt(field='O', type=MBSTRING_ASC, entry='sbs', len=-1, loc=-1,
+            set=0)    # organization name
+        X509Name.add_entry_by_txt(field='OU', type=MBSTRING_ASC, entry='it-department', len=-1, loc=-1,
+            set=0)    # organizational unit name
+        X509Name.add_entry_by_txt(field='CN', type=MBSTRING_ASC, entry='Certificate Authority', len=-1, loc=-1,
+            set=0)    # common name
+        X509Name.add_entry_by_txt(field='Email', type=MBSTRING_ASC, entry='admin@localhost', len=-1, loc=-1,
+            set=0)    # pkcs9 email address
+        X509Name.add_entry_by_txt(field='emailAddress', type=MBSTRING_ASC, entry='admin@localhost', len=-1, loc=-1,
+            set=0)    # pkcs9 email address
+
+        #print X509Name.entry_count ()
+        #print X509Name.as_text ()
+
+        self.X509Certificate.set_issuer_name(X509Name)
+
+        #
+        # signing
+        #
+
+        #              self.X509Certificate.sign( pkey=self.PKey, md='sha1' )
+
+        ca_cert = M2Crypto.X509.load_cert('sslcaudit-test-cacert.pem')
+        ca_pkey = M2Crypto.EVP.load_key('sslcaudit-test-cakey.pem')
+        ca_cert.assign_rsa(ca_pkey, capture=False)
+
+        self.X509Certificate.set_issuer(ca_cert.get_subject())
+        self.X509Certificate.sign(pkey=ca_pkey, md='sha1')
+
+        print self.X509Certificate.as_text()
+
+
+if __name__ == '__main__':
+    run = Cert()
+    run.CreatePKey()
+    run.CreateX509Request()
+    run.CreateX509Certificate()
diff --git a/test/_TestM2CryptoBug.py b/test/_TestM2CryptoBug.py
new file mode 100644 (file)
index 0000000..edc5762
--- /dev/null
@@ -0,0 +1,52 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
+
+import unittest
+from tempfile import NamedTemporaryFile
+from M2Crypto import RSA, EVP, util
+
+class TestM2CryptoBug(unittest.TestCase):
+    '''
+    This unittest reproduces segfault in RSA.save_key()
+    '''
+
+    def test_plain(self):
+        '''
+        generate keypair and save it
+        '''
+        pk = EVP.PKey()
+        k = RSA.gen_key(1024, 65537, util.no_passphrase_callback)
+        pk.assign_rsa(k, capture=False)
+        self._save(k)
+
+    def _gen_key(self, do_assign):
+        pk = EVP.PKey()
+        k = RSA.gen_key(1024, 65537, util.no_passphrase_callback)
+        if do_assign:
+            # apparently, this operation breaks save_key later ok
+            pk.assign_rsa(k, capture=False)
+        return k
+
+    def test_func_noassign(self):
+        '''
+        same as above, but move key generation code into another method
+        '''
+        k = self._gen_key(do_assign=False)
+        self._save(k)
+
+    def test_func_assign(self):
+        '''
+        same as above, but don't do assign pkey
+        '''
+        k = self._gen_key(do_assign=True)
+        self._save(k)
+
+    def _save(self, k):
+        f = NamedTemporaryFile(delete=False)
+        k.save_key(f.name, None)
+
+if __name__ == '__main__':
+    unittest.main()
diff --git a/test/__init__.py b/test/__init__.py
new file mode 100644 (file)
index 0000000..b7c02fb
--- /dev/null
@@ -0,0 +1,5 @@
+''' ----------------------------------------------------------------------
+SSLCAUDIT - a tool for automating security audit of SSL clients
+Released under terms of GPLv3, see COPYING.TXT
+Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+---------------------------------------------------------------------- '''
diff --git a/test/certs/test-ca-cacert.pem b/test/certs/test-ca-cacert.pem
new file mode 100644 (file)
index 0000000..1bf6629
--- /dev/null
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICqzCCAhSgAwIBAgIJALimgW7YUgdrMA0GCSqGSIb3DQEBBQUAMB8xCzAJBgNV
+BAYTAkJFMRAwDgYDVQQDEwd0ZXN0LWNhMB4XDTEyMDUwNjA4NDEyMVoXDTIyMDUw
+NDA4NDEyMVowHzELMAkGA1UEBhMCQkUxEDAOBgNVBAMTB3Rlc3QtY2EwgZ8wDQYJ
+KoZIhvcNAQEBBQADgY0AMIGJAoGBAOq27XvJ98jQMtays+VzlgqXnBd3EfCYcpeC
+9cvr2v+dGWRSzXpE92oEcanp1F8jWUAgXfdHHXGR4s4LfqeYAYNHYZWJ+QSXDMYK
+vE+vAVQTeKMqyltC+ET8kF45TgoPCRORfsxZDFAhWLYO7mXD19VALID06QT+Mfuk
+pF504mrVAgMBAAGjge4wgeswHQYDVR0OBBYEFFuITOUJlGrJ9lKufs8cm1MpwXrr
+ME8GA1UdIwRIMEaAFFuITOUJlGrJ9lKufs8cm1MpwXrroSOkITAfMQswCQYDVQQG
+EwJCRTEQMA4GA1UEAxMHdGVzdC1jYYIJALimgW7YUgdrMA8GA1UdEwEB/wQFMAMB
+Af8wEQYJYIZIAYb4QgEBBAQDAgEGMAkGA1UdEgQCMAAwLwYJYIZIAYb4QgENBCIW
+IEluc2VjdXJlLCBmb3IgdGVzdCBwdXJwb3NlcyBvbmx5MAkGA1UdEQQCMAAwDgYD
+VR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4GBAAX8jhgu1O3zSNzKVIWOy//3
+j/ziC1E/D9aE6HaPilSqTNUvcccLPWp/ZTvmr05xehIyC1z1CZzmbhVgmY0XcP49
+M08RetzlwDSJMHDCc7Dt2BMfo0Q3mluOe5Ade8kxT9vyvTWG4wftk+YrUC7eJUsf
+bA5Wryv6jqZEiD0LXRMJ
+-----END CERTIFICATE-----
diff --git a/test/certs/test-ca-cakey.pem b/test/certs/test-ca-cakey.pem
new file mode 100644 (file)
index 0000000..fc30a77
--- /dev/null
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXAIBAAKBgQDqtu17yffI0DLWsrPlc5YKl5wXdxHwmHKXgvXL69r/nRlkUs16
+RPdqBHGp6dRfI1lAIF33Rx1xkeLOC36nmAGDR2GVifkElwzGCrxPrwFUE3ijKspb
+QvhE/JBeOU4KDwkTkX7MWQxQIVi2Du5lw9fVQCyA9OkE/jH7pKRedOJq1QIDAQAB
+AoGAI7tPcg3wK+EOLEMuQdsT1273M1dMIt2CbHBibPXt9AX9jJlScK+5HqmoiB5x
+1z3xY2LKC1AHOnfkGEwFrwvkBsafrww0pvT+SYhPRK9sdtbmO7wkAjUThMEVYKxN
+sTQG60pq871a0Lp7bUhyrBLylZAmc849/7ZJT59Uq0i2wAECQQD1TSPnjneVRaio
++I7Xg1JlB8bbboIgRjmhWaKtlkwpblrsG+hdusb9Deg7GPW9YDIV38BkkuXS+UIB
+FtarAvrVAkEA9POVRxPr+uUYv3n71vmmjpIMDUSKdnqtMqtOyQ8floUo2CIzPAq9
+h6PSN+exhE7TkKCoh3aiBcJCg2UGVDmwAQJBAOspZL5cSjAEc8hpYScich8A8Zbz
+vjQKnr0cHWSkracacHfh2UXiBVobtwLQzuUaD2oA84R3f3ReGPTKXEndtXECQDvf
+aiaEfRLHesQaue7y+L4yfpWjokCRfdI7wzcr5imxhKlHusQ7T9ZeuZyGmoJfjiD0
+1BzAZ5wGvqFFSUW/EAECQFqUEl2uYLByr76a7vniBr6enio5v4WSEf629bG/3idj
+RJrk6hhwMcqFoel0pg8dELQ8zPJwU0skiPurqD0zoiE=
+-----END RSA PRIVATE KEY-----
diff --git a/test/certs/test-client-cert.pem b/test/certs/test-client-cert.pem
new file mode 100644 (file)
index 0000000..e7e18ca
--- /dev/null
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICmjCCAgOgAwIBAgIBAzANBgkqhkiG9w0BAQUFADAfMQswCQYDVQQGEwJCRTEQ
+MA4GA1UEAxMHdGVzdC1jYTAeFw0xMjA1MDcxMDQwMDJaFw0yMjA1MDMxMDQwMDJa
+MCMxCzAJBgNVBAYTAkJFMRQwEgYDVQQDEwt0ZXN0LWNsaWVudDCBnzANBgkqhkiG
+9w0BAQEFAAOBjQAwgYkCgYEAwQMFv/Ds1zw1sc+fu9XsIOcm0FjDYNuxKxVpsSQW
+RDeUvYfoIwHR+YOFyH9OI8pmTfPFsnyjGq0Rv+1Me1f4mbVzvIK7MqYyZU9Np00y
+RKRV4d5ZP5vJjABN67tCILwyXiPrCuOX5qTf7721vRi4aUDzyanOhP6IWIGKxmqL
+mgkCAwEAAaOB4TCB3jAJBgNVHRMEAjAAMBEGCWCGSAGG+EIBAQQEAwIEsDArBglg
+hkgBhvhCAQ0EHhYcVGlueUNBIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E
+FgQUEOyF/tNfGx/luglciCt4H09qoggwTwYDVR0jBEgwRoAUW4hM5QmUasn2Uq5+
+zxybUynBeuuhI6QhMB8xCzAJBgNVBAYTAkJFMRAwDgYDVQQDEwd0ZXN0LWNhggkA
+uKaBbthSB2swCQYDVR0SBAIwADAJBgNVHREEAjAAMAsGA1UdDwQEAwIFoDANBgkq
+hkiG9w0BAQUFAAOBgQCcqGrU56lkOYLY8sx9/atAJB6nfJPanxkP2mddiq46I4Nc
+CEwmqoVJGqsbgv9GLsyLxOa6ycRNNChvc/onBN/ZplxaXdhymmwfxWXRs9OXPZ7p
+fysew0sNvVJmnNtPbcd8mU0E64Mazaxu00BaofhRnHiC6pJsa6pMPSi91Svcaw==
+-----END CERTIFICATE-----
diff --git a/test/certs/test-client-key.pem b/test/certs/test-client-key.pem
new file mode 100644 (file)
index 0000000..562ae59
--- /dev/null
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQDBAwW/8OzXPDWxz5+71ewg5ybQWMNg27ErFWmxJBZEN5S9h+gj
+AdH5g4XIf04jymZN88WyfKMarRG/7Ux7V/iZtXO8grsypjJlT02nTTJEpFXh3lk/
+m8mMAE3ru0IgvDJeI+sK45fmpN/vvbW9GLhpQPPJqc6E/ohYgYrGaouaCQIDAQAB
+AoGAN+IHJSa9fCf7p+rkZb8vaetjSomYsA+LwVymyFoZdFDfaOzTomchg2u4LW/m
+kOhGLKW7BM2fb9bSP86WCVRULrQE7ZfGpU4t3xfzoj0CdhHU7MqU7PFjcExJrHGo
+sqd1MRQgm4GMLhch8pZV9Sw5K8vLZvKr3SSXBl8otsv79vECQQDpBQaMUKKceGx9
+FwZCxOFykAA/PziT8ClgdmhFmaWTFB+9TpJ0YoU13MnCxDhDu/yjad+2g1BRUM5h
+HOLROyQtAkEA1AvuhczOYmBUx/ohgtDANsPPCXVe8zqmNOi7cc+n78Sjz8f8OuuB
+oivbFeDj/BDq4dfbfI7lEi9BnwgfrilqzQJAFCY2Gb4DQap8Hxj1lqJ1qDVhgBaU
+at5yhX/XpmUR1zT/RZxct6mpQS4VWD0lbF3+C5dlG+Ag+tcU8XrQ9iy6BQJBAKQ3
+QVe5jrO9KqtcWQt4IwPGjNYkYY44g3NCMbgoO0SCouJNXFc8/73Z/OdqrOUPLPgO
+NVq3R0vX8Rf6MJ6uUJkCQQC736mEgiiXo3AolviIla+hvnYAiNqZjFlcdxwj9P+8
+8NnRDILFP+G1UuIenR1fbsByHUqjFtrKEZ4k1XJps2PZ
+-----END RSA PRIVATE KEY-----
diff --git a/test/certs/www.example.com-cert.pem b/test/certs/www.example.com-cert.pem
new file mode 100644 (file)
index 0000000..2744ba6
--- /dev/null
@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE-----
+MIICkTCCAfqgAwIBAgIBAjANBgkqhkiG9w0BAQUFADAfMQswCQYDVQQGEwJCRTEQ
+MA4GA1UEAxMHdGVzdC1jYTAeFw0xMjA1MDYwODQyNDlaFw0yMjA1MDMwODQyNDla
+MCcxCzAJBgNVBAYTAkJFMRgwFgYDVQQDEw93d3cuZXhhbXBsZS5jb20wgZ8wDQYJ
+KoZIhvcNAQEBBQADgY0AMIGJAoGBAL7OBv9wRwtNjN984XSy22/rw6tHM6Lq/Ccf
+NoHKbqwC+PsxgmgJJiGBGewrzBR42toqHJi7EjHhuvrgqV9s2duPQBAANh7tzY1h
+6VekrwhIIt4o1h0F2KB16VXA8s918d+8pRGt2T11GUh/QT3m9yY1VzqdIBeAfklC
+ET6ncPK/AgMBAAGjgdQwgdEwCQYDVR0TBAIwADARBglghkgBhvhCAQEEBAMCBkAw
+KwYJYIZIAYb4QgENBB4WHFRpbnlDQSBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYD
+VR0OBBYEFNGQArEZPKprJTn7A64qEFfl0m4xME8GA1UdIwRIMEaAFFuITOUJlGrJ
+9lKufs8cm1MpwXrroSOkITAfMQswCQYDVQQGEwJCRTEQMA4GA1UEAxMHdGVzdC1j
+YYIJALimgW7YUgdrMAkGA1UdEgQCMAAwCQYDVR0RBAIwADANBgkqhkiG9w0BAQUF
+AAOBgQDWh8A0eBxI9XHy68xdjFsk2oerJeV6qqlcmtPZgz3GlarRcWcKsRJOyLLL
+dCOe7tY5isWQAoLt6XALzDWjbQkTJnxBaKHif1MIikuajaYKT7LA1MvFn50Qrm6n
+f9hG7gvdTpm1rlPcs0qibp1vJVubkU51mT6JT4UnLfeVIjtL7Q==
+-----END CERTIFICATE-----
diff --git a/test/certs/www.example.com-key.pem b/test/certs/www.example.com-key.pem
new file mode 100644 (file)
index 0000000..add6780
--- /dev/null
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXgIBAAKBgQC+zgb/cEcLTYzffOF0sttv68OrRzOi6vwnHzaBym6sAvj7MYJo
+CSYhgRnsK8wUeNraKhyYuxIx4br64KlfbNnbj0AQADYe7c2NYelXpK8ISCLeKNYd
+BdigdelVwPLPdfHfvKURrdk9dRlIf0E95vcmNVc6nSAXgH5JQhE+p3DyvwIDAQAB
+AoGBAIZldIRkP4Z0n2+j9OJQQUS6Wl7AjlyJDAc6cxhE0GOUzG+S1foVx6f92ZaC
+2wLoha75zp691fkQuLWRnXu7nk9QwxQdOppKijIPHdL2cYtUc9UCedN5rExjpcOP
+4Hjwf17YOxK2J0zzmG1djTBB47BKGUedSQ7E1QxGcrESS2XxAkEA+6ey2jy8etWi
+QmCdJJIxXwKRVHCmt5LVwj+IOk/u3sr1AGfBm7spKGU3boCiFt4FmjGMax7B9r/e
+zPaMb34guwJBAMIZX7Vv5gfjvWtgp6pyE/UkjRSOKBpuy9gyiqtLBJwehj/qsBqr
+O6tFmjMFiudVusnVSrEFGAPLV52xf0U4580CQQDkEQ1UH2spX2dYBLslo6A+3NLc
+1eMhx18WVgGd50cyfnkfzuh1vF8GjwR3jvhXBQvKvFDn284pU6YV1vNbL9F1AkEA
+o2CwSwyRV3q+6i9Fchbr7aCCkBbIctdoBeclCeHvU2nuHsbwzMHtS9EeZmv365kh
+zNoYMMDU4fy7FyVct2ua0QJASXtIwYKZ2CAP+lAQqfh+knRRqtqdLt4Lt0mpML5m
+UtsECS8frKeF3mynXfsyRkvC8F2WFiJVJ3+D+y3zYNGlZg==
+-----END RSA PRIVATE KEY-----
diff --git a/test/client-cert-verify--client.sh b/test/client-cert-verify--client.sh
new file mode 100755 (executable)
index 0000000..af208d3
--- /dev/null
@@ -0,0 +1,3 @@
+#!/bin/sh -x
+
+socat -v - OPENSSL:localhost:18443,cert=test/certs/test-client-cert.pem,key=test/certs/test-client-key.pem,cafile=test/certs/test-ca-cacert.pem
diff --git a/test/client-cert-verify--server.sh b/test/client-cert-verify--server.sh
new file mode 100755 (executable)
index 0000000..ef6bb3d
--- /dev/null
@@ -0,0 +1,3 @@
+#!/bin/sh -x
+
+socat -v OPENSSL-LISTEN:18443,reuseaddr,fork,cert=test/certs/www.example.com-cert.pem,key=test/certs/www.example.com-key.pem,cafile=test/certs/test-ca-cacert.pem,verify=1 -
diff --git a/test/client.sh b/test/client.sh
new file mode 100755 (executable)
index 0000000..82519fa
--- /dev/null
@@ -0,0 +1,10 @@
+#!/bin/sh
+
+#cmd="./openssl-1.0.1b/apps/openssl s_client -connect localhost:8443 -CAfile test/certs/sslcaudit-test-cacert.pem -showcerts -verify 9 -showcerts"
+#cmd="socat - OPENSSL:localhost:8443,cafile=test/certs/sslcaudit-test-cacert.pem"
+cmd="curl --cacert test/certs/sslcaudit-test-cacert.pem https://localhost:8443/"
+
+while true ; do
+       $cmd < /dev/null
+       sleep .5
+done
diff --git a/test/exthammer.sh b/test/exthammer.sh
new file mode 100755 (executable)
index 0000000..3e993f0
--- /dev/null
@@ -0,0 +1,112 @@
+#!/bin/sh -xe
+
+# ----------------------------------------------------------------------
+# SSLCAUDIT - a tool for automating security audit of SSL clients
+# Released under terms of GPLv3, see COPYING.TXT
+# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+# ----------------------------------------------------------------------
+
+#
+# Tries to run
+# Exits with 0 if all went through, 1 if hammer fails
+#
+
+ciphers='HIGH MEDIUM LOW EXPORT40 NULL'
+methods='SSLv2 SSLv3 TLSv1'
+
+sslcaudit="./sslcaudit --user-cn=user-cn.nonexistent.gremwell.com"
+test_host='localhost'
+test_port='8443'
+
+wait_on_prefail=.1
+max_nprefailures=10
+max_nconnected=10
+wait_on_postfail=.1
+max_npostfailures=2
+
+NAMEWIDTH=-25
+
+do_test() {
+       local hammer=$1
+       local method=$2
+       local cipher=$3
+
+       outf=`mktemp --tmpdir exthammer-XXXXXX`
+
+       test_name="$hammer $method $cipher"
+
+       # start sslcaudit in background
+       sslcaudit_errf="$outf.sslcaudit"
+
+       $sslcaudit -N "$test_name" -l $test_host:$test_port 2> "$sslcaudit_errf" &
+       sslcaudit_pid=$!
+
+       # start hammering
+       hammer_outf="$outf.hout"
+
+       nprefailures=0
+       nconnected=0
+       npostfailures=0
+
+       echo "START" >> $hammer_outf
+       while true ; do
+               if ${0}_$hammer $test_host $test_port $method $cipher >> $hammer_outf 2>&1 ; then
+                       echo "# CONNECTED" >> $hammer_outf
+                       if [ $npostfailures -gt 0 ] ; then
+                               # connect after a postfailure? wierd
+                               echo "ERROR: connect after npostfailures=$npostfailures"
+                               #cat $hammer_outf
+                               kill $sslcaudit_pid || true
+                               break
+                       else
+                               nconnected=`expr $nconnected + 1`
+                               if [ $nconnected -ge $max_nconnected ] ; then
+                                       printf "%${NAMEWIDTH}s %s\n" "$test_name" "*** excessive nconnected=$nconnected ***"
+                                       kill $sslcaudit_pid || true
+                                       break
+                               fi
+                       fi
+               else
+                       if [ $nconnected -eq 0 ] ; then
+                               echo "# PREFAILURE" >> $hammer_outf
+                               nprefailures=`expr $nprefailures + 1`
+                               if [ $nprefailures -ge $max_nprefailures ] ; then
+                                       printf "%${NAMEWIDTH}s %s\n" "$test_name" "*** excessive nprefailures=$nprefailures ***"
+                                       kill $sslcaudit_pid || true
+                                       break
+                               fi
+
+                               sleep $wait_on_prefail
+                       else
+                               echo "# POSTFAILURE" >> $hammer_outf
+                               npostfailures=`expr $npostfailures + 1`
+                               [ $npostfailures -ge $max_npostfailures ] && break
+
+                               sleep $wait_on_postfail
+                       fi
+               fi
+       done
+
+       # let sslcaudit die, don't care if it is unwell
+       wait $sslcaudit_pid || true
+}
+
+do_tests() {
+       local hammer=$1
+       local method
+       for method in $methods ; do
+               local cipher
+               for cipher_str in $ciphers ; do
+                       do_test $hammer $method $cipher_str
+               done
+       done
+}
+
+# -----------------------------------------------------------------
+
+#[ $# -eq 1 ] || exit
+#local hammer=$1
+
+do_tests socat
+
+exit 0
diff --git a/test/exthammer.sh_socat b/test/exthammer.sh_socat
new file mode 100755 (executable)
index 0000000..a3c13f1
--- /dev/null
@@ -0,0 +1,36 @@
+#!/bin/sh -e
+
+# ----------------------------------------------------------------------------
+# SSLCAUDIT - a tool for automating security audit of SSL clients
+# Released under terms of GPLv3, see COPYING.TXT
+# Copyright (C) 2012 Alexandre Bezroutchko abb@gremwell.com
+# ----------------------------------------------------------------------------
+
+
+[ $# -eq 4 ] || exit 1
+
+host=$1
+port=$2
+method=$3
+cipher=$4
+
+socat_errf=`mktemp --tmpdir exthammer-socat-XXXXXX`
+
+socat EXEC:'date' OPENSSL:$host:$port,method=$method,cipher=$cipher 2> "$socat_errf" > /dev/null || true
+
+if [ -s "$socat_errf" ] ; then
+       # there is something on stderr
+       if grep 'Connection refused$' "$socat_errf" ; then
+               # there is connrefused
+               false
+       else
+               # connrefused not found
+               cat "$socat_errf"
+               true
+       fi
+else
+       # errfile is empty
+       true
+fi
+
+#rm "$socat_errf"
diff --git a/test/ssl-client.py b/test/ssl-client.py
new file mode 100644 (file)
index 0000000..143439c
--- /dev/null
@@ -0,0 +1,31 @@
+import M2Crypto, socket, time
+from M2Crypto.SSL import SSLError
+
+def mycallback():
+    pass
+
+context = M2Crypto.SSL.Context() 
+context.load_verify_info(capath="/etc/ssl/certs/")
+context.set_allow_unknown_ca(True) 
+context.set_verify(M2Crypto.SSL.verify_none, 9, callback=mycallback)
+
+#conn = M2Crypto.SSL.Connection(context) 
+#conn.connect(('localhost', 8443))
+
+
+sock = socket.socket()
+sock.connect(('localhost', 18443))
+
+conn = M2Crypto.SSL.Connection(ctx=context, sock=sock)
+conn.setup_ssl()
+try:
+    res = conn.connect_ssl()
+    print res
+except SSLError as ex:
+    print 'ssl handshake failed: ', ex
+
+server_cert = conn.get_peer_cert()
+if server_cert is not None:
+    print 'server cert available: ', server_cert.get_subject()
+else:
+    print 'server cert is not available'
diff --git a/test/sslcaudit-selftest-all.sh b/test/sslcaudit-selftest-all.sh
new file mode 100755 (executable)
index 0000000..52c7213
--- /dev/null
@@ -0,0 +1,11 @@
+#!/bin/sh -xe
+
+for testno in 0 1 2; do 
+       ./sslcaudit \
+               --user-cn localhost \
+               --server 62.213.200.252:443 \
+               --user-cert test/certs/www.example.com-cert.pem --user-key test/certs/www.example.com-key.pem \
+               --user-ca-cert test/certs/test-ca-cacert.pem --user-ca-key test/certs/test-ca-cakey.pem \
+               -T $testno
+done
+