summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml31
-rw-r--r--AUTHORS4
-rw-r--r--CMakeLists.txt55
-rw-r--r--CONTRIBUTING.md1
-rw-r--r--LICENSE.LGPL504
-rw-r--r--README.md110
-rw-r--r--RELEASE-NOTES.txt168
-rw-r--r--cmake/README.txt1
-rw-r--r--cmake/modules/FindIconv.cmake58
-rw-r--r--cmake/modules/FindLdap.cmake35
-rw-r--r--cmake/modules/FindLibDigiDoc.cmake28
-rw-r--r--cmake/modules/FindLibDigiDocpp.cmake28
-rw-r--r--cmake/modules/FindMiniZip.cmake30
-rw-r--r--cmake/modules/FindPCSCLite.cmake44
-rw-r--r--cmake/modules/FindPKCS11.cmake24
-rw-r--r--cmake/modules/FindXSD.cmake52
-rw-r--r--cmake/modules/FindXercesC.cmake30
-rw-r--r--cmake/modules/FindXmlSecurityC.cmake38
-rw-r--r--cmake/modules/MacOSXBundleInfo.plist.in36
-rw-r--r--cmake/modules/VersionInfo.cmake95
-rw-r--r--cmake/modules/win81.exe.manifest24
-rw-r--r--config.h.cmake7
-rw-r--r--debian/changelog5
-rw-r--r--debian/compat1
-rw-r--r--debian/control129
-rw-r--r--debian/copyright28
-rw-r--r--debian/libdigidoc-common.install2
-rw-r--r--debian/libdigidoc-dev.install4
-rw-r--r--debian/libdigidoc-doc.install1
-rw-r--r--debian/libdigidoc-tools.install2
-rw-r--r--debian/libdigidoc2.install1
-rw-r--r--debian/patches/01-manpage.patch32
-rw-r--r--debian/patches/02-no-rpath.patch12
-rw-r--r--debian/patches/series2
-rwxr-xr-xdebian/rules23
-rw-r--r--debian/source/format1
-rw-r--r--debian/watch3
-rw-r--r--doc/SK-CDD-PRG-GUIDE.docxbin0 -> 783618 bytes
-rw-r--r--doc/SK-CDD-PRG-GUIDE.pdfbin0 -> 1050094 bytes
-rw-r--r--doc/SK-COM-PRG-GUIDE.docxbin0 -> 764984 bytes
-rw-r--r--doc/SK-COM-PRG-GUIDE.pdfbin0 -> 1110158 bytes
-rw-r--r--doc/doxygen-license.txt8
-rw-r--r--doc/mit-license.txt26
-rw-r--r--doc/openssl-license.txt131
-rw-r--r--doc/sample_files_CDD.zipbin0 -> 38033 bytes
-rw-r--r--doc/zlib-license.txt25
-rw-r--r--etc/Doxyfile.in1804
-rw-r--r--etc/certs/EECCRCA.crt24
-rw-r--r--etc/certs/EID-SK 2007 OCSP 2010.crt21
-rw-r--r--etc/certs/EID-SK 2007 OCSP.crt17
-rw-r--r--etc/certs/EID-SK 2007.crt20
-rw-r--r--etc/certs/EID-SK 2011.crt29
-rw-r--r--etc/certs/EID-SK OCSP 2006.crt18
-rw-r--r--etc/certs/EID-SK OCSP.crt20
-rw-r--r--etc/certs/EID-SK.crt24
-rw-r--r--etc/certs/ESTEID-SK 2007 OCSP 2010.crt23
-rw-r--r--etc/certs/ESTEID-SK 2007 OCSP.crt19
-rw-r--r--etc/certs/ESTEID-SK 2007.crt20
-rw-r--r--etc/certs/ESTEID-SK 2011.crt29
-rw-r--r--etc/certs/ESTEID-SK OCSP 2005.crt20
-rw-r--r--etc/certs/ESTEID-SK OCSP.crt22
-rw-r--r--etc/certs/ESTEID-SK.crt29
-rw-r--r--etc/certs/JUUR-SK.crt29
-rw-r--r--etc/certs/KLASS3-SK 2010 EECCRCA.crt27
-rw-r--r--etc/certs/KLASS3-SK 2010 OCSP.crt25
-rw-r--r--etc/certs/KLASS3-SK 2010.crt23
-rw-r--r--etc/certs/KLASS3-SK OCSP 2006.crt18
-rw-r--r--etc/certs/KLASS3-SK OCSP 2009.crt20
-rw-r--r--etc/certs/KLASS3-SK OCSP.crt21
-rw-r--r--etc/certs/KLASS3-SK.crt24
-rw-r--r--etc/certs/README.txt1
-rw-r--r--etc/certs/SK OCSP 2011.crt28
-rw-r--r--etc/certs/TEST EECCRCA.crt24
-rw-r--r--etc/certs/TEST EID-SK 2011.crt28
-rw-r--r--etc/certs/TEST ESTEID-SK 2011.crt28
-rw-r--r--etc/certs/TEST Juur-SK.crt23
-rw-r--r--etc/certs/TEST KLASS3 2010.crt28
-rw-r--r--etc/certs/TEST SK OCSP 2011.crt27
-rw-r--r--etc/certs/TEST-SK OCSP 2005.crt17
-rw-r--r--etc/certs/TEST-SK.crt21
-rw-r--r--etc/digidoc.conf.cmake172
-rw-r--r--libdigidoc.spec69
-rw-r--r--libdigidoc.wxs111
-rw-r--r--libdigidoc/CMakeLists.txt153
-rw-r--r--libdigidoc/DigiCrypt.c1006
-rw-r--r--libdigidoc/DigiCrypt.h28
-rw-r--r--libdigidoc/DigiDocCert.c1981
-rw-r--r--libdigidoc/DigiDocCert.h364
-rw-r--r--libdigidoc/DigiDocConfig.c2211
-rw-r--r--libdigidoc/DigiDocConfig.h425
-rw-r--r--libdigidoc/DigiDocConvert.c1373
-rw-r--r--libdigidoc/DigiDocConvert.h303
-rw-r--r--libdigidoc/DigiDocCsp.c2229
-rw-r--r--libdigidoc/DigiDocCsp.h132
-rw-r--r--libdigidoc/DigiDocDebug.c170
-rw-r--r--libdigidoc/DigiDocDebug.h75
-rw-r--r--libdigidoc/DigiDocDefs.h180
-rw-r--r--libdigidoc/DigiDocDfExtract.c405
-rw-r--r--libdigidoc/DigiDocDfExtract.h48
-rw-r--r--libdigidoc/DigiDocEnc.c2743
-rw-r--r--libdigidoc/DigiDocEnc.h917
-rw-r--r--libdigidoc/DigiDocEncGen.c522
-rw-r--r--libdigidoc/DigiDocEncGen.h74
-rw-r--r--libdigidoc/DigiDocEncSAXParser.c1155
-rw-r--r--libdigidoc/DigiDocEncSAXParser.h70
-rw-r--r--libdigidoc/DigiDocError.c604
-rw-r--r--libdigidoc/DigiDocError.h310
-rw-r--r--libdigidoc/DigiDocGen.c1925
-rw-r--r--libdigidoc/DigiDocGen.h200
-rw-r--r--libdigidoc/DigiDocGlobals.c65
-rw-r--r--libdigidoc/DigiDocGlobals.h69
-rw-r--r--libdigidoc/DigiDocHTTP.c44
-rw-r--r--libdigidoc/DigiDocHTTP.h4
-rw-r--r--libdigidoc/DigiDocLib.c1173
-rw-r--r--libdigidoc/DigiDocLib.h239
-rw-r--r--libdigidoc/DigiDocMem.c291
-rw-r--r--libdigidoc/DigiDocMem.h108
-rw-r--r--libdigidoc/DigiDocOCSP.c1670
-rw-r--r--libdigidoc/DigiDocOCSP.h152
-rw-r--r--libdigidoc/DigiDocObj.c4415
-rw-r--r--libdigidoc/DigiDocObj.h1291
-rw-r--r--libdigidoc/DigiDocPKCS11.c956
-rw-r--r--libdigidoc/DigiDocPKCS11.h86
-rw-r--r--libdigidoc/DigiDocParser.c1243
-rw-r--r--libdigidoc/DigiDocParser.h107
-rw-r--r--libdigidoc/DigiDocSAXParser.c3237
-rw-r--r--libdigidoc/DigiDocSAXParser.h105
-rw-r--r--libdigidoc/DigiDocService.c341
-rw-r--r--libdigidoc/DigiDocService.h102
-rw-r--r--libdigidoc/DigiDocStack.c315
-rw-r--r--libdigidoc/DigiDocStack.h137
-rw-r--r--libdigidoc/DigiDocVerify.c1972
-rw-r--r--libdigidoc/DigiDocVerify.h178
-rw-r--r--libdigidoc/DlgUnit.c688
-rw-r--r--libdigidoc/DlgUnit.h3
-rw-r--r--libdigidoc/DlgUnit.manifest23
-rw-r--r--libdigidoc/DlgUnit.rc134
-rw-r--r--libdigidoc/DlgUnitS.c476
-rw-r--r--libdigidoc/cdigidoc.1.cmake244
-rw-r--r--libdigidoc/cdigidoc.c2559
-rw-r--r--libdigidoc/cdigidoc.rc43
-rw-r--r--libdigidoc/libdigidoc.pc.cmake10
-rw-r--r--libdigidoc/libdigidoc.rc43
-rw-r--r--libdigidoc/pkcs11/cryptoki.h96
-rw-r--r--libdigidoc/pkcs11/pkcs11.h288
-rw-r--r--libdigidoc/pkcs11/pkcs11f.h898
-rw-r--r--libdigidoc/pkcs11/pkcs11t.h1334
-rw-r--r--libdigidoc/pkcs11/unix.h24
-rw-r--r--libdigidoc/rc.rctbin0 -> 488 bytes
-rw-r--r--libdigidoc/res.rc94
-rw-r--r--libdigidoc/resource.h16
-rw-r--r--libxml2-2.9.2-patches.zipbin0 -> 7018 bytes
-rw-r--r--prepare_win_build_environment.ps199
-rw-r--r--vc2008/cdigidoc.vcproj207
-rw-r--r--vc2008/libdigidoc.ncbbin0 -> 27675648 bytes
-rw-r--r--vc2008/libdigidoc.sln37
-rw-r--r--vc2008/libdigidoc.suobin0 -> 53248 bytes
-rw-r--r--vc2008/libdigidoc.vcproj406
-rw-r--r--vc2008/libdigidoc_vs.sln37
-rw-r--r--vc2010/DigiDocLib.vcxproj206
-rw-r--r--vc2010/digidoc.vcxproj146
-rw-r--r--vc2010/libdigidoc.sln61
162 files changed, 50817 insertions, 0 deletions
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..528953b
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,31 @@
+before_install: if [ "${TRAVIS_OS_NAME}" = "osx" ]; then
+ brew update;
+ else
+ sudo apt-get update -qq;
+ sudo apt-get install -y cmake libxml2-dev libssl-dev;
+ fi
+script:
+- mkdir build
+- cd build
+- cmake ..
+- make
+
+os:
+ - linux
+ - osx
+
+env:
+ global:
+ # The next declaration is the encrypted COVERITY_SCAN_TOKEN, created
+ # via the "travis encrypt" command using the project repo's public key
+ - secure: "AhDg868E2SgZbGhsFyDQd19IVCZcQ2a7shdojRTxIxF10TGhAleFEtm4EAoXjjgCPcGY52o1aVaEMea/GRnLR6oLQ592igxNHjTlTGKcDp5w28xVq9m7d4JVrvUeYvKoi+szS4Ah8zhraGdssMaq8LtZzLbaoEXCaMCDRlXPGro="
+
+addons:
+ coverity_scan:
+ project:
+ name: "open-eid/libdigidoc"
+ description: "Build submitted via Travis CI"
+ notification_email: raul@metsma.ee
+ build_command_prepend: "mkdir coverity; cd coverity; cmake .."
+ build_command: make
+ branch_pattern: coverity_scan
diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000..139c00c
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,4 @@
+Veiko Sinivee <veiko.sinivee@seb.se>
+ The main project leader and author of DigiDoc library.
+Martin Paljak <martin@paljak.pri.ee>
+ Integrator, fixer, packaging maintainer.
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..c55cd36
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,55 @@
+cmake_minimum_required( VERSION 2.8 )
+project( libdigidoc )
+
+set( CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules" )
+set( CMAKE_FIND_ROOT_PATH ${CMAKE_OSX_SYSROOT} )
+set( INSTALL_DOC false CACHE BOOL "Install documentation" )
+if( APPLE )
+ set( FRAMEWORK YES CACHE BOOL "Build library as Mac OS X Framework" )
+endif()
+
+include( CheckIncludeFiles )
+include( VersionInfo )
+include( GNUInstallDirs )
+
+if( WIN32 )
+ set( DIGIDOC_CONF_NAME "digidoc.ini" )
+else()
+ set( DIGIDOC_CONF_NAME "digidoc.conf" )
+endif()
+
+find_package( Doxygen )
+find_package( LibXml2 REQUIRED )
+find_package( OpenSSL REQUIRED )
+find_package( PKCS11 )
+find_package( ZLIB REQUIRED )
+find_package( Iconv )
+
+if( INSTALL_DOC )
+ if( DOXYGEN_FOUND )
+ configure_file( ${CMAKE_SOURCE_DIR}/etc/Doxyfile.in Doxyfile @ONLY )
+ add_custom_target( docs ALL
+ ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ COMMENT "Generating API documentation with Doxygen" VERBATIM
+ )
+ install( DIRECTORY ${CMAKE_BINARY_DIR}/doc/ DESTINATION ${CMAKE_INSTALL_DATADIR}/doc/libdigidoc )
+ endif()
+ install( DIRECTORY doc/ DESTINATION ${CMAKE_INSTALL_DATADIR}/doc/libdigidoc PATTERN ".svn" EXCLUDE )
+endif()
+
+configure_file( config.h.cmake config.h )
+
+include_directories(
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${LIBXML2_INCLUDE_DIR}
+ ${OPENSSL_INCLUDE_DIR}
+ ${ZLIB_INCLUDE_DIR}
+)
+if( ICONV_FOUND )
+ include_directories( ${ICONV_INCLUDE_DIR} )
+endif()
+
+add_subdirectory( libdigidoc )
+
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..7e717b5
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1 @@
+Please read the [common contributing guidelines](https://github.com/open-eid/org/blob/master/CONTRIBUTING.md) before you continue!
diff --git a/LICENSE.LGPL b/LICENSE.LGPL
new file mode 100644
index 0000000..5ab7695
--- /dev/null
+++ b/LICENSE.LGPL
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+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 this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+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
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY 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
+LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d263ab8
--- /dev/null
+++ b/README.md
@@ -0,0 +1,110 @@
+# libdigidoc
+
+ * License: LGPL 2.1
+ * &copy; Estonian Information System Authority
+
+Dependencies
+---------------------------
+You need the following dependent librarys to build libdigidoc:
+- openssl - https://www.openssl.org/ - Apache style license
+- libxml2 - http://xmlsoft.org/ - MIT license
+- zlib - http://www.zlib.net/ - zlib license
+- iconv - https://www.gnu.org/software/libiconv/ - LGPL license
+- doxygen - http://www.stack.nl/~dimitri/doxygen/ - doxygen license
+
+
+Full documentation
+----------------------------
+For documentation please see in doc folder SK-CDD-PRG-GUIDE
+Contact for assistance by email abi@id.ee or http://www.id.ee
+
+## Building
+[![Build Status](https://travis-ci.org/open-eid/libdigidoc.svg?branch=master)](https://travis-ci.org/open-eid/libdigidoc)
+[![Coverity Scan Build Status](https://scan.coverity.com/projects/724/badge.svg)](https://scan.coverity.com/projects/724)
+
+### Ubuntu
+
+1. Install dependencies
+
+ sudo apt-get install cmake libxml2-dev libssl-dev
+
+2. Fetch the source
+
+ git clone --recursive https://github.com/open-eid/libdigidoc
+ cd libdigidoc
+
+3. Configure
+
+ mkdir build
+ cd build
+ cmake ..
+
+4. Build
+
+ make
+
+5. Install
+
+ sudo make install
+
+6. Execute
+
+ /usr/local/bin/cdigidoc
+
+### OSX
+
+1. Install dependencies from [http://www.cmake.org](http://www.cmake.org)
+
+2. Fetch the source
+
+ git clone --recursive https://github.com/open-eid/libdigidoc
+ cd libdigidoc
+
+3. Configure
+
+ mkdir build
+ cd build
+ cmake ..
+
+4. Build
+
+ make
+
+5. Install
+
+ sudo make install
+
+6. Execute
+
+ /usr/local/bin/cdigidoc
+
+### Windows
+
+1. Install dependencies from
+ * [Visual Studio Express 2013 for Windows Desktop](http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx)
+ * [Libxml2](http://xmlsoft.org/downloads.html)
+ * [OpenSSL Win32 binaries](https://slproweb.com/products/Win32OpenSSL.html) or [OpenSSL source](https://www.openssl.org/source/)
+ * [ZLib source](http://zlib.net/zlib128.zip)
+2. Fetch the source
+
+ git clone --recursive https://github.com/open-eid/libdigidoc
+ cd libdigidoc
+
+3. Configure
+
+ mkdir build
+ cd build
+ cmake ..
+
+4. Build
+
+ make
+
+5. Execute
+
+ libdigidoc/cdigidoc.exe
+
+## Support
+Official builds are provided through official distribution point [installer.id.ee](https://installer.id.ee). If you want support, you need to be using official builds. Contact for assistance by email [abi@id.ee](mailto:abi@id.ee) or [www.id.ee](http://www.id.ee).
+
+Source code is provided on "as is" terms with no warranty (see license for more information). Do not file Github issues with generic support requests.
diff --git a/RELEASE-NOTES.txt b/RELEASE-NOTES.txt
new file mode 100644
index 0000000..3ca40ce
--- /dev/null
+++ b/RELEASE-NOTES.txt
@@ -0,0 +1,168 @@
+DigiDoc C library 3.10 release notes
+-----------------------------------
+Changes compared to ver 3.9.1
+
+- Changed validation process of OCSP response so that the responder’s certificate reference is taken from the response instead of the signature’s XML.
+- Improved DDOC document validation. It is now checked that the issuance time of the OCSP response would be in the validity period of the signer's certificate.
+- Changed the validation of DDOC documents so that multiple data files with the same name would be allowed in the container.
+- Improved utility program's output during DDOC document validation. If the signer's certificate is from live CA chain but OCSP confirmation has been issued from test OCSP responder then warning 172 "Signer from LIVE CA-chain but OCSP from TEST CA-chain!" is returned.
+- Removed duplicate configuration file entry CA_CERT_6 to fix KLASS3-SK 2010 (KLASS3-SK 2010 EECCRCA.crt) certificate's configuration settings.
+- Removed Finnish CA certificates from digidoc.ini default configuration file. It is recommended to use BDOC format and relevant software instead.
+- Development of the software can now be monitored in GitHub environment: https://github.com/open-eid/libdigidoc
+
+Known issues:
+- Validation of documents in DDOC 1.0 format fails on Ubuntu LTS upgrade 14.4.1 and newer due to incompatibility in OpenSSL base library openssl_1.0.1f-1ubuntu2.8. The problem does not occur on Ubuntu 14.4 with openssl_1.0.1f-1ubuntu2.7, OSX and Windows platforms.
+
+
+
+DigiDoc C library 3.9.1 release notes
+-----------------------------------
+Changes compared to ver 3.9
+
+- DDOC security fixes:
+ - Improved XML structure validation for DDOC files. This is a highly relevant security fix having an effect on the validation of DDOC files. The unfixed library can mistakenly give positive results on validation of invalid DDOC files with incorrect XML elements' ordering.
+
+
+
+DigiDoc C library 3.9 release notes
+-----------------------------------
+Changes compared to ver 3.8
+
+- Improved checking of signer certificate's CA chain length during signature creation and validation. Previously it was not possible to create signature if there was only one CA certificate in the certificate chain.
+- Improved DDOC files' validation, added check that the signer certificate's data would match the X509SerialNumber and X509IssuerName elements' contents.
+- Improved DDOC files validation, added check for Transforms elements which are not supported in DDOC files.
+- Changed signature adding and removal restrictions in case of erroneous files (incl. files that are valid with warnings). No restrictions are made to adding or removing signatures, except of in case of files that are in old format (DIGIDOC-XML 1.0, 1.1, 1.2).
+- Fixed error of handling quotation marks in ClaimedRole and SignatureProductionPlace elements during signature creation and validation. Quotation marks are not replaced during canonicalization according to Canonical XML Version 1.0. Note that as a result, the files that contain quotation marks in the respective elements and have been created with v3.9 might not be compatible with v3.8 of the library.
+- Fixed handling of special characters <, >, & and carriage return in X509IssuerName and ResponderID elements. The characters are now replaced during canonicalization according to Canonical XML Version 1.0. Note that as a result, the files that contain these special characters in the respective elements and have been created with v3.9 might not be compatible with v3.8 of the library.
+- Fixed error which occurred when parsing DDOC document's data file name that contains '&' special character. Previously, the character was erroneously displayed in escaped form.
+- Fixed error that occurred during signature creation when Windows redirected directories were used. Occasionally, writing the ddoc file to redirected directory did not succeed due to synchronization problems.
+- Fixed error that caused the library to exit unexpectedly when trying to parse a DDOC file that contained a large number of validation errors.
+- Changed compression functionality during CDOC encryption process to deprecated, by default the data is never compressed. Removed DENC_COMPRESS_MODE configuration file parameter.
+- Updated cdigidoc.exe utility program's commands "-encrypt-sk", "-encrypt-file" and "-encrypt" so that "MimeType", "OriginalMimeType" and "orig_file" encryption properties are set according to CDOC 1.0 specification.
+- Changed ddsGetStatus() function in DigiDocService.h source file to deprecated status, use ddsGetStatusWithFile() instead. The ddsGetStatusWithFile() function enables to determine the DDOC file name to which the signature value is added.
+- Added command "-mid-test" to cdigidoc-exe utility program, to be used for testing purposes only. The command enables to test the whole Mobile-ID signing process, including creating new DDOC container, adding data file, creating signature, validating the created signature and extracting data files.
+- Fixed cdigidoc utility program's "-libraryerrors" parameter functionality. When the parameter is set then only the errors that are returned by the library are now displayed as "LIBRARY-ERROR".
+- Used coverity.com static analysis tool to find source code defects and vulnerabilities.
+
+
+
+DigiDoc C library 3.8 release notes
+-----------------------------------
+Changes compared to ver 3.7.2
+
+- Started using coverity.com static analysis tool to find source code defects and vulnerabilities. Fixed resource leak and NULL pointer problems that were discovered.
+- Fixed createDataFileInMemory() method, added fixed SHA-1 digest type value when creating new data file.
+- Added support for new KLASS3-SK 2010 CA certificate.
+- Improved the validation of signer's certificate path, added check if all of the chain's certificates validity period includes the signature creation time (producedAt field's value in OCSP response).
+- Improved error handling in case of missing CA certificates and certificates in wrong format, error code 36 is returned in this case. Only PEM format is supported for CA certificates.
+- Added support for extracting data files from container so that the data is kept only in internal memory buffers. Added command –extract-mem to cdigidoc.c utility program.
+- Added validation support for DDOC signatures that are created with Finnish live and test certificates. The certificate files have to be installed with separate packages. The live certificates package contains Finnish root CA certificate (http://fineid.fi/default.aspx?id=596) and certificates which are included in the Finnish national Trust Service List (TSL) (https://www.viestintavirasto.fi/attachments/TSL-Ficora.xml). Finnish test certificates (http://fineid.fi/default.aspx?id=597) are included in the overall test certificates package.
+- Fixed error handling in case of NULL values in DDOC file’s format and version variables. Acknowledgements. Sertifitseerimiskeskus and RIA thank Aivar Liimets for his contribution.
+- Added possibility get all validation error codes that were found during DDOC file’s parsing and validation process instead of only one error code returned by the validation function verifySignatureAndNotary(). Added error code 173, which is returned in case of multiple errors. Library user must check the list of multiple errors by using new API functions getLastErrorsIdx(), getErrorsInfo() (in source file DigiDocError.c).
+- Added warnings system to the library. In case of minor technical errors in the signed DigiDoc file, validation result VALID WITH WARNINGS is used, meaning that the file is legally valid but further alterations (adding/removing signatures) are restricted. It is recommended for the programmers to implement the usage validation status VALID WITH WARNINGS as described in documentation. The warnings system is implemented in cdigidoc.c utility program (identically to DigiDoc3 Client desktop applicaton), warning situations include:
+ - DDOC file's <DataFile> element's xmlns attribute is missing (error code 169)
+ - The DigiDoc file format is older than officially accepted, i.e. the file is DDOC 1.0, 1.1, 1.2 (error code 171).
+ - DDOC file's <X509IssuerName> or <X509SerialNumber> element's xmlns attribute is missing (error code 170).
+ - The signature has been created with a test certificate (error code 172).
+- Changed the priorities of DigiDoc file's validation result statuses.
+- Added error codes 168 (ERR_DF_NAME), 169 (ERR_DF_WRONG_DIG), 170 (ERR_ISSUER_XMLNS), 171 (ERR_OLD_VERSION), 172 (ERR_TEST_SIGNATURE), 173 (ERR_UNKNOWN_ERROR).
+- Fixed nonce asn.1 prefix verification if nonce has no prefix but first 2 bytes match required prefix value.
+- Added validation check of signer’s roles. Maximum 2 <ClaimedRole> elements are supported by the library in a DDOC file.
+- Added check for duplicate <DataFile> element’s fileName attribute. Multiple data files with the same file name in a single container are not supported.
+- Improved <DataFile> element's Id attribute validation. Added support for <DataFile> element’s Id attribute value DO (capital O, not zero).
+- Improved error handling of invalid DDOC files with a missing <DataFile> element. Error 44 ERR_BAD_DATAFILE_COUNT is produced in case of such files.
+- Fixed CDOC file’s <EncryptionProperty Name="DocumentFormat"> element’s value, ENCDOC-XML 1.0 is used instead of ENCDOC-XML 1.1.
+- Fixed –validate command’s output in cdigidoc.c utility program to show validation result correctly in case if one signature among multiple signatures is erroneous.
+- Removed -list command line parameter from cdigidoc.c utility program, changed -verify command so that it replaces the –list command (validates the file and also prints out the data file list).
+- Fixed error handling in cdigidoc.c utility program if input DDOC file name contained also “.cdoc” in the file’s name.
+- It is not allowed to add or remove signatures from DigiDoc files with missing <DataFile> element’s xmlns attribute.
+- Removed configuration file parameter CHECK_SIGNATURE_VALUE_ASN1. Signature values with erroneous ASN.1 prefix values are regarded as not valid.
+- Changed function verifiedByWrongDataFileHash() to deprecated.
+
+- DDOC/CDOC security fixes:
+- Added check that <DigestValue> and <ClaimedRole> elements that are verified are within signed content. This is a highly relevant security fix. Without this fix malicious ddoc files with data not signed by original signer but added by third parties later could have been verified to be valid.
+- Fixed validation of OCSP response, added check that the OCSP response corresponds to the signer’s certificate. This is a highly relevant security fix. Without this fix specially generated ddoc file with changed OCSP response could have been verified to be valid.
+- Changed process of searching for CA certificates. The certificates are searched from the secure Program Files directory that is specified with CA_CERT_PATH configuration file parameter, not from the working directory. This is a highly relevant security fix. Without this fix, CA certificate files that may have been added to the working directory with malicious intent would be used by the library.
+- Fixed the opening of DDOC container with a faulty <DigestValue> tag. This is a highly relevant security fix that has an effect on the validation of DDOC files. Acknowledgements. Sertifitseerimiskeskus and RIA thank Aivar Liimets for his contribution.
+
+
+
+DigiDoc C library 3.7.2 release notes
+--------------------------------------
+Changes compared to ver 3.7.1.992
+
+- DDOC/CDOC security fixes:
+ - Fixed the opening of DDOC container with a faulty DataFile name tag. This is a highly relevant security fix having an effect on the verification of DDOC files. The unfixed library can result in overwrite arbitrary files on the system with the privileges of the victim.
+
+
+
+DigiDoc C library 3.7.1 release notes
+-----------------------------------
+Changes compared to ver 3.7.0.910
+
+- Changed the handling of DigiDoc container which has no xmlns attribute in the <DataFile> element.
+
+
+
+DigiDoc C library 3.7 release notes
+-----------------------------------
+Changes compared to ver 3.6.0.26
+
+- Added the support of slot choice option for CDOC decryption with utility
+- Fixed the search of the signer’s certificate issuer for DDOC verification
+- Fixed the OCSP hash check error handling for DDOC verification: error messages are correct when there are several errors associated with a container
+- Fixed the error handling of the DDOC verification function verifySignatureInfoCERT
+- Added the decrypted transport key option for testing CDOC decryption with utility
+- Fixed padding control for CDOC
+- Fixed padding handling of CDOC PKCS#7: now PKCS#7 padding is managed by the openssl
+- Fixed the DDOC signing function ddocLocateSlotWithSignatureCert: the use of the digital stamp has improved
+- Fixed the OCSP response handling for DDOC signing
+- Fixed CDOC packaging according xml-enc standard
+- Fixed the handling of the initial CDOC file name: the directory path is not added to the CDOC container
+- Fixed the handling of special characters in the CDOC decryption
+- Added Mac OSX keychain support for OCSP server access certificates in DDOC signing
+- Fixed the error handling of DDOC verification in case of the lack of issuer certificates
+- Fixed the DDOC verification function readAuthorityKeyIdentifier
+- Added the function signDocumentWithSlotAndSigner to the signing of DDOC to allow signature over CAPI/CNG
+- Added the support of signing DDOC files in the memory: no temporary files are saved
+- Added the support of encryption and decryption of CDOC in the memory: no temporary files are saved
+- Fixed the logic of the xmlns mirroring in the XML root element in the DDOC signing and verification
+- Added the PKCS12 support for DDOC signing
+- Fixed the EVP_DecodeUpdate CDOC decryption function: buffer size improvement
+- Fixed the notarizeSignatureWithIp and finalizeAndVerifyNotary2 functions for DDOC signing and verification: the setting is supported if the ocsp responder certificate has been issued from another chain than the signer’s certificate
+- Fixed the hash description handling of the ASN.1 signature value for DDOC signing and verification: 13-byte and 15-byte values are supported
+- Added BOM (Byte order mark) support on DDOC verification
+- Fixed error handling of the missing OCSP responder certificate for DDOC verification
+- Removed support for DDOC format version 1.0, 1.1, 1.2 for DDOC signing. Only DDOC verification and exctracting files from container are supported. Creating container, signing and removing signature are not supported
+
+
+- DDOC/CDOC security fixes:
+ - Added the check of the ASN.1 structure of the nonce field for DDOC signing and verification. This is a highly relevant security fix having an effect on the verification of DDOC files. The unfixed library can mistakenly give positive results on verificaton invalid DDOC container with wrong ASN.1 structure on the nonce field.
+ - Added the check of the ASN.1 structure of the signature value for DDOC signing and verification. This is a highly relevant security fix having an effect on the verification of DDOC files. The unfixed library can mistakenly give positive results on verificaton invalid DDOC container with wrong ASN.1 structure on the signature value.
+ - Added the check of the nonce field of the signature for DDOC signing and verification. This is a highly relevant security fix having an effect on the verification of DDOC files. The unfixed library can mistakenly give positive results on verificaton invalid DDOC container with the wrong nonce field value on the signature.
+ - Removed the EMBEDDED type DDOC file support for verification. This is a highly relevant security fix having an effect on the verification of DDOC files. The unfixed library can mistakenly give positive results on verificaton invalid EMBEDDED type DDOC container.
+ - Fixed the signature verification of a DDOC with a faulty DataFile tag. This is a highly relevant security fix having an effect on the verification of DDOC files. The unfixed library can result in the crashing of the application or unauthorized code execution in opening of a DDOC file created with malicious intent.
+
+
+
+
+
+DigiDoc C library 3.6 release notes
+-----------------------------------
+Changes compared to ver 2.6.0.18
+
+- Changes according ETSI Plug test results
+- Changes according Cross library (jdigidoc & libdigidoc & libdigidocpp) test results (DDOC, CDOC)
+- Removed DETACHED, HASHCODE, DDOC 1.4, BDOC support
+- CDOC padding improvements
+- Updated documentation in doc folder SK-CDD-PRG-GUIDE
+- Support for software based private keys
+- Versioning switched to same schema (3.5, 3.6 ...) as other middleware components
+- Added Mobiil-ID signing support for cdigidoc utility
+- API change in functions dencOrigContent_findByIndex, dencMetaInfo_GetLibVersion, dencMetaInfo_GetFormatVersion
+- DDOC/CDOC security updates:
+ - Fix for decrypting or content viewing of CDOC files with broken orig_file tag. This is a significant security fix which affects CDOC decrypting. A library without this security fix can cause application crashes or allow running malicious code upon opening a deliberately created CDOC file.
+ - Fix for decrypting or content viewing of CDOC files with broken EncryptionProperty tag. This is a significant security fix which affects CDOC decrypting. A library without this security fix can cause application crashes or allow running malicious code upon opening a deliberately created CDOC file
+ - DigiDocService intermediate resultate file (DDOC file hashcode) verification fix. This is a significant security fix which affects verification of DDOC files. A library without this security fix can mistakenly give positive results on verificaton of invalid DDOC hashcode container.
+ - Detached DDOC file verification fix. This is a significant security fix which affects verification of DDOC files. A library without this security fix can mistakenly give positive results on verificaton of invalid DDOC container.
+ - Added key usage check in certificate on verification of a signature. This is a significant security fix which affects verification of DDOC files. A library without this security fix can mistakenly give positive results on verificaton of a signature created with incorrect certificate.
diff --git a/cmake/README.txt b/cmake/README.txt
new file mode 100644
index 0000000..6c6e4ab
--- /dev/null
+++ b/cmake/README.txt
@@ -0,0 +1 @@
+Inner component, do not use. Contact for assistance by email abi@id.ee or http://www.id.ee
diff --git a/cmake/modules/FindIconv.cmake b/cmake/modules/FindIconv.cmake
new file mode 100644
index 0000000..7fe482d
--- /dev/null
+++ b/cmake/modules/FindIconv.cmake
@@ -0,0 +1,58 @@
+# /kde/kdesupport/strigi/cmake
+# - Try to find Iconv
+# Once done this will define
+#
+# ICONV_FOUND - system has Iconv
+# ICONV_INCLUDE_DIR - the Iconv include directory
+# ICONV_LIBRARIES - Link these to use Iconv
+# ICONV_SECOND_ARGUMENT_IS_CONST - the second argument for iconv() is const
+#
+include(CheckCSourceCompiles)
+
+IF (ICONV_INCLUDE_DIR AND ICONV_LIBRARIES)
+ # Already in cache, be silent
+ SET(ICONV_FIND_QUIETLY TRUE)
+ENDIF (ICONV_INCLUDE_DIR AND ICONV_LIBRARIES)
+
+FIND_PATH(ICONV_INCLUDE_DIR iconv.h)
+
+FIND_LIBRARY(ICONV_LIBRARIES NAMES iconv libiconv libiconv-2 c)
+
+IF(ICONV_INCLUDE_DIR AND ICONV_LIBRARIES)
+ SET(ICONV_FOUND TRUE)
+ENDIF(ICONV_INCLUDE_DIR AND ICONV_LIBRARIES)
+
+set(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
+set(CMAKE_REQUIRED_LIBRARIES ${ICONV_LIBRARIES})
+IF(ICONV_FOUND)
+ check_c_source_compiles("
+ #include <iconv.h>
+ int main(){
+ iconv_t conv = 0;
+ const char* in = 0;
+ size_t ilen = 0;
+ char* out = 0;
+ size_t olen = 0;
+ iconv(conv, &in, &ilen, &out, &olen);
+ return 0;
+ }
+" ICONV_SECOND_ARGUMENT_IS_CONST )
+ENDIF(ICONV_FOUND)
+set(CMAKE_REQUIRED_INCLUDES)
+set(CMAKE_REQUIRED_LIBRARIES)
+
+IF(ICONV_FOUND)
+ IF(NOT ICONV_FIND_QUIETLY)
+ MESSAGE(STATUS "Found Iconv: ${ICONV_LIBRARIES}")
+ ENDIF(NOT ICONV_FIND_QUIETLY)
+ELSE(ICONV_FOUND)
+ IF(Iconv_FIND_REQUIRED)
+ MESSAGE(FATAL_ERROR "Could not find Iconv")
+ ENDIF(Iconv_FIND_REQUIRED)
+ENDIF(ICONV_FOUND)
+
+MARK_AS_ADVANCED(
+ ICONV_INCLUDE_DIR
+ ICONV_LIBRARIES
+ ICONV_SECOND_ARGUMENT_IS_CONST
+)
diff --git a/cmake/modules/FindLdap.cmake b/cmake/modules/FindLdap.cmake
new file mode 100644
index 0000000..188debd
--- /dev/null
+++ b/cmake/modules/FindLdap.cmake
@@ -0,0 +1,35 @@
+# - Try to find the LDAP client libraries
+# Once done this will define
+#
+# LDAP_FOUND - system has libldap
+# LDAP_INCLUDE_DIR - the ldap include directory
+# LDAP_LIBRARIES - libldap + liblber (if found) library
+# LBER_LIBRARIES - liblber library
+
+if(LDAP_INCLUDE_DIR AND LDAP_LIBRARIES)
+ # Already in cache, be silent
+ set(Ldap_FIND_QUIETLY TRUE)
+endif()
+
+FIND_PATH(LDAP_INCLUDE_DIR ldap.h)
+FIND_LIBRARY(LDAP_LIBRARIES NAMES ldap)
+FIND_LIBRARY(LBER_LIBRARIES NAMES lber)
+
+if(LDAP_INCLUDE_DIR AND LDAP_LIBRARIES)
+ set(LDAP_FOUND TRUE)
+ if(LBER_LIBRARIES)
+ set(LDAP_LIBRARIES ${LDAP_LIBRARIES} ${LBER_LIBRARIES})
+ endif()
+endif()
+
+if(LDAP_FOUND)
+ if(NOT Ldap_FIND_QUIETLY)
+ message(STATUS "Found ldap: ${LDAP_LIBRARIES}")
+ endif()
+else()
+ if(Ldap_FIND_REQUIRED)
+ message(FATAL_ERROR "Could NOT find ldap")
+ endif()
+endif()
+
+MARK_AS_ADVANCED(LDAP_INCLUDE_DIR LDAP_LIBRARIES LBER_LIBRARIES)
diff --git a/cmake/modules/FindLibDigiDoc.cmake b/cmake/modules/FindLibDigiDoc.cmake
new file mode 100644
index 0000000..47ccf00
--- /dev/null
+++ b/cmake/modules/FindLibDigiDoc.cmake
@@ -0,0 +1,28 @@
+# - Find LibDigiDoc
+# Find the native LibDigiDoc includes and library
+#
+# LIBDIGIDOC_INCLUDE_DIR - where to find winscard.h, wintypes.h, etc.
+# LIBDIGIDOC_LIBRARIES - List of libraries when using LibDigiDoc.
+# LIBDIGIDOC_FOUND - True if LibDigiDoc found.
+
+
+IF (LIBDIGIDOC_INCLUDE_DIR)
+ # Already in cache, be silent
+ SET(LIBDIGIDOC_FIND_QUIETLY TRUE)
+ENDIF (LIBDIGIDOC_INCLUDE_DIR)
+
+FIND_PATH(LIBDIGIDOC_INCLUDE_DIR libdigidoc/DigiDocDefs.h PATH_SUFFIXES include)
+FIND_LIBRARY(LIBDIGIDOC_LIBRARY NAMES digidoc)
+
+# handle the QUIETLY and REQUIRED arguments and set LIBDIGIDOC_FOUND to TRUE if
+# all listed variables are TRUE
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibDigiDoc DEFAULT_MSG LIBDIGIDOC_LIBRARY LIBDIGIDOC_INCLUDE_DIR)
+
+IF(LIBDIGIDOC_FOUND)
+ SET( LIBDIGIDOC_LIBRARIES ${LIBDIGIDOC_LIBRARY} )
+ELSE(LIBDIGIDOC_FOUND)
+ SET( LIBDIGIDOC_LIBRARIES )
+ENDIF(LIBDIGIDOC_FOUND)
+
+MARK_AS_ADVANCED(LIBDIGIDOC_LIBRARY LIBDIGIDOC_INCLUDE_DIR)
diff --git a/cmake/modules/FindLibDigiDocpp.cmake b/cmake/modules/FindLibDigiDocpp.cmake
new file mode 100644
index 0000000..8ec6371
--- /dev/null
+++ b/cmake/modules/FindLibDigiDocpp.cmake
@@ -0,0 +1,28 @@
+# - Find LibDigiDocpp
+# Find the native LibDigiDocpp includes and library
+#
+# LIBDIGIDOCPP_INCLUDE_DIR - where to find winscard.h, wintypes.h, etc.
+# LIBDIGIDOCPP_LIBRARIES - List of libraries when using LibDigiDocpp.
+# LIBDIGIDOCPP_FOUND - True if LibDigiDocpp found.
+
+
+IF (LIBDIGIDOCPP_INCLUDE_DIR)
+ # Already in cache, be silent
+ SET(LIBDIGIDOCPP_FIND_QUIETLY TRUE)
+ENDIF (LIBDIGIDOCPP_INCLUDE_DIR)
+
+FIND_PATH(LIBDIGIDOCPP_INCLUDE_DIR digidocpp/Container.h PATH_SUFFIXES include)
+FIND_LIBRARY(LIBDIGIDOCPP_LIBRARY NAMES digidocpp)
+
+# handle the QUIETLY and REQUIRED arguments and set LIBDIGIDOCPP_FOUND to TRUE if
+# all listed variables are TRUE
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibDigiDocpp DEFAULT_MSG LIBDIGIDOCPP_LIBRARY LIBDIGIDOCPP_INCLUDE_DIR)
+
+IF(LIBDIGIDOCPP_FOUND)
+ SET( LIBDIGIDOCPP_LIBRARIES ${LIBDIGIDOCPP_LIBRARY} )
+ELSE(LIBDIGIDOCPP_FOUND)
+ SET( LIBDIGIDOCPP_LIBRARIES )
+ENDIF(LIBDIGIDOCPP_FOUND)
+
+MARK_AS_ADVANCED(LIBDIGIDOCPP_LIBRARY LIBDIGIDOCPP_INCLUDE_DIR)
diff --git a/cmake/modules/FindMiniZip.cmake b/cmake/modules/FindMiniZip.cmake
new file mode 100644
index 0000000..04fb521
--- /dev/null
+++ b/cmake/modules/FindMiniZip.cmake
@@ -0,0 +1,30 @@
+# - Find minizip
+# Find the native MINIZIP includes and library
+#
+# MINIZIP_INCLUDE_DIR - where to find minizip.h, etc.
+# MINIZIP_LIBRARIES - List of libraries when using minizip.
+# MINIZIP_FOUND - True if minizip found.
+
+
+IF (MINIZIP_INCLUDE_DIR)
+ # Already in cache, be silent
+ SET(MINIZIP_FIND_QUIETLY TRUE)
+ENDIF (MINIZIP_INCLUDE_DIR)
+
+FIND_PATH(MINIZIP_INCLUDE_DIR zip.h PATH_SUFFIXES minizip)
+
+SET(MINIZIP_NAMES minizip)
+FIND_LIBRARY(MINIZIP_LIBRARY NAMES ${MINIZIP_NAMES} )
+
+# handle the QUIETLY and REQUIRED arguments and set MINIZIP_FOUND to TRUE if
+# all listed variables are TRUE
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(MiniZip DEFAULT_MSG MINIZIP_LIBRARY MINIZIP_INCLUDE_DIR)
+
+IF(MINIZIP_FOUND)
+ SET( MINIZIP_LIBRARIES ${MINIZIP_LIBRARY} )
+ELSE(MINIZIP_FOUND)
+ SET( MINIZIP_LIBRARIES )
+ENDIF(MINIZIP_FOUND)
+
+MARK_AS_ADVANCED( MINIZIP_LIBRARY MINIZIP_INCLUDE_DIR )
diff --git a/cmake/modules/FindPCSCLite.cmake b/cmake/modules/FindPCSCLite.cmake
new file mode 100644
index 0000000..f6cbc55
--- /dev/null
+++ b/cmake/modules/FindPCSCLite.cmake
@@ -0,0 +1,44 @@
+# - Find PCSC-Lite
+# Find the native PCSC-Lite includes and library
+#
+# PCSCLITE_INCLUDE_DIR - where to find winscard.h, wintypes.h, etc.
+# PCSCLITE_LIBRARIES - List of libraries when using PCSC-Lite.
+# PCSCLITE_FOUND - True if PCSC-Lite found.
+
+
+IF (PCSCLITE_INCLUDE_DIR AND PCSCLITE_LIBRARIES)
+ # Already in cache, be silent
+ SET(PCSCLITE_FIND_QUIETLY TRUE)
+ENDIF (PCSCLITE_INCLUDE_DIR AND PCSCLITE_LIBRARIES)
+
+IF (NOT WIN32)
+ FIND_PACKAGE(PkgConfig)
+ PKG_CHECK_MODULES(PC_PCSCLITE libpcsclite)
+ENDIF (NOT WIN32)
+
+FIND_PATH(PCSCLITE_INCLUDE_DIR winscard.h
+ HINTS
+ /usr/include/PCSC
+ ${PC_PCSCLITE_INCLUDEDIR}
+ ${PC_PCSCLITE_INCLUDE_DIRS}
+ ${PC_PCSCLITE_INCLUDE_DIRS}/PCSC
+ )
+
+FIND_LIBRARY(PCSCLITE_LIBRARY NAMES pcsclite libpcsclite PCSC
+ HINTS
+ ${PC_PCSCLITE_LIBDIR}
+ ${PC_PCSCLITE_LIBRARY_DIRS}
+ )
+
+# handle the QUIETLY and REQUIRED arguments and set PCSCLITE_FOUND to TRUE if
+# all listed variables are TRUE
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(PCSC-Lite DEFAULT_MSG PCSCLITE_LIBRARY PCSCLITE_INCLUDE_DIR)
+
+IF(PCSCLITE_FOUND)
+ SET( PCSCLITE_LIBRARIES ${PCSCLITE_LIBRARY} )
+ELSE(PCSCLITE_FOUND)
+ SET( PCSCLITE_LIBRARIES )
+ENDIF(PCSCLITE_FOUND)
+
+MARK_AS_ADVANCED( PCSCLITE_LIBRARY PCSCLITE_INCLUDE_DIR )
diff --git a/cmake/modules/FindPKCS11.cmake b/cmake/modules/FindPKCS11.cmake
new file mode 100644
index 0000000..d4e3110
--- /dev/null
+++ b/cmake/modules/FindPKCS11.cmake
@@ -0,0 +1,24 @@
+# - Find pkcs11
+# Find the PKCS11 module
+#
+# PKCS11_MODULE - pkcs11 module path and name
+# PKCS11_MODULE_FOUND - True if pkcs11 module found.
+
+if( WIN32 )
+ set( PKCS11_NAME esteid-pkcs11.dll opensc-pkcs11.dll )
+else()
+ set( PKCS11_NAME esteid-pkcs11.so opensc-pkcs11.so )
+endif()
+
+if( APPLE )
+ find_library( PKCS11_MODULE NAMES ${PKCS11_NAME} HINTS /Library/EstonianIDCard/lib /Library/OpenSC/lib )
+else()
+ list( GET PKCS11_NAME 1 PKCS11_MODULE )
+endif()
+
+# handle the QUIETLY and REQUIRED arguments and set PKCS11_MODULE_FOUND to TRUE if
+# all listed variables are TRUE
+include( FindPackageHandleStandardArgs )
+FIND_PACKAGE_HANDLE_STANDARD_ARGS( PKCS11_Module DEFAULT_MSG PKCS11_MODULE )
+
+MARK_AS_ADVANCED( PKCS11_MODULE )
diff --git a/cmake/modules/FindXSD.cmake b/cmake/modules/FindXSD.cmake
new file mode 100644
index 0000000..2e168f1
--- /dev/null
+++ b/cmake/modules/FindXSD.cmake
@@ -0,0 +1,52 @@
+# - Find XSD
+# Find XSD includes and executable
+#
+# XSD_INCLUDE_DIR - Where to find xsd include sub-directory.
+# XSD_EXECUTABLE - XSD compiler.
+# XSD_FOUND - True if XSD found.
+
+
+IF (XSD_INCLUDE_DIR)
+ # Already in cache, be silent.
+ SET(XSD_FIND_QUIETLY TRUE)
+ENDIF (XSD_INCLUDE_DIR)
+
+FIND_PATH(XSD_INCLUDE_DIR xsd/cxx/parser/elements.hxx HINTS /Library/EstonianIDCard/include)
+
+SET(XSD_NAMES xsdcxx xsdgen xsd)
+FIND_PROGRAM(XSD_EXECUTABLE NAMES ${XSD_NAMES} HINTS /Library/EstonianIDCard/bin)
+if(XSD_EXECUTABLE)
+ execute_process (COMMAND ${XSD_EXECUTABLE} "--version" OUTPUT_VARIABLE EXEC_OUT)
+ string(REGEX REPLACE ".*compiler ([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\1" XSD_VERSION_MAJOR ${EXEC_OUT})
+ string(REGEX REPLACE ".*compiler ([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\2" XSD_VERSION_MINOR ${EXEC_OUT})
+ string(REGEX REPLACE ".*compiler ([0-9]+)\\.([0-9]+)\\.([0-9]+).*" "\\3" XSD_VERSION_PATCH ${EXEC_OUT})
+ set(XSD_VERSION "${XSD_VERSION_MAJOR}.${XSD_VERSION_MINOR}.${XSD_VERSION_PATCH}")
+ set(XSD_VERSION_COUNT 3)
+endif()
+
+# Handle the QUIETLY and REQUIRED arguments and set XSD_FOUND to
+# TRUE if all listed variables are TRUE.
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(XSD REQUIRED_VARS XSD_EXECUTABLE XSD_INCLUDE_DIR VERSION_VAR XSD_VERSION)
+
+MARK_AS_ADVANCED( XSD_EXECUTABLE XSD_INCLUDE_DIR )
+
+macro( XSD_SCHEMA SOURCES HEADERS OUTPUT INPUT )
+ get_filename_component( NAME "${INPUT}" NAME )
+ get_filename_component( BASE "${NAME}" NAME_WE )
+ list( APPEND ${SOURCES} ${OUTPUT}/${BASE}.cxx )
+ list( APPEND ${HEADERS} ${OUTPUT}/${BASE}.hxx )
+ add_custom_command(
+ OUTPUT ${OUTPUT}/${BASE}.cxx ${OUTPUT}/${BASE}.hxx
+ COMMAND ${CMAKE_COMMAND} -E make_directory ${OUTPUT}
+ COMMAND ${XSD_EXECUTABLE} cxx-tree
+ --type-naming ucc
+ --function-naming lcc
+ --generate-serialization
+ --std c++11
+ --output-dir ${OUTPUT}
+ ${ARGN}
+ ${INPUT}
+ DEPENDS ${INPUT}
+ )
+endmacro()
diff --git a/cmake/modules/FindXercesC.cmake b/cmake/modules/FindXercesC.cmake
new file mode 100644
index 0000000..2d5c1cf
--- /dev/null
+++ b/cmake/modules/FindXercesC.cmake
@@ -0,0 +1,30 @@
+# - Find Xerces-C
+# Find the Xerces-C includes and library
+#
+# XERCESC_INCLUDE_DIR - Where to find xercesc include sub-directory.
+# XERCESC_LIBRARIES - List of libraries when using Xerces-C.
+# XERCESC_FOUND - True if Xerces-C found.
+
+
+IF (XERCESC_INCLUDE_DIR)
+ # Already in cache, be silent.
+ SET(XERCESC_FIND_QUIETLY TRUE)
+ENDIF (XERCESC_INCLUDE_DIR)
+
+FIND_PATH(XERCESC_INCLUDE_DIR xercesc/dom/DOM.hpp HINTS /Library/EstonianIDCard/include)
+
+SET(XERCESC_NAMES xerces-c xerces-c_3 xerces-c_2)
+FIND_LIBRARY(XERCESC_LIBRARY NAMES ${XERCESC_NAMES} HINTS /Library/EstonianIDCard/lib)
+
+# Handle the QUIETLY and REQUIRED arguments and set XERCESC_FOUND to
+# TRUE if all listed variables are TRUE.
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(XercesC DEFAULT_MSG XERCESC_LIBRARY XERCESC_INCLUDE_DIR)
+
+IF(XERCESC_FOUND)
+ SET( XERCESC_LIBRARIES ${XERCESC_LIBRARY} )
+ELSE(XERCESC_FOUND)
+ SET( XERCESC_LIBRARIES )
+ENDIF(XERCESC_FOUND)
+
+MARK_AS_ADVANCED( XERCESC_LIBRARY XERCESC_INCLUDE_DIR )
diff --git a/cmake/modules/FindXmlSecurityC.cmake b/cmake/modules/FindXmlSecurityC.cmake
new file mode 100644
index 0000000..9912c81
--- /dev/null
+++ b/cmake/modules/FindXmlSecurityC.cmake
@@ -0,0 +1,38 @@
+# - Find XML-Security-C
+# Find the XML-Security-C includes and library
+#
+# XMLSECURITYC_INCLUDE_DIR - Where to find xsec include sub-directory.
+# XMLSECURITYC_LIBRARIES - List of libraries when using XML-Security-C.
+# XMLSECURITYC_FOUND - True if XML-Security-C found.
+
+
+IF (XMLSECURITYC_INCLUDE_DIR)
+ # Already in cache, be silent.
+ SET(XMLSECURITYC_FIND_QUIETLY TRUE)
+ENDIF (XMLSECURITYC_INCLUDE_DIR)
+
+#FIND_PATH(XALANC_INCLUDE_DIR xalanc/XalanTransformer/XalanTransformer.hpp HINTS /Library/EstonianIDCard/include)
+FIND_PATH(XMLSECURITYC_INCLUDE_DIR xsec/utils/XSECPlatformUtils.hpp HINTS /Library/EstonianIDCard/include)
+
+#FIND_LIBRARY(XALANC_LIBRARY NAMES xalan-c xalan-C_1 HINTS /Library/EstonianIDCard/lib)
+#FIND_LIBRARY(XALANMSG_LIBRARY NAMES xalanMsg XalanMessages_1 HINTS /Library/EstonianIDCard/lib)
+FIND_LIBRARY(XMLSECURITYC_LIBRARY NAMES xml-security-c xsec_1 HINTS /Library/EstonianIDCard/lib)
+
+# Handle the QUIETLY and REQUIRED arguments and set XMLSECURITYC_FOUND to
+# TRUE if all listed variables are TRUE.
+INCLUDE(FindPackageHandleStandardArgs)
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(XmlSecurityC DEFAULT_MSG XMLSECURITYC_LIBRARY XMLSECURITYC_INCLUDE_DIR)
+
+IF(XMLSECURITYC_FOUND)
+ SET(XMLSECURITYC_INCLUDE_DIRS ${XMLSECURITYC_INCLUDE_DIR})
+ SET(XMLSECURITYC_LIBRARIES ${XMLSECURITYC_LIBRARY})
+ IF(XALANC_LIBRARY)
+ LIST(APPEND XMLSECURITYC_INCLUDE_DIRS ${XALANC_INCLUDE_DIR})
+ LIST(APPEND XMLSECURITYC_LIBRARIES ${XALANC_LIBRARY})
+ ENDIF()
+ELSE()
+ SET(XMLSECURITYC_INCLUDE_DIRS)
+ SET(XMLSECURITYC_LIBRARIES)
+ENDIF()
+
+MARK_AS_ADVANCED(XMLSECURITYC_LIBRARY XMLSECURITYC_INCLUDE_DIR XALANC_LIBRARY XALANC_INCLUDE_DIR XALANMSG_LIBRARY)
diff --git a/cmake/modules/MacOSXBundleInfo.plist.in b/cmake/modules/MacOSXBundleInfo.plist.in
new file mode 100644
index 0000000..e7f2177
--- /dev/null
+++ b/cmake/modules/MacOSXBundleInfo.plist.in
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>${MACOSX_BUNDLE_EXECUTABLE_NAME}</string>
+ <key>CFBundleIconFile</key>
+ <string>${MACOSX_BUNDLE_ICON_FILE}</string>
+ <key>CFBundleIdentifier</key>
+ <string>${MACOSX_BUNDLE_GUI_IDENTIFIER}</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>${MACOSX_BUNDLE_BUNDLE_NAME}</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>${MACOSX_BUNDLE_SHORT_VERSION_STRING}</string>
+ <key>CFBundleVersion</key>
+ <string>${MACOSX_BUNDLE_BUNDLE_VERSION}</string>
+ <key>NSHumanReadableCopyright</key>
+ <string>${MACOSX_BUNDLE_COPYRIGHT}</string>
+ <key>NSPrincipalClass</key>
+ <string>NSApplication</string>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+ <key>LSHasLocalizedDisplayName</key>
+ <true/>
+ <key>LSApplicationCategoryType</key>
+ <string>public.app-category.utilities</string>
+ <key>LSMinimumSystemVersion</key>
+ <string>10.7</string>
+</dict>
+</plist>
diff --git a/cmake/modules/VersionInfo.cmake b/cmake/modules/VersionInfo.cmake
new file mode 100644
index 0000000..2955ce1
--- /dev/null
+++ b/cmake/modules/VersionInfo.cmake
@@ -0,0 +1,95 @@
+set( MAJOR_VER 3 )
+set( MINOR_VER 10 )
+set( RELEASE_VER 1 )
+set( BUILD_VER 1208 )
+if( $ENV{BUILD_NUMBER} )
+ set( BUILD_VER 1208 )
+endif()
+
+if( WIN32 )
+ execute_process( COMMAND "cmd.exe" "/C date /T" OUTPUT_VARIABLE BUILD_DATE )
+ string( REGEX REPLACE ".*([0-3][0-9]).([0-1][0-9]).([0-9][0-9][0-9][0-9]).*" "\\1.\\2.\\3" BUILD_DATE ${BUILD_DATE} )
+elseif( UNIX )
+ execute_process( COMMAND "date" "+%d.%m.%Y" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE )
+else()
+ message( SEND_ERROR "date not implemented")
+ set( BUILD_DATE "00.00.0000" )
+endif()
+
+set( VERSION ${MAJOR_VER}.${MINOR_VER}.${RELEASE_VER}.${BUILD_VER} )
+add_definitions(
+ -DMAJOR_VER=${MAJOR_VER}
+ -DMINOR_VER=${MINOR_VER}
+ -DRELEASE_VER=${RELEASE_VER}
+ -DBUILD_VER=${BUILD_VER}
+ -DVER_SUFFIX=\"$ENV{VER_SUFFIX}\"
+ -DBUILD_DATE=\"${BUILD_DATE}\"
+ -DDOMAINURL=\"ria.ee\"
+ -DORG=\"RIA\"
+)
+
+set( MACOSX_BUNDLE_COPYRIGHT "(C) 2010-2015 Estonian Information System Authority" )
+set( MACOSX_BUNDLE_SHORT_VERSION_STRING ${MAJOR_VER}.${MINOR_VER}.${RELEASE_VER} )
+set( MACOSX_BUNDLE_BUNDLE_VERSION ${BUILD_VER} )
+set( MACOSX_BUNDLE_ICON_FILE Icon.icns )
+set( MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${MAJOR_VER}.${MINOR_VER}.${RELEASE_VER} )
+set( MACOSX_FRAMEWORK_BUNDLE_VERSION ${BUILD_VER} )
+
+macro( SET_APP_NAME OUTPUT NAME )
+ set( ${OUTPUT} "${NAME}" )
+ add_definitions( -DAPP=\"${NAME}\" )
+ set( MACOSX_BUNDLE_BUNDLE_NAME ${NAME} )
+ set( MACOSX_BUNDLE_GUI_IDENTIFIER "ee.ria.${NAME}" )
+ if( APPLE )
+ file( GLOB_RECURSE RESOURCE_FILES
+ ${CMAKE_CURRENT_SOURCE_DIR}/mac/Resources/*.icns
+ ${CMAKE_CURRENT_SOURCE_DIR}/mac/Resources/*.strings )
+ foreach( _file ${RESOURCE_FILES} )
+ get_filename_component( _file_dir ${_file} PATH )
+ file( RELATIVE_PATH _file_dir ${CMAKE_CURRENT_SOURCE_DIR}/mac ${_file_dir} )
+ set_source_files_properties( ${_file} PROPERTIES MACOSX_PACKAGE_LOCATION ${_file_dir} )
+ endforeach( _file )
+ endif( APPLE )
+endmacro()
+
+macro( add_manifest TARGET )
+ if( WIN32 )
+ add_custom_command(TARGET ${TARGET} POST_BUILD
+ COMMAND mt -manifest "${CMAKE_MODULE_PATH}/win81.exe.manifest" -outputresource:"$<TARGET_FILE:${TARGET}>")
+ endif()
+endmacro()
+
+macro( SET_EX NAME VAR DEF )
+ if( "${VAR}" STREQUAL "" )
+ set( ${NAME} ${DEF} ${ARGN} )
+ else()
+ set( ${NAME} ${VAR} ${ARGN} )
+ endif()
+endmacro()
+
+if(CMAKE_COMPILER_IS_GNUCC OR __COMPILER_GNU)
+ if(NOT DEFINED ENABLE_VISIBILITY)
+ set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -fvisibility-inlines-hidden")
+ #set( CMAKE_C_VISIBILITY_PRESET hidden )
+ #set( CMAKE_CXX_VISIBILITY_PRESET hidden )
+ #set( CMAKE_VISIBILITY_INLINES_HIDDEN 1 )
+ endif()
+
+ if(NOT DISABLE_CXX11)
+ include(CheckCXXCompilerFlag)
+ CHECK_CXX_COMPILER_FLAG(-std=c++11 C11)
+ CHECK_CXX_COMPILER_FLAG(-std=c++0x C0X)
+ if(C11)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
+ elseif(C0X)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
+ endif()
+ set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++0x")
+ endif()
+ if(APPLE)
+ set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
+ set(CMAKE_OSX_DEPLOYMENT_TARGET "10.7")
+ endif()
+endif()
diff --git a/cmake/modules/win81.exe.manifest b/cmake/modules/win81.exe.manifest
new file mode 100644
index 0000000..e74e0f6
--- /dev/null
+++ b/cmake/modules/win81.exe.manifest
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
+ <security>
+ <requestedPrivileges>
+ <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
+ </requestedPrivileges>
+ </security>
+ </trustInfo>
+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+ <application>
+ <!-- Windows Vista -->
+ <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
+ <!-- Windows 7 -->
+ <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
+ <!-- Windows 8 -->
+ <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
+ <!-- Windows 8.1 -->
+ <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
+ <!-- Windows 10 -->
+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
+ </application>
+ </compatibility>
+</assembly>
diff --git a/config.h.cmake b/config.h.cmake
new file mode 100644
index 0000000..e8318f9
--- /dev/null
+++ b/config.h.cmake
@@ -0,0 +1,7 @@
+/* default config file for libdigidoc */
+#define SYSCONFDIR "@CMAKE_INSTALL_FULL_SYSCONFDIR@"
+
+/* Version number of package */
+#define VERSION "@VERSION@"
+#define DIGIDOC_VERSION "@VERSION@"
+#define VERSION_COMMA @MAJOR_VER@,@MINOR_VER@,@RELEASE_VER@,@BUILD_VER@
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..8c8aeb2
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+libdigidoc (3.10.1.1208-1) unstable; urgency=medium
+
+ * Initial upload (Closes: #658300).
+
+ -- Andrew Shadura <andrewsh@debian.org> Sun, 01 Nov 2015 19:41:28 +0100
diff --git a/debian/compat b/debian/compat
new file mode 100644
index 0000000..ec63514
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+9
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..a5bff60
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,129 @@
+Source: libdigidoc
+Section: libs
+Priority: extra
+Maintainer: Andrew Shadura <andrewsh@debian.org>
+Build-Depends:
+ debhelper (>= 9),
+ cmake,
+ libssl-dev,
+ libxml2-dev,
+ zlib1g-dev
+Standards-Version: 3.9.6
+Homepage: https://github.com/open-eid/libdigidoc
+
+Package: libdigidoc-common
+Architecture: all
+Section: misc
+Multi-Arch: foreign
+Depends:
+ ${misc:Depends}
+Breaks:
+ libdigidoc2 (<< ${binary:Version})
+Replaces:
+ libdigidoc2 (<< ${binary:Version})
+Description: DigiDoc digital signature library common files
+ DigiDoc is an XML file format for documents with digital signatures in use by
+ the Estonian ID card infrastructure. This library allows for creation and
+ reading of DigiDoc files.
+ .
+ This library implements a subset of the XAdES digital signature standard on
+ top of Estonian-specific .ddoc container format.
+ .
+ This package contains common architecture-independent files for the
+ applications using the DigiDoc digital signature library.
+
+Package: libdigidoc2
+Replaces:
+ libdigidoc
+Breaks:
+ libdigidoc
+Architecture: any
+Multi-Arch: same
+Pre-Depends:
+ ${misc:Pre-Depends}
+Depends:
+ libdigidoc-common (= ${source:Version}),
+ opensc,
+ pcscd,
+ ${misc:Depends},
+ ${shlibs:Depends}
+Description: DigiDoc digital signature library
+ DigiDoc is an XML file format for documents with digital signatures in use by
+ the Estonian ID card infrastructure. This library allows for creation and
+ reading of DigiDoc files.
+ .
+ This library implements a subset of the XAdES digital signature standard on
+ top of Estonian-specific .ddoc container format.
+ .
+ This package provides the shared libraries.
+
+Package: libdigidoc-tools
+Architecture: any
+Section: misc
+Depends:
+ libdigidoc2 (= ${binary:Version}),
+ ${misc:Depends},
+ ${shlibs:Depends}
+Description: DigiDoc digital signature library tools
+ DigiDoc is an XML file format for documents with digital signatures in use by
+ the Estonian ID card infrastructure. This library allows for creation and
+ reading of DigiDoc files.
+ .
+ This library implements a subset of the XAdES digital signature standard on
+ top of Estonian-specific .ddoc container format.
+ .
+ This package contains tools for manipulating signatures created with the
+ DigiDoc digital signature library.
+
+Package: libdigidoc-dbg
+Architecture: any
+Section: debug
+Multi-Arch: same
+Depends:
+ libdigidoc2 (= ${binary:Version}),
+ libssl1.0.0-dbg,
+ libxml2-dbg,
+ ${misc:Depends}
+Description: debugging symbols for DigiDoc digital signature library
+ DigiDoc is an XML file format for documents with digital signatures in use by
+ the Estonian ID card infrastructure. This library allows for creation and
+ reading of DigiDoc files.
+ .
+ This library implements a subset of the XAdES digital signature standard on
+ top of Estonian-specific .ddoc container format.
+ .
+ This package provides the debugging symbols.
+
+Package: libdigidoc-dev
+Architecture: any
+Section: libdevel
+Depends:
+ libdigidoc2 (= ${binary:Version}),
+ libssl-dev,
+ libxml2-dev,
+ ${misc:Depends}
+Description: DigiDoc digital signature development files
+ DigiDoc is an XML file format for documents with digital signatures in use by
+ the Estonian ID card infrastructure. This library allows for creation and
+ reading of DigiDoc files.
+ .
+ This library implements a subset of the XAdES digital signature standard on
+ top of Estonian-specific .ddoc container format.
+ .
+ This package provides the development files.
+
+Package: libdigidoc-doc
+Architecture: all
+Section: doc
+Depends:
+ ${misc:Depends}
+Description: DigiDoc digital signature library documentation
+ DigiDoc is an XML file format for documents with digital signatures in use by
+ the Estonian ID card infrastructure. This library allows for creation and
+ reading of DigiDoc files.
+ .
+ This library implements a subset of the XAdES digital signature standard on
+ top of Estonian-specific .ddoc container format.
+ .
+ This package contains documentation for developing applications with the
+ DigiDoc digital signature library.
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..fc1f191
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,28 @@
+Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: libdigidoc
+Upstream-Contact: abi@id.ee
+Source: https://github.com/open-eid/libdigidoc
+
+Files: *
+Copyright: 2012—2015 Estonian Information System's Authority
+License: LGPL-2.1+
+
+Files: debian/*
+Copyright:
+ 2012—2015 Estonian Information System's Authority
+ 2015 Andrew Shadura <andrewsh@debian.org>
+License: LGPL-2.1+
+
+License: LGPL-2.1+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+ .
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+ .
+ On Debian systems, the complete text of the GNU Lesser General Public
+ License can be found in </usr/share/common-licenses/LGPL-2.1>.
diff --git a/debian/libdigidoc-common.install b/debian/libdigidoc-common.install
new file mode 100644
index 0000000..468beba
--- /dev/null
+++ b/debian/libdigidoc-common.install
@@ -0,0 +1,2 @@
+debian/tmp/etc
+debian/tmp/usr/share/libdigidoc
diff --git a/debian/libdigidoc-dev.install b/debian/libdigidoc-dev.install
new file mode 100644
index 0000000..af8a8e5
--- /dev/null
+++ b/debian/libdigidoc-dev.install
@@ -0,0 +1,4 @@
+usr/include
+usr/lib/*/lib*.so
+usr/lib/*/pkgconfig
+usr/share/libdigidoc/TEST*
diff --git a/debian/libdigidoc-doc.install b/debian/libdigidoc-doc.install
new file mode 100644
index 0000000..7276ecd
--- /dev/null
+++ b/debian/libdigidoc-doc.install
@@ -0,0 +1 @@
+usr/share/doc
diff --git a/debian/libdigidoc-tools.install b/debian/libdigidoc-tools.install
new file mode 100644
index 0000000..a65408f
--- /dev/null
+++ b/debian/libdigidoc-tools.install
@@ -0,0 +1,2 @@
+usr/bin
+usr/share/man
diff --git a/debian/libdigidoc2.install b/debian/libdigidoc2.install
new file mode 100644
index 0000000..3ddde58
--- /dev/null
+++ b/debian/libdigidoc2.install
@@ -0,0 +1 @@
+usr/lib/*/lib*.so.*
diff --git a/debian/patches/01-manpage.patch b/debian/patches/01-manpage.patch
new file mode 100644
index 0000000..f79a6a6
--- /dev/null
+++ b/debian/patches/01-manpage.patch
@@ -0,0 +1,32 @@
+From fa90da1834c255ed72e377a96e5c92f8e1a858de Mon Sep 17 00:00:00 2001
+From: Andrew Shadura <andrew@shadura.me>
+Date: Sun, 1 Nov 2015 19:07:15 +0100
+Subject: [PATCH] Fix spelling in the manpage
+
+Signed-off-by: Andrew Shadura <andrew@shadura.me>
+---
+ libdigidoc/cdigidoc.1.cmake | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/libdigidoc/cdigidoc.1.cmake b/libdigidoc/cdigidoc.1.cmake
+index 20ad67e..effe492 100644
+--- a/libdigidoc/cdigidoc.1.cmake
++++ b/libdigidoc/cdigidoc.1.cmake
+@@ -200,7 +200,7 @@ Decrypts and possibly decompresses the encrypted file just read in and writes to
+ Input file (required) specifies the input file’s name.
+ Pin (required) represents the recipient’s pin1 (in context of Estonian ID cards).
+ pkcs12-file (optional) specifies the PKCS#12 file if decrypting is done with a software token.
+-slot deafult is slot 0 containing Estonian ID cards authentication keypair. This parameter can be used to decrypt with a key from the second id card attached to the computer etc.
++slot default is slot 0 containing Estonian ID cards authentication keypair. This parameter can be used to decrypt with a key from the second id card attached to the computer etc.
+ Note: There are also alternative commands for decryption, depending on the encrypted file’s format, size and the certificate type used for decrypting it.
+ .RS
+ .TP
+@@ -209,7 +209,7 @@ Offers same functionality as -decrypt-sk, should be used for decrypting small fi
+ Input file (required) specifies the input file’s name.
+ Pin (required) represents the recipient’s pin1 (in contexts of Estonian ID cards).
+ pkcs12-file (optional) specifies the PKCS#12 file if decrypting is done with a software token.
+-slot deafult is slot 0 containing Estonian ID cards authentication keypair. This parameter can be used to decrypt with a key from the second id card attached to the computer etc.
++slot default is slot 0 containing Estonian ID cards authentication keypair. This parameter can be used to decrypt with a key from the second id card attached to the computer etc.
+ .TP
+ .I "-decrypt-file <input-file> <output-file> <pin> [pkcs12-file]"
+ Offers same functionality as -decrypt for decrypting documents, should be used for decrypting large files (which do not need to be inside a DigiDoc container). Expects the encrypted data not to be compressed. Note that the command is not currently tested.
diff --git a/debian/patches/02-no-rpath.patch b/debian/patches/02-no-rpath.patch
new file mode 100644
index 0000000..9e03800
--- /dev/null
+++ b/debian/patches/02-no-rpath.patch
@@ -0,0 +1,12 @@
+Subject: No rpath, please.
+
+--- a/libdigidoc/CMakeLists.txt
++++ b/libdigidoc/CMakeLists.txt
+@@ -94,7 +94,6 @@
+ )
+
+ add_executable(cdigidoc cdigidoc.c cdigidoc.rc)
+-set_target_properties(cdigidoc PROPERTIES INSTALL_RPATH "@loader_path/../../../..;@loader_path/../..")
+ target_link_libraries(cdigidoc digidoc)
+
+ install( TARGETS digidoc
diff --git a/debian/patches/series b/debian/patches/series
new file mode 100644
index 0000000..b8d86dd
--- /dev/null
+++ b/debian/patches/series
@@ -0,0 +1,2 @@
+01-manpage.patch
+02-no-rpath.patch
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 0000000..3104e56
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,23 @@
+#!/usr/bin/make -f
+
+DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)
+
+DEB_CMAKE_EXTRA_FLAGS = \
+ -DCMAKE_INSTALL_SYSCONFDIR="/etc" \
+ -DCMAKE_INSTALL_LIBDIR="lib/$(DEB_HOST_MULTIARCH)" \
+ -DINSTALL_DOC=YES
+
+%:
+ dh "$@" --buildsystem=cmake
+
+override_dh_auto_configure:
+ dh_auto_configure -- $(DEB_CMAKE_EXTRA_FLAGS)
+
+override_dh_strip:
+ dh_strip --dbg-package=libdigidoc-dbg
+
+override_dh_install:
+ dh_install -plibdigidoc-common --exclude=TEST
+ dh_install --remaining-packages --list-missing
+
+.PHONY: override_dh_auto_configure
diff --git a/debian/source/format b/debian/source/format
new file mode 100644
index 0000000..163aaf8
--- /dev/null
+++ b/debian/source/format
@@ -0,0 +1 @@
+3.0 (quilt)
diff --git a/debian/watch b/debian/watch
new file mode 100644
index 0000000..2785dc9
--- /dev/null
+++ b/debian/watch
@@ -0,0 +1,3 @@
+version=3
+
+https://github.com/open-eid/libdigidoc/releases /open-eid/libdigidoc/releases/download/.*/libdigidoc-([\d.]*).tar.gz
diff --git a/doc/SK-CDD-PRG-GUIDE.docx b/doc/SK-CDD-PRG-GUIDE.docx
new file mode 100644
index 0000000..028444f
--- /dev/null
+++ b/doc/SK-CDD-PRG-GUIDE.docx
Binary files differ
diff --git a/doc/SK-CDD-PRG-GUIDE.pdf b/doc/SK-CDD-PRG-GUIDE.pdf
new file mode 100644
index 0000000..5cff0aa
--- /dev/null
+++ b/doc/SK-CDD-PRG-GUIDE.pdf
Binary files differ
diff --git a/doc/SK-COM-PRG-GUIDE.docx b/doc/SK-COM-PRG-GUIDE.docx
new file mode 100644
index 0000000..7f03d56
--- /dev/null
+++ b/doc/SK-COM-PRG-GUIDE.docx
Binary files differ
diff --git a/doc/SK-COM-PRG-GUIDE.pdf b/doc/SK-COM-PRG-GUIDE.pdf
new file mode 100644
index 0000000..4c89c72
--- /dev/null
+++ b/doc/SK-COM-PRG-GUIDE.pdf
Binary files differ
diff --git a/doc/doxygen-license.txt b/doc/doxygen-license.txt
new file mode 100644
index 0000000..56d505c
--- /dev/null
+++ b/doc/doxygen-license.txt
@@ -0,0 +1,8 @@
+Doxygen license
+
+Copyright © 1997-2014 by Dimitri van Heesch.
+
+Permission to use, copy, modify, and distribute this software and its documentation under the terms of the GNU General Public License is hereby granted. No representations are made about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. See the GNU General Public License for more details.
+
+Documents produced by doxygen are derivative works derived from the input used in their production; they are not affected by this license.
+
diff --git a/doc/mit-license.txt b/doc/mit-license.txt
new file mode 100644
index 0000000..4a5892d
--- /dev/null
+++ b/doc/mit-license.txt
@@ -0,0 +1,26 @@
+
+The MIT License (MIT)
+[OSI Approved License]
+
+The MIT License (MIT)
+
+Copyright (c) <year> <copyright holders>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
diff --git a/doc/openssl-license.txt b/doc/openssl-license.txt
new file mode 100644
index 0000000..1c4fd9b
--- /dev/null
+++ b/doc/openssl-license.txt
@@ -0,0 +1,131 @@
+License
+This is a copy of the current LICENSE file inside the CVS repository.
+
+
+ LICENSE ISSUES
+ ==============
+
+ The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
+ the OpenSSL License and the original SSLeay license apply to the toolkit.
+ See below for the actual license texts. Actually both licenses are BSD-style
+ Open Source licenses. In case of any license issues related to OpenSSL
+ please contact openssl-core@openssl.org.
+
+ OpenSSL License
+ ---------------
+
+/* ====================================================================
+ * Copyright (c) 1998-2011 The OpenSSL Project. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * 2. 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.
+ *
+ * 3. All advertising materials mentioning features or use of this
+ * software must display the following acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
+ *
+ * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
+ * endorse or promote products derived from this software without
+ * prior written permission. For written permission, please contact
+ * openssl-core@openssl.org.
+ *
+ * 5. Products derived from this software may not be called "OpenSSL"
+ * nor may "OpenSSL" appear in their names without prior written
+ * permission of the OpenSSL Project.
+ *
+ * 6. Redistributions of any form whatsoever must retain the following
+ * acknowledgment:
+ * "This product includes software developed by the OpenSSL Project
+ * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
+ * EXPRESSED 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 OpenSSL PROJECT OR
+ * ITS 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.
+ * ====================================================================
+ *
+ * This product includes cryptographic software written by Eric Young
+ * (eay@cryptsoft.com). This product includes software written by Tim
+ * Hudson (tjh@cryptsoft.com).
+ *
+ */
+
+ Original SSLeay License
+ -----------------------
+
+/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
+ * All rights reserved.
+ *
+ * This package is an SSL implementation written
+ * by Eric Young (eay@cryptsoft.com).
+ * The implementation was written so as to conform with Netscapes SSL.
+ *
+ * This library is free for commercial and non-commercial use as long as
+ * the following conditions are aheared to. The following conditions
+ * apply to all code found in this distribution, be it the RC4, RSA,
+ * lhash, DES, etc., code; not just the SSL code. The SSL documentation
+ * included with this distribution is covered by the same copyright terms
+ * except that the holder is Tim Hudson (tjh@cryptsoft.com).
+ *
+ * Copyright remains Eric Young's, and as such any Copyright notices in
+ * the code are not to be removed.
+ * If this package is used in a product, Eric Young should be given attribution
+ * as the author of the parts of the library used.
+ * This can be in the form of a textual message at program startup or
+ * in documentation (online or textual) provided with the package.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. 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.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * "This product includes cryptographic software written by
+ * Eric Young (eay@cryptsoft.com)"
+ * The word 'cryptographic' can be left out if the rouines from the library
+ * being used are not cryptographic related :-).
+ * 4. If you include any Windows specific code (or a derivative thereof) from
+ * the apps directory (application code) you must include an acknowledgement:
+ * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
+ *
+ * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
+ *
+ * The licence and distribution terms for any publically available version or
+ * derivative of this code cannot be changed. i.e. this code cannot simply be
+ * copied and put under another distribution licence
+ * [including the GNU Public Licence.]
+ */
+
+
diff --git a/doc/sample_files_CDD.zip b/doc/sample_files_CDD.zip
new file mode 100644
index 0000000..454474a
--- /dev/null
+++ b/doc/sample_files_CDD.zip
Binary files differ
diff --git a/doc/zlib-license.txt b/doc/zlib-license.txt
new file mode 100644
index 0000000..7d05cf5
--- /dev/null
+++ b/doc/zlib-license.txt
@@ -0,0 +1,25 @@
+zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.2.8, April 28th, 2013
+
+ Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+
diff --git a/etc/Doxyfile.in b/etc/Doxyfile.in
new file mode 100644
index 0000000..4856712
--- /dev/null
+++ b/etc/Doxyfile.in
@@ -0,0 +1,1804 @@
+# Doxyfile 1.8.1.2
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a hash (#) is considered a comment and will be ignored.
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ").
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING = UTF-8
+
+# The PROJECT_NAME tag is a single word (or sequence of words) that should
+# identify the project. Note that if you do not use Doxywizard you need
+# to put quotes around the project name if it contains spaces.
+
+PROJECT_NAME = "Estonian ID Card C-library"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER = @DIGIDOC_VERSION@
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer
+# a quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF =
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is
+# included in the documentation. The maximum height of the logo should not
+# exceed 55 pixels and the maximum width should not exceed 200 pixels.
+# Doxygen will copy the logo to the output directory.
+
+PROJECT_LOGO =
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY = @CMAKE_BINARY_DIR@/doc/
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF = "The $name class" \
+ "The $name widget" \
+ "The $name file" \
+ is \
+ provides \
+ specifies \
+ contains \
+ represents \
+ a \
+ an \
+ the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful if your file system
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE = 8
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES =
+
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding
+# "class=itcl::class" will allow you to use the command class in the
+# itcl::class meaning.
+
+TCL_SUBST =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this
+# tag. The format is ext=language, where ext is a file extension, and language
+# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C,
+# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
+# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions
+# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING =
+
+# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all
+# comments according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you
+# can mix doxygen, HTML, and XML commands with Markdown formatting.
+# Disable only in case of backward compatibilities issues.
+
+MARKDOWN_SUPPORT = YES
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also makes the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING = YES
+
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and
+# unions are shown inside the group in which they are included (e.g. using
+# @ingroup) instead of on a separate page (for HTML and Man pages) or
+# section (for LaTeX and RTF).
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and
+# unions with only public data fields will be shown inline in the documentation
+# of the scope in which they are defined (i.e. file, namespace, or group
+# documentation), provided this scope is documented. If set to NO (the default),
+# structs, classes, and unions are shown on a separate page (for HTML and Man
+# pages) or section (for LaTeX and RTF).
+
+INLINE_SIMPLE_STRUCTS = NO
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penalty.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will roughly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+SYMBOL_CACHE_SIZE = 0
+
+# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be
+# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given
+# their name and scope. Since this can be an expensive process and often the
+# same symbol appear multiple times in the code, doxygen keeps a cache of
+# pre-resolved symbols. If the cache is too small doxygen will become slower.
+# If the cache is too large, memory is wasted. The cache size is given by this
+# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols.
+
+LOOKUP_CACHE_SIZE = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE = NO
+
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal scope will be included in the documentation.
+
+EXTRACT_PACKAGE = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC = NO
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES = NO
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS = YES
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespaces are hidden.
+
+EXTRACT_ANON_NSPACES = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES = NO
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME = NO
+
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to
+# do proper type resolution of all parameters of a function it will reject a
+# match between the prototype and the implementation of a member function even
+# if there is only one candidate or it is obvious which candidate to choose
+# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen
+# will still accept a match between prototype and implementation in such cases.
+
+STRICT_PROTO_MATCHING = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or macro consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and macros in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES = YES
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.
+# This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE =
+
+# The CITE_BIB_FILES tag can be used to specify one or more bib files
+# containing the references data. This must be a list of .bib files. The
+# .bib extension is automatically appended if omitted. Using this command
+# requires the bibtex tool to be installed. See also
+# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style
+# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this
+# feature you need bibtex and perl available in the search path.
+
+CITE_BIB_FILES =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR = YES
+
+# The WARN_NO_PARAMDOC option can be enabled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = @CMAKE_SOURCE_DIR@/libdigidoc
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh
+# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py
+# *.f90 *.f *.for *.vhd *.vhdl
+
+FILE_PATTERNS = *.c \
+ *.cpp \
+ *.h
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should be
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
+
+EXCLUDE =
+
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS =
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.
+# If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.
+# Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.
+# The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty or if
+# non of the patterns match the file name, INPUT_FILTER is applied.
+
+FILTER_PATTERNS =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES = NO
+
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any)
+# and it is also possible to disable source filtering for a specific pattern
+# using *.ext= (so without naming a filter). This option only has effect when
+# FILTER_SOURCE_FILES is enabled.
+
+FILTER_SOURCE_PATTERNS =
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER = NO
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C, C++ and Fortran comments will always remain visible.
+
+STRIP_CODE_COMMENTS = YES
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = NO
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION = NO
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.
+# Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header. Note that when using a custom header you are responsible
+# for the proper inclusion of any scripts and style sheets that doxygen
+# needs, which is dependent on the configuration options used.
+# It is advised to generate a default header using "doxygen -w html
+# header.html footer.html stylesheet.css YourConfigFile" and then modify
+# that header. Note that the header is subject to change so you typically
+# have to redo this when upgrading to a newer version of doxygen or when
+# changing the value of configuration settings such as GENERATE_TREEVIEW!
+
+HTML_HEADER =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# style sheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that
+# the files will be copied as-is; there are no commands or markers available.
+
+HTML_EXTRA_FILES =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the style sheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded.
+
+HTML_DYNAMIC_SECTIONS = NO
+
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of
+# entries shown in the various tree structured indices initially; the user
+# can expand and collapse entries dynamically later on. Doxygen will expand
+# the tree to such a level that at most the specified number of entries are
+# visible (unless a fully collapsed tree already exceeds this amount).
+# So setting the number of entries 1 will produce a full collapsed tree by
+# default. 0 is a special value representing an infinite number of entries
+# and will result in a full expanded tree by default.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs)
+# at top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it. Since the tabs have the same information as the
+# navigation tree you can set this option to NO if you already set
+# GENERATE_TREEVIEW to YES.
+
+DISABLE_INDEX = NO
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+# Since the tree basically has the same information as the tab index you
+# could consider to set DISABLE_INDEX to NO when enabling this option.
+
+GENERATE_TREEVIEW = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values
+# (range [0,1..20]) that doxygen will group on one line in the generated HTML
+# documentation. Note that a value of 0 will completely suppress the enum
+# values from appearing in the overview section.
+
+ENUM_VALUES_PER_LINE = 4
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax
+# (see http://www.mathjax.org) which uses client side Javascript for the
+# rendering instead of using prerendered bitmaps. Use this if you do not
+# have LaTeX installed or if you want to formulas look prettier in the HTML
+# output. When enabled you may also need to install MathJax separately and
+# configure the path to it using the MATHJAX_RELPATH option.
+
+USE_MATHJAX = NO
+
+# When MathJax is enabled you need to specify the location relative to the
+# HTML output directory using the MATHJAX_RELPATH option. The destination
+# directory should contain the MathJax.js script. For instance, if the mathjax
+# directory is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to
+# the MathJax Content Delivery Network so you can quickly see the result without
+# installing MathJax.
+# However, it is strongly recommended to install a local
+# copy of MathJax from http://www.mathjax.org before deployment.
+
+MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension
+# names that should be enabled during MathJax rendering.
+
+MATHJAX_EXTENSIONS =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvantages are that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for
+# the generated latex document. The footer should contain everything after
+# the last chapter. If it is left blank doxygen will generate a
+# standard footer. Notice: only use this tag if you know what you are doing!
+
+LATEX_FOOTER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE = NO
+
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See
+# http://en.wikipedia.org/wiki/BibTeX for more info.
+
+LATEX_BIB_STYLE = plain
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS = NO
+
+# Load style sheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.
+# This is useful
+# if you want to understand what is going on.
+# On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# pointed to by INCLUDE_PATH will be searched when a #include is found.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition that
+# overrules the definition found in the source code.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all references to function-like macros
+# that are alone on a line, have an all uppercase name, and do not end with a
+# semicolon, because these will confuse the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles. For each
+# tag file the location of the external documentation should be added. The
+# format of a tag file without this location is as follows:
+#
+# TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#
+# TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths
+# or URLs. Note that each tag file must have a unique name (where the name does
+# NOT include the path). If a tag file is not located in the directory in which
+# doxygen is run, you must also specify the path to the tagfile here.
+
+TAGFILES =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option also works with HAVE_DOT disabled, but it is recommended to
+# install and use dot, since it yields more powerful graphs.
+
+CLASS_DIAGRAMS = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS = 0
+
+# By default doxygen will use the Helvetica font for all dot files that
+# doxygen generates. When you want a differently looking font you can specify
+# the font name using DOT_FONTNAME. You need to make sure dot is able to find
+# the font, which can be done by putting it in a standard location or by setting
+# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the
+# directory containing the font.
+
+DOT_FONTNAME = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE = 10
+
+# By default doxygen will tell dot to use the Helvetica font.
+# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to
+# set the path where dot can find it.
+
+DOT_FONTPATH =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK = YES
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside
+# the class node. If there are many fields or methods and many nodes the
+# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS
+# threshold limits the number of items for each type to make the size more
+# managable. Set this to 0 for no limit. Note that the threshold may be
+# exceeded by 50% before the limit is enforced.
+
+UML_LIMIT_NUM_FIELDS = 10
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will generate a graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY = YES
+
+# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are svg, png, jpg, or gif.
+# If left blank png will be used. If you choose svg you need to set
+# HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible in IE 9+ (other browsers do not have this requirement).
+
+DOT_IMAGE_FORMAT = png
+
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+# Note that this requires a modern browser other than Internet Explorer.
+# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you
+# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files
+# visible. Older versions of IE do not have SVG support.
+
+INTERACTIVE_SVG = NO
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS =
+
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the
+# \mscfile command).
+
+MSCFILE_DIRS =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP = YES
diff --git a/etc/certs/EECCRCA.crt b/etc/certs/EECCRCA.crt
new file mode 100644
index 0000000..013d461
--- /dev/null
+++ b/etc/certs/EECCRCA.crt
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEoMCYGA1UEAwwfRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYG
+CSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIwMTAxMDMwMTAxMDMwWhgPMjAzMDEy
+MTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlBUyBTZXJ0aWZpdHNl
+ZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBS
+b290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEB
+AQUAA4IBDwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUy
+euuOF0+W2Ap7kaJjbMeMTC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvO
+bntl8jixwKIy72KyaOBhU8E2lf/slLo2rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIw
+WFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw93X2PaRka9ZP585ArQ/d
+MtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtNP2MbRMNE
+1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYD
+VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/
+zQas8fElyalL1BSZMEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYB
+BQUHAwMGCCsGAQUFBwMEBggrBgEFBQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEF
+BQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+RjxY6hUFaTlrg4wCQiZrxTFGGV
+v9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqMlIpPnTX/dqQG
+E5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u
+uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIW
+iAYLtqZLICjU3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/v
+GVCJYMzpJJUPwssd8m92kMfMdcGWxZ0=
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK 2007 OCSP 2010.crt b/etc/certs/EID-SK 2007 OCSP 2010.crt
new file mode 100644
index 0000000..2c95b83
--- /dev/null
+++ b/etc/certs/EID-SK 2007 OCSP 2010.crt
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIEMTCCAxmgAwIBAgIESxUA8TANBgkqhkiG9w0BAQUFADBqMQswCQYDVQQGEwJFRTEiMCAGA1UE
+ChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEhMB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3Rl
+ZW51c2VkMRQwEgYDVQQDEwtFSUQtU0sgMjAwNzAeFw0wOTEyMDExMTQxMzBaFw0xNjA4MjYxMzIz
+MDBaMIGEMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEN
+MAsGA1UECxMET0NTUDEoMCYGA1UEAxMfRUlELVNLIDIwMDcgT0NTUCBSRVNQT05ERVIgMjAxMDEY
+MBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+so91KG7EHsjAxMairaCKUHSOyXp5rzxRq5Y9LfDyplVbHfh34fbB7M5G+wnu5CZgJsfJ7DF3MjpA
+7nlAHd5alAynIUl/CNXejf+XnJ/vyF1eQvAoWvnjBPVIS0mbaABgF54ybAGE2E7UKeZVOAj7RoQV
+AMHQcYVjxZW5OWz3yJX9KdaDZPOzqlGtRYKUASHiwAFwExKcqfaHOj0qO8+KdSvEBaVlpe5kunEV
+Evn+kgNKBtzdH2XFMjVFa4im31KW+iq7mNQwUiZDSe9ho6T6UrWu7g8yTQowx3SYLTqVxR0YVgcY
+NCx7nn1AVGNxK3oeonrHHqcBp6qSAIYXeQNfiQIDAQABo4HDMIHAMBMGA1UdJQQMMAoGCCsGAQUF
+BwMJMGkGA1UdIARiMGAwXgYKKwYBBAHOHwQBAjBQMCUGCCsGAQUFBwICMBkaF1NLIHRpbWUgc3Rh
+bXBpbmcgcG9saWN5MCcGCCsGAQUFBwIBFhtodHRwOi8vd3d3LnNrLmVlL2FqYXRlbXBlbC8wHwYD
+VR0jBBgwFoAUHAf0nL+kJWyztJ4iHx+USBtYeo0wHQYDVR0OBBYEFPBOCDPMR+kfp7Ozk5U68E68
+/AseMA0GCSqGSIb3DQEBBQUAA4IBAQCRaqmxZgJiJ+MLamb/P4vyS6azr6/tj8dZCK++V/3GnecR
+m7CiZpR47EnW0NyDzCecGyTWSkVlnZPnNvXRx700Nn0M4Inia5pNhSuVmWS3p5eV70vCbsfRD26+
+6CZhkHWnL/J2xpqeacULtgPPz9gBTyC2ybQr17dv7W5Qc+3UFywmE5N8ozQuEJroGz7P+yCbBEss
+WcmIUNDNdO0xs6aQZ1f+DV4FUB0lajuILYFz4xM+81akYFVqaGPCVwbQgFSWRKmamj8FxfWjA4DC
+rgkHVR1rA3tZyirfCBK9cfWpTCLr8zq9Ur0jTAeGrHRzHlUrB9mYZwyr0kNOyl9293xh
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK 2007 OCSP.crt b/etc/certs/EID-SK 2007 OCSP.crt
new file mode 100644
index 0000000..90ceaaa
--- /dev/null
+++ b/etc/certs/EID-SK 2007 OCSP.crt
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIIDOjCCAiKgAwIBAgIERh9YjTANBgkqhkiG9w0BAQUFADBqMQswCQYDVQQGEwJFRTEiMCAGA1UE
+ChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEhMB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3Rl
+ZW51c2VkMRQwEgYDVQQDEwtFSUQtU0sgMjAwNzAeFw0wNzA0MTMxMDE2NDVaFw0xMDA0MTcwOTE2
+NDVaMH8xCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMQ0w
+CwYDVQQLEwRPQ1NQMSMwIQYDVQQDExpFSUQtU0sgMjAwNyBPQ1NQIFJFU1BPTkRFUjEYMBYGCSqG
+SIb3DQEJARYJcGtpQHNrLmVlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD+Z0LZ6TjBzx4x
++UshExea1nIMsS86xAN6u/amLV8XQE+vodEld8iqtRsrvFiQ74isYOys1JKqiq+1ryic6j2FnMDZ
+ueLiXZl51QWyuhWu+aT4BwEaA8rUxMgKJ94zWksrqSf9cjoaap+9DlDhEsrDa+/89CPl2rlZIB5l
+qeHLQQIDAQABo1cwVTATBgNVHSUEDDAKBggrBgEFBQcDCTAfBgNVHSMEGDAWgBQcB/Scv6QlbLO0
+niIfH5RIG1h6jTAdBgNVHQ4EFgQUMsMzikmZqG6CcdgnD5VAXfQeCrgwDQYJKoZIhvcNAQEFBQAD
+ggEBAH0eUFQ7LznD4R8XWj/6rsNhe0fme3Os7cyZGNkx1EWenkgdMHCV/gN3SyIfrjW7sEJM62sS
+1X+8Ke2J+6b5YH0TcSmSDqYICn6zVbsq5MLtHW5wmwKucBJ5xFgoC3NNCEp8wVrzuQmm6xCvFWQV
+Q6uNhjuxCQxcDKgLwpL7iEcBEMmTTKkvqEtqrvu/LZ/a2OHytkEoXGheN8KlEcIv7AJBPVL8OCv4
+UpgyUOrVnmIeX2F/KG3wmo4U3kVupuF9kaPrOeOGYG3ZzK2HNwfRNkZ/Ej7AuPazkumAHdsJBbpT
+dBYq8d8er8XZKai24Ra/e5eEmcMye+O8IpxAA4ExY+I=
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK 2007.crt b/etc/certs/EID-SK 2007.crt
new file mode 100644
index 0000000..23efede
--- /dev/null
+++ b/etc/certs/EID-SK 2007.crt
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIID4jCCAsqgAwIBAgIERZ4nqjANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcNAQkBFglwa2lA
+c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAw
+DgYDVQQDEwdKdXVyLVNLMB4XDTA3MDEwNTEwMjU0NloXDTE2MDgyNjE0MjMwMVowajELMAkGA1UE
+BhMCRUUxIjAgBgNVBAoTGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMxITAfBgNVBAsTGFNlcnRp
+Zml0c2VlcmltaXN0ZWVudXNlZDEUMBIGA1UEAxMLRUlELVNLIDIwMDcwggEiMA0GCSqGSIb3DQEB
+AQUAA4IBDwAwggEKAoIBAQDifhEdyvuhk/3TJEGMJ1tEZOskE81yMqPGGXaPHXACJ7fncn1D1uQF
+t+RG8/ckh7zDquHV1m4HQk7dchaP00rvgsvRlYC9GPcFt6TW8w3t+BkxY1RNbmONgH3qzikljk7m
+6Nb8UGtL9hOmZdw5k5t9Ht8fgHTnoBkFrxYgsv9d4CCkBTSprNUK+vy/NTak4iAYinWtK6tRHHb1
+fxRsLUXiDLSO42Kz+rehhslANX+9Y5/h0wlh3pcmxLB1JWAP0O9fV6N1LUQ3Ym7wMp/lBXuPvl52
+yJuSZDWUF7GkIp+vUifOSefF6CeGh8K9BXDvuOqg+5c/6gkfEQxpRgdu+q5FAgMBAAGjgZwwgZkw
+EgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAf4wMwYDVR0fBCwwKjAooCagJIYiaHR0
+cDovL3d3dy5zay5lZS9jcmxzL2p1dXIvY3JsLmNybDAfBgNVHSMEGDAWgBQEqnpHo+SJrxrPCkCn
+GD9v7+l9vjAdBgNVHQ4EFgQUHAf0nL+kJWyztJ4iHx+USBtYeo0wDQYJKoZIhvcNAQEFBQADggEB
+ABaiEXv415Oh7AgHODwKRyNFqPcSSOgpLCy1XJB3hl3fi21fslccWuBhfzqHQCiQi0fewh109IJi
+Hq8n1PeKoHBCUVq6NFpxkVsUlUPBr0Qsya1O3SQjuOsBLzUWBvY25dtBuAkBMCo0V1Erf7iTeOzu
+L4LLbCoeOfeQT3HPmEfSqP5f8V10ST8erbiTVPJwzr66vXaT9YKxy8NyAQc2iaOHuYmGKxs8dgDQ
+RkG6b2a/f5q21YEQKDhvz7VvM6tH+F+rohA2wAvVz4tcPtyw5WEYcavr1KHgz4eZVWsqh2OsHUK9
+qMas5m/44O1/hXrjpMy5IQsiB4ASXDuXvdOTVbU=
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK 2011.crt b/etc/certs/EID-SK 2011.crt
new file mode 100644
index 0000000..d3222f4
--- /dev/null
+++ b/etc/certs/EID-SK 2011.crt
@@ -0,0 +1,29 @@
+-----BEGIN CERTIFICATE-----
+MIIFADCCA+igAwIBAgIQQyvUTmJDa0ZNgy+/fS0vWjANBgkqhkiG9w0BAQUFADB1
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEoMCYGA1UEAwwfRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYG
+CSqGSIb3DQEJARYJcGtpQHNrLmVlMB4XDTExMDMxODEwMTExMVoXDTI0MDMxODEw
+MTExMVowYTELMAkGA1UEBhMCRUUxIjAgBgNVBAoMGUFTIFNlcnRpZml0c2Vlcmlt
+aXNrZXNrdXMxFDASBgNVBAMMC0VJRC1TSyAyMDExMRgwFgYJKoZIhvcNAQkBFglw
+a2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2Q1zKMt7D
+ytbntSLoYAAVkEwV+5djSr0vSIG/Zm9seKyx+2PY8sVzXRoUD1CMIYnstDhBSKMj
+n2/+HpA7pOipAIAMrk6uKnpSTTdFbQ+0fzJVPokBgsdsQ6R5TZFPB1nu5zgRRlQm
+WIFxOpDiNHTt0LObUhWLXzUb31vc1Wmao2IYcDx1TCs/1E9+camiCl2B5lXrPEU3
+wBq4waD54izS20DK05+6+hHRg+TqoIg5YSmwbjStEyd/8AQeokwVloyyH49bnpel
+uADcZJgxxE9ZUvVWHoxYfmg1IeRU72jHTcIjNf1cQN2+9/FtHQMnGzDBgmAPpghw
+Wr3JtW0JWvMXAgMBAAGjggGeMIIBmjASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1Ud
+DwEB/wQEAwIBBjCB9AYDVR0gBIHsMIHpMIHmBgsrBgEEAc4fZAEBATCB1jCBsAYI
+KwYBBQUHAgIwgaMegaAASwBhAHMAdQB0AGEAdABhAGsAcwBlACAAZgD8APwAcwBp
+AGwAaQBzAHQAZQBsAGUAIABpAHMAaQBrAHUAdABlAGwAZQAgAHMAZQByAHQAaQBm
+AGkAawBhAGEAdABpAGQAZQAgAHYA5ABsAGoAYQBzAHQAYQBtAGkAcwBlAGsAcwAg
+AGsAbwBtAG0AZQByAHQAcwBhAGwAdQBzAGUAbAAuMCEGCCsGAQUFBwIBFhVodHRw
+czovL3d3dy5zay5lZS9DUFMwHQYDVR0OBBYEFLEQlwL63YbGeEGkwzKI+/4f58AF
+MB8GA1UdIwQYMBaAFBLyWj7qVhy/zQas8fElyalL1BSZMD0GA1UdHwQ2MDQwMqAw
+oC6GLGh0dHA6Ly93d3cuc2suZWUvcmVwb3NpdG9yeS9jcmxzL2VlY2NyY2EuY3Js
+MA0GCSqGSIb3DQEBBQUAA4IBAQAxau3ohdFkpvaiVUR7arNovQUZRCG9Ge3udqHY
+emovyU7N60Hgomc/ZG+uunScATTUhBcv9a5zkQxb1dQ1LYDRfNr9CqI0QvSEE4t9
+Sfu3fOhyLrlmb3s8xhhYLJBJ325uDvtO/qFeXLlcRXMF5nU8FE2IyaZP1CHYKVh5
+QNPPQiGZGSox5oOkCvmt4lUl4lZUwVie75us/WtrD6DJeREBTEDHORIfg8E9RA1y
+/7t2gT9vrU8tabeSZlD03qwXe0nJ9RscI/P0HT8vuo1PGzCfbH9xFqfoZ2jdJ0Hz
+xrFM8VsL/AtCw0dmrxRHLlZzqSw0G7b0W40mwOQauO2gbMfn
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK OCSP 2006.crt b/etc/certs/EID-SK OCSP 2006.crt
new file mode 100644
index 0000000..1809fb0
--- /dev/null
+++ b/etc/certs/EID-SK OCSP 2006.crt
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIDVzCCAj+gAwIBAgIERCKL4zANBgkqhkiG9w0BAQUFADCBizEYMBYGCSqGSIb3DQEJARYJcGtp
+QHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEh
+MB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3RlZW51c2VkMQowCAYDVQQFEwExMQ8wDQYDVQQDEwZF
+SUQtU0swHhcNMDYwMzIzMTE1MjAzWhcNMDkwMzI3MTE1MjAzWjB6MQswCQYDVQQGEwJFRTEiMCAG
+A1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czENMAsGA1UECxMET0NTUDEeMBwGA1UEAxMV
+RUlELVNLIE9DU1AgUkVTUE9OREVSMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwgZ8wDQYJKoZI
+hvcNAQEBBQADgY0AMIGJAoGBAJXYEhLiVs7JNpHWhoze68+oRFEcIsUzVvhXQIpNJowEs7blTp7C
+6UJKdK8DC6RpfiehJUdiZILl+wRGGP28Xg049Uku2oiZYX/B2EW829cGfsktDZGh8wJxya3vlyHj
+XOueAwZjNtK74LxpPXWCWSlePJyzvvW8dGJuYG5Uh0IvAgMBAAGjVzBVMBMGA1UdJQQMMAoGCCsG
+AQUFBwMJMB8GA1UdIwQYMBaAFLS8J3CeB8vFZMMyGWzcH3opLjelMB0GA1UdDgQWBBQRDqx+35L2
+TZfA3b9Xf7cnBm7zUTANBgkqhkiG9w0BAQUFAAOCAQEACUFA/IIgn9jZoB+mF05nU9SK/WOqqVhU
+CFVjYfGNltxtAJjM+HWuNWTpzPEATSxPexaNguNQBSLz57/rU3bgSX8bzwYFjBFQSZuJEWD30Svy
+nf3pSGuLA6yGkZlSH4mfccjXJML8kw7HKjb4RHJAtFCPE5nyxzhCqar6yx7o3OTg7ytf8M7RH0KE
+LbAjCYq9My/yjA8+ML/CzXDFRLWlurhSVJ/9MVZljdJ0Lg2vmnb1NGUcQQmXP/jfHIiJPDUGajYB
+Zd4nx5BiMlCAonuBWXYJ5pJUJ4uz3qMrrYAxp3BWn0NhysUX2fM92KQxxHHqvVWHKD5Q6Ja4W/Ws
+0QU3VA==
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK OCSP.crt b/etc/certs/EID-SK OCSP.crt
new file mode 100644
index 0000000..ae94e21
--- /dev/null
+++ b/etc/certs/EID-SK OCSP.crt
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIIDVzCCAj+gAwIBAgIEQJ+U4jANBgkqhkiG9w0BAQUFADCBizEYMBYGCSqGSIb3
+DQEJARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlm
+aXRzZWVyaW1pc2tlc2t1czEhMB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3RlZW51
+c2VkMQowCAYDVQQFEwExMQ8wDQYDVQQDEwZFSUQtU0swHhcNMDQwNTEwMTQ0MjQy
+WhcNMDcwNTE1MTM0MjQyWjB6MQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2Vy
+dGlmaXRzZWVyaW1pc2tlc2t1czENMAsGA1UECxMET0NTUDEeMBwGA1UEAxMVRUlE
+LVNLIE9DU1AgUkVTUE9OREVSMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwgZ8w
+DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALXQF4I5tdllZwNfb3xap93XqGmL225J
+tPgv6SjBOP5pbPs8OwWkpBaqHEJ2WJy7rvEJPTMACNorrH1zBqyIh2t774iSxxGL
+TTDbQbmdM+hzGnAZMerAfHgQPtxx4ri3iluP/MHwWW5U1WKLyi4b1kSEfvqP8hzH
+RfbtKrkBLQLDAgMBAAGjVzBVMBMGA1UdJQQMMAoGCCsGAQUFBwMJMB8GA1UdIwQY
+MBaAFLS8J3CeB8vFZMMyGWzcH3opLjelMB0GA1UdDgQWBBTOliPaDCUNgr1qHIbI
+prQCQrnKzTANBgkqhkiG9w0BAQUFAAOCAQEAo4givhw0UMEOE/RVjSpdY+uoAz6Z
+uNkWYZrhamrLuziJHQdpvxy1ACAAFfDpHc0lRK+wcnFV8NCWxtohZgCzpWB8HzLV
+NgFnt/40CFBqkzRT6wL3jhVflu6lQdhBLmxPzs06BIEZixP0iEOKrIzezEePf3/e
+a6kapVsg5zjPq8iW9ua39cmBp4D0sQ4yd6BMnLPyn77k7zlEzbQfFhAtLis7z6uF
+S0XRJh9PAvcLRPhBGBBcBnGk+x+TAF35OBGL0BOmv/6XqByx/97ACcpOo8ga/CIo
+tOQgyddpBH6bX0HisicUGpLGcpLkZG0HaUKXOeyibYwE/IDM7jrDrzOrPw==
+-----END CERTIFICATE-----
diff --git a/etc/certs/EID-SK.crt b/etc/certs/EID-SK.crt
new file mode 100644
index 0000000..084ba01
--- /dev/null
+++ b/etc/certs/EID-SK.crt
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIIEBDCCAuygAwIBAgIEQJ9YpTANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdKdXVyLVNLMB4XDTA0MDUxMDEwMjU0
+MVoXDTE0MDUwODA5MjU0MVowgYsxGDAWBgkqhkiG9w0BCQEWCXBraUBzay5lZTEL
+MAkGA1UEBhMCRUUxIjAgBgNVBAoTGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMx
+ITAfBgNVBAsTGFNlcnRpZml0c2VlcmltaXN0ZWVudXNlZDEKMAgGA1UEBRMBMTEP
+MA0GA1UEAxMGRUlELVNLMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
+uj80U//DJVfCY5H+vW9xxzBV5tef7no+ehDez9TXtso0HtI1y2400CTHPZckOxdj
+LgOa0TSKcEboGYATujSpVXfR2w4NOK91cmRTPcmBlk3S/FrZvTbwTkYEMAUG3ED0
+Ofv7uq8rn4UnKiQxzeClJV2gectPu19FdM9pCqJV3DGn95BOng2tcwba0fISDPUh
+vUYnuF4f9ZxblFHJTd82dFh9Qc/EkQ+czl8l72wyMOfWJwO50IbyRJJ5hIglFZ6q
+BWFT4s53W6ubT2RfOOhqoBdywNk3W5u1sUXCnkIr4MVjwWSeUvv0caanXhYskKTx
+tOYXFe0Rq/IsGrxUasRB5QIDAQABo4GcMIGZMBIGA1UdEwEB/wQIMAYBAf8CAQAw
+DgYDVR0PAQH/BAQDAgHmMDMGA1UdHwQsMCowKKAmoCSGImh0dHA6Ly93d3cuc2su
+ZWUvY3Jscy9qdXVyL2NybC5jcmwwHwYDVR0jBBgwFoAUBKp6R6Pkia8azwpApxg/
+b+/pfb4wHQYDVR0OBBYEFLS8J3CeB8vFZMMyGWzcH3opLjelMA0GCSqGSIb3DQEB
+BQUAA4IBAQBXF6vhu1kgHOBzET0WK5JjgNHbB7vX0JR2r8SGoNnkmWsnqlNtZxCU
+5YdB/HK/TmNmQykmf1qSI0gmarvCZ0aZfNNDERT5I67o15zlsoI207XvYIJ1oHPb
+Ia5VVKUnzb7nP3xcWx7HhDGb5A2qVvrMoxsWv+CcvoTKx1nvCCsOXiiSCZYVqQK5
+lw/NptHqwRh/e4ywE5ReQrUmD2MzfEB4s4aBHfOWSH4+ucJVFRvsIJqAFXwueq9E
+LgJYEnaqVtmmCl3Gfaff0Pi6eTAfZDrJ9v7lKRYOLtImDpiJUMygTtnX0YFa/zaW
+oMNrPAZ4RYS3FOq+6+XfoXx+IDLl+oew
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK 2007 OCSP 2010.crt b/etc/certs/ESTEID-SK 2007 OCSP 2010.crt
new file mode 100644
index 0000000..dd1a6a7
--- /dev/null
+++ b/etc/certs/ESTEID-SK 2007 OCSP 2010.crt
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIIEkjCCA3qgAwIBAgIESxUPmTANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQGEwJFRTEiMCAGA1UE
+ChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEPMA0GA1UECxMGRVNURUlEMRcwFQYDVQQDEw5F
+U1RFSUQtU0sgMjAwNzAeFw0wOTEyMDExMjQ1MDBaFw0xNjA4MjYxMzIzMDBaMIGHMQswCQYDVQQG
+EwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czENMAsGA1UECwwET0NTUDEr
+MCkGA1UEAwwiRVNURUlELVNLIDIwMDcgT0NTUCBSRVNQT05ERVIgMjAxMDEYMBYGCSqGSIb3DQEJ
+ARYJcGtpQHNrLmVlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA48pyM/QfeiU1Kbu4
+AdcAUKXBiwbYbBl4gCltZHC5fZ77fKj2mqfPX2/XW1EqzbVvG0PYIkapkQzBr3R1S6Uaxh1DLC2C
+c8BRnqmhXoE03o8En7N9xpN9dGGDBHp2aElBcVVZnAvF4jgbPDCNFAeo3cvpjIx18n0URiVOZFEd
+xDvF8PFo/exKXtjRM+jk3K6+9doHYvSXn9klFbT8Wge87Qdll3gQzZE3L8QMXF0z4xbBH1lyTmVL
+t5yZ0fxoE0jNlZFvn2w2EDnU4CKfId8w6Zjd5kdxomcwDzGuuLzdiJllPt05USJcY4FHn9YAVKWm
+ofYY/o6xOUzU8fAz6yA1tQIDAQABo4IBLzCCASswEwYDVR0lBAwwCgYIKwYBBQUHAwkwaQYDVR0g
+BGIwYDBeBgorBgEEAc4fBAECMFAwJQYIKwYBBQUHAgIwGRoXU0sgdGltZSBzdGFtcGluZyBwb2xp
+Y3kwJwYIKwYBBQUHAgEWG2h0dHA6Ly93d3cuc2suZWUvYWphdGVtcGVsLzCBiQYDVR0jBIGBMH+A
+FEgG3r6Mh1eVgHhj+pwjKyugOhh1oWGkXzBdMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUxCzAJ
+BgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdK
+dXVyLVNLggRFm6ANMB0GA1UdDgQWBBQ4AhAwumZ6EXROIl5wZQXedXpOFDANBgkqhkiG9w0BAQUF
+AAOCAQEAJ/LvPUevNRcBp+J78fZRofhk/ifKNLxCUoh8T3MjtU9u5R0KojRlye+1NU8MqH/zrKhr
+6TPxuXD0cRrFQ9Hy60II7IzzaegrQVNgq7UgQINvCuNxWZcGtEa3ba9M7tBpQeFxqp3CpBytGeVu
+Xn65hqOBKdp/zYEiMUUkYNAT5A6SSPYLAOgARCI/ydBx+cw0l0fwYvw72FKZa2Mlt5DmXBccCtrQ
+4l/sb95xfANCNe5n5sBvBhY4F+sIWZUVJ8fTVh7iGaVPSayQfeAAei0m/4/ksiXBwfx6qhzyB3yq
+cnSk489oBrrCegua/t+3LizfHpNZvDphKMPuAZ4uheLfQA==
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK 2007 OCSP.crt b/etc/certs/ESTEID-SK 2007 OCSP.crt
new file mode 100644
index 0000000..cc56a7b
--- /dev/null
+++ b/etc/certs/ESTEID-SK 2007 OCSP.crt
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDnDCCAoSgAwIBAgIERZ0acjANBgkqhkiG9w0BAQUFADBbMQswCQYDVQQGEwJFRTEiMCAGA1UE
+ChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEPMA0GA1UECxMGRVNURUlEMRcwFQYDVQQDEw5F
+U1RFSUQtU0sgMjAwNzAeFw0wNzAxMDQxNTE3MDZaFw0xMDAxMDgxNTE3MDZaMG8xCzAJBgNVBAYT
+AkVFMQ8wDQYDVQQKEwZFU1RFSUQxDTALBgNVBAsTBE9DU1AxJjAkBgNVBAMTHUVTVEVJRC1TSyAy
+MDA3IE9DU1AgUkVTUE9OREVSMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwgZ8wDQYJKoZIhvcN
+AQEBBQADgY0AMIGJAoGBAJmoB3SJCpPzcoHNqK1J0tRNQjgr5iuB27uE1VacIbITjD/Nc1AefKz5
+ydNPIaBNehm4yKxBYGxEeWOSJHVXyhJMg53EAUOw/45c46gvznXupHuJ6TEiGjh1pxaXTeLSnTqz
+NDZDAGQsOTgIbwGLa5U5ad8rXYu2YkJKsAfo6jT5AgMBAAGjgdcwgdQwEwYDVR0lBAwwCgYIKwYB
+BQUHAwkwEgYJKwYEBQUHMAEFBAUwAwQBMDCBiQYDVR0jBIGBMH+AFEgG3r6Mh1eVgHhj+pwjKyug
+Ohh1oWGkXzBdMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQK
+ExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdKdXVyLVNLggRFm6ANMB0GA1Ud
+DgQWBBRJ/snw1GDL3fUH9n9Cpn8yhXiC7DANBgkqhkiG9w0BAQUFAAOCAQEAYzGkZD/uaXlWPeye
+1z5IiI83nmAjiJyvoj/r3BB9ZFWMX+ZY4Fz6/V/fzD0xXoeDpWbBKxcuctPXzXYxEH17n0/3yGOz
+8jhdJNBUCwRmd+96oHsU9aWSf+D2tiq1jPw6HVCiUYOhC/OWjg/+JpFlWsBV4gTW8/2PSGig85Xl
+EsWLK7i7tIe60nnw/rWnfbCckMRcbrAF1L/JIlnUYUdkGOGQ9KPVqwR/MyWrwFIcSy2QIbcIaWMu
+iUc1nt8bmIXKoFZxbLzXYC00zba9cY7lSC4WPuhBtrQJ9JWb4OeoXd5j6O45UaH6XbarfrhER1GH
+L06cTyksT18p2L2GrMuEJg==
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK 2007.crt b/etc/certs/ESTEID-SK 2007.crt
new file mode 100644
index 0000000..b36e3e2
--- /dev/null
+++ b/etc/certs/ESTEID-SK 2007.crt
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIID0zCCArugAwIBAgIERZugDTANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcNAQkBFglwa2lA
+c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRAw
+DgYDVQQDEwdKdXVyLVNLMB4XDTA3MDEwMzEyMjIzN1oXDTE2MDgyNjE0MjMwMVowWzELMAkGA1UE
+BhMCRUUxIjAgBgNVBAoTGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMxDzANBgNVBAsTBkVTVEVJ
+RDEXMBUGA1UEAxMORVNURUlELVNLIDIwMDcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
+AQDtWp2jLCsA7K9AxoPDOL0geM1GoR0Q6wSUICCJYyFkUMboEMxpSzFB6tlb0ySlHEU6Fs+tjA4Q
+rSqwaw0uNk4BXv1lkoOr6DUc+20+AQd5jB6A0atrltZ1XG5IvDEep3DJPykkk2MPxUz7dZx7XUEr
+/kdUWI9cDIkFWic7y9oTBY9JaV6lxm08kweZ/qTw5PU8/bTvZCE0ygvBXU4TDS2FpUJ/+jTzM2oc
+Wa3QjFQv2Sir6LBvgNY3du/m+WLABq0dgN18R4nhFtmaVepqAeUuEi8eRBl6yLTSmMwYCY46LsK5
+CdjTCZSZv934FtNuyY6Ph9nCXJAgNAY+GfNJfdMXAgMBAAGjgZwwgZkwEgYDVR0TAQH/BAgwBgEB
+/wIBADAOBgNVHQ8BAf8EBAMCAf4wMwYDVR0fBCwwKjAooCagJIYiaHR0cDovL3d3dy5zay5lZS9j
+cmxzL2p1dXIvY3JsLmNybDAfBgNVHSMEGDAWgBQEqnpHo+SJrxrPCkCnGD9v7+l9vjAdBgNVHQ4E
+FgQUSAbevoyHV5WAeGP6nCMrK6A6GHUwDQYJKoZIhvcNAQEFBQADggEBACO6SJrjN5WZuiLSMy/t
+SmT/w3dd/KPErSAdUIJYkC7hOIauW7jZ3VNgNUMHSIkUoP8AviEMjGA4lkT61YScpJAdmgl8Y80H
+FdZV5CsThhddoIdZ3cZjSI4NZmTVkSduTjoySALxKL3ZEIPrepQDvNEeV1WSpI5+u/vMekUWJSPc
+8BK9O2av1e9ResKyPJidqrIksHFjNS+Yt8Ouw7F10MHaPPzMiwoa0DYTVsIKJncPTQmvdJG8M0DD
+ToiiNPQuUy5d1CA75Wtjs+yILGZXpOfbdoQhE7G4pbZaF1s69jKp+zc0ZT4g2OoKfI2TiIX9qeGJ
+MxkOENcd1DDqYVfePmo=
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK 2011.crt b/etc/certs/ESTEID-SK 2011.crt
new file mode 100644
index 0000000..69cb046
--- /dev/null
+++ b/etc/certs/ESTEID-SK 2011.crt
@@ -0,0 +1,29 @@
+-----BEGIN CERTIFICATE-----
+MIIFBTCCA+2gAwIBAgIQKVKTqv2MxtRNgzCjwmRRDTANBgkqhkiG9w0BAQUFADB1
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEoMCYGA1UEAwwfRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYG
+CSqGSIb3DQEJARYJcGtpQHNrLmVlMB4XDTExMDMxODEwMTQ1OVoXDTI0MDMxODEw
+MTQ1OVowZDELMAkGA1UEBhMCRUUxIjAgBgNVBAoMGUFTIFNlcnRpZml0c2Vlcmlt
+aXNrZXNrdXMxFzAVBgNVBAMMDkVTVEVJRC1TSyAyMDExMRgwFgYJKoZIhvcNAQkB
+Fglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCz6Xxs
+Zh6r/aXcNe3kSpNMOqmQoAXUpzzcr4ZSaGZh/7JHIiplvNi6tbW/lK7sAiRsb65K
+zMWROEauld66ggbDPga6kU97C+AXGu7+DROXstjUOv6VlrHZVAnLmIOkycpWaxjM
++EfQPZuDxEbkw96B3/fG69Zbp3s9y6WEhwU5Y9IiQl8YTkGnNUxidQbON1BGQm+H
+VEsgTf22J6r6G3FsE07rnMNskNC3DjuLSCUKF4kH0rVGVK9BdiCdFaZjHEykjwjI
+GzqnyxyRKe4YbJ6B9ABm95eSFgMBHtZEYU+q0VUIQGhAGAurOTXjWi1TssA42mnL
+GQZEI5GXMXtabp51AgMBAAGjggGgMIIBnDASBgNVHRMBAf8ECDAGAQH/AgEAMA4G
+A1UdDwEB/wQEAwIBBjCB9gYDVR0gBIHuMIHrMIHoBgsrBgEEAc4fZAEBATCB2DCB
+sgYIKwYBBQUHAgIwgaUegaIASwBhAHMAdQB0AGEAdABhAGsAcwBlACAAaQBzAGkA
+awB1AHQAdAD1AGUAbgBkAGEAdgBhAGwAZQAgAGQAbwBrAHUAbQBlAG4AZABpAGwA
+ZQAgAGsAYQBuAHQAYQB2AGEAdABlACAAcwBlAHIAdABpAGYAaQBrAGEAYQB0AGkA
+ZABlACAAdgDkAGwAagBhAHMAdABhAG0AaQBzAGUAawBzAC4wIQYIKwYBBQUHAgEW
+FWh0dHBzOi8vd3d3LnNrLmVlL0NQUzAdBgNVHQ4EFgQUe2ryVVBcuNl6CIdBrvqi
+Kz1bV3YwHwYDVR0jBBgwFoAUEvJaPupWHL/NBqzx8SXJqUvUFJkwPQYDVR0fBDYw
+NDAyoDCgLoYsaHR0cDovL3d3dy5zay5lZS9yZXBvc2l0b3J5L2NybHMvZWVjY3Jj
+YS5jcmwwDQYJKoZIhvcNAQEFBQADggEBAKC4IN3FC2gVDIH05TNMgFrQOCGSnXhz
+oJclRLoQ81BCOXTZI4qn7N74FHEnrAy6uNG7SS5qANqSaPIL8dp63jg/L4qn4iWa
+B5q5GGJOV07SnTHS7gUrqChGClnUeHxiZbL13PkP37Lnc+TKl1SKfgtn5FbH5cqr
+hvbA/VF3Yzlimu+L7EVohW9HKxZ//z8kDn6ieiPFfZdTOov/0eXVLlxqklybUuS6
+LYRRDiqQupgBKQBTwNbC8x0UHX00HokW+dCVcQvsUbv4xLhRq/MvyTthE+RdbkrV
+0JuzbfZvADfj75nA3+ZAzFYS5ZpMOjZ9p4rQVKpzQTklrF0m6mkdcEo=
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK OCSP 2005.crt b/etc/certs/ESTEID-SK OCSP 2005.crt
new file mode 100644
index 0000000..b534532
--- /dev/null
+++ b/etc/certs/ESTEID-SK OCSP 2005.crt
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIIDPDCCAiSgAwIBAgIEQi2iwTANBgkqhkiG9w0BAQUFADB8MRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMQ8wDQYDVQQLEwZFU1RFSUQxCjAIBgNVBAQTATExEjAQ
+BgNVBAMTCUVTVEVJRC1TSzAeFw0wNTAzMDgxMzA0MDFaFw0xMjAxMTIxMzA0MDFa
+MG8xCzAJBgNVBAYTAkVFMQ8wDQYDVQQKEwZFU1RFSUQxDTALBgNVBAsTBE9DU1Ax
+JjAkBgNVBAMTHUVTVEVJRC1TSyBPQ1NQIFJFU1BPTkRFUiAyMDA1MRgwFgYJKoZI
+hvcNAQkBFglwa2lAc2suZWUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAI8m
+LeLkRHLxMNCB5Pz8R5DnvPdVxBS91PoHboLnbhjlp1ecByVosjwGpXCGu8tUPuv8
+1Azgqq97AsSugM1J7Pu0gj4bg0Mf6O/9XyoT7RI7H0BuEn4KJQlFcw7tXizI5KUW
+FFZ4Qg8kfg0xwrDrLIjusBtRbeRARG3DhH8dgZBpAgMBAAGjVzBVMBMGA1UdJQQM
+MAoGCCsGAQUFBwMJMB8GA1UdIwQYMBaAFHgXtQX5s1jNWYzeZ15EBkx1hmldMB0G
+A1UdDgQWBBRM+GJhloJeOPpJDgvA0clxQXdnVTANBgkqhkiG9w0BAQUFAAOCAQEA
+fD8dP+swtSeigLxL3uUXV/tmQkjre7Ww39Uey71LdtxQ6zC7MDjcsLW13JaU0pRu
+u/p/eGe6h4/w46tSMsBx/U+D1WnHeCj1ED9SFWwfNQFVz9FkM5JEkPDm7lw5hHox
+IghRHAC3NMbR3sCrVQA2YELf2WypslROoz8XlRT1LN4pwVehpBeWO7xbQPUtoaxK
+rSCGumtxtxA3KRJ7POHPTAH4cvipxaZhS1ZcXbKtxsesGW+7KLZirpTBT17ICXEA
+1CFXDWmJ8MHRhbeNWK3G1PERgTiGtBQV7Z00CzmJPHmb1yfcT27+WZ1W9tRQsjhG
+EWyMVkNnZooWHIjLpNucQA==
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK OCSP.crt b/etc/certs/ESTEID-SK OCSP.crt
new file mode 100644
index 0000000..3113d04
--- /dev/null
+++ b/etc/certs/ESTEID-SK OCSP.crt
@@ -0,0 +1,22 @@
+-----BEGIN CERTIFICATE-----
+MIIDuDCCAqCgAwIBAgIEPJilyDANBgkqhkiG9w0BAQUFADB8MRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMQ8wDQYDVQQLEwZFU1RFSUQxCjAIBgNVBAQTATExEjAQ
+BgNVBAMTCUVTVEVJRC1TSzAeFw0wMjAzMjAxNTA3NTJaFw0wNTAzMjQxNTA3NTJa
+MGoxCzAJBgNVBAYTAkVFMQ8wDQYDVQQKEwZFU1RFSUQxDTALBgNVBAsTBE9DU1Ax
+ITAfBgNVBAMTGEVTVEVJRC1TSyBPQ1NQIFJFU1BPTkRFUjEYMBYGCSqGSIb3DQEJ
+ARYJcGtpQHNrLmVlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC10BeCObXZ
+ZWcDX298Wqfd16hpi9tuSbT4L+kowTj+aWz7PDsFpKQWqhxCdlicu67xCT0zAAja
+K6x9cwasiIdre++IkscRi00w20G5nTPocxpwGTHqwHx4ED7cceK4t4pbj/zB8Flu
+VNVii8ouG9ZEhH76j/Icx0X27Sq5AS0CwwIDAQABo4HXMIHUMBMGA1UdJQQMMAoG
+CCsGAQUFBwMJMBIGCSsGBAUFBzABBQQFMAMEATAwgYkGA1UdIwSBgTB/gBR4F7UF
++bNYzVmM3mdeRAZMdYZpXaFhpF8wXTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVl
+MQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEQMA4GA1UEAxMHSnV1ci1TS4IEPERcgjAdBgNVHQ4EFgQUzpYj2gwlDYK9ahyG
+yKa0AkK5ys0wDQYJKoZIhvcNAQEFBQADggEBADrq0tGkwsrddEqUbsOpXi75Xs4G
+VkOyseysNqZZCvLqCF7qTSMiC+fzRxQbXQDhuOT7QQvi3JAoA5zTIm2RvIO1fmrV
+nJ6CsObjxxvXtcSLI+bICG4uQYgEA+duDRgICpmtCCjtmxb+2/cSJLGioaKiwn0Y
+wgeEowOgjDMh2o4otm6FjtyT1GZsZm56U7WkFa7tSwkHKw427iZUWVrED6W9AfAT
+Y14rNnAk8Jqz06w4rPnGE4kYjO+UqMLmFU2KImdrTp1O7h4YLCVlxH/e/He8r7FS
+gzXSG4EqlD/TMEdCLu7DSWR3SEgJPvKWCpNWzv2DRldHp+kQO3k+R/f2c80=
+-----END CERTIFICATE-----
diff --git a/etc/certs/ESTEID-SK.crt b/etc/certs/ESTEID-SK.crt
new file mode 100644
index 0000000..678952b
--- /dev/null
+++ b/etc/certs/ESTEID-SK.crt
@@ -0,0 +1,29 @@
+-----BEGIN CERTIFICATE-----
+MIIFAjCCA+qgAwIBAgIEPERcgjANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdKdXVyLVNLMB4XDTAyMDExNTE2NDQ1
+MFoXDTEyMDExMzE2NDQ1MFowfDEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMQsw
+CQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEP
+MA0GA1UECxMGRVNURUlEMQowCAYDVQQEEwExMRIwEAYDVQQDEwlFU1RFSUQtU0sw
+ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCLeZO5NVo3zbwA8eFVCrrb
+eZQKvPDB7LUDPvzCqw7U2sC+IwEOdjjpJRF4lxFs+f8yC1bP+rqtWzrKhhJ2owfS
+AlIZMbly/OFjfLqOcyyi7qdfA/66u+69u/DY9tW5fqW93D73v5WNcNoIemCTydh9
+IFkQvMihWKH7LblBzCHa4W6qUcBZ7QsBgYpQS9n9fGJt5D2wCDeq0pF1Zy72G3CQ
+FrpuR/aPG28tv9r+C7oqncapbiJ7xIOa77Fm3o07M/9aarq/m1oHEp9CxYiH9nmD
+3kyMe8yxw5v02MTMmAcxOm83z5O4oXSDTALG5gDfZNPjJaNPno7J8FuGrI3vV8z3
+AgMBAAGjggGpMIIBpTAMBgNVHRMEBTADAQH/MA4GA1UdDwEB/wQEAwIB5jCCARYG
+A1UdIASCAQ0wggEJMIIBBQYKKwYBBAHOHwEBATCB9jCB0AYIKwYBBQUHAgIwgcMe
+gcAAUwBlAGUAIABzAGUAcgB0AGkAZgBpAGsAYQBhAHQAIABvAG4AIAB2AOQAbABq
+AGEAcwB0AGEAdAB1AGQAIABBAFMALQBpAHMAIABTAGUAcgB0AGkAZgBpAHQAcwBl
+AGUAcgBpAG0AaQBzAGsAZQBzAGsAdQBzACAAYQBsAGEAbQAtAFMASwAgAHMAZQBy
+AHQAaQBmAGkAawBhAGEAdABpAGQAZQAgAGsAaQBuAG4AaQB0AGEAbQBpAHMAZQBr
+AHMwIQYIKwYBBQUHAgEWFWh0dHA6Ly93d3cuc2suZWUvY3BzLzArBgNVHR8EJDAi
+MCCgHqAchhpodHRwOi8vd3d3LnNrLmVlL2p1dXIvY3JsLzAfBgNVHSMEGDAWgBQE
+qnpHo+SJrxrPCkCnGD9v7+l9vjAdBgNVHQ4EFgQUeBe1BfmzWM1ZjN5nXkQGTHWG
+aV0wDQYJKoZIhvcNAQEFBQADggEBAFIsMHaq4Ffkrxmzw38rHYh5Ia5JGxjtWfPp
+ag9pBtQNZHzY8j97xfPI15haE9Ah3u1WC+bsU2SndVSUGaZ0gKafMxDOy2DUw3B8
+4ymbNRiAFSWty+aKrMCjtdlPktbSQmxNSJAX9vVtM4Y2ory+dtAQ7g11GKHJ+l8B
+DUpOJA+l8hvS2l4K5whWDHCSqlplMiHPIKgBVArFRNzAq6dquMY+kS3e2PL+PM4G
+dDW5lRHR/6KUy0BHP2gX/BO4mYQ3BH2BHImUclNras0HISnV/pt6hIkgd1PsFt3r
+tEolAWP4DWBmc4zAYQJ5t0cEwFM329zCXSGIQIm3a1cMugF5Q/k=
+-----END CERTIFICATE-----
diff --git a/etc/certs/JUUR-SK.crt b/etc/certs/JUUR-SK.crt
new file mode 100644
index 0000000..269961b
--- /dev/null
+++ b/etc/certs/JUUR-SK.crt
@@ -0,0 +1,29 @@
+-----BEGIN CERTIFICATE-----
+MIIE5jCCA86gAwIBAgIEO45L/DANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdKdXVyLVNLMB4XDTAxMDgzMDE0MjMw
+MVoXDTE2MDgyNjE0MjMwMVowXTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMQsw
+CQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEQ
+MA4GA1UEAxMHSnV1ci1TSzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
+AIFxNj4zB9bjMI0TfncyRsvPGbJgMUaXhvSYRqTCZUXP00B841oiqBB4M8yIsdOB
+SvZiF3tfTQou0M+LI+5PAk676w7KvRhj6IAcjeEcjT3g/1tf6mTll+g/mX8MCgkz
+ABpTpyHhOEvWgxutr2TC+Rx6jGZITWYfGAriPrsfB2WThbkasLnE+w0R9vXW+RvH
+LCu3GFH+4Hv2qEivbDtPL+/40UceJlfwUR0zlv/vWT3aTdEVNMfqPxZIe5EcgEMP
+PbgFPtGzlc3Yyg/CQ2fbt5PgIoIuvvVoKIO5wTtpeyDaTpxt4brNj3pssAki14sL
+2xzVWiZbDcDq5WDQn/413z8CAwEAAaOCAawwggGoMA8GA1UdEwEB/wQFMAMBAf8w
+ggEWBgNVHSAEggENMIIBCTCCAQUGCisGAQQBzh8BAQEwgfYwgdAGCCsGAQUFBwIC
+MIHDHoHAAFMAZQBlACAAcwBlAHIAdABpAGYAaQBrAGEAYQB0ACAAbwBuACAAdgDk
+AGwAagBhAHMAdABhAHQAdQBkACAAQQBTAC0AaQBzACAAUwBlAHIAdABpAGYAaQB0
+AHMAZQBlAHIAaQBtAGkAcwBrAGUAcwBrAHUAcwAgAGEAbABhAG0ALQBTAEsAIABz
+AGUAcgB0AGkAZgBpAGsAYQBhAHQAaQBkAGUAIABrAGkAbgBuAGkAdABhAG0AaQBz
+AGUAawBzMCEGCCsGAQUFBwIBFhVodHRwOi8vd3d3LnNrLmVlL2Nwcy8wKwYDVR0f
+BCQwIjAgoB6gHIYaaHR0cDovL3d3dy5zay5lZS9qdXVyL2NybC8wHQYDVR0OBBYE
+FASqekej5ImvGs8KQKcYP2/v6X2+MB8GA1UdIwQYMBaAFASqekej5ImvGs8KQKcY
+P2/v6X2+MA4GA1UdDwEB/wQEAwIB5jANBgkqhkiG9w0BAQUFAAOCAQEAe8EYlFOi
+CfP+JmeaUOTDBS8rNXiRTHyoERF5TElZrMj3hWVcRrs7EKACr81Ptcw2Kuxd/u+g
+kcm2k298gFTsxwhwDY77guwqYHhpNjbRxZyLabVAyJRld/JXIWY7zoVAtjNjGr95
+HvxcHdMdkxuLDF2FvZkwMhgJkVLpfKG6/2SSmuz+Ne6ML678IIbsSt4beDI3poHS
+na9aEhbKmVv8b20OxaAehsmR0FyYgl9jDIpaq9iVpszLita/ZEuOyoqysOkhMp6q
+qIWYNIE5ITuoOlIyPfZrN4YGWhWY3PARZv40ILcD9EEQfTmEeZZyY7aWAuVrua0Z
+TbvGRNs2yyqcjg==
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK 2010 EECCRCA.crt b/etc/certs/KLASS3-SK 2010 EECCRCA.crt
new file mode 100644
index 0000000..53dabc1
--- /dev/null
+++ b/etc/certs/KLASS3-SK 2010 EECCRCA.crt
@@ -0,0 +1,27 @@
+-----BEGIN CERTIFICATE-----
+MIIErDCCA5SgAwIBAgIQAznVp1LayatNgy6bN8f9QjANBgkqhkiG9w0BAQUFADB1
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEoMCYGA1UEAwwfRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYG
+CSqGSIb3DQEJARYJcGtpQHNrLmVlMB4XDTExMDMxODEwMDYxOFoXDTI0MDMxODEw
+MDYxOFowbTELMAkGA1UEBhMCRUUxIjAgBgNVBAoTGUFTIFNlcnRpZml0c2Vlcmlt
+aXNrZXNrdXMxITAfBgNVBAsTGFNlcnRpZml0c2VlcmltaXN0ZWVudXNlZDEXMBUG
+A1UEAxMOS0xBU1MzLVNLIDIwMTAwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
+AoIBAQCrlaYRX2v89k8Hd0ADaOfnUcIn7iM6aOXkAR+jp5827ZhDqDyNddF9ZUoB
+gPghGNIrkHbH7qwex39YnI0ka24lCjcwEMvQMPbyPnX/a4RyJ+wEZttmjBl++Ffr
+ZK54L+vD7Dyy4YYB0Og9ktB4qptsDBj+giiv/MGPeGeNs3TacJdNb7+3splTPtPK
+lDfrufvq4H6jNOv9S9bC+j2VVY9uCFXUro8AA3hoOEKJdSjlpYCa51N8KGLVJYRu
+c/K81xqi054Jz+Cy/HY/AcXkk2JkxlpJoEXmcuTkxjO/QE/Xbd+mRJHnq6+HurOi
+KcxKwZCPAa+d+dvRPkbyq9ohMXH9AgMBAAGjggE+MIIBOjASBgNVHRMBAf8ECDAG
+AQH/AgEAMA4GA1UdDwEB/wQEAwIBxjCBlAYDVR0gBIGMMIGJMIGGBgsrBgEEAc4f
+ZAEBATB3MCEGCCsGAQUFBwIBFhVodHRwczovL3d3dy5zay5lZS9jcHMwUgYIKwYB
+BQUHAgIwRh5EAEEAcwB1AHQAdQBzAGUAIABzAGUAcgB0AGkAZgBpAGsAYQBhAHQA
+LgAgAEMAbwByAHAAbwByAGEAdABlACAASQBEAC4wHQYDVR0OBBYEFF11FBGM9KWO
+Qo97skBEo+7WejtyMB8GA1UdIwQYMBaAFBLyWj7qVhy/zQas8fElyalL1BSZMD0G
+A1UdHwQ2MDQwMqAwoC6GLGh0dHA6Ly93d3cuc2suZWUvcmVwb3NpdG9yeS9jcmxz
+L2VlY2NyY2EuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQC3qNBgY2I9Wqm4LZYKAjCY
+kc2Nltm1RS9frMvQJ4aEE4Y4TtW2LPcQp2lenOf9aYdEB8G/E9CytZSPlFuvDdsd
+knj6fg1XCeu6ITR2wIkxJeAeLQvrFEfb1mcAa5tU9RNalZhYc7MFMFQTjQP+GBNx
+z+KIjNDVASFdv7TCe7GBjsW8Dfes9lQGHaWsBRkHCyuPGIHfH+cmMuhLtWqa4Qlg
+4f54kcsGO7s4buKtk6XqEj8Cj2ITdfk/aUs9QoxxkYWGwSUlCueTamzufXEJo9yz
+5Jp6IFdGjotmjb/EBUCf2sFfI83a4Cm1D3L3/KYb5g3cYlDEpPWNqbNuA1XosIqK
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK 2010 OCSP.crt b/etc/certs/KLASS3-SK 2010 OCSP.crt
new file mode 100644
index 0000000..73ba848
--- /dev/null
+++ b/etc/certs/KLASS3-SK 2010 OCSP.crt
@@ -0,0 +1,25 @@
+-----BEGIN CERTIFICATE-----
+MIIELzCCAxegAwIBAgICAMswDQYJKoZIhvcNAQEFBQAwbTELMAkGA1UEBhMCRUUx
+IjAgBgNVBAoTGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMxITAfBgNVBAsTGFNl
+cnRpZml0c2VlcmltaXN0ZWVudXNlZDEXMBUGA1UEAxMOS0xBU1MzLVNLIDIwMTAw
+HhcNMTAwNDA4MDgwMTMxWhcNMTYwODI1MjIwMDAwWjCBgjEYMBYGCSqGSIb3DQEJ
+ARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRz
+ZWVyaW1pc2tlc2t1czENMAsGA1UECxMET0NTUDEmMCQGA1UEAxMdS0xBU1MzLVNL
+IDIwMTAgT0NTUCBSRVNQT05ERVIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
+AoIBAQDhWwGpngF0sdGCgOgiyT12A/Vdm9sMPr/cUwZhU7DA5C8rU1yJhbrh28fM
+pv0eas6/+IC1oDxI24zjfWIKfHwpBmhUTFsmvmKRIu4a1F6VwNwYEdoAZrQDpzZS
+ve6H6R/+0Uy0BAolebdhPUK22pKd8V1CBY3de886Ray8uUJu09MAU8j+xsoUNOzy
+xiWdAVp1YTXRhhUt+EQVYJ22RBZ6+b9fPQvgb9aWgE/WwqUh7OrgTnrGZVzgO46p
+rfE7zkALG0FYZCzQTCMH8aIqqte0E3HwSVlKh9qwbRPB9WTDCtCqajh4qgGRTXvW
+T4vATlHvx8GpJ3roZkp5AlQno3hTAgMBAAGjgcIwgb8waAYDVR0gBGEwXzBdBgor
+BgEEAc4fBAECME8wJQYIKwYBBQUHAgIwGRoXU0sgdGltZSBzdGFtcGluZyBwb2xp
+Y3kwJgYIKwYBBQUHAgEWGmh0dHA6Ly93d3cuc2suZWUvYWphdGVtcGVsMBMGA1Ud
+JQQMMAoGCCsGAQUFBwMJMB8GA1UdIwQYMBaAFF11FBGM9KWOQo97skBEo+7Wejty
+MB0GA1UdDgQWBBQ3MJkXG2Go/6j4bem465aue3P5qjANBgkqhkiG9w0BAQUFAAOC
+AQEAKhoVTII1ECecFkyt9Ogr0XW3WEFprrqTDE4IycMlx+LNjWk30aknMldEtzIC
+5nCDX27NCWkpbN1o/3ddBv0cKMa05ZK8sHQxU6A5Oev8DCp72/LFEChq5IDqgqW2
+BiHhyfPfr93JIuV03b/Wgq3fpRyBd21VE9254W4A90xeNxDvdpqxlrD2Lonzm/V/
+oomzEHsp4kKxXkPmRU4vGtTnxxAnxYp9OuLkvpUCLNoAWMbYqb4cbYzaZ9tQIkBy
+3nJ352Rs5obYDb3R/ZVWuYLLSocWL7b2QwlDP7LA8VNDqmQvioHt8GcyKXQ5/eWM
+vj2ePt58waVhwfSdd4nANKtq1g==
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK 2010.crt b/etc/certs/KLASS3-SK 2010.crt
new file mode 100644
index 0000000..dc85ca7
--- /dev/null
+++ b/etc/certs/KLASS3-SK 2010.crt
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIID5TCCAs2gAwIBAgIES7MTKDANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdKdXVyLVNLMB4XDTEwMDMzMTA5MTcy
+OFoXDTE2MDgyNjE0MjMwMVowbTELMAkGA1UEBhMCRUUxIjAgBgNVBAoTGUFTIFNl
+cnRpZml0c2VlcmltaXNrZXNrdXMxITAfBgNVBAsTGFNlcnRpZml0c2VlcmltaXN0
+ZWVudXNlZDEXMBUGA1UEAxMOS0xBU1MzLVNLIDIwMTAwggEiMA0GCSqGSIb3DQEB
+AQUAA4IBDwAwggEKAoIBAQCrlaYRX2v89k8Hd0ADaOfnUcIn7iM6aOXkAR+jp582
+7ZhDqDyNddF9ZUoBgPghGNIrkHbH7qwex39YnI0ka24lCjcwEMvQMPbyPnX/a4Ry
+J+wEZttmjBl++FfrZK54L+vD7Dyy4YYB0Og9ktB4qptsDBj+giiv/MGPeGeNs3Ta
+cJdNb7+3splTPtPKlDfrufvq4H6jNOv9S9bC+j2VVY9uCFXUro8AA3hoOEKJdSjl
+pYCa51N8KGLVJYRuc/K81xqi054Jz+Cy/HY/AcXkk2JkxlpJoEXmcuTkxjO/QE/X
+bd+mRJHnq6+HurOiKcxKwZCPAa+d+dvRPkbyq9ohMXH9AgMBAAGjgZwwgZkwEgYD
+VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAcYwMwYDVR0fBCwwKjAooCag
+JIYiaHR0cDovL3d3dy5zay5lZS9jcmxzL2p1dXIvY3JsLmNybDAfBgNVHSMEGDAW
+gBQEqnpHo+SJrxrPCkCnGD9v7+l9vjAdBgNVHQ4EFgQUXXUUEYz0pY5Cj3uyQESj
+7tZ6O3IwDQYJKoZIhvcNAQEFBQADggEBADFuAGtSoO8PsWRw/QxFzc5EZtbq2KXC
+9yZ8YQPWBLY4Mh3OVLFJqWyKC+8JHy9D5tJTG49F5UHyDJPufD/XvC2rjRlkqvS/
+W7sy3MqGh7e+6bg+aD4mo+98Oalnqi12UD+ki+N8JKPXjHNJ31AvH6E/xDsCsvtz
+ubylxI+FU8R0XODIUFbBqRtatRI1/zVaKRhD6LNGPt3rz/3IJKmuEv6b29mzL+p4
+oNULqpPr6aTmheZme8ZHuEIh3Zp5kdoX3i2D4hsmgClpevZifo196zeKRLk0Qs6n
+mRjoMxyk6jYIric3/VnV81oyhXSBY1GZnbM4qP1w2S5kSA2bb1pkwFo=
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK OCSP 2006.crt b/etc/certs/KLASS3-SK OCSP 2006.crt
new file mode 100644
index 0000000..02133fc
--- /dev/null
+++ b/etc/certs/KLASS3-SK OCSP 2006.crt
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIDXTCCAkWgAwIBAgIERCKLGDANBgkqhkiG9w0BAQUFADCBjjEYMBYGCSqGSIb3DQEJARYJcGtp
+QHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEh
+MB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3RlZW51c2VkMQowCAYDVQQFEwExMRIwEAYDVQQDEwlL
+TEFTUzMtU0swHhcNMDYwMzIzMTE0ODQwWhcNMDkwMzI3MTE0ODQwWjB9MQswCQYDVQQGEwJFRTEi
+MCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czENMAsGA1UECxMET0NTUDEhMB8GA1UE
+AxMYS0xBU1MzLVNLIE9DU1AgUkVTUE9OREVSMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwgZ8w
+DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKKTI8Aex0Gva9eeeBkM3fGTiNOEvjj2McN3tOJBMAEv
+G/G7Npu0/2fAEKFFUv4NnPyH3MiC7s6R8PtPMhV5GBG6kWVztL/gQnlIjAbo1l654+jApIQjT3vd
+VZDIYyS6lKlYoAdG40CgLlVtRihargQ77azlfORkyRfhKZcSQe8tAgMBAAGjVzBVMBMGA1UdJQQM
+MAoGCCsGAQUFBwMJMB8GA1UdIwQYMBaAFOU/DJ1xPW+8Gb+a9G6/Cf5A652WMB0GA1UdDgQWBBQU
+QsudE6pYaIJSuWurylGItfy52DANBgkqhkiG9w0BAQUFAAOCAQEAV+Vu+qzrHe7HDjMHq9DdOQTz
+833QcMRY0huSgphMOgqNjqjPqTNpHPgNvE6HKGdQ0+VWr8IyRWcxnPMZNihmaCGMpFMpYuH0fx9n
+sjXDbjat8MfGuX2m1EADGOwjtjMuoYTEGEUe3MBeFkmPFDIYpeuS+I4Qv34tOsGvFOpsDkobSATq
+4EFw/5hI9WfWaEMYkmBXdeokoVjbNpt+gtdGKNBU42AlxLrcc+YzAE1hj5qH99/hl0X6r63pTjUb
+1ZMRjGQg7ELwmddms7wB5LKKi5kbfmag5hBtDKGs2s0xW1be4ylNOrT9lqUYuPn9lwcHNg1IS42m
+YVChV97Tlt/5vw==
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK OCSP 2009.crt b/etc/certs/KLASS3-SK OCSP 2009.crt
new file mode 100644
index 0000000..af5f7d1
--- /dev/null
+++ b/etc/certs/KLASS3-SK OCSP 2009.crt
@@ -0,0 +1,20 @@
+-----BEGIN CERTIFICATE-----
+MIIDzzCCAregAwIBAgIEScskSjANBgkqhkiG9w0BAQUFADCBjjEYMBYGCSqGSIb3DQEJARYJcGtp
+QHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEh
+MB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3RlZW51c2VkMQowCAYDVQQFEwExMRIwEAYDVQQDEwlL
+TEFTUzMtU0swHhcNMDkwMzI2MDY0NDI2WhcNMTIwNTA0MDU0NDI2WjCBgjELMAkGA1UEBhMCRUUx
+IjAgBgNVBAoTGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMxDTALBgNVBAsTBE9DU1AxJjAkBgNV
+BAMTHUtMQVNTMy1TSyBPQ1NQIFJFU1BPTkRFUiAyMDA5MRgwFgYJKoZIhvcNAQkBFglwa2lAc2su
+ZWUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKi6weNl7Wj7sL6JD4YUNt/JXQ79KL53x5m4
+QGRsijGJaV5YggE5rJyVZGlsX4FSd9JFIV597ypAUGDbLPf0nDdlSIGteP7zamyETI3GI6bKfkeU
+uIE707r7uC+8FFe9iHOOL20+pi7WFzwnyXT9yuWs0eCoKdjQvLpMiq0MBIm9AgMBAAGjgcIwgb8w
+EwYDVR0lBAwwCgYIKwYBBQUHAwkwaAYDVR0gBGEwXzBdBgorBgEEAc4fBAECME8wJQYIKwYBBQUH
+AgIwGRoXU0sgdGltZSBzdGFtcGluZyBwb2xpY3kwJgYIKwYBBQUHAgEWGmh0dHA6Ly93d3cuc2su
+ZWUvYWphdGVtcGVsMB8GA1UdIwQYMBaAFOU/DJ1xPW+8Gb+a9G6/Cf5A652WMB0GA1UdDgQWBBT5
+9PTkSIzYXNBxQQnAhqH3BtED0TANBgkqhkiG9w0BAQUFAAOCAQEAhyl3H6fo1bz3mD0JcD4eY1sl
+cwec92Qgkn6i9TsO5TlDQCJxiC/80zlh+H5dgIMcNQ6gNbr1cWsUw7xAanv2hGlg20IWq7uCyy5L
+DghFpO2BWDzTJjmiVTXzyVEvqST0W6efDiwi1tA8H7b+aAzc9ItWm7pYlucGvneKJq07t/UvU9ON
+SDUfVLPNMr8slwCMOexVDZ+eiBlvrLL3N7NouPs7UpFh/+m5JsERmeLbbrNYimHUUn2PJ/trJ3kB
+EVFToO+nFdBElfzC3bjSlbPXFxSOL+AqSgvRIaB4CEWUxa33wzoZNaVpCh5AupxQOGdr4u7ajw5h
+kV8Y9VZ7OFej6A==
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK OCSP.crt b/etc/certs/KLASS3-SK OCSP.crt
new file mode 100644
index 0000000..af973e5
--- /dev/null
+++ b/etc/certs/KLASS3-SK OCSP.crt
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIDXTCCAkWgAwIBAgIEPolzuzANBgkqhkiG9w0BAQUFADCBjjEYMBYGCSqGSIb3
+DQEJARYJcGtpQHNrLmVlMQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlm
+aXRzZWVyaW1pc2tlc2t1czEhMB8GA1UECxMYU2VydGlmaXRzZWVyaW1pc3RlZW51
+c2VkMQowCAYDVQQFEwExMRIwEAYDVQQDEwlLTEFTUzMtU0swHhcNMDMwNDAxMTEx
+MDUxWhcNMDYwNDA1MTAxMDUxWjB9MQswCQYDVQQGEwJFRTEiMCAGA1UEChMZQVMg
+U2VydGlmaXRzZWVyaW1pc2tlc2t1czENMAsGA1UECxMET0NTUDEhMB8GA1UEAxMY
+S0xBU1MzLVNLIE9DU1AgUkVTUE9OREVSMRgwFgYJKoZIhvcNAQkBFglwa2lAc2su
+ZWUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALXQF4I5tdllZwNfb3xap93X
+qGmL225JtPgv6SjBOP5pbPs8OwWkpBaqHEJ2WJy7rvEJPTMACNorrH1zBqyIh2t7
+74iSxxGLTTDbQbmdM+hzGnAZMerAfHgQPtxx4ri3iluP/MHwWW5U1WKLyi4b1kSE
+fvqP8hzHRfbtKrkBLQLDAgMBAAGjVzBVMBMGA1UdJQQMMAoGCCsGAQUFBwMJMB8G
+A1UdIwQYMBaAFOU/DJ1xPW+8Gb+a9G6/Cf5A652WMB0GA1UdDgQWBBTOliPaDCUN
+gr1qHIbIprQCQrnKzTANBgkqhkiG9w0BAQUFAAOCAQEAd/8FCyPC9zXxcAZN67KC
+NU4+XNJ8e+LmG602lBe+lS7Pw4pOgMKebgULKh1fEBHQ2K7FSUWMZdPWkDHaKVRh
+646yVbFZbfEmKNq4LhRf13/hoUdrG5uRVmCsV03WSfgfUVfb1cZf8tDMIwCmsNXu
+22k9wykeHallpUmGUfbVZygqfKE2NVQpm2FULiKWBFKXqbMtW5R3xmDS3bjrAIAd
+UdYhxhfdCHCphsQf/FJlxb8UFOUa8SeRNr5eL7s8znLnrC5pKPpWGbUNSlrhLJZH
+IeXfwbOamae6UVvjto6bMqRe2sxCsMA0dGz+tMiglfmTVInxpEKBkyvF/on/2qwt
+Vw==
+-----END CERTIFICATE-----
diff --git a/etc/certs/KLASS3-SK.crt b/etc/certs/KLASS3-SK.crt
new file mode 100644
index 0000000..2edcfa9
--- /dev/null
+++ b/etc/certs/KLASS3-SK.crt
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIIEBDCCAuygAwIBAgIEPNkU9TANBgkqhkiG9w0BAQUFADBdMRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMRAwDgYDVQQDEwdKdXVyLVNLMB4XDTAyMDUwODEyMDcx
+N1oXDTEyMDUwNTExMDcxN1owgY4xGDAWBgkqhkiG9w0BCQEWCXBraUBzay5lZTEL
+MAkGA1UEBhMCRUUxIjAgBgNVBAoTGUFTIFNlcnRpZml0c2VlcmltaXNrZXNrdXMx
+ITAfBgNVBAsTGFNlcnRpZml0c2VlcmltaXN0ZWVudXNlZDEKMAgGA1UEBRMBMTES
+MBAGA1UEAxMJS0xBU1MzLVNLMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
+AQEAvIIeK3GJxoPCXVwan+HjJwYGaH3nb/rTPEqg5v9e1c7dnTDBdD2Yteg+lUdH
+BZDHLj1Tz+J/W9Foc0dzEr96S8+6nMXoonK2x0854JNH2UVbS/+YOGUM6iWSxkHw
+525tvn5tFaIQoaeh46aQFp9Dngcnv4Gatd0/7NCkLggjFrKmnNTPINpLAG9VoCpV
+yIMvcVCyTNvSQ+n33ToPO5vtULNYOtCF9MDVND+uNRE2o0tWIG0l84owYPA47tJO
+LgCpAxLNFR5Ys0nB/ofBYcO+YiCri0yc6t7ZPs/vcfbR6czIwW0GMjyHmVPLB+/W
+HS3P1sk29DdgIC42RTMthJS6ZQIDAQABo4GZMIGWMA8GA1UdEwQIMAYBAf8CAQAw
+DgYDVR0PAQH/BAQDAgHmMDMGA1UdHwQsMCowKKAmoCSGImh0dHA6Ly93d3cuc2su
+ZWUvY3Jscy9qdXVyL2NybC5jcmwwHwYDVR0jBBgwFoAUBKp6R6Pkia8azwpApxg/
+b+/pfb4wHQYDVR0OBBYEFOU/DJ1xPW+8Gb+a9G6/Cf5A652WMA0GCSqGSIb3DQEB
+BQUAA4IBAQASvWB+YrgN23EMLW7C5/XUwQLNN1RMDhr6UzOo5XHZ3pxUXq2Erk5g
+giS+UJIxkQaSg4OHRru8KTchoJDvS2neeYHOz05zJcAIwoy2GGkHq1iVN+QZaprD
+aDNYR5GGKgJb3FZrMtyX4dNwnrZzMFzd6t5YibCW+BDPAmqGJvNHzJ5YYdA7I3WT
+9Baan1ncKd4FtUVb54fppd19NkbCKKSUd7qRYDduNYqVs1C/C0qqLq4TrxoxoxSo
++WNLiD01896sIRiPIy8qDOAXJU67382J5XXETe9wZO6o7+NaG0CrpzVY1OaaD2O6
+Wv/vSpxE2ugqaf0WsP35+coFCWdM2uHZ
+-----END CERTIFICATE-----
diff --git a/etc/certs/README.txt b/etc/certs/README.txt
new file mode 100644
index 0000000..282a06d
--- /dev/null
+++ b/etc/certs/README.txt
@@ -0,0 +1 @@
+Internal component, do not use. Contact for assistance by email abi@id.ee or http://www.id.ee
diff --git a/etc/certs/SK OCSP 2011.crt b/etc/certs/SK OCSP 2011.crt
new file mode 100644
index 0000000..1f5b9e8
--- /dev/null
+++ b/etc/certs/SK OCSP 2011.crt
@@ -0,0 +1,28 @@
+-----BEGIN CERTIFICATE-----
+MIIEvDCCA6SgAwIBAgIQcpyVmdruRVxNgzI3N/NZQTANBgkqhkiG9w0BAQUFADB1
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEoMCYGA1UEAwwfRUUgQ2VydGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYG
+CSqGSIb3DQEJARYJcGtpQHNrLmVlMB4XDTExMDMxODEwMjE0M1oXDTI0MDMxODEw
+MjE0M1owgZ0xCzAJBgNVBAYTAkVFMQ4wDAYDVQQIEwVIYXJqdTEQMA4GA1UEBxMH
+VGFsbGlubjEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czENMAsG
+A1UECxMET0NTUDEfMB0GA1UEAxMWU0sgT0NTUCBSRVNQT05ERVIgMjAxMTEYMBYG
+CSqGSIb3DQEJARYJcGtpQHNrLmVlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+CgKCAQEAihvGyhMVrgReHluKln1za6gvCE/mlSREmWjJFpL9llvuEUZoPFIypYA8
+g5u1VfgkeW5gDq25jAOq4FyXeDGIa+pJn2h0o2Wc2aeppVG/emfGm/jA8jjeyMrw
+H8fAJrqVQ7c9X2xSwJEch/P2d8CfMZt5YF6gqLtPvG1b+n6otBZA5wjIFfJ/inJB
+MUvqHSz3+PLfxO2/T3Wyk/c8M9HIMqTelqyiMGRgWehiU1OsL9armv3dQrHs1wm6
+vHaxfpfWB9YAFpeo9aYqhPCxVt/zo2NQB6vxyZS0hsOrXL7SxRToOJaqsnvlbf0e
+rPPFtRHUvbojYYgl+fzlz0Jt6QJoNwIDAQABo4IBHTCCARkwEwYDVR0lBAwwCgYI
+KwYBBQUHAwkwHQYDVR0OBBYEFKWhSGFt537NmJ50nCm7vYrecgxZMIGCBgNVHSAE
+ezB5MHcGCisGAQQBzh8EAQIwaTA+BggrBgEFBQcCAjAyHjAAUwBLACAAdABpAG0A
+ZQAgAHMAdABhAG0AcABpAG4AZwAgAHAAbwBsAGkAYwB5AC4wJwYIKwYBBQUHAgEW
+G2h0dHBzOi8vd3d3LnNrLmVlL2FqYXRlbXBlbDAfBgNVHSMEGDAWgBQS8lo+6lYc
+v80GrPHxJcmpS9QUmTA9BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vd3d3LnNrLmVl
+L3JlcG9zaXRvcnkvY3Jscy9lZWNjcmNhLmNybDANBgkqhkiG9w0BAQUFAAOCAQEA
+w2sKwvTHtYGtD8Jw9mNUuj/mWiBSBEBeY2LhW8V6tjBPAPp3s6iWOh0FbVR2LUyr
+qRwgT3fyWiGsiDm/6cIqM+IblLp/8ztfRQjquhW6XCD9SK02OQ9ZSdBwcmoAApZL
+GXQC34wdgmV/hLTTNxONnDACBKz9U+Dy9a4ZT4tpNkbH8jq/BMne8FzbvRt1bjpX
+BP7gjLX+zdx8/hp0Wq4tD+f9NVX0+vm9ahEKuzx4QzPnSB7hhWM9OnLZT7noRQa+
+KWk5c+e5VoR5R2t7MjVl8Cd+2llxiSxqMSbU5/23BzAKgN+NQdrBZAzpZ7lfaAuL
+FaICP+bAm6uW2JUrM6abOw==
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST EECCRCA.crt b/etc/certs/TEST EECCRCA.crt
new file mode 100644
index 0000000..a752611
--- /dev/null
+++ b/etc/certs/TEST EECCRCA.crt
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIIEEzCCAvugAwIBAgIQc/jtqiMEFERMtVvsSsH7sjANBgkqhkiG9w0BAQUFADB9
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEwMC4GA1UEAwwnVEVTVCBvZiBFRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290
+IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwIhgPMjAxMDEwMDcxMjM0NTZa
+GA8yMDMwMTIxNzIzNTk1OVowfTELMAkGA1UEBhMCRUUxIjAgBgNVBAoMGUFTIFNl
+cnRpZml0c2VlcmltaXNrZXNrdXMxMDAuBgNVBAMMJ1RFU1Qgb2YgRUUgQ2VydGlm
+aWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVl
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1gGpqCtDmNNEHUjC8LXq
+xRdC1kpjDgkzOTxQynzDxw/xCjy5hhyG3xX4RPrW9Z6k5ZNTNS+xzrZgQ9m5U6uM
+ywYpx3F3DVgbdQLd8DsLmuVOz02k/TwoRt1uP6xtV9qG0HsGvN81q3HvPR/zKtA7
+MmNZuwuDFQwsguKgDR2Jfk44eKmLfyzvh+Xe6Cr5+zRnsVYwMA9bgBaOZMv1TwTT
+VNi9H1ltK32Z+IhUX8W5f2qVP33R1wWCKapK1qTX/baXFsBJj++F8I8R6+gSyC3D
+kV5N/pOlWPzZYx+kHRkRe/oddURA9InJwojbnsH+zJOa2VrNKakNv2HnuYCIonzu
+pwIDAQABo4GKMIGHMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G
+A1UdDgQWBBS1NAqdpS8QxechDr7EsWVHGwN2/jBFBgNVHSUEPjA8BggrBgEFBQcD
+AgYIKwYBBQUHAwEGCCsGAQUFBwMDBggrBgEFBQcDBAYIKwYBBQUHAwgGCCsGAQUF
+BwMJMA0GCSqGSIb3DQEBBQUAA4IBAQAj72VtxIw6p5lqeNmWoQ48j8HnUBM+6mI0
+I+VkQr0EfQhfmQ5KFaZwnIqxWrEPaxRjYwV0xKa1AixVpFOb1j+XuVmgf7khxXTy
+Bmd8JRLwl7teCkD1SDnU/yHmwY7MV9FbFBd+5XK4teHVvEVRsJ1oFwgcxVhyoviR
+SnbIPaOvk+0nxKClrlS6NW5TWZ+yG55z8OCESHaL6JcimkLFjRjSsQDWIEtDvP4S
+tH3vIMUPPiKdiNkGjVLSdChwkW3z+m0EvAjyD9rnGCmjeEm5diLFu7VMNVqupsbZ
+SfDzzBLc5+6TqgQTOG7GaZk2diMkn03iLdHGFrh8ML+mXG9SjEPI
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST EID-SK 2011.crt b/etc/certs/TEST EID-SK 2011.crt
new file mode 100644
index 0000000..54087de
--- /dev/null
+++ b/etc/certs/TEST EID-SK 2011.crt
@@ -0,0 +1,28 @@
+-----BEGIN CERTIFICATE-----
+MIIEuDCCA6CgAwIBAgIQWwOHv2K/GORNdNgZblP5YDANBgkqhkiG9w0BAQUFADB9
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEwMC4GA1UEAwwnVEVTVCBvZiBFRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290
+IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwHhcNMTEwMzA3MTMwNTI5WhcN
+MjMwOTA3MTIwNTI5WjBpMQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlm
+aXRzZWVyaW1pc2tlc2t1czEcMBoGA1UEAwwTVEVTVCBvZiBFSUQtU0sgMjAxMTEY
+MBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
+MIIBCgKCAQEAr5TNCQvKX1IApzLX5KLWSIOhyueYlpc5WKsFLdMWWG40QwJpHm0c
+dudK51IIvdoDX5/uJlyf6/wd4NNSOF5rCogfkzD696NFuiplvXBYKZdshXqsxRhM
+9mcp+9NqND5AGK4BtuUK2S83cxIRUiOxf7O43QxX3py5MDJRNa+kUOHBic8ekvR+
+MsdVpF+3A5V6WE6DNzxecBP6TF1+l/3B7L1Hz8hsaJ6QTsc6/O011WXG9y23dMpb
+ho+JMyy9y3fe791sP87rqWhaFNT5kTnH3JOHK9fxgx0TDP66dde4nvnykRCadEmq
+bOGLEar0xmnirAJgO/yrGrQ/A7gmDdhomwIDAQABo4IBRjCCAUIwDwYDVR0TAQH/
+BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwgZkGA1UdIASBkTCBjjCBiwYKKwYBBAHO
+HwMBATB9MFgGCCsGAQUFBwICMEweSgBBAGkAbgB1AGwAdAAgAHQAZQBzAHQAaQBt
+AGkAcwBlAGsAcwAuACAATwBuAGwAeQAgAGYAbwByACAAdABlAHMAdABpAG4AZwAu
+MCEGCCsGAQUFBwIBFhVodHRwczovL3d3dy5zay5lZS9DUFMwHQYDVR0OBBYEFNQi
+siFrcquz1GPk1pe0bVcUzgEuMB8GA1UdIwQYMBaAFLU0Cp2lLxDF5yEOvsSxZUcb
+A3b+MEMGA1UdHwQ8MDowOKA2oDSGMmh0dHBzOi8vd3d3LnNrLmVlL3JlcG9zaXRv
+cnkvY3Jscy90ZXN0X2VlY2NyY2EuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQA8uY6L
+qaZKfLx6iKpoAEGxbuFwzrT4BVGqEzpZJNVkM2hhoS9qrttzUrC2hLmfWBbbsScV
+GvcWNV7GIcHLYBioZV+ostku/jXXxzhNVhVvX5B8X10uKQDtcrkGbjUpF1JSes8T
+9EsUBSIh5MmpNKc1IP8FfvL3qMU2mxU30KQdQy4IjM4Pv7T+MAWMqjrn6txfOZDu
+5k6Sak/NBn4cozX0HenY/7301snxAT3BaWhwMKqleCyM7w3wfnFGevEs/4C7qn3S
+QncgCEZlvL3lYxSIJ697LyZo0Lsc3s8+gXPT4Q/V8UqjmecgzZWHvyxCrf02iAqU
+YRawXmDuuoGMwwlJ
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST ESTEID-SK 2011.crt b/etc/certs/TEST ESTEID-SK 2011.crt
new file mode 100644
index 0000000..f48bf6d
--- /dev/null
+++ b/etc/certs/TEST ESTEID-SK 2011.crt
@@ -0,0 +1,28 @@
+-----BEGIN CERTIFICATE-----
+MIIEuzCCA6OgAwIBAgIQSxRID7FoIaNNdNhBeucLvDANBgkqhkiG9w0BAQUFADB9
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEwMC4GA1UEAwwnVEVTVCBvZiBFRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290
+IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwHhcNMTEwMzA3MTMwNjA5WhcN
+MjMwOTA3MTIwNjA5WjBsMQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlm
+aXRzZWVyaW1pc2tlc2t1czEfMB0GA1UEAwwWVEVTVCBvZiBFU1RFSUQtU0sgMjAx
+MTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMIIBIjANBgkqhkiG9w0BAQEFAAOC
+AQ8AMIIBCgKCAQEA0SMr+A2QGMJuNpu60MgqKG0yLL7JfvjNtgs2hqWADDn1AQeD
+79o+8r4SRYp9kowSFA8E1v38XXTHRq3nSZeToOC5DMAWjsKlm4x8hwwp31BXCs/H
+rl9VmikIgAlaHvv3Z+MzS6qeLdzyYi/glPVrY42A6/kBApOJlOVLvAFdySNmFkY+
+Ky7MZ9jbBr+Nx4py/V7xm9VD62Oe1lku4S4qd+VYcQ5jftbr4OFjBp9Nn58/5svQ
+xrLjv3B67i19d7sNh7UPnMiO6BeBb6yb3P1lqdHofE1lElStIPViJlzjPOh4puxW
+adHDvVYUCJgW2aM58mTfjFhZbVfcrVn5OyIiTQIDAQABo4IBRjCCAUIwDwYDVR0T
+AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwgZkGA1UdIASBkTCBjjCBiwYKKwYB
+BAHOHwMBATB9MFgGCCsGAQUFBwICMEweSgBBAGkAbgB1AGwAdAAgAHQAZQBzAHQA
+aQBtAGkAcwBlAGsAcwAuACAATwBuAGwAeQAgAGYAbwByACAAdABlAHMAdABpAG4A
+ZwAuMCEGCCsGAQUFBwIBFhVodHRwczovL3d3dy5zay5lZS9DUFMwHQYDVR0OBBYE
+FEG2/sWxsbRTE4z6+mLQNG1tIjQKMB8GA1UdIwQYMBaAFLU0Cp2lLxDF5yEOvsSx
+ZUcbA3b+MEMGA1UdHwQ8MDowOKA2oDSGMmh0dHBzOi8vd3d3LnNrLmVlL3JlcG9z
+aXRvcnkvY3Jscy90ZXN0X2VlY2NyY2EuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQBd
+h5R23K7qkrO78j51xN6CR2qwxUcK/cgcTLWv0obPmJ7jRax3PX0pFhaUE6EhAR0d
+gS4u6XZrjPgVrt/mwq1h8lJP1MF2ueAHKyS0SGj7aFLkcC+ULwu1k6yiortFJ0Ds
+49ZGA+ioGzYWPQ+g1Zl4wSDIz52ot0cHUijnf39Szq7E2z7MDfZkYg8HZeHrO493
+EFghXcnSH7J7z47cgP3GWFNUKv1V2c0eVE4OxRulZ3KmBLPWbJKZ0TyGa/Aooc+T
+orEjxz//WzcF/Sklp4FeD0MU39UURIlg7LfEcm832bPzZzVGFd4drBd5Dy0Uquu6
+3kW7RDqr+wQFSxKr9DIH
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST Juur-SK.crt b/etc/certs/TEST Juur-SK.crt
new file mode 100644
index 0000000..f4433f5
--- /dev/null
+++ b/etc/certs/TEST Juur-SK.crt
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIID5TCCAs2gAwIBAgIEO43dLzANBgkqhkiG9w0BAQUFADBiMRgwFgYJKoZIhvcN
+AQkBFglwa2lAc2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZp
+dHNlZXJpbWlza2Vza3VzMRUwEwYDVQQDEwxURVNUIEp1dXItU0swHhcNMDEwODMw
+MDYyOTA0WhcNMTYwODI3MDUyOTA0WjBiMRgwFgYJKoZIhvcNAQkBFglwa2lAc2su
+ZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vz
+a3VzMRUwEwYDVQQDEwxURVNUIEp1dXItU0swggEiMA0GCSqGSIb3DQEBAQUAA4IB
+DwAwggEKAoIBAQDJIyr2hhDhkZgOJnsFv8VHQJGGK+vld0kGRvpl9Bx81/ZFvEwO
+LDfiReuHlTXCOin2FU3f+UJ2TriA+7K4jMCrkXW4oL9vmy99JmZY3esOSzMoAGvJ
+XTkSN3/U99LajIzZ718e1kslmxgjVrlmlWI2VR/dPNkZN2KVuT4s9zYHzM3frPsa
+DqFd7yMnuqF4YP4yt6DHtqaF+R4vgP/mPRsusoN4NJBiEin6Sm/8me3MS0y8o0qY
+fOw+wYgFM2o/XTsu3B7drY/9AoTCVTSp5Lo6xw33yxgVrtKqOSPeV6YBy8lgs8kl
+75BaEt+zJ06b/aD8JB81Mtn65Tfq1rMK/HrnAgMBAAGjgaIwgZ8wDwYDVR0TAQH/
+BAUwAwEB/zA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vd3d3LnNrLmVlL2NybHMv
+dGVzdC90ZXN0LWp1dXItc2suY3JsMB0GA1UdDgQWBBSBwuAMBRryEG40E0wsjD7c
+iCkyeDAfBgNVHSMEGDAWgBSBwuAMBRryEG40E0wsjD7ciCkyeDAOBgNVHQ8BAf8E
+BAMCAeYwDQYJKoZIhvcNAQEFBQADggEBAAvvh+xwmeD8wk2Fq0SycwqMXcVw8lFf
+osXCIhw/CKpnIzJUrYLyoonNatT7XLt/nmduewUrl3GzKSdTovJA2k1d4srJvU9s
+9AEyMJysgD/hwxBYfAThrxMsYV4NwLdQAv5AAgL3NNH/qpFZacDpGonJXH0jLE/M
+9r/rHI52nlkLQEfnwx5Abjq+xowzf9o1NiFUhYP8u4Fmie5EvnFnEn9S/X1aPNBU
+nH1C2jC3rLqca0qv4fj52w3iYRSwrg30saZA6/VFDXVNV7sCsdWDDQU6AYvonXf0
+mqWg61UrLBc0E0GtCW4vijVXotjpf517Au/9SIhdtDZ3cY+rfsU1sqw=
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST KLASS3 2010.crt b/etc/certs/TEST KLASS3 2010.crt
new file mode 100644
index 0000000..f3a1b6a
--- /dev/null
+++ b/etc/certs/TEST KLASS3 2010.crt
@@ -0,0 +1,28 @@
+-----BEGIN CERTIFICATE-----
+MIIExzCCA6+gAwIBAgIQIrzOHDuBOQRPabRVIaWqEzANBgkqhkiG9w0BAQUFADB9
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEwMC4GA1UEAwwnVEVTVCBvZiBFRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290
+IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwHhcNMTIwMzIxMTA1ODI5WhcN
+MjUwMzIxMTA1ODI5WjB1MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlm
+aXRzZWVyaW1pc2tlc2t1czEhMB8GA1UECwwYU2VydGlmaXRzZWVyaW1pc3RlZW51
+c2VkMR8wHQYDVQQDDBZURVNUIG9mIEtMQVNTMy1TSyAyMDEwMIIBIjANBgkqhkiG
+9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7Ua/6IAAqXvy2COvRLW9yCSeImQ23XRAzf/x
+HmJ6fYiSs0LaR8c19IOSOkOarAgUrt0XDG5KWBdE5qwuVc0gQN9ZjYwmDg3dq4LV
+o89FdvATKk2Tao01Iu1N+2eGSEifgGBH5iWfYqu1hGJ2nJPHIG9bKXZXfw+ET2gy
+mO5bHnt8iOJmq+YynMXEvxtUTl2hKh0o6m28i3YKXru0jm5qe5/YCJ9HFw9yKn8e
+LnI2/9Jfruxe5F1AMOkVXhVtA57yeQARv18a8uEQZV0CS/WDmCPi+hl6GqSwhWZB
+dB9igOMsnZdNS1s7kr2/46doZQVPa2X3vJyYMTl/oaWB++VfAQIDAQABo4IBSTCC
+AUUwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAcYwgZkGA1UdIASB
+kTCBjjCBiwYKKwYBBAHOHwMBATB9MCEGCCsGAQUFBwIBFhVodHRwczovL3d3dy5z
+ay5lZS9jcHMwWAYIKwYBBQUHAgIwTB5KAEEAaQBuAHUAbAB0ACAAdABlAHMAdABp
+AG0AaQBzAGUAawBzAC4AIABPAG4AbAB5ACAAZgBvAHIAIAB0AGUAcwB0AGkAbgBn
+AC4wHQYDVR0OBBYEFNFoQ5JN1Wc5Ii9tzYgGEg662Wp2MB8GA1UdIwQYMBaAFLU0
+Cp2lLxDF5yEOvsSxZUcbA3b+MEMGA1UdHwQ8MDowOKA2oDSGMmh0dHBzOi8vd3d3
+LnNrLmVlL3JlcG9zaXRvcnkvY3Jscy90ZXN0X2VlY2NyY2EuY3JsMA0GCSqGSIb3
+DQEBBQUAA4IBAQCiE8G8gwZpeeHm0PoqHd54/KbfH2cAklqO5rcg2m9fhhvPNtMQ
+9Wc19JWauE2YuNsnJNKetglUAnA/yd64DhQKBf+2JUgYJas4dTscRgXXlz8huuve
+nNUpfPd3iispVc2WNBQ2qjBEZXdqhbkG0/RgM42Hb28+1v23HsoLhCGY2YjHhYyn
+mOk/8BULI/ArsgA7FJflXi5Xp/cdC8BJQ87vtPlAnxm0axZMvASNXMUvvQTUjCTg
+0yczX3d8+I3EBNBlzfPMsyU1LCn6Opbs2/DGF/4enhRGk/49L6ltfOyOA73buSog
+S2JkvCweSx6Y2cs1fXVyFszm2HJmQgwbZYfR
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST SK OCSP 2011.crt b/etc/certs/TEST SK OCSP 2011.crt
new file mode 100644
index 0000000..d9b6863
--- /dev/null
+++ b/etc/certs/TEST SK OCSP 2011.crt
@@ -0,0 +1,27 @@
+-----BEGIN CERTIFICATE-----
+MIIEijCCA3KgAwIBAgIQaI8x6BnacYdNdNwlYnn/mzANBgkqhkiG9w0BAQUFADB9
+MQswCQYDVQQGEwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1
+czEwMC4GA1UEAwwnVEVTVCBvZiBFRSBDZXJ0aWZpY2F0aW9uIENlbnRyZSBSb290
+IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwHhcNMTEwMzA3MTMyMjQ1WhcN
+MjQwOTA3MTIyMjQ1WjCBgzELMAkGA1UEBhMCRUUxIjAgBgNVBAoMGUFTIFNlcnRp
+Zml0c2VlcmltaXNrZXNrdXMxDTALBgNVBAsMBE9DU1AxJzAlBgNVBAMMHlRFU1Qg
+b2YgU0sgT0NTUCBSRVNQT05ERVIgMjAxMTEYMBYGCSqGSIb3DQEJARYJcGtpQHNr
+LmVlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0cw6Cja17BbYbHi6
+frwccDI4BIQLk/fiCE8L45os0xhPgEGR+EHE8LPCIqofPgf4gwN1vDE6cQNUlK0O
+d+Ush39i9Z45esnfpGq+2HsDJaFmFr5+uC1MEz5Kn1TazEvKbRjkGnSQ9BertlGe
+r2BlU/kqOk5qA5RtJfhT0psc1ixKdPipv59wnf+nHx1+T+fPWndXVZLoDg4t3w8l
+IvIE/KhOSMlErvBIHIAKV7yH1hOxyeGLghqzMiAn3UeTEOgoOS9URv0C/T5C3mH+
+Y/uakMSxjNuz41PneimCzbEJZJRiEaMIj8qPAubcbL8GtY03MWmfNtX6/wh6u6TM
+fW8S2wIDAQABo4H+MIH7MBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMJMB0GA1UdDgQW
+BBR9/5CuRokEgGiqSzYuZGYAogl8TzCBoAYDVR0gBIGYMIGVMIGSBgorBgEEAc4f
+AwEBMIGDMFgGCCsGAQUFBwICMEweSgBBAGkAbgB1AGwAdAAgAHQAZQBzAHQAaQBt
+AGkAcwBlAGsAcwAuACAATwBuAGwAeQAgAGYAbwByACAAdABlAHMAdABpAG4AZwAu
+MCcGCCsGAQUFBwIBFhtodHRwOi8vd3d3LnNrLmVlL2FqYXRlbXBlbC8wHwYDVR0j
+BBgwFoAUtTQKnaUvEMXnIQ6+xLFlRxsDdv4wDQYJKoZIhvcNAQEFBQADggEBAAba
+j7kTruTAPHqToye9ZtBdaJ3FZjiKug9/5RjsMwDpOeqFDqCorLd+DBI4tgdu0g4l
+haI3aVnKdRBkGV18kqp84uU97JRFWQEf6H8hpJ9k/LzAACkP3tD+0ym+md532mV+
+nRz1Jj+RPLAUk9xYMV7KPczZN1xnl2wZDJwBbQpcSVH1DjlZv3tFLHBLIYTS6qOK
+4SxStcgRq7KdRczfW6mfXzTCRWM3G9nmDei5Q3+XTED41j8szRWglzYf6zOv4djk
+ja64WYraQ5zb4x8Xh7qTCk6UupZ7je+0oRfuz0h/3zyRdjcRPkjloSpQp/NG8Rmr
+cnr874p8d9fdwCrRI7U=
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST-SK OCSP 2005.crt b/etc/certs/TEST-SK OCSP 2005.crt
new file mode 100644
index 0000000..3c8aac7
--- /dev/null
+++ b/etc/certs/TEST-SK OCSP 2005.crt
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIIDKDCCAhCgAwIBAgIEQi1s4zANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJFRTEiMCAGA1UE
+ChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEaMBgGA1UECxMRVGVzdHNlcnRpZmlrYWFkaWQx
+EDAOBgNVBAMTB1RFU1QtU0swHhcNMDUwMzA4MDkxNDEwWhcNMTIwNDA2MjEwMDAwWjB4MQswCQYD
+VQQGEwJFRTEaMBgGA1UECgwRVGVzdHNlcnRpZmlrYWFkaWQxDTALBgNVBAsMBE9DU1AxJDAiBgNV
+BAMMG1RFU1QtU0sgT0NTUCBSRVNQT05ERVIgMjAwNTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVl
+MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2RdrY11V9ekC7Injanf4RshjWp6jf51tGOvzE
+cbG2Tmyo66H7AR6hauoUygIYrbEjAVXhIznnffngJtrG69I+6cGgCNHguPlpdyAwexUPi36cfJw2
+FKv9bbxyIqtxo+1uZ1XZWgcua6OXMLh0T0aZWglJ1OiAlZys6hxbOg1G8wIDAQABo1cwVTATBgNV
+HSUEDDAKBggrBgEFBQcDCTAfBgNVHSMEGDAWgBQCBSfdqHKHt4LAWzkqf+M48vpSCTAdBgNVHQ4E
+FgQUK9Rcl4ROS8UmFo8JH8ep5oRSJFgwDQYJKoZIhvcNAQEFBQADggEBAHZd/Bqzc7FsC05Hq8Zh
+PxK4lJVMwuC+mO843jsX8cWaGMBOYWqD96gFduMjiIXVIWFpiZ1o6q+JuRbPTRhpzRvv0Yc9oMaq
+j7sBhYr8mqcu0FOOMD8wlJzqFr9TZZ58ba9e/UDZPDUYvEfWEuW6giwSkPLuu0Jbz94QqmG0ErG8
+8h6B14Nge7P1pR4hZfvm4I2PX8sX619OdHRf7kxS+ZXve5BHGHX5YXSPreRAvriJc/cgRFokcPyt
+v7y+tebcqB+1/Dj7o2brNr+dKxIL5IseBeQD4lJ5UtvuPE7pZexUSt2EOcDAAMtHsUB30cIVwPw8
+/CwfT9FBP9H3tUUCtOQ=
+-----END CERTIFICATE-----
diff --git a/etc/certs/TEST-SK.crt b/etc/certs/TEST-SK.crt
new file mode 100644
index 0000000..fbbbaaa
--- /dev/null
+++ b/etc/certs/TEST-SK.crt
@@ -0,0 +1,21 @@
+-----BEGIN CERTIFICATE-----
+MIIECTCCAvGgAwIBAgIEPLKVuDANBgkqhkiG9w0BAQUFADBiMRgwFgYJKoZIhvcNAQkBFglwa2lA
+c2suZWUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKExlBUyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMRUw
+EwYDVQQDEwxURVNUIEp1dXItU0swHhcNMDIwNDA5MDcxODE2WhcNMTYwODI2MDYxODE2WjBfMQsw
+CQYDVQQGEwJFRTEiMCAGA1UEChMZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEaMBgGA1UECxMR
+VGVzdHNlcnRpZmlrYWFkaWQxEDAOBgNVBAMTB1RFU1QtU0swggEiMA0GCSqGSIb3DQEBAQUAA4IB
+DwAwggEKAoIBAQCpEFGWIT863MTfk2NoRURZiP40ASAEcyq5ColRFkK08mdJ7uauO3nr9v8ac11/
+LCJPrFXb75kVt7vXRsR+1wM2jYKIWeuwUB84ByfPOGqJMs2nX+mJt+FbKIpTIS1PKL1RWKw1lOzK
+dt6/aTdvMbNo4IPHMv0Kr/yYaOym5+hfYBgh9tLQ1njgObJTLRuFSc7KE3oHOKsB0DxReLMtDvFy
+MLM2Mbt7Kf8SIxWJYjzVc2TxA2fhlnDlfypZmfJaaXc6vjfCbVbUiEML+AVaVbBFABmIzTfqs5WL
+KV5orvLZcvZr+NxAdTLK+MactUEnYNd6+x+k8TP19dIHytcFiENFAgMBAAGjgckwgcYwDwYDVR0T
+AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAf4wJQYIKwYBBQUHAQEEGTAXMBUGCCsGAQUFBzACgQlw
+a2lAc2suZWUwPAYDVR0fBDUwMzAxoC+gLYYraHR0cDovL3d3dy5zay5lZS9jcmxzL3Rlc3QvdGVz
+dC1qdXVyLXNrLmNybDAfBgNVHSMEGDAWgBSBwuAMBRryEG40E0wsjD7ciCkyeDAdBgNVHQ4EFgQU
+AgUn3ahyh7eCwFs5Kn/jOPL6UgkwDQYJKoZIhvcNAQEFBQADggEBALk6ALjx0wJpvFdtCadHxYx2
+11YcThJqtywxfIl9yXVCDfu8JzrLnVowJJj+gBIkBrz7QyOYpxqnRRxRXSP3SXCdOCnNLRuX9nvT
+yJsMqhSql8Zw1roB8xYb133ztLAqVRoyo4e/c1VUZCVsXmmh5HGUepDU7QKQWQYKbq3tjrKvwXMZ
+QbXbp0L4eiuIbRzN00EOfnrIxBvsHfqZyc2gYqSHfM9YldlboGqNFGO5NQo2wOZ7jByi2aLaRkkN
+1Sx2EJX4Mudpb9RD08txailOBAcjl1j37ey1tU2AnGiyeYYPkXG88K6+L05ggIstR6kBU94wat8L
+qk3z5V5ScVGXOiw=
+-----END CERTIFICATE-----
diff --git a/etc/digidoc.conf.cmake b/etc/digidoc.conf.cmake
new file mode 100644
index 0000000..b2076a9
--- /dev/null
+++ b/etc/digidoc.conf.cmake
@@ -0,0 +1,172 @@
+#--------------------------------------------------
+# @DIGIDOC_CONF_NAME@
+# DigiDoc library global configuration file
+#--------------------------------------------------
+
+[ca]
+CA_CERT_PATH=@CMAKE_INSTALL_FULL_DATADIR@/libdigidoc
+CA_CERTS=17
+
+CA_CERT_1=JUUR-SK.crt
+CA_CERT_1_CN=Juur-SK
+CA_CERT_2=ESTEID-SK.crt
+CA_CERT_2_CN=ESTEID-SK
+CA_CERT_3=ESTEID-SK 2007.crt
+CA_CERT_3_CN=ESTEID-SK 2007
+CA_CERT_4=KLASS3-SK.crt
+CA_CERT_4_CN=KLASS3-SK
+CA_CERT_5=KLASS3-SK 2010.crt
+CA_CERT_5_CN=KLASS3-SK 2010
+CA_CERT_6=KLASS3-SK 2010 EECCRCA.crt
+CA_CERT_6_CN=KLASS3-SK 2010
+CA_CERT_7=EID-SK.crt
+CA_CERT_7_CN=EID-SK
+CA_CERT_8=EID-SK 2007.crt
+CA_CERT_8_CN=EID-SK 2007
+
+CA_CERT_9=EECCRCA.crt
+CA_CERT_9_CN=EE Certification Centre Root CA
+CA_CERT_10=ESTEID-SK 2011.crt
+CA_CERT_10_CN=ESTEID-SK 2011
+CA_CERT_11=EID-SK 2011.crt
+CA_CERT_11_CN=EID-SK 2011
+
+CA_CERT_12=TEST Juur-SK.crt
+CA_CERT_12_CN=TEST Juur-SK
+CA_CERT_13=TEST-SK.crt
+CA_CERT_13_CN=TEST-SK
+
+CA_CERT_14=TEST EECCRCA.crt
+CA_CERT_14_CN=TEST of EE Certification Centre Root CA
+CA_CERT_15=TEST ESTEID-SK 2011.crt
+CA_CERT_15_CN=TEST of ESTEID-SK 2011
+CA_CERT_16=TEST EID-SK 2011.crt
+CA_CERT_16_CN=TEST of EID-SK 2011
+CA_CERT_17=TEST KLASS3 2010.crt
+CA_CERT_17_CN=TEST of KLASS3-SK 2010
+
+
+
+
+DIGIDOC_DEFAULT_DRIVER=1
+DIGIDOC_DRIVERS=1
+DIGIDOC_DRIVER_1_NAME=OpenSC
+DIGIDOC_DRIVER_1_DESC=OpenSC projects PKCS#11 driver
+DIGIDOC_DRIVER_1_FILE=@PKCS11_MODULE@
+DIGIDOC_SIGNATURE_SLOT=1
+CHECK_OCSP_NONCE=0
+
+SIGN_OCSP=0
+USE_PROXY=0
+DIGIDOC_OCSP_URL=http://ocsp.sk.ee
+
+DIGIDOC_OCSP_RESPONDER_CERTS=24
+
+DIGIDOC_OCSP_RESPONDER_CERT_1=TEST-SK OCSP 2005.crt
+DIGIDOC_OCSP_RESPONDER_CERT_1_CN=TEST-SK OCSP RESPONDER 2005
+DIGIDOC_OCSP_RESPONDER_CERT_1_CA=TEST-SK
+DIGIDOC_OCSP_RESPONDER_CERT_1_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_2=KLASS3-SK OCSP 2009.crt
+DIGIDOC_OCSP_RESPONDER_CERT_2_CN=KLASS3-SK OCSP RESPONDER 2009
+DIGIDOC_OCSP_RESPONDER_CERT_2_CA=KLASS3-SK
+
+DIGIDOC_OCSP_RESPONDER_CERT_3=ESTEID-SK OCSP 2005.crt
+DIGIDOC_OCSP_RESPONDER_CERT_3_CN=ESTEID-SK OCSP RESPONDER 2005
+DIGIDOC_OCSP_RESPONDER_CERT_3_CA=ESTEID-SK
+
+DIGIDOC_OCSP_RESPONDER_CERT_4=ESTEID-SK 2007 OCSP.crt
+DIGIDOC_OCSP_RESPONDER_CERT_4_CN=ESTEID-SK 2007 OCSP RESPONDER
+DIGIDOC_OCSP_RESPONDER_CERT_4_CA=ESTEID-SK 2007
+
+DIGIDOC_OCSP_RESPONDER_CERT_5=EID-SK 2007 OCSP.crt
+DIGIDOC_OCSP_RESPONDER_CERT_5_CN=EID-SK 2007 OCSP RESPONDER
+DIGIDOC_OCSP_RESPONDER_CERT_5_CA=EID-SK 2007
+
+DIGIDOC_OCSP_RESPONDER_CERT_6=EID-SK OCSP 2006.crt
+DIGIDOC_OCSP_RESPONDER_CERT_6_1=EID-SK OCSP.crt
+DIGIDOC_OCSP_RESPONDER_CERT_6_CN=EID-SK OCSP RESPONDER
+DIGIDOC_OCSP_RESPONDER_CERT_6_CA=EID-SK
+
+DIGIDOC_OCSP_RESPONDER_CERT_7=ESTEID-SK OCSP.crt
+DIGIDOC_OCSP_RESPONDER_CERT_7_CN=ESTEID-SK OCSP RESPONDER
+DIGIDOC_OCSP_RESPONDER_CERT_7_CA=ESTEID-SK
+
+DIGIDOC_OCSP_RESPONDER_CERT_8=KLASS3-SK OCSP 2006.crt
+DIGIDOC_OCSP_RESPONDER_CERT_8_1=KLASS3-SK OCSP.crt
+DIGIDOC_OCSP_RESPONDER_CERT_8_CN=KLASS3-SK OCSP RESPONDER
+DIGIDOC_OCSP_RESPONDER_CERT_8_CA=KLASS3-SK
+
+DIGIDOC_OCSP_RESPONDER_CERT_9=EID-SK 2007 OCSP 2010.crt
+DIGIDOC_OCSP_RESPONDER_CERT_9_CN=EID-SK 2007 OCSP RESPONDER 2010
+DIGIDOC_OCSP_RESPONDER_CERT_9_CA=EID-SK 2007
+
+DIGIDOC_OCSP_RESPONDER_CERT_10=ESTEID-SK 2007 OCSP 2010.crt
+DIGIDOC_OCSP_RESPONDER_CERT_10_CN=ESTEID-SK 2007 OCSP RESPONDER 2010
+DIGIDOC_OCSP_RESPONDER_CERT_10_CA=ESTEID-SK 2007
+
+DIGIDOC_OCSP_RESPONDER_CERT_11=KLASS3-SK 2010 OCSP.crt
+DIGIDOC_OCSP_RESPONDER_CERT_11_CN=KLASS3-SK 2010 OCSP RESPONDER
+DIGIDOC_OCSP_RESPONDER_CERT_11_CA=KLASS3-SK 2010
+
+DIGIDOC_OCSP_RESPONDER_CERT_12=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_12_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_12_CA=EE Certification Centre Root CA
+
+DIGIDOC_OCSP_RESPONDER_CERT_13=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_13_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_13_CA=ESTEID-SK 2011
+
+DIGIDOC_OCSP_RESPONDER_CERT_14=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_14_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_14_CA=EID-SK 2011
+
+DIGIDOC_OCSP_RESPONDER_CERT_15=TEST SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_15_CN=TEST of SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_15_CA=TEST of EE Certification Centre Root CA
+DIGIDOC_OCSP_RESPONDER_CERT_15_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_16=TEST SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_16_CN=TEST of SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_16_CA=TEST of ESTEID-SK 2011
+DIGIDOC_OCSP_RESPONDER_CERT_16_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_17=TEST SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_17_CN=TEST of SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_17_CA=TEST of EID-SK 2011
+DIGIDOC_OCSP_RESPONDER_CERT_17_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_18=TEST SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_18_CN=TEST of SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_18_CA=TEST of KLASS3-SK 2010
+DIGIDOC_OCSP_RESPONDER_CERT_18_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_19=TEST SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_19_CN=TEST of SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_19_CA=VRK CA for Test Purposes
+DIGIDOC_OCSP_RESPONDER_CERT_19_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_20=TEST SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_20_CN=TEST of SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_20_CA=VRK TEST Root CA
+DIGIDOC_OCSP_RESPONDER_CERT_20_URL=http://www.openxades.org/cgi-bin/ocsp.cgi
+
+DIGIDOC_OCSP_RESPONDER_CERT_21=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_21_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_21_CA=VRK Gov. Root CA
+DIGIDOC_OCSP_RESPONDER_CERT_21_URL=http://ocsp.sk.ee/_proxy
+
+DIGIDOC_OCSP_RESPONDER_CERT_22=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_22_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_22_CA=VRK Gov. CA for Citizen Qualified Certificates
+DIGIDOC_OCSP_RESPONDER_CERT_22_URL=http://ocsp.sk.ee/_proxy
+
+DIGIDOC_OCSP_RESPONDER_CERT_23=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_23_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_23_CA=VRK CA for Healthcare Professionals Qualified Certificates
+DIGIDOC_OCSP_RESPONDER_CERT_23_URL=http://ocsp.sk.ee/_proxy
+
+DIGIDOC_OCSP_RESPONDER_CERT_24=SK OCSP 2011.crt
+DIGIDOC_OCSP_RESPONDER_CERT_24_CN=SK OCSP RESPONDER 2011
+DIGIDOC_OCSP_RESPONDER_CERT_24_CA=VRK CA for Qualified Certificates
+DIGIDOC_OCSP_RESPONDER_CERT_24_URL=http://ocsp.sk.ee/_proxy
diff --git a/libdigidoc.spec b/libdigidoc.spec
new file mode 100644
index 0000000..6bc0874
--- /dev/null
+++ b/libdigidoc.spec
@@ -0,0 +1,69 @@
+Name: libdigidoc
+Version: 3.3
+Release: 1%{?dist}
+Summary: DigiDoc library
+Group: System Environment/Libraries
+License: LGPLv2+
+URL: http://www.ria.ee
+Source0: libdigidoc.tar.gz
+BuildRoot: %{_tmppath}/-%{version}-%{release}-root-%(%{__id_u} -n)
+BuildRequires: cmake, gcc, libxml2-devel, openssl-devel
+Requires: opensc, esteidcerts
+%if %{defined suse_version}
+Requires: libpcsclite1
+%endif
+%description
+Library for creating DigiDoc signature files
+
+%if %{defined suse_version}
+%debug_package
+%endif
+
+%package devel
+Summary: DigiDoc library devel files
+Group: System Environment/Libraries
+Requires: %{name}%{?_isa} = %{version}-%{release}, libxml2-devel, esteidcerts-devel
+%description devel
+Devel files for DigiDoc library
+
+
+%prep
+%setup -q -n %{name}
+cmake . \
+ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
+ -DCMAKE_INSTALL_PREFIX=/usr \
+ -DCMAKE_INSTALL_SYSCONFDIR=/etc \
+ -DCMAKE_VERBOSE_MAKEFILE=ON
+
+%build
+make
+
+%install
+rm -rf %{buildroot}
+cd %{_builddir}/%{name}
+make install DESTDIR=%{buildroot}
+
+%clean
+rm -rf %{buildroot}
+cd %{_builddir}/%{name}
+make clean
+
+%files
+%defattr(-,root,root,-)
+%{_bindir}/*
+%{_libdir}/*.so.*
+%{_mandir}
+%config(noreplace) %{_sysconfdir}/*
+
+%files devel
+%defattr(-,root,root,-)
+%{_includedir}/*
+%{_libdir}/*.so
+%{_libdir}/pkgconfig/*
+
+%changelog
+* Fri Aug 13 2010 RIA <info@ria.ee> 1.0-1
+- first build no changes
+
+%post -p /sbin/ldconfig
+%postun -p /sbin/ldconfig
diff --git a/libdigidoc.wxs b/libdigidoc.wxs
new file mode 100644
index 0000000..9c35308
--- /dev/null
+++ b/libdigidoc.wxs
@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<?ifdef env.VS120COMNTOOLS ?>
+<?define MergeModules="C:\Program Files (x86)\Common Files\Merge Modules\Microsoft_VC120" ?>
+<?else?>
+<?define MergeModules="C:\Program Files (x86)\Common Files\Merge Modules\Microsoft_VC110" ?>
+<?endif?>
+
+<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
+ <Product Name="Estonian ID Card C-library for developers" Id="*" UpgradeCode="{3EA5EA77-4660-4306-A8A2-7A56423E4EA6}"
+ Language="1033" Version="$(var.MSI_VERSION)" Codepage="1251" Manufacturer="RIA">
+ <Package Keywords="Installer" InstallerVersion="405" Compressed="yes"/>
+ <MediaTemplate EmbedCab="yes" CompressionLevel="high"/>
+
+ <Icon Id="IDIcon" SourceFile="ID.ico"/>
+ <Property Id="ARPPRODUCTICON" Value="Company.ico"/>
+ <Property Id="REINSTALLMODE" Value="amus"/>
+
+ <MajorUpgrade AllowSameVersionUpgrades="yes" DowngradeErrorMessage=
+ "A newer version of [ProductName] is already installed. If you are trying to downgrade, please uninstall the newer version first."/>
+
+ <Directory Id="TARGETDIR" Name="SourceDir">
+ <Merge Id='CRT' Language='0' SourceFile='$(var.MergeModules)_CRT_x86.msm' DiskId='1'/>
+ <Directory Id='ProgramFilesFolder'>
+ <Directory Id="DEVPACKAGESFOLDER" Name="Estonian ID Card Development">
+ <Directory Id="APPLICATIONFOLDER" Name="libdigidoc">
+ <Component Id="libdigidoc" Guid="fbc4572c-6256-4df7-a42d-b9c996e69092">
+ <File Source="C:/OpenSSL-Win32/bin/libeay32.dll"/>
+ <File Source="C:/OpenSSL-Win32/bin/ssleay32.dll"/>
+ <File Source="$(var.PREFIX)/zlib/x86/bin/zlib1.dll"/>
+ <File Source="$(var.PREFIX)/libxml2/x86/bin/libxml2.dll"/>
+ <File Source="$(var.libdigidoc)/x86/bin/digidoc.dll"/>
+ <File Source="$(var.libdigidoc)/x86/bin/digidoc.lib"/>
+ <File Source="$(var.libdigidoc)/x86/bin/cdigidoc.exe"/>
+ <File Source="$(var.libdigidoc)/x86/etc/digidoc.ini"/>
+ <IniFile Id="setCaCertPathX86" Action="addLine" Directory="APPLICATIONFOLDER" Section="ca"
+ Name="digidoc.ini" Key="CA_CERT_PATH" Value="[APPLICATIONFOLDER]certs"/>
+ <File Source="$(var.libdigidoc)/x86/bin/cdigidoc.pdb"/>
+ <File Source="$(var.libdigidoc)/x86/bin/digidoc.pdb"/>
+ </Component>
+ <Directory Id="CertificatesFolder" Name="certs"/>
+ <Directory Id="DocumentationFolder" Name="documentation"/>
+ <Directory Id="SourceFolder" Name="source"/>
+ <Directory Id="HeadersFolder" Name="."/>
+ </Directory>
+ </Directory>
+ </Directory>
+ </Directory>
+
+ <Property Id="WIXUI_INSTALLDIR" Value="APPLICATIONFOLDER" />
+ <UI Id="WixUI_InstallDir">
+ <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" />
+ <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" />
+ <TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" />
+
+ <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />
+ <Property Id="WixUI_Mode" Value="InstallDir" />
+
+ <DialogRef Id="BrowseDlg" />
+ <DialogRef Id="DiskCostDlg" />
+ <DialogRef Id="ErrorDlg" />
+ <DialogRef Id="FatalError" />
+ <DialogRef Id="FilesInUse" />
+ <DialogRef Id="MsiRMFilesInUse" />
+ <DialogRef Id="PrepareDlg" />
+ <DialogRef Id="ProgressDlg" />
+ <DialogRef Id="ResumeDlg" />
+ <DialogRef Id="UserExit" />
+
+ <Publish Dialog="BrowseDlg" Control="OK" Event="DoAction" Value="WixUIValidatePath" Order="3">1</Publish>
+ <Publish Dialog="BrowseDlg" Control="OK" Event="SpawnDialog" Value="InvalidDirDlg" Order="4"><![CDATA[WIXUI_INSTALLDIR_VALID<>"1"]]></Publish>
+
+ <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish>
+
+ <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="InstallDirDlg">NOT Installed</Publish>
+ <Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">Installed AND PATCH</Publish>
+
+ <Publish Dialog="InstallDirDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg">1</Publish>
+ <Publish Dialog="InstallDirDlg" Control="Next" Event="SetTargetPath" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish>
+ <Publish Dialog="InstallDirDlg" Control="Next" Event="DoAction" Value="WixUIValidatePath" Order="2">NOT WIXUI_DONTVALIDATEPATH</Publish>
+ <Publish Dialog="InstallDirDlg" Control="Next" Event="SpawnDialog" Value="InvalidDirDlg" Order="3"><![CDATA[NOT WIXUI_DONTVALIDATEPATH AND WIXUI_INSTALLDIR_VALID<>"1"]]></Publish>
+ <Publish Dialog="InstallDirDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg" Order="4">WIXUI_DONTVALIDATEPATH OR WIXUI_INSTALLDIR_VALID="1"</Publish>
+ <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Property="_BrowseProperty" Value="[WIXUI_INSTALLDIR]" Order="1">1</Publish>
+ <Publish Dialog="InstallDirDlg" Control="ChangeFolder" Event="SpawnDialog" Value="BrowseDlg" Order="2">1</Publish>
+
+ <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="InstallDirDlg" Order="1">NOT Installed</Publish>
+ <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="2">Installed AND NOT PATCH</Publish>
+ <Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="2">Installed AND PATCH</Publish>
+
+ <Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg">1</Publish>
+
+ <Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
+ <Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
+ <Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg">1</Publish>
+
+ <Property Id="ARPNOMODIFY" Value="1" />
+ </UI>
+
+ <UIRef Id="WixUI_Common" />
+
+ <Feature Id="InstallLibdigidoc" Level="1" Title="C-teek">
+ <MergeRef Id="CRT"/>
+ <ComponentRef Id="libdigidoc"/>
+ <ComponentGroupRef Id="Certs"/>
+ <ComponentGroupRef Id="Source"/>
+ <ComponentGroupRef Id="Headers"/>
+ <ComponentGroupRef Id="Documentation"/>
+ </Feature>
+
+ </Product>
+</Wix>
diff --git a/libdigidoc/CMakeLists.txt b/libdigidoc/CMakeLists.txt
new file mode 100644
index 0000000..eceebfe
--- /dev/null
+++ b/libdigidoc/CMakeLists.txt
@@ -0,0 +1,153 @@
+configure_file(
+ ${CMAKE_SOURCE_DIR}/etc/digidoc.conf.cmake
+ ${CMAKE_CURRENT_BINARY_DIR}/${DIGIDOC_CONF_NAME}
+ @ONLY
+)
+FILE( GLOB CERTS ${CMAKE_SOURCE_DIR}/etc/certs/*.crt )
+
+set( PUBLIC_HEADER
+ DigiDocCert.h
+ DigiDocConfig.h
+ DigiDocConvert.h
+ DigiDocDebug.h
+ DigiDocDefs.h
+ DigiDocDfExtract.h
+ DigiDocEncGen.h
+ DigiDocEnc.h
+ DigiDocEncSAXParser.h
+ DigiDocError.h
+ DigiDocGen.h
+ DigiDocLib.h
+ DigiDocMem.h
+ DigiDocObj.h
+ DigiDocOCSP.h
+ DigiDocParser.h
+# DigiDocPKCS11.h
+ DigiDocSAXParser.h
+ DigiDocStack.h
+ DigiDocVerify.h
+ DigiDocHTTP.h
+ DigiDocService.h
+)
+
+if( WIN32 )
+ add_definitions( -DWITH_SOAPDEFS_H )
+ list( APPEND libdigidoc_SRCS DigiDocGlobals.c DigiDocCSP.c DigiCrypt.c DlgUnit.c DlgUnitS.c )
+ set( EXT_LIBRARIES Crypt32 Comctl32 )
+endif()
+
+if( MSVC )
+ add_definitions(
+ -D_CRT_NONSTDC_NO_DEPRECATE
+ -D_CRT_SECURE_NO_DEPRECATE
+ -D_CRT_SECURE_NO_WARNINGS
+ -D_SCL_SECURE_NO_WARNINGS
+ )
+endif()
+
+add_library( digidoc SHARED
+ ${PUBLIC_HEADER}
+ ${CMAKE_CURRENT_BINARY_DIR}/${DIGIDOC_CONF_NAME}
+ ${libdigidoc_SRCS}
+ ${CERTS}
+ libdigidoc.rc
+ DigiDocConfig.c
+ DigiDocLib.c
+ DigiDocObj.c
+ DigiDocPKCS11.c
+ DigiDocError.c
+ DigiDocParser.c
+ DigiDocDebug.c
+ DigiDocSAXParser.c
+ DigiDocMem.c
+ DigiDocStack.c
+ DigiDocEnc.c
+ DigiDocEncGen.c
+ DigiDocEncSAXParser.c
+ DigiDocCert.c
+ DigiDocConvert.c
+ DigiDocGen.c
+ DigiDocVerify.c
+ DigiDocOCSP.c
+ DigiDocDfExtract.c
+ DigiDocHTTP.c
+ DigiDocService.c
+)
+
+target_link_libraries( digidoc
+ ${CMAKE_DL_LIBS}
+ ${LIBXML2_LIBRARIES}
+ ${OPENSSL_LIBRARIES}
+ ${ZLIB_LIBRARIES}
+ ${EXT_LIBRARIES}
+)
+
+set_target_properties( digidoc PROPERTIES
+ VERSION ${MAJOR_VER}.${MINOR_VER}.${RELEASE_VER}
+ SOVERSION 2
+ PUBLIC_HEADER "${PUBLIC_HEADER}"
+ RESOURCE ${CMAKE_CURRENT_BINARY_DIR}/${DIGIDOC_CONF_NAME}
+ FRAMEWORK_VERSION 2
+ FRAMEWORK "${FRAMEWORK}"
+ MACOSX_FRAMEWORK_IDENTIFIER "ee.ria.libdigidoc"
+ MACOSX_RPATH YES
+)
+
+add_executable(cdigidoc cdigidoc.c cdigidoc.rc)
+target_link_libraries(cdigidoc digidoc)
+
+install( TARGETS digidoc
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ RESOURCE DESTINATION ${CMAKE_INSTALL_SYSCONFDIR}
+ PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libdigidoc
+ FRAMEWORK DESTINATION /Library/Frameworks
+)
+
+if(WIN32)
+ install( DIRECTORY ${PROJECT_BINARY_DIR}/libdigidoc/ DESTINATION ${CMAKE_INSTALL_LIBDIR} FILES_MATCHING PATTERN "*.pdb" )
+endif()
+
+if( FRAMEWORK )
+ set_target_properties( digidoc PROPERTIES
+ OUTPUT_NAME "libdigidoc"
+ COMPILE_DEFINITIONS "FRAMEWORK"
+ LINK_FLAGS "-framework CoreFoundation -framework Security"
+ RESOURCE "${CERTS};${CMAKE_CURRENT_BINARY_DIR}/${DIGIDOC_CONF_NAME}"
+ )
+ add_custom_command( TARGET cdigidoc POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:cdigidoc> $<TARGET_FILE_DIR:digidoc>/Resources )
+ add_custom_target( codesign DEPENDS cdigidoc
+ COMMAND codesign -f -s \"$$SIGNCERT\" $<TARGET_FILE_DIR:digidoc>/Resources/cdigidoc
+ COMMAND codesign -f -s \"$$SIGNCERT\" $<TARGET_FILE_DIR:digidoc>/../..
+ COMMAND touch $<TARGET_FILE:cdigidoc>
+ )
+ add_custom_target( pkgbuild DEPENDS codesign
+ COMMAND make install DESTDIR=install \; pkgbuild
+ --root install
+ --sign \"$$INSTCERT\"
+ ${CMAKE_BINARY_DIR}/libdigidoc_${VERSION}$ENV{VER_SUFFIX}.pkg
+ )
+ add_custom_target( zipdebug DEPENDS cdigidoc
+ COMMAND dsymutil -o libdigidoc.dSYM $<TARGET_FILE:digidoc>
+ COMMAND dsymutil -o libdigidoc.dSYM $<TARGET_FILE:cdigidoc>
+ COMMAND zip -r ${CMAKE_BINARY_DIR}/libdigidoc-dbg_${VERSION}$ENV{VER_SUFFIX}.zip libdigidoc.dSYM
+ )
+else()
+ install( TARGETS cdigidoc DESTINATION ${CMAKE_INSTALL_BINDIR} )
+ configure_file( libdigidoc.pc.cmake libdigidoc.pc @ONLY )
+ configure_file( cdigidoc.1.cmake cdigidoc.1 )
+ install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libdigidoc.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig )
+ install( FILES ${CMAKE_CURRENT_BINARY_DIR}/cdigidoc.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1 )
+ install( FILES ${CERTS} DESTINATION ${CMAKE_INSTALL_FULL_DATADIR}/libdigidoc )
+endif()
+
+#install( FILES
+# pkcs11/pkcs11.h
+# pkcs11/pkcs11f.h
+# pkcs11/pkcs11t.h
+# pkcs11/unix.h
+# pkcs11/cryptoki.h
+# DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/libdigidoc/pkcs11
+#)
diff --git a/libdigidoc/DigiCrypt.c b/libdigidoc/DigiCrypt.c
new file mode 100644
index 0000000..0930a31
--- /dev/null
+++ b/libdigidoc/DigiCrypt.c
@@ -0,0 +1,1006 @@
+//==========< HISTORY >=============================
+// 29.10.2003 Changes by AA
+// ReadCertFromCard adapted
+// from Tarmo's example
+// 09.10.2003 Changes by AA
+// 02.09.2003 Changes from Tarmo Milva
+//Changed functions:
+//DigiCrypt_GetDataFromCert
+//DigiCrypt_GetFirstAllowedCSPName
+//DigiCrypt_GetDefaultKeyContainerName
+//DigiCrypt_SelectFromAllKeysCerts
+//
+#include "DigiCrypt.h"
+#include "DigiDocDefs.h"
+#include "DigiDocConfig.h"
+#include <stdio.h>
+#include <tchar.h>
+
+#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
+
+#define dSTRING_ITEM_LEN 255
+#define dNAME_ITEM_LEN 1024
+#define dCSPTYPE_NOTDEFINED -1
+
+static char *psData_CSP_Path = "SOFTWARE\\Microsoft\\Cryptography\\Defaults\\Provider\\";
+static char *psData_Extra_CSP_Name = "Advanced Setec SetCSP";
+static char *psData_Ignore_CSP_Name ="XXXEstEID";
+static char *psData_Est_CSP_Name = "EstEID";
+
+//Global data
+static HCRYPTPROV oG_hProvider = 0;
+static char oG_sCSPName[dSTRING_ITEM_LEN+1];
+static char oG_sKeyContainerName[dNAME_ITEM_LEN+1];
+static BOOL oG_fDialogUserCancel;
+
+extern int RunDialogUnit(char *psList[], int iWinWidth, int iWinHeight);
+ PCCERT_CONTEXT DigiCrypt_ReadCertFromCard(void);
+static BOOL DigiCrypt_AddCertToStore(PCCERT_CONTEXT pCert);
+
+static BOOL OpenProvider(HCRYPTPROV *phProv, char *psProvider, DWORD dwFlags);
+static HCERTSTORE DigiCrypt_OpenStore(void);
+static char *DigiCrypt_GetFirstAllowedCSPNameNew(void);
+static char *DigiCrypt_GetFirstAllowedCSPName(void);
+static void DigiCrypt_ReleaseFirstAllowedCSP(void);
+static BOOL DigiCrypt_GetCSPFromCert(PCCERT_CONTEXT pCertContext, char *psResult, int iMaxResLen);
+static BOOL DigiCrypt_GetContainerFromCert(PCCERT_CONTEXT pCertContext, char *psResult, int iMaxResLen);
+static BOOL DigiCrypt_CertIsSig(PCCERT_CONTEXT pCertContext);
+
+static char *DigiCrypt_GetDefaultKeyContainerName(char *psCSPName);
+static char *DigiCrypt_GetDefaultKeyContainerNameSimple(char *psCSPName);
+static char *DigiCrypt_GetDefaultCSPName(void);
+static BOOL DigiCrypt_GetDataFromCert(PCCERT_CONTEXT pCertContext);
+static PCCERT_CONTEXT DigiCrypt_SelectFromAllCerts(void);
+static PCCERT_CONTEXT DigiCrypt_SelectFromAllKeysCerts(HCRYPTPROV hProvider);
+static void DigiCrypt_SelectCertsFromKeyContainer(HCRYPTPROV hProv, char *psContainerName);
+static void DigiCrypt_ChangeContainerName(char *psContainerName);
+
+static void RunDlg_Clear(void);
+static BOOL RunDlg_AddItem(PCCERT_CONTEXT pCertContext, BOOL fTimeCheck);
+static PCCERT_CONTEXT RunDlg_RunDlg(void);
+static BOOL RunDlg_FillItem(PCCERT_CONTEXT pCertContext, char *psRes, int len);
+
+static void IntLogToFile(char *psMsg, int iMsgLen);
+static BOOL IsLogEnabled(void);
+
+PCCERT_CONTEXT DigiCrypt_FindContext(BOOL fByKeyContainer, DWORD *dwResult)
+{
+ PCCERT_CONTEXT hCert = NULL;
+ char *psCSPName;
+ char *psDefaultKeyContainerName;
+ oG_fDialogUserCancel = FALSE;
+
+ *dwResult = dDigiCrypt_Okey;
+ memset(oG_sCSPName, 0, sizeof(oG_sCSPName));
+ memset(oG_sKeyContainerName, 0, sizeof(oG_sKeyContainerName));
+
+ if (fByKeyContainer == TRUE) {
+ hCert = DigiCrypt_ReadCertFromCard();
+ //TEST
+ //Test_ReadCertDataC(hCert);
+ //ENDTEST
+ if (hCert == NULL) {
+ psCSPName = DigiCrypt_GetFirstAllowedCSPNameNew();
+ if (psCSPName == NULL)
+ *dwResult = dDigiCrypt_Error_NotFoundCSP;
+ else {
+ psDefaultKeyContainerName = DigiCrypt_GetDefaultKeyContainerName(oG_sCSPName);
+ if (psDefaultKeyContainerName == NULL)
+ *dwResult = dDigiCrypt_Error_NoDefaultKey;
+ else
+ hCert = DigiCrypt_SelectFromAllKeysCerts(oG_hProvider);
+ }
+ }
+ } else {
+ hCert = DigiCrypt_SelectFromAllCerts();
+ if (hCert != NULL)
+ DigiCrypt_GetDataFromCert(hCert);
+ }
+ if (hCert == NULL) {
+ if (oG_fDialogUserCancel == TRUE)
+ *dwResult = dDigiCrypt_Error_UserCancel;
+ else {
+ if (*dwResult == dDigiCrypt_Okey)
+ *dwResult = dDIgiCrypt_Error_NotFoundCert;
+ }
+ }
+ return(hCert);
+}
+
+PCCERT_CONTEXT DigiCrypt_ReadCertFromCard(void)
+{
+HCRYPTPROV hCryptProv;
+BYTE *pbData = NULL;
+HCRYPTKEY hKey;
+DWORD cbData = 0;
+DWORD dwKeyType=0, dwKeySpec = AT_SIGNATURE;
+DWORD dwErrCode=0;
+DWORD cspType=0;
+DWORD cspFlag=CRYPT_SILENT;
+char *psCspName = NULL;
+char *psKeyContainer;
+BOOL fRes = FALSE;
+PCCERT_CONTEXT pCertContext = NULL;
+CRYPT_KEY_PROV_INFO KeyProvInfo;
+LPWSTR wszContainerName=NULL;
+LPWSTR wszProvName=NULL;
+DWORD cchContainerName;
+DWORD cchCSPName;
+HCRYPTPROV hProv;
+
+
+DigiCrypt_ReleaseFirstAllowedCSP();
+
+psCspName=DigiCrypt_GetFirstAllowedCSPNameNew();
+
+//very dummy thing.. i check from csp creators why i should do so...
+if(!lstrcmp(psCspName,"EstEID Card CSP"))
+ fRes = CryptAcquireContext(&hProv,"XXX",psCspName,2, CRYPT_SILENT);
+// end dummy//
+
+if (psCspName == NULL || strstr(psCspName,psData_Est_CSP_Name) == NULL)
+ return(pCertContext);
+
+cspType=DigiCrypt_FindContext_GetCSPType(psCspName);
+
+psKeyContainer=DigiCrypt_GetDefaultKeyContainerName(psCspName);
+
+fRes = CryptAcquireContext(&hCryptProv,psKeyContainer,psCspName,cspType, CRYPT_SILENT);
+if (fRes == FALSE)
+ return(pCertContext);
+
+// VS: use alsu auth keys if KEY_USAGE_CHECK=false
+dwKeySpec = ConfigItem_lookup_int("KEY_USAGE_CHECK", 1) ? AT_SIGNATURE : 0;
+
+fRes=CryptGetUserKey(hCryptProv, dwKeySpec, &hKey);
+if (fRes == TRUE)
+ {
+ fRes=CryptGetKeyParam(hKey, KP_CERTIFICATE, NULL, &cbData, 0);
+ if (fRes == TRUE)
+ {
+ pbData = malloc(cbData);
+ if (pbData == NULL)
+ fRes = FALSE;
+ }
+ if (fRes == TRUE)
+ fRes=CryptGetKeyParam(hKey, KP_CERTIFICATE, pbData, &cbData, 0);
+ if (fRes == TRUE)
+ {
+ pCertContext = CertCreateCertificateContext(MY_ENCODING_TYPE,pbData,cbData);
+ if (pCertContext != NULL)
+ {
+ wszContainerName=NULL;
+ wszProvName=NULL;
+ cchContainerName = (lstrlen(psKeyContainer) + 1) * sizeof(WCHAR);
+ cchCSPName = (lstrlen(psCspName) + 1) * sizeof(WCHAR);
+ wszContainerName = (LPWSTR) malloc(cchContainerName);
+ wszProvName = (LPWSTR) malloc(cchCSPName);
+ mbstowcs(wszContainerName, psKeyContainer,cchContainerName);
+ mbstowcs(wszProvName, psCspName, cchCSPName);
+ ZeroMemory((PVOID)&KeyProvInfo, sizeof(CRYPT_KEY_PROV_INFO));
+ KeyProvInfo.pwszContainerName = (LPWSTR) wszContainerName;
+ KeyProvInfo.pwszProvName = (LPWSTR) wszProvName;
+ KeyProvInfo.dwProvType = PROV_RSA_SIG;
+ KeyProvInfo.dwFlags = 0;
+ KeyProvInfo.dwKeySpec = dwKeyType;
+ fRes = CertSetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID, 0, (const void *) &KeyProvInfo);
+ if (wszContainerName != NULL)
+ free(wszContainerName);
+ if (wszProvName != NULL)
+ free(wszProvName);
+
+ }
+ }
+ }
+
+//if (pCertContext != NULL)
+// DigiCrypt_AddCertToStore(pCertContext);
+if (fRes == FALSE && pCertContext != NULL)
+ {
+ CertFreeCertificateContext(pCertContext);
+ pCertContext = NULL;
+ }
+if (pbData != NULL)
+ free(pbData);
+if (hCryptProv != 0)
+ CryptReleaseContext(hCryptProv, 0);
+return(pCertContext);
+}
+
+
+static BOOL DigiCrypt_AddCertToStore(PCCERT_CONTEXT pCert)
+{
+BOOL fRes = FALSE;
+HCERTSTORE hSystemStore = NULL; // The system store handle.
+if (pCert != NULL)
+ {
+ if (hSystemStore = CertOpenStore(
+ CERT_STORE_PROV_SYSTEM_A,
+ 0, // Encoding type not needed with this PROV.
+ 0, // Accept the default HCRYPTPROV.
+ CERT_STORE_NO_CRYPT_RELEASE_FLAG |
+ CERT_SYSTEM_STORE_CURRENT_USER,"MY"))
+ {
+ if (CertAddCertificateContextToStore(hSystemStore, pCert, CERT_STORE_ADD_REPLACE_EXISTING,NULL))
+ fRes = TRUE;
+ }
+ }
+if (hSystemStore != NULL)
+ CertCloseStore(hSystemStore, CERT_CLOSE_STORE_CHECK_FLAG);
+return(fRes);
+}
+
+
+char *DigiCrypt_FindContext_GetKeyName()
+{
+ if (lstrlen(oG_sKeyContainerName) > 0)
+ return(oG_sKeyContainerName);
+ else
+ return(NULL);
+}
+
+char *DigiCrypt_FindContext_GetCSPName()
+{
+ if (lstrlen(oG_sCSPName) > 0)
+ return(oG_sCSPName);
+ else
+ return(NULL);
+}
+
+DWORD DigiCrypt_FindContext_GetCSPType(char *psCSPName)
+{
+ DWORD dwRes = PROV_RSA_SIG;
+ DWORD dwType = REG_DWORD;
+ DWORD dwLen = dSTRING_ITEM_LEN;
+ DWORD *pdwVal;
+ HKEY hKey;
+ LONG lRes;
+ char sKeyNameBuf[dSTRING_ITEM_LEN+1];
+ char sValue[dSTRING_ITEM_LEN+1];
+
+ strncpy(sKeyNameBuf, psData_CSP_Path, sizeof(sKeyNameBuf));
+ strncat(sKeyNameBuf, psCSPName, sizeof(sKeyNameBuf) - strlen(sKeyNameBuf));
+ lRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE,sKeyNameBuf, 0, KEY_READ, &hKey);
+ if (lRes == ERROR_SUCCESS) {
+ lRes = RegQueryValueEx(hKey, "Type", 0, &dwType, (LPBYTE)sValue, &dwLen);
+ if (lRes == ERROR_SUCCESS) {
+ pdwVal = (DWORD *)sValue;
+ dwRes = (*pdwVal);
+ }
+ RegCloseKey(hKey);
+ }
+ return(dwRes);
+}
+
+static BOOL OpenProvider(HCRYPTPROV *phProv, char *psProvider, DWORD dwFlags)
+{
+ BOOL fRes;
+ DWORD dwType = DigiCrypt_FindContext_GetCSPType(psProvider);
+ fRes = CryptAcquireContext(phProv,NULL,psProvider, dwType, dwFlags);
+ return(fRes);
+}
+
+static HCERTSTORE DigiCrypt_OpenStore(void)
+{
+HCERTSTORE hStore;
+hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,CERT_SYSTEM_STORE_CURRENT_USER,L"MY");
+return(hStore);
+}
+
+
+static BOOL DigiCrypt_GetCSPFromCert(PCCERT_CONTEXT pCertContext, char *psResult, int iMaxResLen)
+{
+BOOL fRes = FALSE;
+CRYPT_KEY_PROV_INFO *poKeyInfo;
+DWORD pcbData;
+DWORD dwLen;
+if (pCertContext == NULL || psResult == 0)
+ return(fRes);
+fRes = CertGetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID,NULL,&pcbData);
+if (fRes == TRUE)
+ {
+ poKeyInfo = malloc(pcbData);
+ if (poKeyInfo != NULL)
+ {
+ fRes = CertGetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID,poKeyInfo,&pcbData);
+ if (fRes == TRUE)
+ {
+ if (poKeyInfo->pwszProvName != NULL)
+ {
+ dwLen = WideCharToMultiByte(CP_ACP,0,poKeyInfo->pwszProvName,-1,psResult,iMaxResLen,NULL,NULL);
+ }
+ else
+ fRes = FALSE;
+ }
+ free(poKeyInfo);
+ }
+ }
+return(fRes);
+}
+
+static BOOL DigiCrypt_GetContainerFromCert(PCCERT_CONTEXT pCertContext, char *psResult, int iMaxResLen)
+{
+BOOL fRes = FALSE;
+CRYPT_KEY_PROV_INFO *poKeyInfo;
+DWORD pcbData;
+DWORD dwLen;
+if (pCertContext == NULL || psResult == 0)
+ return(fRes);
+fRes = CertGetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID,NULL,&pcbData);
+if (fRes == TRUE)
+ {
+ poKeyInfo = malloc(pcbData);
+ if (poKeyInfo != NULL)
+ {
+ fRes = CertGetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID,poKeyInfo,&pcbData);
+ if (fRes == TRUE)
+ {
+ if (poKeyInfo->pwszContainerName != NULL)
+ {
+
+ dwLen = WideCharToMultiByte(CP_ACP,0,poKeyInfo->pwszContainerName,-1,psResult,iMaxResLen,NULL,NULL);
+ }
+ else
+ fRes = FALSE;
+ }
+ free(poKeyInfo);
+ }
+ }
+return(fRes);
+}
+
+static BOOL DigiCrypt_CertIsSig(PCCERT_CONTEXT pCertContext)
+{
+BOOL fRes = FALSE;
+CRYPT_KEY_PROV_INFO *poKeyInfo;
+DWORD pcbData;
+if (pCertContext == NULL)
+ return(fRes);
+fRes = CertGetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID,NULL,&pcbData);
+if (fRes == TRUE)
+ {
+ poKeyInfo = malloc(pcbData);
+ if (poKeyInfo != NULL)
+ {
+ fRes = CertGetCertificateContextProperty(pCertContext,CERT_KEY_PROV_INFO_PROP_ID,poKeyInfo,&pcbData);
+ if (fRes == TRUE)
+ {
+ if (poKeyInfo->dwProvType == PROV_RSA_SIG)
+ fRes = TRUE;
+ }
+ free(poKeyInfo);
+ }
+ }
+return(fRes);
+}
+
+
+static BOOL DigiCrypt_GetDataFromCert(PCCERT_CONTEXT pCertContext)
+{
+ BOOL fRes = FALSE;
+ char sContainer[dNAME_ITEM_LEN+1];
+ //DWORD dwLen;
+ if (pCertContext == NULL)
+ return(fRes);
+ fRes = DigiCrypt_GetCSPFromCert(pCertContext, oG_sCSPName,dSTRING_ITEM_LEN);
+
+ if (fRes == TRUE) {
+ // DigiCrypt_GetDefaultKeyContainerNameSimple(oG_sCSPName); //this is not usable. Tarmo changed that! Instead we should use the following:
+ if (DigiCrypt_GetContainerFromCert(pCertContext, sContainer, dNAME_ITEM_LEN) == TRUE) {
+ strncpy(oG_sKeyContainerName, sContainer, sizeof(oG_sKeyContainerName));
+ }
+ }
+ return(fRes);
+}
+
+static char *DigiCrypt_GetFirstAllowedCSPNameNew(void)
+{
+ char *psRes = NULL;
+ HKEY hKey = NULL;
+ LONG lRet=0;
+ DWORD dwIndex = 0;
+ BOOL fRes;
+ char sProvName[dSTRING_ITEM_LEN+1];
+ char sKeyNameBuf[dSTRING_ITEM_LEN+1];
+ HCRYPTPROV hProvide = 0;
+ DWORD dwBufLen;
+ FILETIME oTime;
+ //char buff[200];
+ BYTE pbData[dNAME_ITEM_LEN+1];
+ DWORD cbData=dNAME_ITEM_LEN+1;
+ //
+ DWORD dwProvType;
+
+ strncpy(sKeyNameBuf, psData_CSP_Path, sizeof(sKeyNameBuf));
+ lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,sKeyNameBuf,0, KEY_READ, &hKey);
+
+ while (lRet == ERROR_SUCCESS) {
+ dwBufLen = dSTRING_ITEM_LEN;
+ lRet = RegEnumKeyEx(hKey,dwIndex,sProvName,&dwBufLen,NULL,NULL,0,&oTime);
+ if (lRet == ERROR_SUCCESS) {
+ if (lstrcmp(sProvName,psData_Ignore_CSP_Name) != 0) {
+ dwProvType = DigiCrypt_FindContext_GetCSPType(sProvName);
+ LOG("CSP %s",sProvName);
+ //printf("%s :",sProvName);
+ if ((lstrcmp(sProvName,psData_Extra_CSP_Name) != 0) && (lstrcmp(sProvName,"Belgium Identity Card CSP")!=0)) {
+ //fRes = OpenProvider(&hProvide, sProvName, CRYPT_SILENT);
+ fRes = CryptAcquireContext(&hProvide,NULL,sProvName,dwProvType, CRYPT_SILENT);
+ fRes=CryptGetProvParam(hProvide, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
+ // printf("X\n");
+ } else {
+ //fRes = OpenProvider(&hProvide, sProvName, CRYPT_VERIFYCONTEXT);
+ //fRes = CryptAcquireContext(&hProvide,"SetCARDKeyContainer",sProvName,dwProvType, CRYPT_SILENT);
+ fRes = CryptAcquireContext(&hProvide,NULL,sProvName,dwProvType, CRYPT_VERIFYCONTEXT);
+ if (fRes == TRUE) {
+ //the extra csp might give wrong answer. We should ask from provider, why.
+ //The following is the work-around -- try to lookup key container from the card.
+ //if the result is negative this is a not the csp what is needed.
+ fRes=CryptGetProvParam(hProvide, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
+ if (fRes == TRUE)
+ fRes=CryptAcquireContext(&hProvide,(char*)pbData,sProvName,dwProvType, CRYPT_SILENT);
+ }
+ }
+ //printf("fRes: %x\n",GetLastError());
+ if (fRes == TRUE) { // && dwProvType == 2)
+ // printf("OK %d %s\n",cbData, pbData);
+ //set global values
+ LOG("CSP %s accepted",sProvName);
+ //is it hardware token?
+ cbData=dNAME_ITEM_LEN+1;
+ if (CryptGetProvParam(hProvide, PP_IMPTYPE, pbData, &cbData, 0)) {
+ //printf("implementat: %d\n",pbData[0]);
+ if((pbData[0] & 1)) // hardware token
+ {
+ strncpy(oG_sCSPName, sProvName, sizeof(oG_sCSPName));
+ //CryptReleaseContext(hProvide, 0);
+ psRes = oG_sCSPName;
+ break;
+ }
+ }
+ }
+ }
+ }
+ //hProvide = 0;
+ CryptReleaseContext(hProvide, 0);
+ dwIndex++;
+ }
+ if (hKey != NULL)
+ RegCloseKey(hKey);
+ return(psRes);
+}
+
+
+static char *DigiCrypt_GetFirstAllowedCSPName(void)
+{
+ char *psRes = NULL;
+ HKEY hKey = NULL;
+ LONG lRet=0;
+ DWORD dwIndex = 0;
+ BOOL fRes;
+ char sProvName[dSTRING_ITEM_LEN+1];
+ char sKeyNameBuf[dSTRING_ITEM_LEN+1];
+ HCRYPTPROV hProvide = 0;
+ DWORD dwBufLen;
+ FILETIME oTime;
+ //char buff[200];
+ BYTE pbData[dNAME_ITEM_LEN+1];
+ DWORD cbData=dNAME_ITEM_LEN+1;
+ DWORD dwProvType;
+
+ strncpy(sKeyNameBuf, psData_CSP_Path, sizeof(sKeyNameBuf));
+ lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,sKeyNameBuf,0, KEY_READ, &hKey);
+ while (lRet == ERROR_SUCCESS) {
+ dwBufLen = dSTRING_ITEM_LEN;
+ lRet = RegEnumKeyEx(hKey,dwIndex,sProvName,&dwBufLen,NULL,NULL,0,&oTime);
+ if (lRet == ERROR_SUCCESS) {
+ if (lstrcmp(sProvName,psData_Ignore_CSP_Name) != 0) {
+ dwProvType = DigiCrypt_FindContext_GetCSPType(sProvName);
+ LOG("CSP %s",sProvName);
+ if (lstrcmp(sProvName,psData_Extra_CSP_Name) != 0)
+ fRes = OpenProvider(&hProvide, sProvName, CRYPT_SILENT);
+ else {
+ fRes = OpenProvider(&hProvide, sProvName, CRYPT_VERIFYCONTEXT);
+ //fRes = CryptAcquireContext(&hProvide,"SetCARDKeyContainer",sProvName,dwProvType, CRYPT_SILENT);
+ fRes = CryptAcquireContext(&hProvide,NULL,sProvName,dwProvType, CRYPT_VERIFYCONTEXT);
+ if(fRes) {
+ //the extra csp might give wrong answer. We should ask from provider, why.
+ //The following is the work-around -- try to lookup key container from the card.
+ //if the result is negative this is a not the csp what is needed.
+ fRes=CryptGetProvParam(hProvide, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
+ }
+ }
+ if (fRes == TRUE) { // && dwProvType == 2)
+ //set global values
+ LOG("CSP %s accepted",sProvName);
+ strncpy(oG_sCSPName, sProvName, sizeof(oG_sCSPName));
+ CryptReleaseContext(hProvide, 0);
+ psRes = oG_sCSPName;
+ break;
+ }
+ }
+ }
+ //hProvide = 0;
+ CryptReleaseContext(hProvide, 0);
+ dwIndex++;
+ }
+ if (hKey != NULL)
+ RegCloseKey(hKey);
+ return(psRes);
+}
+
+
+static void DigiCrypt_ReleaseFirstAllowedCSP(void)
+{
+ //clear global values
+ if (oG_hProvider != 0)
+ CryptReleaseContext(oG_hProvider, 0);
+ oG_hProvider = 0;
+ oG_sCSPName[0] = 0;
+}
+
+static char *DigiCrypt_GetDefaultKeyContainerName(char *psCSPName)
+{
+ char *psRes = NULL;
+ HCRYPTPROV hProvider;
+ BOOL fRes;
+ DWORD dwFlags = CRYPT_VERIFYCONTEXT;
+ BYTE pbData[dNAME_ITEM_LEN+1];
+ DWORD cbData = dNAME_ITEM_LEN;
+ DWORD dwError;
+ DWORD dwProvType;
+
+ ZeroMemory(pbData,cbData);
+ ZeroMemory(oG_sKeyContainerName,1000);
+ dwProvType = DigiCrypt_FindContext_GetCSPType(psCSPName);
+ //LOG("GetDefaultKeyContainerName CSP=%s",psCSPName);
+ if (lstrcmp(psCSPName,psData_Extra_CSP_Name) != 0)
+ fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,dwProvType, CRYPT_SILENT);
+ else
+ fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,dwProvType, CRYPT_VERIFYCONTEXT);
+ if (fRes == FALSE && dwFlags == CRYPT_SILENT) {
+ //by description must be CRYPT_VERIFYCONTEXT
+ fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,dwProvType, CRYPT_VERIFYCONTEXT);
+ }
+ if (fRes == TRUE) {
+ cbData = dNAME_ITEM_LEN;
+ fRes = CryptGetProvParam(hProvider, PP_CONTAINER, pbData, &cbData, 0);
+ /*if (fRes == FALSE)
+ dwError = GetLastError();*/
+ }
+ //Some cards should not have default key container
+ //let try to find key containers on the card.
+ if (fRes == FALSE) {
+ fRes=CryptGetProvParam(hProvider, PP_ENUMCONTAINERS, pbData, &cbData,CRYPT_FIRST);
+ if (fRes == FALSE)
+ dwError = GetLastError();
+ }
+ if (fRes == TRUE) {
+ //oG_hProvider = hProvider;
+ strncpy(oG_sKeyContainerName, (char *) pbData, sizeof(oG_sKeyContainerName));
+ //psRes = oG_sKeyContainerName;
+ DigiCrypt_ChangeContainerName(oG_sKeyContainerName);
+ } else {
+
+ }
+ if (psRes != NULL)
+ LOG("GetDefaultKeyContainerName CSP=%s",psCSPName);
+ else
+ LOG("GetDefaultKeyContainerName Not found");
+ if (hProvider != 0)
+ CryptReleaseContext(hProvider, 0);
+ return(oG_sKeyContainerName);
+}
+
+static char *DigiCrypt_GetDefaultKeyContainerNameSimple(char *psCSPName)
+{
+ char *psRes = NULL;
+ HCRYPTPROV hProvider=0;
+ BOOL fRes;
+ DWORD dwFlags = 0;
+ BYTE pbData[dNAME_ITEM_LEN+1];
+ DWORD cbData = dNAME_ITEM_LEN;
+ DWORD dwError;
+
+ fRes = OpenProvider(&hProvider, psCSPName, dwFlags);
+ //fRes = CryptAcquireContext(&hProvider,NULL,psCSPName,PROV_RSA_SIG, dwFlags);
+ if (fRes == TRUE) {
+ fRes = CryptGetProvParam(hProvider, PP_CONTAINER, pbData, &cbData, 0);
+ if (fRes == FALSE)
+ dwError = GetLastError();
+ }
+ if (fRes == TRUE) {
+ strncpy(oG_sKeyContainerName, pbData, sizeof(oG_sKeyContainerName));
+ psRes = oG_sKeyContainerName;
+ DigiCrypt_ChangeContainerName(oG_sKeyContainerName);
+ }
+ if (hProvider != 0)
+ CryptReleaseContext(hProvider, 0);
+ return(psRes);
+}
+
+
+static PCCERT_CONTEXT DigiCrypt_SelectFromAllCerts(void)
+{
+PCCERT_CONTEXT pCertContext = NULL;
+HCERTSTORE hStore;
+hStore = DigiCrypt_OpenStore();
+if (hStore != NULL)
+ {
+ while (TRUE)
+ {
+ pCertContext = CertEnumCertificatesInStore(hStore,pCertContext);
+ if (pCertContext == NULL)
+ break;
+ else
+ {
+ //TEST
+ //Test_ReadCertDataC(pCertContext);
+ //END TEST
+ RunDlg_AddItem(pCertContext,TRUE);
+ }
+ }
+ pCertContext = RunDlg_RunDlg();
+ }
+return(pCertContext);
+}
+
+static void DigiCrypt_SelectCertsFromKeyContainer(HCRYPTPROV hProv, char *psContainerName)
+{
+PCCERT_CONTEXT pCertContext = NULL;
+HCERTSTORE hStore;
+BOOL fRelease = FALSE;
+char sContainer[dNAME_ITEM_LEN+1];
+
+if (memcmp(psContainerName,"AUT",3) == 0)
+ {
+ LOG("Find1 Ignore AUT cert");
+ return;
+ }
+hStore = DigiCrypt_OpenStore();
+if (hStore != NULL)
+ {
+ while (TRUE)
+ {
+ pCertContext = CertEnumCertificatesInStore(hStore,pCertContext);
+ if (pCertContext == NULL)
+ break;
+ else
+ {
+ if (DigiCrypt_GetContainerFromCert(pCertContext, sContainer, dNAME_ITEM_LEN) == TRUE)
+ {
+
+ LOG("Find1 Container %s %s",sContainer,psContainerName);
+ if (lstrcmp(sContainer+3,psContainerName+3) == 0)
+ {
+ LOG("Find1 Container %s accepted",sContainer);
+ RunDlg_AddItem(pCertContext,TRUE);
+ }
+ }
+ }
+ }
+ }
+else
+ LOG("Find1 Can't open store");
+if (fRelease == TRUE)
+ CryptReleaseContext(hProv, 0);
+}
+
+static PCCERT_CONTEXT DigiCrypt_SelectFromAllKeysCerts(HCRYPTPROV hProvider)
+{
+PCCERT_CONTEXT pCertContext = NULL;
+HCRYPTPROV hProv;
+BYTE pbData[dNAME_ITEM_LEN+1];
+DWORD cbData = dNAME_ITEM_LEN;
+DWORD dwFlag;
+BOOL fRes;
+BOOL fRelease = FALSE;
+CRYPT_KEY_PROV_INFO* poKeyInfo = NULL;
+char sContainer[dNAME_ITEM_LEN+1];
+
+hProv = hProvider;
+
+
+if (hProv == 0)
+ {
+ fRes = OpenProvider(&hProv, oG_sCSPName, CRYPT_VERIFYCONTEXT);
+ //fRes = CryptAcquireContext(&hProv,NULL,oG_sCSPName,PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
+ if (fRes == FALSE)
+ {
+
+ LOG("Find1 - Can't open provider");
+ return(pCertContext);
+ }
+ fRelease = TRUE;
+ }
+ dwFlag = CRYPT_FIRST;
+ fRes = TRUE;
+ while (fRes == TRUE)
+ {
+ cbData = dNAME_ITEM_LEN;
+ cbData = 0;
+ fRes = CryptGetProvParam(hProv, PP_ENUMCONTAINERS, NULL, &cbData, dwFlag);
+ if (fRes == TRUE)
+ fRes = CryptGetProvParam(hProv, PP_ENUMCONTAINERS, pbData, &cbData, dwFlag);
+ dwFlag = 0;
+
+ if (fRes == FALSE)
+ {
+ if (GetLastError() == ERROR_NO_MORE_ITEMS)
+ {
+ LOG("Find1 End");
+ fRes = TRUE;
+ break;
+ }
+ }
+ else
+ {
+ LOG("Find1 select certs from %s",pbData);
+ DigiCrypt_SelectCertsFromKeyContainer(hProv, pbData);
+ }
+ }
+ pCertContext = RunDlg_RunDlg();
+ //we have selected the cert, but do we know corresponding key?
+ //let change values of globals when these are different
+ if(DigiCrypt_GetContainerFromCert(pCertContext, sContainer, dNAME_ITEM_LEN) == TRUE) {
+ strncpy(oG_sKeyContainerName, sContainer, sizeof(oG_sKeyContainerName));
+ }
+ if(fRelease == TRUE)
+ CryptReleaseContext(hProv, 0);
+ return(pCertContext);
+}
+
+
+static BOOL DigiCrypt_IsValidCert(PCCERT_CONTEXT pCertContext, BOOL fTimeCheck)
+{
+BOOL fIsValid = FALSE;
+BOOL fRes = FALSE;
+BOOL fKuCheck = TRUE;
+BYTE bKeyUsageBits = CERT_NON_REPUDIATION_KEY_USAGE;
+DWORD dwKeyUsageBytes = 1;
+// VS use auth certs if key_usage_check = 0
+fKuCheck = (BOOL)ConfigItem_lookup_int("KEY_USAGE_CHECK", 1);
+bKeyUsageBits = fKuCheck ? CERT_NON_REPUDIATION_KEY_USAGE : 0;
+//LOG("KEY_USAGE_CHECK: %d ku: %d", fKuCheck, bKeyUsageBits);
+//Old version
+//FILETIME oCurrentTime;
+if (pCertContext != NULL && pCertContext->pCertInfo != NULL)
+ {
+ //not needed (info from Tarmo Milva)
+ //if (DigiCrypt_CertIsSig(pCertContext) == TRUE)
+ fRes = CertGetIntendedKeyUsage(X509_ASN_ENCODING,pCertContext->pCertInfo,&bKeyUsageBits,dwKeyUsageBytes);
+ //else
+ // fRes = FALSE;
+ if (fRes == TRUE)
+ {
+ //LOG("KU non-repu: %d", (bKeyUsageBits & CERT_NON_REPUDIATION_KEY_USAGE));
+ if(!fKuCheck || (bKeyUsageBits & CERT_NON_REPUDIATION_KEY_USAGE))
+ fIsValid = TRUE;
+ if(bKeyUsageBits & CERT_KEY_CERT_SIGN_KEY_USAGE) // don't display CA certs
+ fIsValid = FALSE;
+ }
+ if (fIsValid == TRUE && fTimeCheck == TRUE)
+ {
+ //Old version
+ //GetSystemTimeAsFileTime(&oCurrentTime);
+ //if (CompareFileTime(&oCurrentTime, &pCertContext->pCertInfo->NotBefore) < 0 ||
+ // CompareFileTime(&oCurrentTime, &pCertContext->pCertInfo->NotAfter) > 0 )
+ // fIsValid = FALSE;
+ //New version
+ //NULL, if current datetime
+ if (CertVerifyTimeValidity(NULL,pCertContext->pCertInfo) != 0)
+ fIsValid = FALSE;
+ }
+ }
+return(fIsValid);
+}
+
+static void DigiCrypt_ChangeContainerName(char *psContainerName)
+{
+if (memcmp(psContainerName,"AUT",3) == 0)
+ memmove(psContainerName,"SIG",3);
+}
+
+//dialog functions
+#define DLGMAXIEMS 512
+static char *psListItems[DLGMAXIEMS];
+static PCCERT_CONTEXT psListItemsCert[DLGMAXIEMS];
+static int iListItems=0;
+
+static void RunDlg_Clear(void)
+{
+int iI;
+for (iI=0; iI < DLGMAXIEMS;++iI)
+ {
+ psListItems[iI] = NULL;
+ psListItemsCert[iI] = NULL;
+ }
+iListItems=0;
+}
+
+static BOOL RunDlg_AddItem(PCCERT_CONTEXT pCertContext, BOOL fTimeCheck)
+{
+BOOL fRes = TRUE;
+BOOL fAddToList = TRUE;
+char *psData;
+int iI, len;
+if (iListItems == (DLGMAXIEMS-1))
+ return(FALSE);
+if (iListItems == 0)
+ {
+ for (iI=0; iI < DLGMAXIEMS;++iI)
+ {
+ psListItems[iI] = NULL;
+ psListItemsCert[iI] = NULL;
+ }
+ }
+if (pCertContext != NULL)
+ {
+ fAddToList = DigiCrypt_IsValidCert(pCertContext,fTimeCheck);
+ if (fAddToList == TRUE)
+ {
+ len = dSTRING_ITEM_LEN*4;
+ psListItems[iListItems] = (char *)LocalAlloc(LMEM_ZEROINIT,(len));
+ psListItemsCert[iListItems] = CertDuplicateCertificateContext(pCertContext);
+ //Make data buffer for list
+ psData = psListItems[iListItems];
+ RunDlg_FillItem(pCertContext, psData, len);
+ ++iListItems;
+ }
+ }
+return(fRes);
+}
+
+
+static PCCERT_CONTEXT RunDlg_RunDlg(void)
+{
+PCCERT_CONTEXT hCert = NULL;
+int iRes = -1;
+int iI;
+oG_fDialogUserCancel = FALSE;
+if (iListItems > 1)
+ {
+ LOG("StartDialog");
+ iRes = RunDialogUnit(psListItems, 450,300);
+ if (iRes < 0)
+ oG_fDialogUserCancel = TRUE;
+ LOG("EndDialog");
+ }
+else
+ {
+ if (iListItems == 1)
+ iRes = 0;
+ }
+for (iI=0; iI < iListItems;++iI)
+ {
+ LocalFree(psListItems[iI]);
+ if (iRes != iI)
+ CertFreeCertificateContext(psListItemsCert[iI]);
+ else
+ hCert = psListItemsCert[iI];
+ }
+iListItems = 0;
+return(hCert);
+}
+
+static BOOL RunDlg_FillItem(PCCERT_CONTEXT pCertContext, char *psRes, int len)
+{
+ char sTemp[dSTRING_ITEM_LEN+1];
+ SYSTEMTIME oT;
+ PCERT_INFO pCertInfo;
+ BOOL fRes = TRUE;
+ *psRes = 0;
+
+ if (pCertContext == NULL || pCertContext->pCertInfo == NULL || psRes == NULL)
+ return(FALSE);
+ pCertInfo = pCertContext->pCertInfo;
+ CertGetNameString(pCertContext,CERT_NAME_SIMPLE_DISPLAY_TYPE,CERT_NAME_ISSUER_FLAG,NULL,sTemp,dSTRING_ITEM_LEN);
+ if (lstrlen(sTemp) > 0) {
+ strncat(psRes, sTemp, len - strlen(psRes));
+ strncat(psRes, " \t", len - strlen(psRes));
+ }
+ CertGetNameString(pCertContext,CERT_NAME_SIMPLE_DISPLAY_TYPE,0,NULL,sTemp,dSTRING_ITEM_LEN);
+ //CorrectCharacters(sTemp);
+ if (lstrlen(sTemp) > 0) {
+ strncat(psRes, sTemp, len - strlen(psRes));
+ strncat(psRes, " \t", len - strlen(psRes));
+ }
+ if (FileTimeToSystemTime(&pCertInfo->NotBefore,&oT) == TRUE) {
+ snprintf(sTemp, sizeof(sTemp), "%02d/%02d/%02d \t",oT.wYear,oT.wMonth,oT.wDay);
+ strncat(psRes, sTemp, len - strlen(psRes));
+ }
+ else
+ fRes = FALSE;
+ if (FileTimeToSystemTime(&pCertInfo->NotAfter,&oT) == TRUE) {
+ snprintf(sTemp, sizeof(sTemp), "02d/%02d/%02d \t",oT.wYear,oT.wMonth,oT.wDay);
+ strncat(psRes,sTemp, len - strlen(psRes));
+ }
+ else
+ fRes = FALSE;
+ if (DigiCrypt_GetCSPFromCert(pCertContext, sTemp, dSTRING_ITEM_LEN) == TRUE)
+ strncat(psRes,sTemp, len - strlen(psRes));
+ return(fRes);
+}
+
+static char sLogLine[4096];
+static char sLogFile[256];
+static int iLogCheck = -1;
+
+static BOOL IsLogEnabled(void)
+{
+ BOOL fRes = FALSE;
+ DWORD dwRes;
+ char cVal;
+ HANDLE hSearch;
+ WIN32_FIND_DATA oF;
+
+ if(iLogCheck == -1) {
+ iLogCheck = 0;
+ dwRes = GetModuleFileName(NULL, sLogFile, 255);
+ //strcpy(sLogFile, "z:\\digicrypt.log"); dwRes=1;iLogCheck = 1;
+ //MessageBox(NULL,sLogFile,"LogFile=",MB_OK|MB_SYSTEMMODAL|MB_ICONERROR);
+ while (dwRes > 1) {
+ cVal = sLogFile[dwRes-1];
+ if (cVal == '.') {
+ strncat(sLogFile, "log", sizeof(sLogFile) - strlen(sLogFile));
+ hSearch = FindFirstFile(sLogFile,&oF);
+ if (hSearch != INVALID_HANDLE_VALUE) {
+ iLogCheck = 1;
+ FindClose(hSearch);
+ }
+ break;
+ }
+ --dwRes;
+ }
+ }
+ fRes = (BOOL)iLogCheck;
+ return(fRes);
+}
+
+void LOG(char *psMsgFmt, ...)
+{
+ int iLen;
+ char buff[200];
+ va_list ArgList;
+ va_start(ArgList, psMsgFmt);
+ iLen = wvsprintf((LPTSTR)sLogLine, (LPTSTR)psMsgFmt, ArgList);
+ snprintf(buff, sizeof(buff), (LPTSTR)psMsgFmt,ArgList);
+ //MessageBox(NULL,(LPTSTR)sLogLine,"Teade",0);
+ va_end(ArgList);
+ if (IsLogEnabled() == TRUE)
+ IntLogToFile(sLogLine,iLen);
+}
+
+static void IntLogToFile(char *psMsg, int iMsgLen)
+{
+char sLogFormat1[]="%02d%02d%02d %02d:%02d.%02d ";
+char sTimeBuf[64];
+HANDLE hFile;
+DWORD dwLen;
+SYSTEMTIME oTime;
+if (psMsg == NULL || iMsgLen == 0)
+ return;
+GetLocalTime(&oTime);
+wsprintf((LPTSTR)sTimeBuf,(LPTSTR)sLogFormat1, oTime.wYear-2000, oTime.wMonth, oTime.wDay,
+ oTime.wHour, oTime.wMinute, oTime.wSecond);
+hFile = CreateFile((LPCTSTR)sLogFile,
+ GENERIC_READ|GENERIC_WRITE,FILE_SHARE_WRITE, NULL,
+ OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+
+if (hFile != INVALID_HANDLE_VALUE)
+ {
+ if (psMsg != NULL)
+ {
+ SetFilePointer(hFile,0,NULL,FILE_END);
+ WriteFile(hFile,sTimeBuf, strlen(sTimeBuf), &dwLen, NULL);
+ if (iMsgLen < 0)
+ iMsgLen = strlen(psMsg);
+ if (iMsgLen > 0)
+ WriteFile(hFile,psMsg, iMsgLen, &dwLen, NULL);
+ WriteFile(hFile,"\r\n", 2, &dwLen, NULL);
+ }
+ CloseHandle(hFile);
+ }
+}
+
+
+
diff --git a/libdigidoc/DigiCrypt.h b/libdigidoc/DigiCrypt.h
new file mode 100644
index 0000000..a2ee1f4
--- /dev/null
+++ b/libdigidoc/DigiCrypt.h
@@ -0,0 +1,28 @@
+#ifndef DigiCryptH
+#define DigiCryptH
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#include <windows.h>
+#include <wincrypt.h>
+
+#define dDigiCrypt_Okey 0
+#define dDigiCrypt_Error_NotFoundCSP 1
+#define dDigiCrypt_Error_UserCancel 2
+#define dDigiCrypt_Error_NoDefaultKey 3
+#define dDIgiCrypt_Error_NotFoundCert 4
+
+PCCERT_CONTEXT DigiCrypt_FindContext(BOOL fByKeyContainer, DWORD *dwResult);
+char *DigiCrypt_FindContext_GetCSPName(void);
+char *DigiCrypt_FindContext_GetKeyName(void);
+DWORD DigiCrypt_FindContext_GetCSPType(char *psCSPName);
+void LOG(char *psMsgFmt, ...);
+
+#ifdef __cplusplus
+}
+#endif
+#endif \ No newline at end of file
diff --git a/libdigidoc/DigiDocCert.c b/libdigidoc/DigiDocCert.c
new file mode 100644
index 0000000..3d248bd
--- /dev/null
+++ b/libdigidoc/DigiDocCert.c
@@ -0,0 +1,1981 @@
+//==================================================
+// FILE: DigiDocCert.c
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for certificate handling
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 09.09.2004 Veiko Sinivee
+// Creation
+//==================================================
+
+#include <libdigidoc/DigiDocDefs.h>
+#include <libdigidoc/DigiDocCert.h>
+#include <libdigidoc/DigiDocConvert.h>
+#include <libdigidoc/DigiDocLib.h>
+#include <libdigidoc/DigiDocError.h>
+#include <libdigidoc/DigiDocDebug.h>
+#include <libdigidoc/DigiDocMem.h>
+#include <libdigidoc/DigiDocOCSP.h>
+
+#include <openssl/sha.h>
+#include <openssl/rsa.h>
+#include <openssl/evp.h>
+#include <openssl/objects.h>
+#include <openssl/x509.h>
+#include <openssl/x509v3.h>
+#include <openssl/err.h>
+#include <openssl/pem.h>
+#include <openssl/ssl.h>
+#include <openssl/ocsp.h>
+#include <openssl/pkcs12.h>
+#include <openssl/rand.h>
+#include <string.h>
+
+//==========< forward declarations >====================
+
+extern int createOCSPRequest(SignedDoc* pSigDoc, OCSP_REQUEST **req,
+ X509 *cert, X509 *pCA, byte* nonce, int nlen);
+extern int signOCSPRequestPKCS12(OCSP_REQUEST *req, const char* filename, const char* passwd);
+
+extern int verifyOCSPResponse(OCSP_RESPONSE* pResp,
+ const X509** caCerts, const char *CApath,
+ const X509* notCert);
+extern int hasUmlauts(const char* str);
+extern int checkNonceAndCertbyOCSP(OCSP_RESPONSE* resp, X509* cert, byte* nonce1, int nonceLen);
+
+
+//==========< utility functions >====================
+
+
+//--------------------------------------------------
+// Reads a certificate file
+// certfile - name of the certificate file
+//--------------------------------------------------
+EXP_OPTION int ReadCertificate(X509 **x509, const char *szCertfile)
+{
+ BIO *in;
+
+ RETURN_IF_NULL_PARAM(szCertfile);
+ if((in = BIO_new_file(szCertfile, "rb")) != NULL) {
+ *x509 = PEM_read_bio_X509(in, NULL, NULL, 0);
+ BIO_free(in);
+ if(!*x509) SET_LAST_ERROR_RETURN_CODE(ERR_NULL_CERT_POINTER);
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_READ);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Reads a certificate file
+// certfile - name of the certificate file
+//--------------------------------------------------
+EXP_OPTION int ReadCertificateNoErr(X509 **x509, const char *szCertfile)
+{
+ BIO *in;
+
+ RETURN_IF_NULL_PARAM(szCertfile);
+ if((in = BIO_new_file(szCertfile, "rb")) != NULL) {
+ *x509 = PEM_read_bio_X509(in, NULL, NULL, 0);
+ BIO_free(in);
+ if(!*x509) return ERR_NULL_CERT_POINTER;
+ } else
+ return ERR_FILE_READ;
+ return ERR_OK;
+}
+
+
+//--------------------------------------------------
+// Reads a certificate from pkcs12 conteiner
+//--------------------------------------------------
+EXP_OPTION int ReadCertificateByPKCS12(X509 **x509, const char *pkcs12file, const char *passwd, EVP_PKEY **pkey)
+{
+ BIO *bio;
+ PKCS12 *p12;
+
+ //memset(debugBuf,0,sizeof(debugBuf));
+ RETURN_IF_NULL_PARAM(pkcs12file);
+ bio=BIO_new_file(pkcs12file, "rb");
+ RETURN_IF_NULL(bio);
+ p12 = d2i_PKCS12_bio(bio, NULL);
+ BIO_free(bio);
+ RETURN_IF_NOT(p12, ERR_OCSP_PKCS12_CONTAINER);
+ PKCS12_parse(p12, passwd, pkey, x509, NULL);
+ // Hack: clear PKCS12_parse error "ERROR: 185073780 - error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch
+ ERR_get_error();
+ PKCS12_free(p12);
+
+ RETURN_IF_NOT(*x509, ERR_OCSP_PKCS12_CONTAINER);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Reads certificates serial number
+// szSerial - buffer for serial number
+// nMaxLen - maximum serial number buffer length
+// certfile - name of the certificate file
+//--------------------------------------------------
+EXP_OPTION int GetCertSerialNumber(char *szSerial, int nMaxLen, const char *szCertfile)
+{
+ BIO *in;
+ X509 *x509;
+
+ RETURN_IF_NULL_PARAM(szSerial);
+ RETURN_IF_NULL_PARAM(szCertfile);
+ if((in = BIO_new_file(szCertfile, "rb")) != NULL) {
+ x509 = PEM_read_bio_X509(in, NULL, NULL, 0);
+ BIO_free(in);
+ RETURN_IF_NOT(x509, ERR_NULL_CERT_POINTER);
+ ReadCertSerialNumber(szSerial, nMaxLen, x509);
+ X509_free(x509);
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_READ);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Reads certificates serial number
+// x509 - certificate object
+//--------------------------------------------------
+int ReadCertSerialNumber(char* szSerial, int nMaxLen, X509 *x509)
+{
+ ASN1_INTEGER *bs = NULL;
+ BIGNUM* bn;
+ char* str;
+ int err = ERR_OK;
+
+ RETURN_IF_NOT(x509, ERR_NULL_CERT_POINTER);
+ RETURN_IF_NOT(szSerial, ERR_NULL_POINTER);
+ bs = X509_get_serialNumber(x509);
+ RETURN_IF_NOT(bs, ERR_NULL_SER_NUM_POINTER);
+ bn = ASN1_INTEGER_to_BN(bs, NULL);
+ RETURN_IF_NOT(bn, ERR_NULL_SER_NUM_POINTER);
+ str = BN_bn2dec(bn);
+ RETURN_IF_NOT(str, ERR_NULL_SER_NUM_POINTER);
+ memset(szSerial, 0, nMaxLen);
+ strncpy(szSerial, str, nMaxLen -1);
+ if(strlen(str) > (unsigned int)nMaxLen) {
+ err = ERR_BUF_LEN;
+ SET_LAST_ERROR(ERR_BUF_LEN);
+ }
+ //AM 28.05.08 bn should be freed too
+ if(bn)
+ BN_free(bn);
+ OPENSSL_free(str);
+ checkErrors();
+ return err;
+}
+
+
+
+//--------------------------------------------------
+// Reads a public key file
+// certfile - name of the certificate file
+//--------------------------------------------------
+int ReadPublicKey(EVP_PKEY **PublicKey, const char *szCertfile)
+{
+ EVP_PKEY *pkey = NULL;
+ X509 *x509 = NULL;
+ int err = ERR_OK;
+
+ RETURN_IF_NULL_PARAM(szCertfile);
+ RETURN_IF_NULL_PARAM(PublicKey); // SVEN - ver 1.92 - crashbug fixed
+ if((err = ReadCertificate(&x509, szCertfile)) == ERR_OK) {
+ pkey = X509_extract_key(x509);
+ X509_free(x509);
+ RETURN_IF_NOT(pkey, ERR_NULL_KEY_POINTER);
+ *PublicKey = pkey;
+ return ERR_OK;
+ } else
+ SET_LAST_ERROR_RETURN_CODE(err);
+}
+
+
+//--------------------------------------------------
+// Reads a public key file
+// certfile - name of the certificate file
+//--------------------------------------------------
+int GetPublicKey(EVP_PKEY **pubKey, const X509* x509)
+{
+ EVP_PKEY *pkey = NULL;
+
+ RETURN_IF_NULL_PARAM(x509);
+ // SET_LAST_ERROR_RETURN_IF_NOT(x509, ERR_NULL_CERT_POINTER, pkey);
+ // pkey = X509_extract_key((X509*)x509);
+ pkey = X509_get_pubkey((X509*)x509);
+ RETURN_IF_NOT(pkey, ERR_NULL_KEY_POINTER);
+ *pubKey = pkey;
+ return ERR_OK;
+}
+
+
+//--------------------------------------------------
+// Callback routine for passing key password
+//--------------------------------------------------
+int pemkey_callback(char *buf, int size, int rwflag, void *userdata)
+{
+ RETURN_OBJ_IF_NULL(buf, 0);
+ RETURN_OBJ_IF_NULL(userdata, 0);
+ memset(buf, 0, size);
+ strncpy(buf, (char*)userdata, size);
+ return strlen(buf);
+}
+
+
+//--------------------------------------------------
+// Reads a private key file
+// keyfile - name of the private key file
+// passwd - key password (problems with encrypted passwwords!)
+// format - file format (PEM or DER)
+//--------------------------------------------------
+EXP_OPTION int ReadPrivateKey(EVP_PKEY **privKey, const char *keyfile, const char* passwd, int format)
+{
+ BIO *in;
+ EVP_PKEY *pkey = NULL;
+
+ RETURN_IF_NULL_PARAM(keyfile);
+ RETURN_IF_NULL_PARAM(passwd);
+ if((in = BIO_new_file(keyfile, "rb")) != NULL) {
+ switch(format) {
+ case FILE_FORMAT_ASN1:
+ pkey = d2i_PrivateKey_bio(in,NULL);
+ break;
+ case FILE_FORMAT_PEM:
+ PEM_read_bio_PrivateKey(in, &pkey, pemkey_callback, (void*)passwd);
+ break;
+ }
+ BIO_free(in);
+ RETURN_IF_NOT(pkey, ERR_NULL_KEY_POINTER);
+ *privKey = pkey;
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_READ);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Writes a private key file
+// keyfile - name of the private key file
+// passwd - key password (problems with encrypted passwwords!)
+// format - file format (PEM or DER)
+//--------------------------------------------------
+EXP_OPTION int WritePrivateKey(EVP_PKEY *privKey, const char *keyfile, const char* passwd, int format)
+{
+ BIO *out = NULL;
+ EVP_PKEY *pkey = privKey;
+
+ RETURN_IF_NULL_PARAM(privKey);
+ RETURN_IF_NULL_PARAM(keyfile);
+ if((out = BIO_new_file(keyfile, "wb")) != NULL) {
+ switch(format) {
+ case FILE_FORMAT_ASN1:
+ i2d_PUBKEY_bio(out, pkey);
+ break;
+ case FILE_FORMAT_PEM:
+ PEM_write_bio_PrivateKey(out, pkey, (passwd ? EVP_des_ede3_cbc() : NULL),
+ (unsigned char*)passwd, strlen(passwd), pemkey_callback, (void*)passwd) ;
+ break;
+ }
+ BIO_free(out);
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_WRITE);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Writes a private key and cert to a PEM file
+// privKey - private key
+// pCert - certificate
+// keyfile - name of the private key file
+// passwd - key password (problems with encrypted passwwords!)
+//--------------------------------------------------
+EXP_OPTION int ddocWriteKeyAndCertPem(EVP_PKEY *privKey, X509* pCert,
+ const char *keyfile, const char* passwd)
+{
+ BIO *out = NULL;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(privKey);
+ RETURN_IF_NULL_PARAM(keyfile);
+ if((out = BIO_new_file(keyfile, "wb")) != NULL) {
+ PEM_write_bio_X509(out, pCert);
+ PEM_write_bio_PrivateKey(out, privKey, (passwd ? EVP_des_ede3_cbc() : NULL),
+ (unsigned char*)passwd, (passwd ? strlen(passwd) : 0), pemkey_callback, (void*)passwd);
+ BIO_free(out);
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_WRITE);
+ return ERR_OK;
+}
+
+
+
+//--------------------------------------------------
+// Reads an RSA private key file
+// keyfile - name of the private key file
+// passwd - key password (problems with encrypted passwwords!)
+// format - file format (PEM or DER)
+//--------------------------------------------------
+int ReadRSAPrivateKey(RSA **privKey, const char *keyfile, const char* passwd, int format)
+{
+
+ BIO *in = 0;
+ RSA *pkey = 0;
+
+ RETURN_IF_NULL_PARAM(keyfile);
+ RETURN_IF_NULL_PARAM(passwd);
+ if((in = BIO_new_file(keyfile, "rb")) != 0) {
+ switch(format) {
+ case FILE_FORMAT_ASN1:
+ pkey = d2i_RSAPrivateKey_bio(in,NULL);
+ break;
+ case FILE_FORMAT_PEM:
+ PEM_read_bio_RSAPrivateKey(in, &pkey, pemkey_callback, (void*)passwd);
+ break;
+ }
+ BIO_free(in);
+ RETURN_IF_NOT(pkey, ERR_NULL_KEY_POINTER);
+ *privKey = pkey;
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_READ);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Verifys a certificate by sending an OCSP_REQUEST object
+// to the notary server and checking the response.
+// Uses servers timestamps hash code as nonce value.
+// pCert - certificate to test
+// caCerts - responder CA certs chain
+// notaryCert - notarys cert search
+// proxyHost - proxy servers name
+// proxyPort - proxy servers port
+// notaryURL - notarys URL
+// ppResp - address to return OCSP response. Use NULL if
+// you don't want OCSP response to be returned
+// return 0 for OK, or error code
+//--------------------------------------------------
+EXP_OPTION int verifyCertificateByOCSP(X509* pCert, const X509** caCerts,
+ const X509* notaryCert, char* notaryURL,
+ char* proxyHost, char* proxyPort,
+ const char* pkcs12file, const char* pkcs12paswd,
+ OCSP_RESPONSE **ppResp)
+{
+ return verifyCertificateByOCSPWithIp(pCert, caCerts, notaryCert,
+ notaryURL, proxyHost, proxyPort, pkcs12file, pkcs12paswd, ppResp, 0);
+}
+
+//--------------------------------------------------
+// Verifys a certificate by sending an OCSP_REQUEST object
+// to the notary server and checking the response.
+// Uses servers timestamps hash code as nonce value.
+// pCert - certificate to test
+// caCerts - responder CA certs chain
+// notaryCert - notarys cert search
+// proxyHost - proxy servers name
+// proxyPort - proxy servers port
+// notaryURL - notarys URL
+// ppResp - address to return OCSP response. Use NULL if
+// you don't want OCSP response to be returned
+// return 0 for OK, or error code
+//--------------------------------------------------
+EXP_OPTION int verifyCertificateByOCSPWithIp(X509* pCert, const X509** caCerts,
+ const X509* notaryCert, char* notaryURL,
+ char* proxyHost, char* proxyPort,
+ const char* pkcs12file, const char* pkcs12paswd,
+ OCSP_RESPONSE **ppResp, unsigned long ip)
+
+{
+ OCSP_REQUEST *req = 0;
+ OCSP_RESPONSE *resp = 0;
+ int err = ERR_OK, l1, i;
+ byte nonce1[DIGEST_LEN+2];
+ time_t tNow;
+ X509* pCA = NULL;
+
+ RETURN_IF_NULL(pCert);
+ //RETURN_IF_NULL(notaryCert);
+ //RETURN_IF_NULL(caCerts);
+ RETURN_IF_NULL(notaryURL);
+
+ // mark as not found yet
+ if(ppResp)
+ *ppResp = 0;
+ time(&tNow);
+ l1 = sizeof(nonce1);
+ calculateDigest((const byte*)&tNow, sizeof(tNow), DIGEST_SHA1, nonce1, &l1);
+ // find lowest CA
+ for(i = 0; (caCerts != NULL) && (caCerts[i] != NULL); i++)
+ pCA = (X509*)caCerts[i];
+ err = createOCSPRequest(NULL, &req, pCert, pCA, nonce1, l1);
+ if(err == ERR_OK && pkcs12file)
+ err = signOCSPRequestPKCS12(req, pkcs12file, pkcs12paswd);
+ if(err == ERR_OK) {
+ //WriteOCSPRequest("test1.req", req);
+ err = sendOCSPRequest(&resp, req, notaryURL, proxyHost, proxyPort, ip);
+ //WriteOCSPResponse("test1.resp", resp);
+ //printf("sendOCSPRequest returned %d\n", err);
+ if(err == ERR_OK) {
+ if(caCerts && notaryCert) {
+ ddocDebug(1, "verifyCertificateByOCSPWithIp", "Verify OCSP resp with known CA certs");
+ // check the response signature
+ err = verifyOCSPResponse(resp, (const X509**)caCerts, NULL, notaryCert);
+ }
+ if(err == ERR_OK)
+ err = checkNonceAndCertbyOCSP(resp, pCert, nonce1, l1);
+ //WriteOCSPResponse("test1.resp", resp);
+ }
+ }
+ // free OCSP request, if allocated;
+ if (req)
+ OCSP_REQUEST_free(req);
+ // return OCSP response if required
+ if(ppResp)
+ *ppResp = resp;
+ else
+ OCSP_RESPONSE_free(resp);
+ return err;
+}
+
+//============================================================
+// Decodes binary (DER) cert data and returns a cert object
+// certData - binary (DER) cert data
+// certLen - cert data length
+//============================================================
+EXP_OPTION int ddocDecodeX509Data(X509 **ppX509, const byte* certData, int certLen)
+{
+ BIO* b1 = NULL;
+
+ // check input params
+ RETURN_IF_NULL_PARAM(certData);
+ RETURN_IF_NULL_PARAM(ppX509);
+ // mark as not read yet
+ *ppX509 = 0;
+ // create memory BIO on it
+ b1 = BIO_new_mem_buf((void*)certData, certLen);
+ RETURN_IF_NOT(b1, ERR_CERT_INVALID);
+ *ppX509 = d2i_X509_bio(b1, NULL);
+ ddocDebug(4, "ddocDecodeX509Data", "Decoding %d bytes DER data - cert %s", certLen, (*ppX509 ? "OK" : "ERROR"));
+ // cleanup
+ BIO_free(b1);
+ RETURN_IF_NOT(*ppX509, ERR_CERT_INVALID);
+ return ERR_OK;
+}
+
+//============================================================
+// Decodes base64 (PEM) cert data and returns a cert object
+// certData - base64 (PEM) cert data
+// certLen - cert data length
+//============================================================
+EXP_OPTION int ddocDecodeX509PEMData(X509 **ppX509, const char* certData, int certLen)
+{
+ byte* p1 = 0;
+ int l1 = 0, err = ERR_OK;
+
+ // check input params
+ RETURN_IF_NULL_PARAM(certData);
+ RETURN_IF_NULL_PARAM(ppX509);
+ // mark as not read yet
+ *ppX509 = 0;
+ // allocate memory for decoding
+ l1 = certLen; // should be enough as it shrinks
+ p1 = (byte*)malloc(l1);
+ RETURN_IF_BAD_ALLOC(p1);
+ memset(p1, 0, l1);
+ // decode base64 data
+ decode((const byte*)certData, certLen, p1, &l1);
+ // decode cert
+ err = ddocDecodeX509Data(ppX509, p1, l1);
+ ddocDebug(4, "ddocDecodeX509PEMData",
+ "Decoding %d bytes PEM data - cert %s", certLen, (*ppX509 ? "OK" : "ERROR"));
+ // cleanup
+ if(p1)
+ free(p1);
+ return err;
+}
+
+//============================================================
+// Checks if the cert is valid (between begin and end date)
+// cert - certificate object
+// tDate - date to check the cert
+//============================================================
+EXP_OPTION int isCertValid(X509* cert, time_t tDate)
+{
+ int err = ERR_OK;
+ ASN1_TIME *tm = 0;
+ time_t tStart, tEnd;
+
+ RETURN_IF_NULL_PARAM(cert);
+ tm = X509_get_notBefore(cert);
+ RETURN_IF_NULL(tm);
+ asn1time2time_t_local(tm, &tStart);
+ tm = X509_get_notAfter(cert);
+ RETURN_IF_NULL(tm);
+ asn1time2time_t_local(tm, &tEnd);
+ if(tDate < tStart || tDate > tEnd) {
+ err = ERR_CERT_INVALID;
+ SET_LAST_ERROR(err);
+ }
+ return err;
+}
+
+//============================================================
+// Retrieves the certificates first validity time as tim_t in GMT zone
+// pCert - certificate object
+// returns certificates first validity time as tim_t in GMT zone
+//============================================================
+EXP_OPTION time_t getCertNotBeforeTimeT(X509* pCert)
+{
+ time_t t1 = 0;
+ ASN1_TIME *tm = 0;
+
+ if(pCert) {
+ tm = X509_get_notBefore(pCert);
+ if(tm)
+ asn1time2time_t_local(tm, &t1);
+ }
+ return t1;
+}
+
+//============================================================
+// Retrieves the certificates last validity time as tim_t in GMT zone
+// pCert - certificate object
+// returns certificates last validity time as tim_t in GMT zone
+//============================================================
+EXP_OPTION time_t getCertNotAfterTimeT(X509* pCert)
+{
+ time_t t1 = 0;
+ ASN1_TIME *tm = 0;
+
+ if(pCert) {
+ tm = X509_get_notAfter(pCert);
+ if(tm)
+ asn1time2time_t_local(tm, &t1);
+ }
+ return t1;
+}
+
+//============================================================
+// Checks if the cert has been signed by this CA-cert
+// cert - certificate object
+// cafile - CA cert file
+//============================================================
+EXP_OPTION int isCertSignedBy(X509* cert, const char* cafile)
+{
+ int err = ERR_OK;
+ EVP_PKEY* pubkey = NULL; // SVEN - ver 1.92 - crashbug fixed
+
+ (void)ReadPublicKey(&pubkey, cafile);
+ RETURN_IF_NOT(pubkey, ERR_PUBKEY_READ);
+
+ err = X509_verify(cert, pubkey);
+ if(err == ERR_LIB_NONE)
+ err = ERR_OK;
+ else {
+ err = ERR_CERT_ISSUER;
+ SET_LAST_ERROR(err);
+ }
+ // checkErrors();
+ //332:error:0D0890A1:lib(13):func(137):reason(161):.\crypto\asn1\a_verify.c:141:
+ EVP_PKEY_free(pubkey);
+ return err;
+}
+
+//============================================================
+// Writes cert to file without the usual PEM headers
+// bout - output file
+// cert - certificate object
+// returns error code
+//============================================================
+int writeCertToXMLFile(BIO* bout, X509* cert)
+{
+ int l1, l2;
+ char *p1, *p2;
+
+ RETURN_IF_NULL_PARAM(bout);
+ RETURN_IF_NULL_PARAM(cert);
+ l1 = i2d_X509(cert, NULL);
+ p1 = (char*)malloc(l1+10);
+ RETURN_IF_BAD_ALLOC(p1);
+ p2 = p1;
+ i2d_X509(cert, (unsigned char**)&p2);
+ l2 = l1 * 2;
+ p2 = (char*)malloc(l2);
+ if (p2 == NULL) {
+ free(p1);
+ RETURN_IF_BAD_ALLOC(p2);
+ }
+ encode((const byte*)p1, l1, (byte*)p2, &l2);
+ BIO_puts(bout, p2);
+ free(p2);
+ free(p1);
+ return ERR_OK;
+}
+
+//============================================================
+// Converts the certificate to PEM form with or without headers
+// cert - certificate object
+// bHeaders - 1= with headers, 0=no headers
+// buf - output buffer newly allocated
+// returns error code
+//============================================================
+EXP_OPTION int getCertPEM(X509* cert, int bHeaders, char** buf)
+{
+ int l1, l2;
+ char *p1, *p2;
+
+ RETURN_IF_NULL_PARAM(buf);
+ RETURN_IF_NULL_PARAM(cert);
+ l1 = i2d_X509(cert, NULL);
+ p1 = (char*)malloc(l1+10);
+ RETURN_IF_BAD_ALLOC(p1);
+ p2 = p1;
+ i2d_X509(cert, (unsigned char**)&p2);
+ l2 = l1 * 2 + 200;
+ *buf = (char*)malloc(l2);
+ if(*buf == NULL) {
+ free(p1);
+ RETURN_IF_BAD_ALLOC(*buf);
+ }
+ memset(*buf, 0, l2);
+ if(bHeaders)
+ strncpy(*buf, "-----BEGIN CERTIFICATE-----\n", l2);
+ encode((const byte*)p1, l1, (byte*)strchr(*buf, 0), &l2);
+ l2 = l1 * 2 + 200 - strlen(*buf);
+ if(bHeaders)
+ strncat(*buf, "\n-----END CERTIFICATE-----", l2);
+ free(p1);
+ return ERR_OK;
+}
+
+
+
+//--------------------------------------------------
+// Returns the certificates validity first date
+// cert - certificate data
+// timestamp - timestamp buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getCertNotBefore(const SignedDoc* pSigDoc, X509* cert, char* timestamp, int len)
+{
+ int err = ERR_OK;
+ ASN1_TIME *tm = 0;
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(timestamp);
+
+ tm = X509_get_notBefore(cert);
+ RETURN_IF_NULL(tm);
+ err = asn1time2strYear(pSigDoc, tm, timestamp, 1900, len);
+
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+
+//--------------------------------------------------
+// Returns the certificates validity last date
+// cert - certificate data
+// timestamp - timestamp buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getCertNotAfter(const SignedDoc* pSigDoc, X509* cert, char* timestamp, int len)
+{
+ int err = ERR_OK;
+ ASN1_TIME *tm = 0;
+
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(timestamp);
+
+ tm = X509_get_notAfter(cert);
+ RETURN_IF_NULL(tm);
+ err = asn1time2strYear(pSigDoc, tm, timestamp, 1900, len);
+
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+
+//--------------------------------------------------
+// Saves the certificate in a file
+// cert - certificate data
+// szFileName - destination filename
+// nFormat - cert format
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int saveCert(X509* cert, const char* szFileName, int nFormat)
+{
+ // int err = ERR_OK;
+ BIO* b;
+
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(szFileName);
+
+ if((b = BIO_new_file(szFileName, "w")) != NULL) {
+ if(nFormat == FILE_FORMAT_PEM)
+ PEM_write_bio_X509(b, cert);
+ if(nFormat == FILE_FORMAT_ASN1)
+ i2d_X509_bio(b, cert);
+ BIO_free(b);
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_FILE_WRITE);
+ return ERR_OK;
+}
+
+// new functions for Win client
+
+EXP_OPTION void* decodeCert(const char* pemData)
+{
+ BIO* b1;
+ X509* x509;
+ int l1;
+
+ RETURN_OBJ_IF_NULL(pemData, NULL);
+ l1 = strlen(pemData);
+ b1 = BIO_new_mem_buf((void*)pemData, l1);
+ RETURN_OBJ_IF_NULL(b1, 0);
+ x509 = PEM_read_bio_X509(b1, NULL, NULL, 0);
+ if(!x509)
+ SET_LAST_ERROR(ERR_CERT_READ);
+ // checkErrors();
+ BIO_free(b1);
+ return x509;
+}
+
+
+
+
+//===========================================================
+// Encodes certificate from X509 to binary
+//===========================================================
+EXP_OPTION void encodeCert(const X509* x509, char * encodedCert, int* encodedCertLen)
+{
+ if(x509==NULL){
+ *encodedCertLen = 0;
+ return;
+ }
+ if(encodedCert==NULL){
+ *encodedCertLen = 0;
+ return;
+ }
+ *encodedCertLen = i2d_X509((X509*)x509, NULL);
+ i2d_X509((X509*)x509, (unsigned char**)&encodedCert);
+}
+
+//============================================================
+// Checks if the cert has been signed by this CA-cert
+// cert - certificate object
+// cafile - CA cert file
+//============================================================
+EXP_OPTION int isCertSignedByCERT(const X509* cert, const X509* caCert)
+{
+ int err = ERR_OK;
+ EVP_PKEY* pubkey;
+ DigiDocMemBuf mbuf1, mbuf2, mbuf3;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ mbuf3.pMem = 0;
+ mbuf3.nLen = 0;
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(caCert);
+ err = ddocCertGetSubjectCN((X509*)caCert, &mbuf1);
+ err = ddocCertGetSubjectCN((X509*)cert, &mbuf2);
+ err = ddocCertGetIssuerCN((X509*)cert, &mbuf3);
+ ddocDebug(3, "isCertSignedByCERT",
+ "Issuer: %s, Subject: %s, Subjects-issuer: %s",
+ (const char*)mbuf1.pMem, (const char*)mbuf2.pMem,
+ (const char*)mbuf3.pMem);
+ ddocMemBuf_free(&mbuf1);
+ ddocMemBuf_free(&mbuf2);
+ ddocMemBuf_free(&mbuf3);
+ err = GetPublicKey(&pubkey, caCert);
+ if(err == ERR_OK) {
+ err = X509_verify((X509*)cert, pubkey);
+ ddocDebug(3, "isCertSignedByCERT", "verify: %d", err);
+ if(err == ERR_LIB_NONE)
+ err = ERR_OK;
+ else
+ err = ERR_CERT_ISSUER;
+ if(err != ERR_OK) {
+ ddocDebug(3, "isCertSignedByCERT", "Cert not issued by ca verify: %d", err);
+ checkErrors();
+ }
+ EVP_PKEY_free(pubkey);
+ }
+ else
+ err = ERR_PUBKEY_READ;
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+
+/*int utc2latin1(const char* data, int len, char* dest)
+{
+ int i, j;
+
+ for(i = j = 0; i < len; i++) {
+ if(data[i]) {
+ dest[j] = data[i];
+ j++;
+ }
+ }
+ dest[j] = 0;
+ return j;
+ }*/
+
+//--------------------------------------------------------
+// Checks if the desired key-usage bit is set on a given cert
+// pCert - certificate
+// nBit - flag index
+// return 1 if bit is set
+//--------------------------------------------------------
+EXP_OPTION int ddocCertCheckKeyUsage(X509 *pCert, int nBit)
+{
+ int crit = -1, extIdx = -1;
+ ASN1_BIT_STRING *keyUsage;
+
+ if(pCert && nBit >= 0 && nBit < 8) {
+ keyUsage = (ASN1_BIT_STRING *)X509_get_ext_d2i(pCert, NID_key_usage, &crit, &extIdx);
+ if(keyUsage) {
+ ddocDebug(3, "ddocCertCheckKeyUsage", "Bit: %d set: %d", nBit, ASN1_BIT_STRING_get_bit(keyUsage, nBit));
+ return ASN1_BIT_STRING_get_bit(keyUsage, nBit);
+ }
+ }
+ return 0;
+}
+
+
+//--------------------------------------------------------
+// Finds and copies a substring from source string that is
+// prefixed by szLabel and terminated by szTerminator
+// szSrc - source string
+// szLabel - prefix of searched string
+// szTerminator - terminator string
+// szDest - found string. Caller must free this mem.
+//--------------------------------------------------------
+int ddocCertCopySubstring(const char* szSrc, const char* szLabel, const char* szTerminator, char** szDest)
+{
+ ptrdiff_t l;
+ char *p1, *p2;
+
+ RETURN_IF_NULL_PARAM(szSrc);
+ RETURN_IF_NULL_PARAM(szLabel);
+ RETURN_IF_NULL_PARAM(szTerminator);
+ RETURN_IF_NULL_PARAM(szDest);
+ *szDest = 0; // mark as empty
+ p1 = strstr(szSrc, szLabel);
+ if(p1) {
+ p1 += strlen(szLabel);
+ p2 = strstr(p1, szTerminator);
+ if(!p2)
+ p2 = strchr(p1, 0);
+ if(p2 && p2 > p1) {
+ l = p2 - p1 + 1;
+ *szDest = (char*)malloc(l);
+ if(*szDest) {
+ memset(*szDest, 0, l);
+ strncpy(*szDest, p1, p2 - p1);
+ }
+ }
+ }
+ return ERR_OK;
+}
+
+EXP_OPTION int readCertPoliciesFromOU(X509* pX509, PolicyIdentifier** pPolicies, int* nPols)
+{
+ DigiDocMemBuf mbuf1;
+ int err = ERR_OK;
+ char *pUri, *pDesc, *pOid;
+ PolicyIdentifier *pTmp;
+
+ RETURN_IF_NULL_PARAM(pX509);
+ RETURN_IF_NULL_PARAM(pPolicies);
+ RETURN_IF_NULL_PARAM(nPols);
+ mbuf1.nLen = 0;
+ mbuf1.pMem = 0;
+ pUri = pDesc = pOid = 0;
+ err = ddocCertGetSubjectOrganizationUnit(pX509, &mbuf1);
+ if(!err && mbuf1.pMem) {
+ err = ddocCertCopySubstring((const char*)mbuf1.pMem, "SP Desc:", "\n", &pDesc);
+ if(!err) {
+ err = ddocCertCopySubstring((const char*)mbuf1.pMem, "SP URI:", "\n", &pUri);
+ if(!err) {
+ err = ddocCertCopySubstring((const char*)mbuf1.pMem, "SP OID:", "\n", &pOid);
+ if(!err && (pDesc || pUri || pOid)) {
+ pTmp = (PolicyIdentifier*)realloc(*pPolicies, sizeof(PolicyIdentifier) * ((*nPols) + 1));
+ if(pTmp) {
+ *pPolicies = pTmp;
+ pTmp = (*pPolicies) + (*nPols);
+ *nPols = (*nPols) + 1;
+ pTmp->szOID = (pOid ? strdup((const char*)pOid) : 0);
+ pTmp->szUserNotice = (pDesc ? strdup((const char*)pDesc) : 0);
+ pTmp->szCPS = (pUri ? strdup((const char*)pUri) : 0);
+ }
+ }
+ free(pOid);
+ }
+ free(pUri);
+ }
+ free(pDesc);
+ }
+ ddocMemBuf_free(&mbuf1);
+ return err;
+}
+
+//--------------------------------------------------
+// Reads certificates PolicyIdentifiers and returns
+// them in a newly allocated structure. Caller must
+// free this, regardless of function return status.
+// pX509 - certificate
+// pPolicies - returned PolicyIdentifiers array
+// nPols - number of returned policies
+//--------------------------------------------------
+EXP_OPTION int readCertPolicies(X509* pX509, PolicyIdentifier** pPolicies, int* nPols)
+{
+ char buf[512], *p;
+ int err = 0, i, k, j, pos, l;
+ PolicyIdentifier *pPol, *pTmp;
+
+ RETURN_IF_NULL_PARAM(pX509);
+ RETURN_IF_NULL_PARAM(pPolicies);
+ RETURN_IF_NULL_PARAM(nPols);
+ *pPolicies = NULL;
+ *nPols = 0;
+ // try read from certificates OU first
+ if(!err)
+ err = readCertPoliciesFromOU(pX509, pPolicies, nPols);
+ // read from usual place
+ pos = X509_get_ext_by_NID(pX509, NID_certificate_policies, -1);
+ if(pos >= 0) {
+ POLICYINFO *pol;
+ STACK_OF(POLICYINFO)* pPols;
+ STACK_OF(POLICYQUALINFO)* pQuals;
+ POLICYQUALINFO* pQual;
+ X509_EXTENSION* pExt = X509_get_ext(pX509, pos);
+ // X509V3_EXT_METHOD *method = X509V3_EXT_get(pExt);
+ //pPols = (STACK*)X509V3_EXT_d2i(pExt);
+ pPols = X509V3_EXT_d2i(pExt);
+ for(i = 0; i < sk_POLICYINFO_num(pPols); i++) {
+ pol = sk_POLICYINFO_value(pPols, i);
+ if(*pPolicies && *nPols) {
+ pTmp = (PolicyIdentifier*)realloc(*pPolicies, sizeof(PolicyIdentifier) * ((*nPols) + 1));
+ if (pTmp != NULL) {
+ *pPolicies = pTmp;
+ *nPols = (*nPols) + 1;
+ pPol = (*pPolicies) + ((*nPols) - 1);
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ } else {
+ pTmp = (PolicyIdentifier*)malloc(sizeof(PolicyIdentifier));
+ if (pTmp != NULL) {
+ *pPolicies = pTmp;
+ pPol = *pPolicies;
+ *nPols = 1;
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ }
+ pPol->szCPS = pPol->szOID = pPol->szUserNotice = NULL;
+ // check
+ i2t_ASN1_OBJECT(buf, sizeof(buf), pol->policyid);
+ pPol->szOID = strdup(buf);
+ pQuals = pol->qualifiers;
+ for(k = 0; k < sk_POLICYQUALINFO_num(pQuals); k++) {
+ pQual = sk_POLICYQUALINFO_value(pQuals, k);
+ switch(OBJ_obj2nid(pQual->pqualid)) {
+ case NID_id_qt_cps:
+ pPol->szCPS = strdup((const char*)pQual->d.cpsuri->data);
+ // if strdup fails, szCPS will be NULL
+ break;
+ case NID_id_qt_unotice:
+ ddocDebug(4, "readCertPolicies", "Exptext: %d - \'%s\'",
+ pQual->d.usernotice->exptext->length, pQual->d.usernotice->exptext->data);
+ if(pQual->d.usernotice->exptext) {
+ if(pQual->d.usernotice->exptext->type == V_ASN1_UTF8STRING) {
+ pPol->szUserNotice = strdup((const char*)pQual->d.usernotice->exptext->data);
+ } else {
+ p = 0;
+ l = ASN1_STRING_to_UTF8((unsigned char**)&p, pQual->d.usernotice->exptext);
+ pPol->szUserNotice = strdup(p);
+ OPENSSL_free(p);
+ }
+ /*if(pQual->d.usernotice->exptext->data[0]) {
+ pPol->szUserNotice = strdup((const char*)pQual->d.usernotice->exptext->data);
+ } else {
+ utc2latin1((const char*)pQual->d.usernotice->exptext->data,
+ pQual->d.usernotice->exptext->length, buf);
+ pPol->szUserNotice = strdup(buf);
+ // if strdup fails, szUserNotice will be NULL
+ }*/
+ }
+ if(pQual->d.usernotice->noticeref) {
+ NOTICEREF *ref = pQual->d.usernotice->noticeref;
+ p = 0;
+ l = 0;
+ // calculate the memory required
+ l += strlen((const char*)ref->organization->data) + 1;
+ for(j = 0; j < sk_ASN1_INTEGER_num(ref->noticenos); j++) {
+ ASN1_INTEGER *num;
+ char *tmp;
+ num = sk_ASN1_INTEGER_value(ref->noticenos, j);
+ tmp = i2s_ASN1_INTEGER(NULL, num);
+ l += strlen(tmp) + 2;
+ OPENSSL_free(tmp);
+ }
+ // now alloc mem and copy data
+ l += 10; // alloc with a little extra
+ p = (char*)malloc(l);
+ if(p) {
+ memset(p, 0, l);
+ strncpy(p, (const char*)ref->organization->data, l);
+ strncat(p, " ", l - strlen(p));
+ for(j = 0; j < sk_ASN1_INTEGER_num(ref->noticenos); j++) {
+ ASN1_INTEGER *num;
+ char *tmp;
+ num = sk_ASN1_INTEGER_value(ref->noticenos, j);
+ if (j) strncat(p, ", ", l - strlen(p));
+ tmp = i2s_ASN1_INTEGER(NULL, num);
+ strncat(buf, tmp, sizeof(buf) - strlen(buf));
+ OPENSSL_free(tmp);
+ }
+ pPol->szUserNotice = p;
+ }
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ sk_POLICYINFO_pop_free(pPols, POLICYINFO_free);
+ }
+ ddocDebug(4, "readCertPolicies", "End");
+ return err;
+}
+
+
+
+//--------------------------------------------------
+// Frees policy identifiers array
+// pPolicies - PolicyIdentifiers array
+// nPols - number of policies
+//--------------------------------------------------
+EXP_OPTION void PolicyIdentifiers_free(PolicyIdentifier* pPolicies, int nPols)
+{
+ int i;
+ for(i = 0; i < nPols; i++) {
+ free(pPolicies[i].szOID);
+ free(pPolicies[i].szCPS);
+ free(pPolicies[i].szUserNotice);
+ //free(pPolicies[i]);
+ }
+ free(pPolicies);
+}
+
+//--------------------------------------------------
+// Reads certificates extension value
+// pCert - certificate
+// pMemBuf - memory buffer to return data
+// nExt - extension code
+//--------------------------------------------------
+EXP_OPTION int readCertExtData(X509* pCert, DigiDocMemBuf* pMemBuf, int nExt, int nOff)
+{
+ int err = ERR_OK, pos;
+ X509_EXTENSION* pExt;
+/* char buf1[300];
+ int l1;*/
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+ pos = X509_get_ext_by_NID(pCert, nExt, -1);
+ if(pos >= 0) {
+ pExt = X509_get_ext(pCert, pos);
+ if(pExt && pExt->value && pExt->value->data) {
+ /* memset(buf1, 0, sizeof(buf1));
+ l1 = sizeof(buf1);
+ bin2hex(pExt->value->data, pExt->value->length, buf1, &l1);
+ ddocDebug(3, "readCertExtData", "Ext: %d len: %d data: %s", nExt, pExt->value->length, buf1);*/
+ if(pExt->value->length > 20 && nOff)
+ //ddocMemAssignData(pMemBuf, ((char*)pExt->value->data) + (pExt->value->length - 20), 20);
+ ddocMemAssignData(pMemBuf, ((char*)pExt->value->data) + nOff, 20);
+ else
+ ddocMemAssignData(pMemBuf, ((char*)pExt->value->data), pExt->value->length);
+ }
+ }
+ return err;
+}
+
+//--------------------------------------------------
+// Reads certificates authority key identifier
+// pCert - certificate
+// pMemBuf - memory buffer to return data
+//--------------------------------------------------
+EXP_OPTION int readAuthorityKeyIdentifier(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ int err = ERR_OK;
+ int crit = 0, l1;
+ char *p = 0;
+
+ AUTHORITY_KEYID *pAkid = X509_get_ext_d2i(pCert, NID_authority_key_identifier, &crit, NULL);
+ if(pAkid) {
+ l1 = i2d_ASN1_OCTET_STRING(pAkid->keyid, (unsigned char **)&p);
+ if(l1 > 20)
+ ddocMemAssignData(pMemBuf, p + (l1 - 20), 20);
+ else
+ ddocMemAssignData(pMemBuf, (char*)p, l1);
+ OPENSSL_free(p);
+ AUTHORITY_KEYID_free(pAkid);
+ }
+ return err;
+ //return readCertExtData(pCert, pMemBuf, NID_authority_key_identifier, 5);
+}
+
+//--------------------------------------------------
+// Reads certificates subject key identifier
+// pCert - certificate
+// pMemBuf - memory buffer to return data
+//--------------------------------------------------
+EXP_OPTION int readSubjectKeyIdentifier(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return readCertExtData(pCert, pMemBuf, NID_subject_key_identifier, 2);
+}
+
+
+//--------------------------------------------------
+// Checks if this is a company CPS policy
+// pPolicy - PolicyIdentifier to be checked
+//--------------------------------------------------
+EXP_OPTION int isCompanyCPSPolicy(PolicyIdentifier* pPolicy)
+{
+ //return (strstr(pPolicy->szCPS, "1.3.6.4.1.10015.7") != NULL);
+ if(pPolicy && pPolicy->szCPS)
+ return (strstr(pPolicy->szCPS, "1.3.6.1.4.1.10015.5") != NULL);
+ else
+ return 0;
+}
+
+
+//--------------------------------------------------
+// Returns the certificates sha1 hash.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocCertGetDigest(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ int err = ERR_OK;
+ unsigned int l1;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+ l1 = 30;
+ err = ddocMemSetLength(pMemBuf, l1);
+ X509_digest(pCert, EVP_sha1(), (unsigned char*)pMemBuf->pMem, &l1);
+ pMemBuf->nLen = l1;
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates public key sha1 hash.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocCertGetPubkeyDigest(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ int err = ERR_OK;
+ unsigned int l1;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+ l1 = 30;
+ err = ddocMemSetLength(pMemBuf, l1);
+ X509_pubkey_digest(pCert, EVP_sha1(), (unsigned char*)pMemBuf->pMem, &l1);
+ pMemBuf->nLen = l1;
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates subject name sha1 hash.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocCertGetSubjectNameDigest(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ int err = ERR_OK;
+ unsigned int l1;
+ X509_NAME *iname;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+ l1 = 30;
+ err = ddocMemSetLength(pMemBuf, l1);
+ iname = X509_get_subject_name(pCert);
+ X509_NAME_digest(iname, EVP_sha1(), (unsigned char*)pMemBuf->pMem, &l1);
+ pMemBuf->nLen = l1;
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates issuer name sha1 hash.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocCertGetIssuerNameDigest(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ int err = ERR_OK;
+ unsigned int l1;
+ X509_NAME *iname;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+ l1 = 30;
+ err = ddocMemSetLength(pMemBuf, l1);
+ iname = X509_get_issuer_name(pCert);
+ X509_NAME_digest(iname, EVP_sha1(), (unsigned char*)pMemBuf->pMem, &l1);
+ pMemBuf->nLen = l1;
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates DN. Internal function.
+// Do not call directly, subject to change
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// bIssuer - 1=issuer, 0=subject
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocCertGetDN(X509* pCert, DigiDocMemBuf* pMemBuf, int bIssuer)
+{
+ int err = ERR_OK;
+ X509_NAME *pName = 0;
+ X509_NAME_ENTRY *pNe = 0;
+ int i, n, l, t, b = 0;
+ const char *s;
+ unsigned char* p;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+
+ // initialize
+ if(pMemBuf->pMem)
+ err = ddocMemBuf_free(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+
+ // iterate over name entries
+ if(bIssuer)
+ pName = X509_get_issuer_name(pCert);
+ else
+ pName = X509_get_subject_name(pCert);
+ RETURN_IF_NULL(pName)
+ for(i = 0; (err == ERR_OK) && (i < sk_X509_NAME_ENTRY_num(pName->entries)); i++) {
+ pNe = sk_X509_NAME_ENTRY_value(pName->entries, i);
+ n = OBJ_obj2nid(pNe->object);
+ s = OBJ_nid2sn(n);
+ t = pNe->value->type;
+ // mostly we find here:
+ // V_ASN1_PRINTABLESTRING, V_ASN1_TELETEXSTRING or V_ASN1_BMPSTRING
+ // that we convert to UTF, but V_ASN1_UTF8STRING allready is in UTF8
+ // handle only the enry types we know
+ if(n != NID_undef && s != NULL) {
+ // convert to UTF8 only
+ p = 0;
+ if(t == V_ASN1_UTF8STRING) {
+ p = pNe->value->data;
+ l = pNe->value->length;
+ } else
+ l = ASN1_STRING_to_UTF8(&p, pNe->value);
+ ddocDebug(5, "ddocCertGetDN",
+ "NameEntry nid: %d type: %d len: %d item: %s value: \'%s\'",
+ n, t, l, s, (p ? (const char*)p : "NULL"));
+ // append separator if necessary
+ if(b)
+ err = ddocMemAppendData(pMemBuf, ",", -1); // RFC2253 must use ,
+ else
+ b = 1;
+ // print the entry
+ err = ddocMemAppendData(pMemBuf, s, -1);
+ err = ddocMemAppendData(pMemBuf, "=", -1);
+ err = ddocMemAppendData(pMemBuf, (const char*)p, l);
+ // cleanup
+ if(p && t != V_ASN1_UTF8STRING)
+ OPENSSL_free(p);
+ }
+ ddocDebug(5, "ddocCertGetDN", "Subject: \'%s\' len: %d",
+ (const char*)pMemBuf->pMem, pMemBuf->nLen);
+ } // for
+
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates issuer name.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetIssuerDN(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDN(pCert, pMemBuf, 1);
+}
+
+
+//--------------------------------------------------
+// Returns the certificates subject name.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectDN(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDN(pCert, pMemBuf, 0);
+}
+
+//--------------------------------------------------
+// Returns the certificates DN.
+// Do not call directly, subject to change
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// bIssuer - 1=issuer, 0=subject
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetDNFromName(X509_NAME* pName, DigiDocMemBuf* pMemBuf)
+{
+ int err = ERR_OK;
+ X509_NAME_ENTRY *pNe = 0;
+ int i, n, l, t, b = 0;
+ const char *s;
+ unsigned char* p;
+
+ RETURN_IF_NULL_PARAM(pMemBuf);
+
+ // initialize
+ if(pMemBuf->pMem)
+ err = ddocMemBuf_free(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+
+ for(i = 0; (err == ERR_OK) && (i < sk_X509_NAME_ENTRY_num(pName->entries)); i++) {
+ pNe = sk_X509_NAME_ENTRY_value(pName->entries, i);
+ n = OBJ_obj2nid(pNe->object);
+ s = OBJ_nid2sn(n);
+ t = pNe->value->type;
+ // mostly we find here:
+ // V_ASN1_PRINTABLESTRING, V_ASN1_TELETEXSTRING or V_ASN1_BMPSTRING
+ // that we convert to UTF, but V_ASN1_UTF8STRING allready is in UTF8
+ // handle only the enry types we know
+ if(n != NID_undef && s != NULL) {
+ // convert to UTF8 only
+ p = 0;
+ if(t == V_ASN1_UTF8STRING) {
+ p = pNe->value->data;
+ l = pNe->value->length;
+ } else
+ l = ASN1_STRING_to_UTF8(&p, pNe->value);
+ ddocDebug(5, "ddocCertGetDN",
+ "NameEntry nid: %d type: %d len: %d item: %s value: \'%s\'",
+ n, t, l, s, (p ? (const char*)p : "NULL"));
+ // append separator if necessary
+ if(b)
+ err = ddocMemAppendData(pMemBuf, "/", -1);
+ else
+ b = 1;
+ // print the entry
+ err = ddocMemAppendData(pMemBuf, s, -1);
+ err = ddocMemAppendData(pMemBuf, "=", -1);
+ err = ddocMemAppendData(pMemBuf, (const char*)p, l);
+ // cleanup
+ if(p && t != V_ASN1_UTF8STRING)
+ OPENSSL_free(p);
+ }
+ ddocDebug(5, "ddocCertGetDN", "Subject: \'%s\' len: %d",
+ (const char*)pMemBuf->pMem, pMemBuf->nLen);
+ } // for
+
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates subject name and returns
+// the desired item from it.
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// nNid - cert name part NID
+// bIssuer - 1=from issuer DN, 0=from subject DN
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocCertGetDNPart(X509* pCert, DigiDocMemBuf* pMemBuf, int nNid, int bIssuer)
+{
+ int err = ERR_OK;
+ X509_NAME *pName = 0;
+ X509_NAME_ENTRY *pNe = 0;
+ int i, n, l, t, m, j;
+ const char *s;
+ unsigned char* p = 0;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+
+ // initialize
+ if(pMemBuf->pMem)
+ err = ddocMemBuf_free(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+
+ // iterate over name entries
+ if(bIssuer)
+ pName = X509_get_issuer_name(pCert);
+ else
+ pName = X509_get_subject_name(pCert);
+ for(i = 0; (err == ERR_OK) && (i < sk_X509_NAME_ENTRY_num(pName->entries)); i++) {
+ pNe = sk_X509_NAME_ENTRY_value(pName->entries, i);
+ n = OBJ_obj2nid(pNe->object);
+ s = OBJ_nid2sn(n);
+ t = pNe->value->type;
+ // mostly we find here:
+ // V_ASN1_PRINTABLESTRING, V_ASN1_TELETEXSTRING or V_ASN1_BMPSTRING
+ // that we convert to UTF, but V_ASN1_UTF8STRING allready is in UTF8
+ // handle only the enry types we know
+ if(n == nNid && s != NULL) {
+ // convert to UTF8 only
+ if(t == V_ASN1_UTF8STRING) {
+ p = pNe->value->data;
+ l = pNe->value->length;
+ } else
+ l = ASN1_STRING_to_UTF8(&p, pNe->value);
+ // test for 0x0
+ m = (p ? strlen(p) : 0);
+ if(m < l && p) {
+ for(j = 0; j < l; j++)
+ if(p[j] == 0)
+ p[j] = ' ';
+ }
+ ddocDebug(5, "ddocCertGetDNPart",
+ "NameEntry type: %d len: %d item: %s value: \'%s\'",
+ t, l, s, (p ? (const char*)p : "NULL"));
+ if(pMemBuf->pMem && strlen(pMemBuf->pMem))
+ ddocMemAppendData(pMemBuf, "\n", -1);
+ err = ddocMemAppendData(pMemBuf, (const char*)p, l);
+ // cleanup
+ if(p && t != V_ASN1_UTF8STRING)
+ OPENSSL_free(p);
+ // continue search
+ }
+ } // for
+
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates subject CN
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectCN(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_commonName, 0);
+}
+
+
+//--------------------------------------------------
+// Returns the certificates issuer CN
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetIssuerCN(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_commonName, 1);
+}
+
+
+//--------------------------------------------------
+// Returns the certificates subject first name
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectFirstName(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_firstName, 0);
+}
+
+
+//--------------------------------------------------
+// Returns the certificates subject last name
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectLastName(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_lastName, 0);
+}
+
+
+//--------------------------------------------------
+// Returns the certificates subject personal code
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectPerCode(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_perCode, 0);
+}
+
+//--------------------------------------------------
+// Returns the certificates subject country code
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectCountryName(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_countryName, 0);
+}
+
+//--------------------------------------------------
+// Returns the certificates subject organization
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectOrganization(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_organization, 0);
+}
+
+//--------------------------------------------------
+// Returns the certificates subject organization unit
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocCertGetSubjectOrganizationUnit(X509* pCert, DigiDocMemBuf* pMemBuf)
+{
+ return ddocCertGetDNPart(pCert, pMemBuf, NID_organizationUnit, 0);
+}
+
+//--------------------------------------------------
+// Returns the desired item from string rep of DN
+// sDn - certificate DN
+// sId - searched DN part
+// pMBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocGetDNPartFromString(const char* sDn, const char* sId, DigiDocMemBuf* pMBuf)
+{
+ int err = ERR_OK, j, l;
+ char *p0 = 0, *p1 = 0;
+ char buf1[30];
+
+ RETURN_IF_NULL_PARAM(sDn);
+ RETURN_IF_NULL_PARAM(sId);
+ RETURN_IF_NULL_PARAM(pMBuf);
+ // initialize
+ if(pMBuf->pMem)
+ err = ddocMemBuf_free(pMBuf);
+ pMBuf->pMem = 0;
+ pMBuf->nLen = 0;
+ memset(buf1, 0, sizeof(buf1));
+ snprintf(buf1, sizeof(buf1)-1, "%s=", sId);
+ p0 = strstr(sDn, buf1);
+ if(p0) {
+ p0 += strlen(buf1);
+ p1 = strchr(p0, ',');
+ if(p1) {
+ while(p1 && *(p1-1) == '\\')
+ p1 = strchr(p1, ',');
+ if(p1 && *p1 == ',') p1--;
+ } else {
+ p1 = strchr(p0, '/');
+ if(p1) {
+ while(p1 && *(p1-1) == '\\')
+ p1 = strchr(p1, '/');
+ if(p1 && *p1 == '/') p1--;
+ } else
+ p1 = (char*)sDn + strlen(sDn);
+ }
+ //
+ if(p0 && p1 && (int)(p1 - p0) > 0) {
+ l = (int)(p1 - p0) + 1;
+ ddocMemAppendData(pMBuf, (const char*)p0, l);
+ ((char*)pMBuf->pMem)[l] = 0;
+ }
+ }
+ return err;
+}
+
+//AM 06.03.08
+//--------------------------------------------------
+// Returns the certificates DN. Internal function.
+// Do not call directly, subject to change
+// pCert - certificate data
+// pMemBuf - memory buffer object for storing DN
+// bIssuer - 1=issuer, 0=subject
+// returns error code or ERR_OK
+//--------------------------------------------------
+int bdocCertGetDN(X509* pCert, DigiDocMemBuf* pMemBuf, int bIssuer)
+{
+ int err = ERR_OK;
+ X509_NAME *pName = 0;
+ X509_NAME_ENTRY *pNe = 0;
+ int i, n, l, t, b = 0;
+ const char *s;
+ unsigned char* p;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+
+ // initialize
+ if(pMemBuf->pMem)
+ err = ddocMemBuf_free(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+
+ // iterate over name entries
+ if(bIssuer)
+ pName = X509_get_issuer_name(pCert);
+ else
+ pName = X509_get_subject_name(pCert);
+ for(i = 0; (err == ERR_OK) && (i < sk_X509_NAME_ENTRY_num(pName->entries)); i++) {
+ pNe = sk_X509_NAME_ENTRY_value(pName->entries, i);
+ n = OBJ_obj2nid(pNe->object);
+ s = OBJ_nid2sn(n);
+ t = pNe->value->type;
+ // mostly we find here:
+ // V_ASN1_PRINTABLESTRING, V_ASN1_TELETEXSTRING or V_ASN1_BMPSTRING
+ // that we convert to UTF, but V_ASN1_UTF8STRING allready is in UTF8
+ // handle only the enry types we know
+ if(n != NID_undef && s != NULL) {
+ // convert to UTF8 only
+ p = 0;
+ if(t == V_ASN1_UTF8STRING) {
+ p = pNe->value->data;
+ l = pNe->value->length;
+ } else
+ l = ASN1_STRING_to_UTF8(&p, pNe->value);
+ ddocDebug(5, "ddocCertGetDN",
+ "NameEntry nid: %d type: %d len: %d item: %s value: \'%s\'",
+ n, t, l, s, (p ? (const char*)p : "NULL"));
+ // append separator if necessary
+ if(b)
+ err = ddocMemAppendData(pMemBuf, ",", -1);
+ else
+ b = 1;
+ // print the entry
+ err = ddocMemAppendData(pMemBuf, s, -1);
+ err = ddocMemAppendData(pMemBuf, "=", -1);
+ err = ddocMemAppendData(pMemBuf, (const char*)p, l);
+ // cleanup
+ if(p && t != V_ASN1_UTF8STRING)
+ OPENSSL_free(p);
+ }
+ ddocDebug(5, "ddocCertGetDN", "Subject: \'%s\' len: %d",
+ (const char*)pMemBuf->pMem, pMemBuf->nLen);
+ } // for
+
+ return err;
+}
+
+//================< deprecated functions> =================================
+
+#ifdef WITH_DEPRECATED_FUNCTIONS
+
+//============================================================
+// Decodes base64 (PEM) cert data and returns a cert object
+// certData - base64 (PEM) cert data
+// certLen - cert data length
+//============================================================
+// FIXME : Ugly as hell...
+#pragma message ("Function decodeCertificateData may be removed from future releases. Please use function ddocDecodeX509PEMData() instead.")
+EXP_OPTION int decodeCertificateData(X509 **newX509, const byte* certData, int certLen)
+{
+ int l1, l2;
+ char *buf1;
+ BIO* b1 = NULL;
+ X509* x509 = NULL;
+
+ RETURN_IF_NULL_PARAM(certData);
+
+ l2 = certLen * 2;
+ buf1 = (char*)malloc(l2);
+ RETURN_IF_BAD_ALLOC(buf1);
+ memset(buf1, 0, l2);
+ strncpy(buf1, "-----BEGIN CERTIFICATE-----\r\n", l2);
+ l1 = l2 - strlen(buf1);
+ encode(certData, certLen, (byte*)strchr(buf1,0), &l1);
+ l1 = l2 - strlen(buf1);
+ strncat(buf1, "\n-----END CERTIFICATE-----", l1);
+ l1 = strlen(buf1);
+ b1 = BIO_new_mem_buf(buf1, l1);
+ if (!b1) {
+ free(buf1);
+ SET_LAST_ERROR_RETURN_CODE(ERR_NULL_POINTER);
+ }
+ x509 = PEM_read_bio_X509(b1, NULL, NULL, 0);
+ BIO_free(b1);
+ free(buf1);
+ RETURN_IF_NOT(x509, ERR_CERT_INVALID);
+
+ *newX509 = x509;
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Returns the certificates issuer name
+// cert - certificate data
+// buf - usser name buffer
+// buflen - pointer to buffer length (will be modified)
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getCertIssuerName(X509* cert, char* buf, int* buflen)
+{
+ int l1;
+ char buf1[X509_NAME_BUF_LEN];
+
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(buf);
+ RETURN_IF_NULL_PARAM(buflen);
+
+ if(*buflen >= X509_NAME_LEN) {
+ l1 = sizeof(buf1);
+ memset(buf1,0,l1);
+ memset(buf, 0, *buflen);
+ X509_NAME_oneline(X509_get_issuer_name(cert), buf1, l1);
+ unicode2ascii(buf1, buf);
+ ddocDebug(5, "getCertIssuerName", "Issuer: \'%s\' -> \'%s\'", buf1, buf);
+ *buflen = strlen(buf);
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BUF_LEN);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Returns the certificates subject name. This finction
+// is also used in the COM library
+// cert - certificate data
+// buf - user name buffer
+// buflen - pointer to buffer length (will be modified)
+// returns error code or ERR_OK
+//--------------------------------------------------
+#pragma message ("Function getCertSubjectName may be removed from future releases. Please use function ddocCertGetSubjectDN() instead.")
+EXP_OPTION int getCertSubjectName(X509* cert, char* buf, int* buflen)
+{
+ int err = ERR_OK;
+ DigiDocMemBuf mbuf;
+
+ mbuf.pMem = 0;
+ mbuf.nLen = 0;
+ err = ddocCertGetSubjectDN(cert, &mbuf);
+ if(err == ERR_OK) {
+ if(*buflen >= X509_NAME_LEN) {
+#ifdef WIN32
+ utf82oem((const char*)mbuf.pMem, buf, buflen);
+#else
+ utf82ascii((const char*)mbuf.pMem, buf, buflen);
+#endif
+ *buflen = strlen(buf);
+ } else
+ SET_LAST_ERROR(ERR_BUF_LEN);
+ ddocMemBuf_free(&mbuf);
+ }
+
+ return err;
+}
+
+//--------------------------------------------------
+// Returns the certificates subjects DN
+// cert - certificate data
+// buf - usser name buffer
+// buflen - pointer to buffer length (will be modified)
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getCertSubjectDN(X509* cert, char* buf, int* buflen, int bUTF8)
+{
+ int l1;
+ char buf1[X509_NAME_BUF_LEN];
+
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(buf);
+ RETURN_IF_NULL_PARAM(buflen);
+ if(*buflen >= X509_NAME_LEN) {
+ l1 = sizeof(buf1);
+ memset(buf1, 0, l1);
+ memset(buf, 0, *buflen);
+ X509_NAME_oneline(X509_get_subject_name(cert), buf1, l1);
+ if (bUTF8) {
+ unicode2ascii(buf1, buf);
+ *buflen = strlen(buf);
+ } else {
+ ascii2utf8(buf1, buf, buflen);
+ }
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BUF_LEN);
+ return ERR_OK;
+}
+
+
+//--------------------------------------------------
+// Returns the certificates subjects name's CN part
+// cert - certificate data
+// buf - usser name buffer
+// buflen - pointer to buffer length (will be modified)
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getCertSubjectCN(X509* cert, char* buf, int* buflen, int bUTF8)
+{
+ int l1, err = ERR_OK;
+ char buf1[X509_NAME_BUF_LEN], *p , *p2, buf2[X509_NAME_BUF_LEN];
+
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(buf);
+ RETURN_IF_NULL_PARAM(buflen);
+
+ if(*buflen >= X509_NAME_LEN) {
+ l1 = sizeof(buf1);
+ memset(buf1,0,l1);
+ memset(buf, 0, *buflen);
+ err = getCertSubjectName(cert, buf1, &l1);
+ if(bUTF8 && hasUmlauts(buf1)) {
+ //printf("Converting umlauts toi UTF8\n");
+ l1 = sizeof(buf2);
+ ascii2utf8(buf1, buf2, &l1);
+ strncpy(buf1, buf2, sizeof(buf1));
+ ddocDebug(4, "getCertSubjectCN", "Subject: \'%s\'", buf1);
+ }
+ /*if (!bUTF8) {
+ l1 = sizeof(buf2);
+ utf82ascii(buf1, buf2, &l1);
+ //strcpy(buf1, buf2);
+ }*/
+ //printf("SUBJECT: %s\n", buf1);
+ p = strstr(buf1, "CN=");
+ if(p) {
+ p += 3;
+ p2 = strchr(p, '/');
+ if(!p2)
+ p2 = p + strlen(p);
+ if(p2) {
+ strncpy(buf, p, p2-p);
+ buf[p2-p] = 0;
+ }
+ }
+ *buflen = strlen(buf);
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BUF_LEN);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Returns the certificates issuer name's CN part
+// cert - certificate data
+// buf - usser name buffer
+// buflen - pointer to buffer length (will be modified)
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getCertIssuerCN(X509* cert, char* buf, int* buflen, int bUTF8)
+{
+ int l1;
+ char buf1[X509_NAME_BUF_LEN], *p , *p2, buf2[X509_NAME_BUF_LEN];
+
+ RETURN_IF_NULL_PARAM(cert);
+ RETURN_IF_NULL_PARAM(buf);
+ RETURN_IF_NULL_PARAM(buflen);
+
+ if(*buflen >= X509_NAME_LEN) {
+ l1 = sizeof(buf1);
+ memset(buf1,0,l1);
+ memset(buf, 0, *buflen);
+ X509_NAME_oneline(X509_get_issuer_name(cert), buf1, l1);
+ if (bUTF8) {
+ unicode2ascii(buf1, buf2);
+ } else {
+ l1 = sizeof(buf2);
+ ascii2utf8(buf1, buf2, &l1);
+ }
+ //printf("SUBJECT: %s\n", buf2);
+ p = strstr(buf2, "CN=");
+ if(p) {
+ p += 3;
+ p2 = strchr(p, '/');
+ if(!p2)
+ p2 = p + strlen(p);
+ if(p2) {
+ strncpy(buf, p, p2-p);
+ buf[p2-p] = 0;
+ }
+ }
+ *buflen = strlen(buf);
+ }
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BUF_LEN);
+ return ERR_OK;
+}
+
+// get cert owners id-code
+EXP_OPTION int getCertOwnerCode(const X509* pCert, char* buf, int len)
+{
+ int err, l1;
+ char buf1[500], *p;
+
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(buf);
+ l1 = sizeof(buf1);
+ err = getCertSubjectName((void*)pCert, buf1, &l1);
+ if (err != ERR_OK) SET_LAST_ERROR_RETURN_CODE(err);
+ err = ERR_CERT_READ;
+ p = strstr(buf1, "CN=");
+ if (p) {
+ p = strchr(p, ',');
+ if(p) {
+ p = strchr(p+1, ',');
+ if(p) {
+ strncpy(buf, p+1, 1en);
+ buf[1en] = 0;
+ err = ERR_OK;
+ }
+ } else { // no comma -> no id-code !
+ buf[0] = 0;
+ // is this really an error ?
+ err = ERR_WRONG_CERT;
+ }
+ }
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+
+#endif // WITH_DEPRECATED_FUNCTIONS
diff --git a/libdigidoc/DigiDocCert.h b/libdigidoc/DigiDocCert.h
new file mode 100644
index 0000000..4fd86ff
--- /dev/null
+++ b/libdigidoc/DigiDocCert.h
@@ -0,0 +1,364 @@
+#ifndef __DIGI_DOC_CERT_H__
+#define __DIGI_DOC_CERT_H__
+//==================================================
+// FILE: DigiDocCert.h
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for certificate handling
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.ode
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+//==================================================
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <openssl/evp.h>
+#include <openssl/objects.h>
+#include <openssl/x509.h>
+#include <openssl/x509v3.h>
+
+#include <libdigidoc/DigiDocDefs.h>
+#include <libdigidoc/DigiDocLib.h>
+
+// structure for reading certificate policies
+typedef struct PolicyIdentifier_st {
+ char* szOID; // stringified OID
+ char* szCPS; // CPS URL
+ char* szUserNotice; // user notice
+} PolicyIdentifier;
+
+
+EXP_OPTION int ReadPrivateKey(EVP_PKEY **privKey, const char *keyfile, const char* passwd, int format);
+EXP_OPTION int WritePrivateKey(EVP_PKEY *privKey, const char *keyfile, const char* passwd, int format);
+int ReadPublicKey(EVP_PKEY **pkey, const char *certfile);
+int GetPublicKey(EVP_PKEY **pubKey, const X509* x509);
+
+//--------------------------------------------------
+// Writes a private key and cert to a PEM file
+// privKey - private key
+// pCert - certificate
+// keyfile - name of the private key file
+// passwd - key password (problems with encrypted passwwords!)
+//--------------------------------------------------
+EXP_OPTION int ddocWriteKeyAndCertPem(EVP_PKEY *privKey, X509* pCert,
+ const char *keyfile, const char* passwd);
+
+
+EXP_OPTION int ReadCertificate(X509 **x509, const char *certfile);
+EXP_OPTION int ReadCertificateNoErr(X509 **x509, const char *szCertfile);
+EXP_OPTION int ReadCertSerialNumber(char* szSerial, int nMaxLen, X509 *x509);
+EXP_OPTION int ReadCertificateByPKCS12(X509 **x509, const char *pkcs12file, const char *passwd, EVP_PKEY **pkey);
+
+// Decodes binary (DER) cert data and returns a cert object
+EXP_OPTION int ddocDecodeX509Data(X509 **ppX509, const byte* certData, int certLen);
+
+// Decodes base64 (PEM) cert data and returns a cert object
+EXP_OPTION int ddocDecodeX509PEMData(X509 **ppX509, const char* certData, int certLen);
+
+// get certificate PEM form
+EXP_OPTION int getCertPEM(X509* cert, int bHeaders, char** buf);
+
+
+// retrieves this certificates serial number
+EXP_OPTION int GetCertSerialNumber(char* szSerial, int nMaxLen, const char *szCertfile);
+// Returns the certificates validity first date
+EXP_OPTION int getCertNotBefore(const SignedDoc* pSigDoc, X509* cert, char* timestamp, int len);
+
+// Retrieves the certificates first validity time as tim_t in GMT zone
+EXP_OPTION time_t getCertNotBeforeTimeT(X509* pCert);
+// Retrieves the certificates last validity time as tim_t in GMT zone
+EXP_OPTION time_t getCertNotAfterTimeT(X509* pCert);
+
+// Returns the certificates validity last date
+EXP_OPTION int getCertNotAfter(const SignedDoc* pSigDoc, X509* cert, char* timestamp, int len);
+// Saves the certificate in a file
+EXP_OPTION int saveCert(X509* cert, const char* szFileName, int nFormat);
+// decodes PEM cert data
+EXP_OPTION void* decodeCert(const char* pemData);
+// encodes certificate
+EXP_OPTION void encodeCert(const X509* x509, char * encodedCert, int* encodedCertLen);
+
+// Reads certificates PolicyIdentifiers and returns
+// them in a newly allocated structure
+EXP_OPTION int readCertPolicies(X509* pX509, PolicyIdentifier** pPolicies, int* nPols);
+
+// Frees policy identifiers array
+EXP_OPTION void PolicyIdentifiers_free(PolicyIdentifier* pPolicies, int nPols);
+
+// Checks if this is a company CPS policy
+EXP_OPTION int isCompanyCPSPolicy(PolicyIdentifier* pPolicy);
+
+EXP_OPTION int isCertValid(X509* cert, time_t tDate);
+EXP_OPTION int isCertSignedBy(X509* cert, const char* cafile);
+int writeCertToXMLFile(BIO* bout, X509* cert);
+
+//--------------------------------------------------
+// Verifys a certificate by sending an OCSP_REQUEST object
+// to the notary server and checking the response.
+// Uses servers timestamps hash code as nonce value.
+// pCert - certificate to test
+// caCerts - responder CA certs chain
+// notaryCert - notarys cert search
+// proxyHost - proxy servers name
+// proxyPort - proxy servers port
+// notaryURL - notarys URL
+// ppResp - address to return OCSP response. Use NULL if
+// you don't want OCSP response to be returned
+// return 0 for OK, or error code
+//--------------------------------------------------
+EXP_OPTION int verifyCertificateByOCSP(X509* pCert, const X509** caCerts,
+ const X509* notaryCert, char* notaryURL,
+ char* proxyHost, char* proxyPort,
+ const char* pkcs12file, const char* pkcs12paswd,
+ OCSP_RESPONSE **ppResp);
+
+//--------------------------------------------------
+// Verifys a certificate by sending an OCSP_REQUEST object
+// to the notary server and checking the response.
+// Uses servers timestamps hash code as nonce value.
+// pCert - certificate to test
+// caCerts - responder CA certs chain
+// notaryCert - notarys cert search
+// proxyHost - proxy servers name
+// proxyPort - proxy servers port
+// notaryURL - notarys URL
+// ppResp - address to return OCSP response. Use NULL if
+// you don't want OCSP response to be returned
+// return 0 for OK, or error code
+//--------------------------------------------------
+EXP_OPTION int verifyCertificateByOCSPWithIp(X509* pCert, const X509** caCerts,
+ const X509* notaryCert, char* notaryURL,
+ char* proxyHost, char* proxyPort,
+ const char* pkcs12file, const char* pkcs12paswd,
+ OCSP_RESPONSE **ppResp, unsigned long ip);
+
+ //--------------------------------------------------
+ // Returns the certificates sha1 hash.
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing DN
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ int ddocCertGetDigest(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates public key sha1 hash.
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing DN
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ int ddocCertGetPubkeyDigest(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates issuer name.
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing DN
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetIssuerDN(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject name.
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing DN
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectDN(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject name sha1 hash.
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing DN
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ int ddocCertGetSubjectNameDigest(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates issuer name sha1 hash.
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing DN
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ int ddocCertGetIssuerNameDigest(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates DN.
+ // Do not call directly, subject to change
+ // pName - certificate X509 name
+ // pMemBuf - memory buffer object for storing DN
+ // bIssuer - 1=issuer, 0=subject
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetDNFromName(X509_NAME* pName, DigiDocMemBuf* pMemBuf);
+
+#define KUIDX_DIGITAL_SIGNATURE 0
+#define KUIDX_NON_REPUDIATION 1
+#define KUIDX_KEY_ENCIPHERMENT 2
+#define KUIDX_DATA_ENCIPHERMENT 3
+#define KUIDX_KEY_AGREEMENT 4
+#define KUIDX_KEY_CERT_SIGN 5
+#define KUIDX_CRL_SIGN 6
+#define KUIDX_ENCIPHERMENT_ONLY 7
+#define KUIDX_DECIPHERMENT_ONLY 8
+
+#define NID_firstName 99
+#define NID_lastName 100
+#define NID_perCode 105
+#define NID_countryName 14
+#define NID_serialNumber 105
+#define NID_organization 17
+#define NID_organizationUnit 18
+#define NID_commonName 13
+#define NID_emailAddress 48
+
+
+ //--------------------------------------------------------
+ // Checks if the desired key-usage bit is set on a given cert
+ // pCert - certificate
+ // nBit - flag index
+ // return 1 if bit is set
+ //--------------------------------------------------------
+ EXP_OPTION int ddocCertCheckKeyUsage(X509 *pCert, int nBit);
+
+ //--------------------------------------------------
+ // Returns the certificates subject CN
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectCN(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates issuer CN
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetIssuerCN(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject first name
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectFirstName(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject last name
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectLastName(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject personal code
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectPerCode(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject country code
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectCountryName(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject organization
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectOrganization(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Returns the certificates subject organization unit
+ // pCert - certificate data
+ // pMemBuf - memory buffer object for storing result
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ EXP_OPTION int ddocCertGetSubjectOrganizationUnit(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Reads certificates authority key identifier
+ // pCert - certificate
+ // pMemBuf - memory buffer to return data
+ //--------------------------------------------------
+ EXP_OPTION int readAuthorityKeyIdentifier(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+ //--------------------------------------------------
+ // Reads certificates subject key identifier
+ // pCert - certificate
+ // pMemBuf - memory buffer to return data
+ //--------------------------------------------------
+ EXP_OPTION int readSubjectKeyIdentifier(X509* pCert, DigiDocMemBuf* pMemBuf);
+
+//================< deprecated functions> =================================
+// these functions are deprecated. Use the replacements in DigiDocCert.h
+// these functions will be removed in future releases!
+#ifdef WITH_DEPRECATED_FUNCTIONS
+
+// decodes cert data - deprecated!
+// USE ddocDecodeX509PEMData() instead!
+EXP_OPTION int decodeCertificateData(X509 **newX509, const byte* certData, int certLen);
+
+// Returns the certificates issuer name
+// USE: ddocCertGetIssuerDN()
+EXP_OPTION int getCertIssuerName(X509* cert, char* buf, int* buflen);
+
+// Returns the certificates subject name
+// USE: ddocCertGetSubjectDN()
+EXP_OPTION int getCertSubjectName(X509* cert, char* buf, int* buflen);
+
+
+// reads cert issuers CN
+// USE: ddocCertGetIssuerCN()
+EXP_OPTION int getCertIssuerCN(X509* cert, char* buf, int* buflen, int bUTF8);
+
+// Returns the certificates subjects DN
+// USE: ddocCertGetSubjectDN()
+EXP_OPTION int getCertSubjectDN(X509* cert, char* buf, int* buflen, int bUTF8);
+
+// reads cert subjects CN
+// USE: ddocCertGetSubjectCN()
+EXP_OPTION int getCertSubjectCN(X509* cert, char* buf, int* buflen, int bUTF8);
+
+// get certificate owners id-code
+// USE: ddocCertGetSubjectPerCode()
+EXP_OPTION int getCertOwnerCode(const X509* pCert, char* buf, int len);
+
+//--------------------------------------------------
+// Returns the desired item from string rep of DN
+// sDn - certificate DN
+// sId - searched DN part
+// pMBuf - memory buffer object for storing result
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocGetDNPartFromString(const char* sDn, const char* sId, DigiDocMemBuf* pMBuf);
+
+#endif // WITH_DEPRECATED_FUNCTIONS
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif // __DIGI_DOC_CERT_H__
+
diff --git a/libdigidoc/DigiDocConfig.c b/libdigidoc/DigiDocConfig.c
new file mode 100644
index 0000000..67db4d7
--- /dev/null
+++ b/libdigidoc/DigiDocConfig.c
@@ -0,0 +1,2211 @@
+//==================================================
+// FILE: DigiDocCfonfig.c
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for configuration management
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 17.06.2004 Fixed buffer overflow vulnerability in setPrivateConfigFile()
+// 27.03.2004 Fixed ConfigItem_lookup_bool()
+// 20.03.2004 Added functions createOrReplacePrivateConfigItem()
+// writeConfigFile(), writePrivateConfigFile()
+// 20.03.2004 changed function notarizeSignature to check for PKCS12 arguments
+// 10.02.2004 Integrated
+// 29.01.2004 changed function notarizeSignature
+// 26.01.2004 Added <Windows.h> include
+// 08.01.2004 Veiko Sinivee
+// Creation
+//==================================================
+
+// config data comes from there
+#include <config.h>
+
+//AA 04/01/26
+#ifdef WIN32
+#include <windows.h>
+#define snprintf _snprintf
+#elif defined(__APPLE__)
+#include <CoreFoundation/CoreFoundation.h>
+#endif
+
+#include "libdigidoc/DigiDocConfig.h"
+#include "libdigidoc/DigiDocPKCS11.h"
+#include "libdigidoc/DigiDocDebug.h"
+#include "libdigidoc/DigiDocCert.h"
+#include "libdigidoc/DigiDocObj.h"
+#include "libdigidoc/DigiDocOCSP.h"
+#include "libdigidoc/DigiDocConvert.h"
+#ifdef WIN32
+#include "libdigidoc/DigiDocCsp.h"
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <memory.h>
+#include <string.h>
+#include <ctype.h>
+
+#ifndef _MAX_PATH
+ #define _MAX_PATH 200
+#endif
+
+#ifdef WIN32
+ #define DIGIDOC_CONF_NAME "digidoc.ini"
+ #define HOME_ENV "USERPROFILE"
+ #define DIGIDOC_CONF_FMT "%s\\%s"
+ char g_szGlobalConfigFile[_MAX_PATH];
+#else
+ #define DIGIDOC_CONF_NAME "digidoc.conf"
+ #define HOME_ENV "HOME"
+ #define DIGIDOC_CONF_FMT "%s/.%s"
+ char g_szGlobalConfigFile[_MAX_PATH] = SYSCONFDIR "/" DIGIDOC_CONF_NAME;
+# ifdef FRAMEWORK
+ char g_frameworkResources[_MAX_PATH];
+# endif
+#endif
+
+char g_szPrivateConfigFile[_MAX_PATH];
+
+#define NUM_SEARCH_CAS 10
+
+//==========< private types and functions >====================
+
+
+// forward deklarations of private helper functions
+int ConfigItem_new(ConfigItem** pItem, const char* key, const char* value, int type, int status);
+void ConfigItem_free(ConfigItem* pItem);
+ConfigItem* ConfigItem_find(const char* key);
+
+int CertificateItem_new(CertificateItem** pItem, const char* key, X509* pCert);
+void CertificateItem_free(CertificateItem* pItem);
+CertificateItem* CertificateItem_find(const char* key);
+X509* Cert_find(const char* key);
+
+
+//==========< global variables >====================
+
+// currently I see the need only for one common configuration store
+// Distinction can be made by item type
+ConfigurationStore g_configStore = {0, 0, 0, 0};
+
+//==========< win32 specific functions >===================
+
+#ifdef WIN32
+
+
+//--------------------------------------------------
+// Retrieves a Windows registry key value
+// key - key name
+// buf - value buffer
+// len - value buffer length
+//--------------------------------------------------
+void getRegKey(const char* key, LPBYTE buf, DWORD* len)
+{
+ LONG rc;
+ HKEY hKey;
+
+ memset(buf, 0, *len);
+ rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(key),
+ 0, KEY_QUERY_VALUE, &hKey );
+ if(rc == ERROR_SUCCESS) {
+ rc = RegQueryValueEx(hKey, NULL, NULL, NULL, buf, len);
+ RegCloseKey( hKey );
+ if(rc == ERROR_SUCCESS) {
+ buf[*len] = 0;
+ } else {
+ buf[0] = 0;
+ }
+ }
+}
+
+//--------------------------------------------------
+// Retrieves a Windows registry key value. If the key
+// is not set then uses the default value and sets it
+// key - key name
+// buf - value buffer
+// len - value buffer length
+// defValue - default value
+//--------------------------------------------------
+void getOrSetRegKey(const char* key, LPBYTE buf, DWORD* len, const char* defValue)
+{
+ LONG rc;
+ HKEY hKey;
+
+ memset(buf, 0, *len);
+ rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(key),
+ 0, KEY_QUERY_VALUE, &hKey );
+ if(rc == ERROR_SUCCESS) {
+ rc = RegQueryValueEx(hKey, TEXT(""), NULL, NULL, buf, len);
+ RegCloseKey( hKey );
+ if(rc == ERROR_SUCCESS) {
+ buf[*len] = 0;
+ }
+ } else {
+ rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT(key),
+ 0, "", 0, KEY_READ | KEY_WRITE, 0, &hKey, 0);
+ if(rc == ERROR_SUCCESS) {
+ rc = RegSetValueEx(hKey, TEXT(""), 0, REG_SZ,
+ (const BYTE*)defValue, lstrlen(defValue));
+ RegCloseKey(hKey);
+ }
+ }
+}
+
+//--------------------------------------------------
+// Sets a Windows registry key value
+// key - key name
+// buf - value buffer
+// len - value buffer length
+//--------------------------------------------------
+void setRegKey(const char* key, LPBYTE buf, DWORD len)
+{
+ LONG rc;
+ HKEY hKey;
+
+ rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT(key),
+ 0, "", 0, KEY_READ | KEY_WRITE, 0, &hKey, 0);
+ if(rc == ERROR_SUCCESS) {
+ rc = RegSetValueEx(hKey, TEXT(""), 0, REG_SZ, buf, len);
+ RegCloseKey(hKey);
+ }
+}
+
+
+//--------------------------------------------------
+// Retrieves the number of subkeys Windows registry
+// key value.
+// returns number of subkeys
+//--------------------------------------------------
+int getNumSubKeys(const char* key)
+{
+ int n = 0;
+ HKEY hKey;
+ DWORD num;
+
+ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(key),
+ 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) {
+ if(RegQueryInfoKey(hKey, NULL, NULL, NULL, &num,
+ NULL, NULL, NULL, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)
+ n = (int)num;
+ RegCloseKey( hKey );
+ }
+ return n;
+}
+
+//--------------------------------------------------
+// Deletes a subkey from Windows registry
+// key - parent key
+// subkey - subkey to be deleted
+//--------------------------------------------------
+void deleteSubKey(const char* key, const char* subkey)
+{
+ HKEY hKey;
+
+ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(key),
+ 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS) {
+ RegDeleteKey(hKey, subkey);
+ RegCloseKey(hKey);
+ }
+}
+
+char* g_regDigiDocRoot = "SOFTWARE\\DigiDocLib";
+
+//--------------------------------------------------
+// Retrieves the digidoc librarys config items from registry
+// returns error coder or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int readConfigFromRegistry()
+{
+ HKEY hKey;
+ DWORD rc, l, i;
+ int err = 0;
+ char keyName[255], fullName[500];
+ char keyValue[3000];
+ FILETIME ft;
+
+ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(g_regDigiDocRoot),
+ 0, KEY_READ, &hKey ) != ERROR_SUCCESS )
+ return ERR_CONF_FILE;
+
+ i = 0;
+ do {
+ l = sizeof(keyName);
+ *keyName = 0;
+ rc = RegEnumKeyEx(hKey, i, keyName, &l, NULL, NULL, NULL, &ft);
+ if ( (rc == ERROR_SUCCESS) && *keyName ) {
+ l = sizeof(keyValue);
+ *keyValue = 0;
+ snprintf(fullName, sizeof(fullName), "%s\\%s", g_regDigiDocRoot, keyName);
+ getRegKey(fullName, (BYTE*)keyValue, &l);
+ if (*keyValue) {
+ ddocDebug(3, "readConfigFromRegistry", "Reg key: %s val: %s", (const char*)keyName, (const char*)keyValue);
+ err = addConfigItem(NULL, (const char*)keyName, (const char*)keyValue, ITEM_TYPE_PRIVATE, ITEM_STATUS_OK);
+ }
+ SET_LAST_ERROR_IF_NOT(err == ERR_OK, err);
+ }
+ i++;
+ } while ( (rc == ERROR_SUCCESS) && *keyName );
+ RegCloseKey(hKey);
+ return err;
+}
+
+#endif // WIN32
+
+//==========< item handling functions >====================
+
+//--------------------------------------------------
+// Returns true (not 0) if config store structure has been inited
+//--------------------------------------------------
+EXP_OPTION int isConfigInited()
+{
+ return g_configStore.pItems && g_configStore.nItems;
+}
+
+//--------------------------------------------------
+// Initializes configuration store
+// szConfigFile - name of config file. Use NULL for default
+//--------------------------------------------------
+EXP_OPTION int initConfigStore(const char* szConfigFile)
+{
+ int err = ERR_OK, at_least_one_conf = 0;
+
+ //g_configStore.nItems = 0;
+ //g_configStore.pItems = 0;
+ if (szConfigFile && checkFileExists(szConfigFile)) {
+ err = readConfigFile(szConfigFile, ITEM_TYPE_GLOBAL);
+ //printf("config file: %s rc: %d", szConfigFile, err);
+ return err;
+ }
+
+#ifdef WIN32
+ snprintf(g_szGlobalConfigFile, sizeof(g_szGlobalConfigFile), "%s\\%s", getenv("SystemRoot"), DIGIDOC_CONF_NAME);
+ /*if(!*g_szGlobalConfigFile && getenv("SystemRoot")) {
+ strncpy(g_szGlobalConfigFile, getenv("SystemRoot"), sizeof(g_szGlobalConfigFile));
+ printf("Init win32 2: %s\n", g_szGlobalConfigFile);
+ if(!g_szGlobalConfigFile[strlen(g_szGlobalConfigFile)-1] == '\\')
+ strncat(g_szGlobalConfigFile, "\\", sizeof(g_szGlobalConfigFile) - strlen(g_szGlobalConfigFile));
+ printf("Init win32 3: %s\n", g_szGlobalConfigFile);
+ strncat(g_szGlobalConfigFile, DIGIDOC_CONF_NAME, sizeof(g_szGlobalConfigFile) - strlen(g_szGlobalConfigFile));
+ }*/
+#endif
+#ifdef FRAMEWORK
+ CFStringRef identifier = CFStringCreateWithCString(0, "ee.ria.libdigidoc", kCFStringEncodingUTF8);
+ CFBundleRef bundle = CFBundleGetBundleWithIdentifier(identifier);
+ if(bundle)
+ {
+ CFURLRef url = CFBundleCopyResourcesDirectoryURL(bundle);
+ if(url)
+ {
+ if(CFURLGetFileSystemRepresentation(url, TRUE, (UInt8 *)g_frameworkResources, _MAX_PATH))
+ snprintf(g_szGlobalConfigFile, _MAX_PATH, "%s/%s", g_frameworkResources, DIGIDOC_CONF_NAME);
+ CFRelease(url);
+ }
+ CFRelease(bundle);
+ }
+ CFRelease(identifier);
+#endif
+ //printf( "Reading global config file: %s\n", g_szGlobalConfigFile);
+ ddocDebug(3, "initConfigStore", "Reading global config file: %s", g_szGlobalConfigFile);
+ if(checkFileExists(g_szGlobalConfigFile))
+ err = readConfigFile(g_szGlobalConfigFile, ITEM_TYPE_GLOBAL); // MEMLEAK: ???
+ if(err == ERR_CONF_FILE)
+ err = ERR_OK;
+ else
+ at_least_one_conf = 1;
+ if(err)
+ return err;
+
+ setPrivateConfigFile(NULL); // set default private conf file
+ if(g_szPrivateConfigFile[0]) {
+ //printf( "Reading private config file: %s\n", g_szPrivateConfigFile);
+ ddocDebug(3, "initConfigStore", "Reading private config file: %s", (g_szPrivateConfigFile ? g_szPrivateConfigFile : "NULL"));
+ if(checkFileExists(g_szPrivateConfigFile))
+ err = readConfigFile(g_szPrivateConfigFile, ITEM_TYPE_PRIVATE);
+ if(err == ERR_CONF_FILE)
+ err = ERR_OK;
+ else
+ at_least_one_conf = 1;
+ if(err)
+ return err;
+ }
+ if(DIGIDOC_CONF_NAME) {
+ //printf( "Reading config file: %s\n", DIGIDOC_CONF_NAME);
+ ddocDebug(2, "initConfigStore", "Reading config file: %s", (DIGIDOC_CONF_NAME ? DIGIDOC_CONF_NAME: "NULL"));
+ if(checkFileExists(DIGIDOC_CONF_NAME))
+ err = readConfigFile(DIGIDOC_CONF_NAME, ITEM_TYPE_PRIVATE);
+ if(err == ERR_CONF_FILE)
+ err = ERR_OK;
+ else
+ at_least_one_conf = 1;
+ if(err)
+ return err;
+ }
+#ifdef WIN32
+ err = readConfigFromRegistry();
+ if(err == ERR_CONF_FILE)
+ err = ERR_OK;
+ else
+ at_least_one_conf = 1;
+ if(err)
+ return err;
+#endif
+ // init certs
+ err = initCertificateItems();
+
+ if(!at_least_one_conf)
+ err = ERR_CONF_FILE;
+ return err;
+}
+
+
+//--------------------------------------------------
+// Cleans memory of configuration store
+// pConfStore - configuration collection (use NULL for default)
+//--------------------------------------------------
+EXP_OPTION void cleanupConfigStore(ConfigurationStore *pConfStore)
+{
+ int i;
+
+ if(!pConfStore)
+ pConfStore = &g_configStore;
+ for(i = 0; (i < pConfStore->nItems) && pConfStore->pItems && pConfStore->pItems[i]; i++)
+ ConfigItem_free(pConfStore->pItems[i]);
+ free(pConfStore->pItems);
+ pConfStore->pItems = 0;
+ pConfStore->nItems = 0;
+ for(i = 0; (i < pConfStore->nCerts) && pConfStore->pCerts && pConfStore->pCerts[i]; i++)
+ CertificateItem_free(pConfStore->pCerts[i]);
+ free(pConfStore->pCerts);
+ pConfStore->pCerts = 0;
+ pConfStore->nCerts = 0;
+}
+
+//--------------------------------------------------
+// Creates a new configration item
+// pItem - address of new pointer location
+// key - items key
+// value - items value
+// type - item type
+// status - item status
+// returns ERR_OK on success
+//--------------------------------------------------
+int ConfigItem_new(ConfigItem** pItem, const char* key, const char* value, int type, int status)
+{
+ RETURN_IF_NULL_PARAM(key);
+ RETURN_IF_NULL_PARAM(value);
+ RETURN_IF_NULL_PARAM(pItem);
+
+ if((*pItem = (ConfigItem*)malloc(sizeof(ConfigItem))) != NULL) {
+ (*pItem)->szKey = strdup(key);
+ (*pItem)->szValue = strdup(value);
+ (*pItem)->nType = type;
+ (*pItem)->nStatus = status;
+ if(!(*pItem)->szKey || !(*pItem)->szValue) {
+ ConfigItem_free(*pItem);
+ *pItem = NULL;
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ }
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Cleanup of config items memory
+// pItem - address of config item
+//--------------------------------------------------
+void ConfigItem_free(ConfigItem* pItem)
+{
+ if(pItem) {
+ if(pItem->szKey)
+ free(pItem->szKey);
+ if(pItem->szValue)
+ free(pItem->szValue);
+ free(pItem);
+ }
+}
+
+
+//--------------------------------------------------
+// Adds a new configration item
+// pConfStore - configuration collection (use NULL for default)
+// key - items key
+// value - items value
+// type - item type
+// status - item status
+// returns ERR_OK on success
+//--------------------------------------------------
+EXP_OPTION int addConfigItem(ConfigurationStore *pConfStore, const char* key, const char* value, int type, int status)
+{
+ int err = ERR_OK;
+ ConfigItem* pItem;
+ ConfigItem** pItems;
+
+ if(!pConfStore)
+ pConfStore = &g_configStore;
+ if((err = ConfigItem_new(&pItem, key, value, type, status)) == ERR_OK) {
+ if((pItems = (ConfigItem**)realloc(pConfStore->pItems,
+ sizeof(void*) * (pConfStore->nItems + 1))) != NULL) {
+ pItems[pConfStore->nItems] = pItem;
+ pConfStore->nItems++;
+ pConfStore->pItems = pItems;
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ } else
+ SET_LAST_ERROR_RETURN_CODE(err);
+ return ERR_OK;
+}
+
+
+//--------------------------------------------------
+// Creates a new cert item
+// pItem - address of new pointer location
+// key - items key
+// pCert - certificate
+// returns ERR_OK on success
+//--------------------------------------------------
+int CertificateItem_new(CertificateItem** pItem, const char* key, X509* pCert)
+{
+ RETURN_IF_NULL_PARAM(key);
+ RETURN_IF_NULL_PARAM(pCert);
+ RETURN_IF_NULL_PARAM(pItem);
+
+ if((*pItem = (CertificateItem*)malloc(sizeof(CertificateItem))) != NULL) {
+ (*pItem)->szKey = strdup(key);
+ (*pItem)->pCert = pCert; // take ownership !
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Cleanup of cert items memory
+// pItem - address of cert item
+//--------------------------------------------------
+void CertificateItem_free(CertificateItem* pItem)
+{
+ if(pItem) {
+ if(pItem->szKey)
+ free(pItem->szKey);
+ if(pItem->pCert)
+ X509_free(pItem->pCert);
+ free(pItem);
+ }
+}
+
+//--------------------------------------------------
+// Adds a new cert item
+// pConfStore - configuration collection (use NULL for default)
+// key - items key
+// pCert - certificate
+// returns ERR_OK on success
+//--------------------------------------------------
+EXP_OPTION int addCertificateItem(ConfigurationStore *pConfStore, const char* key, X509* pCert)
+{
+ int err = ERR_OK;
+ CertificateItem* pItem;
+ CertificateItem** pItems;
+
+ if(!pConfStore)
+ pConfStore = &g_configStore;
+ if((err = CertificateItem_new(&pItem, key, pCert)) == ERR_OK) {
+ if((pItems = (CertificateItem**)realloc(pConfStore->pCerts, sizeof(void*) * (pConfStore->nCerts + 1))) != NULL) {
+ pItems[pConfStore->nCerts] = pItem;
+ pConfStore->nCerts++;
+ pConfStore->pCerts = pItems;
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ } else
+ SET_LAST_ERROR_RETURN_CODE(err);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Finds a new cert item by key
+// key - items key
+// returns item pointer or NULL if not found
+//--------------------------------------------------
+CertificateItem* CertificateItem_find(const char* key)
+{
+ int i;
+
+ for(i = 0; (i < g_configStore.nCerts) && g_configStore.pCerts && g_configStore.pCerts[i]; i++) {
+ if(g_configStore.pCerts[i]->szKey && !strcmp(g_configStore.pCerts[i]->szKey, key))
+ return g_configStore.pCerts[i];
+ }
+ return NULL;
+}
+
+//--------------------------------------------------
+// Finds a cert by key
+// key - items key
+// returns X509 pointer or NULL if not found. Must be X509_free()-d because it will be duplicated here
+//--------------------------------------------------
+X509* Cert_find(const char* key)
+{
+ int i;
+ X509* pCert = 0;
+
+ for(i = 0; (i < g_configStore.nCerts) && g_configStore.pCerts && g_configStore.pCerts[i] && !pCert; i++) {
+ if(g_configStore.pCerts[i]->szKey && !strcmp(g_configStore.pCerts[i]->szKey, key))
+ pCert = g_configStore.pCerts[i]->pCert;
+ }
+ ddocDebug(3, "Cert_find", "%s cache %s", key, (pCert ? "OK" : "NULL"));
+ return X509_dup(pCert);
+}
+
+//--------------------------------------------------
+// Adds a new private configration item or modifies
+// an existing one
+// pConfStore - configuration collection (use NULL for default)
+// key - items key
+// value - items value
+// returns ERR_OK on success
+//--------------------------------------------------
+EXP_OPTION int createOrReplacePrivateConfigItem(ConfigurationStore *pConfStore, const char* key, const char* value)
+{
+ int err = ERR_OK, i;
+ ConfigItem* pItem = NULL;
+#ifdef WIN32
+ char keyName[500];
+#endif
+ ddocDebug(3, "createOrReplacePrivateConfigItem", "%s = %s", (key ? key : "NULL"), (value ? value : "NULL"));
+ if(!pConfStore)
+ pConfStore = &g_configStore;
+ // first try to find a private config item
+ for(i = 0; (i < pConfStore->nItems) && pConfStore->pItems && pConfStore->pItems[i]; i++) {
+ if(pConfStore->pItems[i]->szKey && !strcmp(pConfStore->pItems[i]->szKey, key) &&
+ pConfStore->pItems[i]->nType == ITEM_TYPE_PRIVATE) {
+ pItem = pConfStore->pItems[i];
+ break;
+ }
+ }
+ if(pItem) { // if found then modify it
+ if(pItem->szValue)
+ free(pItem->szValue);
+ pItem->szValue = (char*)malloc(strlen(value)+1);
+ if(pItem->szValue)
+ strncpy(pItem->szValue, value, strlen(value)+1);
+ else
+ SET_LAST_ERROR_RETURN_CODE(ERR_BAD_ALLOC);
+ pItem->nStatus = ITEM_STATUS_MODIFIED;
+ } else { // else create a new private config item
+ err = addConfigItem(pConfStore, key, value, ITEM_TYPE_PRIVATE, ITEM_STATUS_MODIFIED);
+ }
+#ifdef WIN32
+ snprintf(keyName, sizeof(keyName), "%s\\%s", g_regDigiDocRoot, key);
+ setRegKey(keyName, (BYTE*)value, (value ? (DWORD)strlen(value) : (DWORD)0));
+ if(pItem)
+ pItem->nStatus = ITEM_STATUS_OK;
+#endif
+ return err;
+}
+
+//--------------------------------------------------
+// Deletes configration item
+// key - items key
+// returns ERR_OK on success
+//--------------------------------------------------
+EXP_OPTION int ConfigItem_delete(const char* key)
+{
+ int err = ERR_OK, i, j;
+
+ // first try to find a private config item
+ for(i = j = 0; (i < g_configStore.nItems) && g_configStore.pItems && g_configStore.pItems[i]; i++) {
+ if(g_configStore.pItems[i]->szKey && !strcmp(g_configStore.pItems[i]->szKey, key) &&
+ g_configStore.pItems[i]->nType == ITEM_TYPE_PRIVATE) {
+ ConfigItem_free(g_configStore.pItems[i]);
+ g_configStore.pItems[i] = 0;
+ continue;
+ }
+ g_configStore.pItems[j] = g_configStore.pItems[i]; // no-op until moving the last items forward
+ j++;
+ }
+ g_configStore.nItems = j;
+#ifdef WIN32
+ deleteSubKey(g_regDigiDocRoot, key);
+#endif
+ return err;
+}
+
+
+//--------------------------------------------------
+// Finds a new configration item by key
+// key - items key
+// returns item pointer or NULL if not found
+//--------------------------------------------------
+ConfigItem* ConfigItem_find(const char* key)
+{
+ int i;
+
+ for(i = 0; (i < g_configStore.nItems) && g_configStore.pItems && g_configStore.pItems[i]; i++) {
+ if(g_configStore.pItems[i]->szKey && !strcmp(g_configStore.pItems[i]->szKey, key))
+ return g_configStore.pItems[i];
+ }
+ return NULL;
+}
+
+//--------------------------------------------------
+// Finds a all configration items that start with this prefix
+// prefix - item keys prefix
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ConfigItem_findByPrefix(ConfigurationStore *pConfStore, const char* prefix)
+{
+ int i, err = ERR_OK;
+
+ for(i = 0; (i < g_configStore.nItems) && g_configStore.pItems && g_configStore.pItems[i]; i++) {
+ if(g_configStore.pItems[i]->szKey && !strncmp(g_configStore.pItems[i]->szKey, prefix, strlen(prefix)))
+ err = addConfigItem(pConfStore, g_configStore.pItems[i]->szKey,
+ g_configStore.pItems[i]->szValue,
+ g_configStore.pItems[i]->nType,
+ g_configStore.pItems[i]->nStatus);
+ }
+ return err;
+}
+
+
+//--------------------------------------------------
+// Finds a new configration items value by key
+// key - items key
+// returns value of config item or NULL if not found
+//--------------------------------------------------
+EXP_OPTION const char* ConfigItem_lookup(const char* key)
+{
+#ifdef FRAMEWORK
+ if(strcmp(key, "CA_CERT_PATH") == 0)
+ return g_frameworkResources;
+#endif
+ int i;
+ // first try to find a private item
+ for(i = 0; (i < g_configStore.nItems) && g_configStore.pItems && g_configStore.pItems[i]; i++) {
+ if(g_configStore.pItems[i]->szKey && !strcmp(g_configStore.pItems[i]->szKey, key) &&
+ g_configStore.pItems[i]->nType == ITEM_TYPE_PRIVATE)
+ return g_configStore.pItems[i]->szValue;
+ } // if not found use any type of item with the given key
+ for(i = 0; (i < g_configStore.nItems) && g_configStore.pItems && g_configStore.pItems[i]; i++) {
+ if(g_configStore.pItems[i]->szKey && !strcmp(g_configStore.pItems[i]->szKey, key))
+ return g_configStore.pItems[i]->szValue;
+ }
+ return NULL;
+}
+
+//--------------------------------------------------
+// Finds a new configration items value by key from the store
+// key - items key
+// pConfStore - store to search in
+// returns value of config item or NULL if not found
+//--------------------------------------------------
+EXP_OPTION const char* ConfigItem_lookup_fromStore(ConfigurationStore *pConfStore, const char* key)
+{
+ int i;
+
+ for(i = 0; pConfStore && (i < pConfStore->nItems) &&
+ pConfStore->pItems && pConfStore->pItems[i]; i++) {
+ if(pConfStore->pItems[i]->szKey && !strcmp(pConfStore->pItems[i]->szKey, key))
+ return pConfStore->pItems[i]->szValue;
+ }
+ return NULL;
+}
+
+//--------------------------------------------------
+// Finds a numeric configration items value by key
+// key - items key
+// defValue - default value to be returned
+// returns value of config item or defValue if not found
+//--------------------------------------------------
+EXP_OPTION int ConfigItem_lookup_int(const char* key, int defValue)
+{
+ int rc = defValue;
+ const char* p = ConfigItem_lookup(key);
+ if (p)
+ rc = atoi(p);
+ return rc;
+}
+
+//--------------------------------------------------
+// Finds a new configration items value by key
+// key - items key
+// returns value of config item or NULL if not found
+//--------------------------------------------------
+EXP_OPTION const char* ConfigItem_lookup_str(const char* key, const char* defValue)
+{
+ const char* p = ConfigItem_lookup(key);
+ if (p)
+ return p;
+ else
+ return defValue;
+}
+
+//--------------------------------------------------
+// Finds a bolean configration items value by key
+// key - items key
+// defValue - default value to be returned
+// returns value of config item or defValue if not found
+//--------------------------------------------------
+EXP_OPTION int ConfigItem_lookup_bool(const char* key, int defValue)
+{
+ int rc = defValue;
+ const char* p = ConfigItem_lookup(key);
+ if(p)
+#ifdef WIN32
+ rc = (!stricmp(p, "true")) ? 1 : 0;
+#else
+ rc = (!strcasecmp(p, "TRUE")) ? 1 : 0;
+#endif
+ return rc;
+}
+
+
+//--------------------------------------------------
+// Reads and parses configuration file
+// fileName - configuration file name
+// type - type of config file global/private
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int readConfigFile(const char* fileName, int type)
+{
+ FILE* hFile;
+ char buf[5000];
+ char *p;
+ int err = ERR_OK;
+
+ if((hFile = fopen(fileName, "rt")) != NULL) {
+ ddocDebug(2, "readConfigFile", "Reading config file: %s", fileName);
+ while(fgets(buf, sizeof(buf), hFile) != NULL && !err) {
+ // trim line separators and spaces
+ while(strlen(buf) && (buf[strlen(buf)-1] == '\n' ||
+ buf[strlen(buf)-1] == '\r' ||
+ buf[strlen(buf)-1] == '\t' ||
+ buf[strlen(buf)-1] == ' '))
+ buf[strlen(buf)-1] = 0;
+ if(strlen(buf) && buf[0] != '#') {
+ if((p = strchr(buf, '=')) != NULL) {
+ *p = 0;
+ p++;
+ err = addConfigItem(NULL, (const char*)buf, (const char*)p, type, ITEM_STATUS_OK);
+ SET_LAST_ERROR_IF_NOT(err == ERR_OK, err);
+ //printf("CONF: %s = %s\n", buf, p);
+ }
+ }
+ }
+ fclose(hFile);
+ return err;
+ } else {
+ ddocDebug(1, "readConfigFile", "Error opening config file: %s", fileName);
+ SET_LAST_ERROR_RETURN_CODE(ERR_CONF_FILE); // MEMLEAK: ???
+ }
+}
+
+
+//--------------------------------------------------
+// Writes a configuration file
+// fileName - configuration file name
+// type - type of config file global/private
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int writeConfigFile(const char* fileName, int type)
+{
+ FILE* hFile;
+ //char buf[300];
+ //char *p;
+ int err = ERR_OK, i;
+
+ if((hFile = fopen(fileName, "wt")) != NULL) {
+ // first try to find a private item
+ for(i = 0; (i < g_configStore.nItems) &&
+ g_configStore.pItems && g_configStore.pItems[i]; i++) {
+ if(g_configStore.pItems[i]->nType == type) {
+ fprintf(hFile, "%s=%s\n", g_configStore.pItems[i]->szKey,
+ g_configStore.pItems[i]->szValue);
+ g_configStore.pItems[i]->nStatus = ITEM_STATUS_OK;
+ }
+ }
+ fclose(hFile);
+ return err;
+ } else
+ SET_LAST_ERROR_RETURN_CODE(ERR_CONF_FILE);
+}
+
+//--------------------------------------------------
+// Saves all private config items in correct file
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int writePrivateConfigFile()
+{
+#ifndef WIN32
+ return writeConfigFile(g_szPrivateConfigFile, ITEM_TYPE_PRIVATE);
+#else
+ return ERR_OK;
+#endif
+}
+
+//--------------------------------------------------
+// Sets a new name for private config file. Can be
+// used to override default of env(HOME)/.digidoc.conf
+// Use NULL to restore default value
+//--------------------------------------------------
+EXP_OPTION void setPrivateConfigFile(const char* fileName)
+{
+ if (fileName) {
+ strncpy( g_szPrivateConfigFile, fileName, sizeof(g_szPrivateConfigFile) );
+ } else { // use default
+ snprintf(g_szPrivateConfigFile, sizeof(g_szPrivateConfigFile)-1,
+ DIGIDOC_CONF_FMT, getenv(HOME_ENV), DIGIDOC_CONF_NAME);
+ }
+}
+
+//--------------------------------------------------
+// Finds CA certificates index by it's CN
+// idx - address if index
+// cn - CN of the CA
+// return -1 if not found or 0 for success
+//--------------------------------------------------
+int findCAindexByCN(int* idx, const char* cn)
+{
+ int i, n;
+ char buf1[100];
+ const char* p;
+
+ *idx = 0;
+ p = ConfigItem_lookup("CA_CERTS");
+ RETURN_IF_NOT(p != NULL, ERR_CONF_LINE);
+ n = atoi(p);
+ for(i = 1; (i <= n) && !(*idx); i++) {
+ snprintf(buf1, sizeof(buf1), "CA_CERT_%d_CN", i);
+ p = ConfigItem_lookup(buf1);
+ ddocDebug(1, "findCAindexByCN", "ERR112 Unknown CA: %s", buf1);
+ RETURN_IF_NOT(p != NULL, ERR_UNKNOWN_CA);
+ if(!strcmp(p, cn)) { // found it
+ *idx = i;
+ break;
+ }
+ }
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Finds Responder certificates index by it's CN
+// idx - address if index
+// cn - CN of the responder cert
+// hash - responder certs hash in base64 form
+// ca - responder CA CN
+// return error code or 0 for success
+//--------------------------------------------------
+int findResponderIndex(int* idx, const char* cn, const char* hash, const char* ca)
+{
+ int err = ERR_OK, i, n;
+ char buf1[100];
+ const char* p;
+
+ *idx = 0;
+ ddocDebug(3, "findResponderIndex", "Find CA: %s hash: %s ca-cn: %s", (cn ? cn : "NULL"),
+ (hash ? hash : "NULL"), (ca ? ca : "NULL"));
+ p = ConfigItem_lookup("DIGIDOC_OCSP_RESPONDER_CERTS");
+ RETURN_IF_NOT(p != NULL, ERR_CONF_LINE);
+ n = atoi(p);
+ for(i = 1; (i <= n) && !(*idx); i++) {
+ if(cn) {
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d_CN", i);
+ p = ConfigItem_lookup(buf1);
+ if(p && !strcmp(p, cn)) { // found it
+ *idx = i;
+ break;
+ }
+ }
+ else if(hash) {
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d_HASH", i);
+ p = ConfigItem_lookup(buf1);
+ if(p && !strcmp(p, hash)) { // found it
+ *idx = i;
+ break;
+ }
+ }
+ else if(ca) {
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d_CA", i);
+ p = ConfigItem_lookup(buf1);
+ if(p && !strcmp(p, ca)) { // found it
+ *idx = i;
+ break;
+ }
+ }
+ }
+ return err;
+}
+
+//--------------------------------------------------
+// Finds CA certificate by CN
+// ppCA - address of found CA
+// szCN - CA certs common name
+// pHash - authority-key-identifier to search for CA
+// return error code or 0 for success
+//--------------------------------------------------
+DIGIDOC_DEPRECATED EXP_OPTION int findCAForCN(X509** ppCA, const char* szCN, DigiDocMemBuf *pHash)
+{
+ return findCAForCNAndSigTime(ppCA, szCN, pHash, 0);
+}
+
+//--------------------------------------------------
+// Read ca and ocsp responder certs from files and cache in memory
+//--------------------------------------------------
+int initCertificateItems()
+{
+ int err = ERR_OK, i, n, e2, j;
+ const char *p1, *p2, *p3;
+ char buf2[300], buf1[50];
+ X509 *x509 = NULL;
+
+ // read CA certs
+ p1 = ConfigItem_lookup("CA_CERTS");
+ RETURN_IF_NOT(p1 != NULL, ERR_CONF_LINE);
+ p2 = ConfigItem_lookup("CA_CERT_PATH");
+ RETURN_IF_NOT(p2 != NULL, ERR_CONF_LINE);
+ ddocDebug(3, "initCertificateItems", "Init ca certs: %s ca-path: %s", p1, p2);
+ n = atoi(p1);
+ for(i = 1; i <= n; i++) {
+ snprintf(buf1, sizeof(buf1), "CA_CERT_%d_CN", i);
+ p1 = ConfigItem_lookup(buf1);
+ snprintf(buf1, sizeof(buf1), "CA_CERT_%d", i);
+ p3 = ConfigItem_lookup(buf1);
+ if(p1 && p3) {
+#ifdef WIN32
+ snprintf(buf2, sizeof(buf2), "%s\\%s", p2, p3);
+#else
+ snprintf(buf2, sizeof(buf2), "%s/%s", p2, p3);
+#endif
+ x509 = 0;
+ e2 = ReadCertificateNoErr(&x509, buf2);
+ if(x509) {
+ ddocDebug(3, "initCertificateItems", "CA Cert item: %d CN: %s file: %s", i, p1, p3);
+ addCertificateItem(&g_configStore, p1, x509); // release ownership on x509!
+ } else {
+ ddocDebug(1, "initCertificateItems", "Error: %d reading item: %d CN: %s file: %s", e2, i, p1, p3);
+ }
+ }
+ }
+ // read ocsp responder certs
+ p1 = ConfigItem_lookup("DIGIDOC_OCSP_RESPONDER_CERTS");
+ RETURN_IF_NOT(p1 != NULL, ERR_CONF_LINE);
+ ddocDebug(3, "initCertificateItems", "Init ocsp certs: %s ca-path: %s", p1, p2);
+ n = atoi(p1);
+ for(i = 1; i <= n; i++) {
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d_CN", i);
+ p1 = ConfigItem_lookup(buf1);
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d", i);
+ p3 = ConfigItem_lookup(buf1);
+ if(p1 && p3) {
+#ifdef WIN32
+ snprintf(buf2, sizeof(buf2), "%s\\%s", p2, p3);
+#else
+ snprintf(buf2, sizeof(buf2), "%s/%s", p2, p3);
+#endif
+ x509 = 0;
+ e2 = ReadCertificateNoErr(&x509, buf2);
+ if(x509) {
+ ddocDebug(3, "initCertificateItems", "OCSP Cert item: %d CN: %s file: %s", i, p1, p3);
+ addCertificateItem(&g_configStore, buf1, x509); // release ownership on x509!
+ } else {
+ ddocDebug(1, "initCertificateItems", "Error: %d reading item: %d CN: %s file: %s", e2, i, p1, p3);
+ }
+ }
+ for(j = 1; j < 10; j++) {
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d_%d", i, j);
+ p3 = ConfigItem_lookup(buf1);
+ if(p1 && p3) {
+#ifdef WIN32
+ snprintf(buf2, sizeof(buf2), "%s\\%s", p2, p3);
+#else
+ snprintf(buf2, sizeof(buf2), "%s/%s", p2, p3);
+#endif
+ x509 = 0;
+ e2 = ReadCertificateNoErr(&x509, buf2);
+ if(x509) {
+ ddocDebug(3, "initCertificateItems", "OCSP Cert item: %d CN: %s file: %s", i, p1, p3);
+ addCertificateItem(&g_configStore, buf1, x509); // release ownership on x509!
+ } else {
+ ddocDebug(1, "initCertificateItems", "Error: %d reading item: %d CN: %s file: %s", e2, i, p1, p3);
+ }
+ }
+ }
+ }
+
+ return err;
+}
+
+//--------------------------------------------------
+// Finds CA certificate by CN
+// ppCA - address of found CA
+// szCN - CA certs common name
+// pHash - authority-key-identifier to search for CA
+// tSigTime - signing time or 0
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int findCAForCNAndSigTime(X509** ppCA, const char* szCN, DigiDocMemBuf *pHash, time_t tSigTime)
+{
+ int err = ERR_OK, i, n;
+ char buf2[300], buf1[30], buf3[50];
+ const char *p1, *p2;
+ X509 *x509 = NULL;
+ DigiDocMemBuf mbuf2, mbuf3, mbuf1;
+ time_t tFrom = 0, tTo = 0;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ mbuf3.pMem = 0;
+ mbuf3.nLen = 0;
+ ddocEncodeBase64(pHash, &mbuf3);
+ ddocBin2Hex(pHash, &mbuf2);
+ ddocDebug(3, "findCAForCN", "Find CN: %s subj-hash: %s subj-hash-hex: %s sig-time: %ld", szCN, (char*)mbuf3.pMem, (char*)mbuf2.pMem, (unsigned long)tSigTime);
+ ddocMemBuf_free(&mbuf3);
+ ddocMemBuf_free(&mbuf2);
+ // initialize
+ *ppCA = NULL;
+ p1 = ConfigItem_lookup("CA_CERTS");
+ RETURN_IF_NOT(p1 != NULL, ERR_CONF_LINE);
+ n = atoi(p1);
+ for(i = 1; (i <= n) && !(*ppCA); i++) {
+ snprintf(buf1, sizeof(buf1), "CA_CERT_%d_CN", i);
+ p1 = ConfigItem_lookup(buf1);
+ x509 = NULL;
+ ddocDebug(3, "findCAForCN", "CA: %s -> %s", buf1, p1);
+ if(p1 && !strcmp(p1, szCN)) { // found CN, try read cert
+ snprintf(buf1, sizeof(buf1), "CA_CERT_%d", i);
+ p1 = ConfigItem_lookup(buf1);
+ if(p1) {
+ p2 = ConfigItem_lookup("CA_CERT_PATH");
+ RETURN_IF_NOT(p2 != NULL, ERR_CONF_LINE);
+#ifdef WIN32
+ snprintf(buf2, sizeof(buf2), "%s\\%s", p2, p1);
+#else
+ snprintf(buf2, sizeof(buf2), "%s/%s", p2, p1);
+#endif
+ // check cache first
+ x509 = Cert_find(szCN);
+ if(!x509)
+ err = ReadCertificate(&x509, buf2);
+ ddocDebug(4, "findCAForCN", "Read cert: %s rc: %d\n", buf2, err);
+ if(err == ERR_FILE_READ) err = ERR_UNKNOWN_CA;
+ if(pHash && pHash->pMem && x509) {
+ memset(buf3, 0, sizeof(buf3));
+ ReadCertSerialNumber(buf3, sizeof(buf3), x509);
+ readSubjectKeyIdentifier(x509, &mbuf2);
+ ddocEncodeBase64(&mbuf2, &mbuf3);
+ ddocBin2Hex(&mbuf2, &mbuf1);
+ tFrom = getCertNotBeforeTimeT(x509);
+ tTo = getCertNotAfterTimeT(x509);
+ if(!ddocMemCompareMemBufs(pHash, &mbuf2) &&
+ (!tSigTime || (tSigTime >= tFrom && tSigTime <= tTo))) {
+ *ppCA = x509;
+ err = ERR_OK;
+ ddocDebug(4, "findCAForCN", "Found cert: %s with nr: %s from: %ld to: %ld", szCN, buf3, tFrom, tTo);
+ } else {
+ ddocDebug(4, "findCAForCN", "Release cert: %s with nr: %s", szCN, buf3);
+ X509_free(x509); // release wrong cert
+ *ppCA = NULL;
+ err = ERR_UNKNOWN_CA;
+ }
+ ddocDebug(3, "findCAForCN", "Compare CA: %s subj-hash: %s hex: %s err: %d", buf1, (char*)mbuf3.pMem, (char*)mbuf1.pMem, err);
+ ddocMemBuf_free(&mbuf2);
+ ddocMemBuf_free(&mbuf3);
+ ddocMemBuf_free(&mbuf1);
+ } else { // plain CN match is enough
+ if(x509) {
+ *ppCA = x509;
+ err = ERR_OK;
+ ddocDebug(4, "findCAForCN", "Found cert: %s with cn", szCN);
+ }
+ }
+
+ } else {
+ ddocDebug(3, "findCAForCN", "No cert file for: %s", buf1);
+ }
+ }
+ }
+ RETURN_IF_NOT(err == ERR_OK, err);
+ //*ppCA = x509;
+ if(*ppCA) {
+ ddocCertGetSubjectDN(*ppCA, &mbuf2);
+ ddocDebug(4, "findCAForCN", "Found cert: %s with cn %s", (char*)mbuf2.pMem, szCN);
+ ddocMemBuf_free(&mbuf2);
+ }
+ return err;
+}
+
+
+//--------------------------------------------------
+// Finds Responders certificate by CN
+// ppResp - address of found cert
+// szCN - Responder certs common name
+// hash - responder certs hash in base64
+// nIdx - index of the certificate for this respnder. Starts at 0
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int findResponderByCNAndHashAndIndex(X509** ppResp, const char* szCN,
+ const char* hash, int nIdx)
+{
+ int err = ERR_OK, i;
+ char buf[300];
+ const char *p1, *p2;
+
+ RETURN_IF_NULL_PARAM(ppResp);
+ // initialize
+ *ppResp = NULL;
+ err = findResponderIndex(&i, szCN, hash, NULL);
+ ddocDebug(3, "findResponderByCNAndHashAndIndex", "CN: %s hash: %s resp-index: %d, cert-index: %d",
+ (szCN ? szCN : "NULL"), (hash ? hash : "NULL"), i, nIdx);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ // check cache first
+ *ppResp = Cert_find(szCN);
+ if(*ppResp) return ERR_OK;
+
+ // compose search key
+ if(!nIdx)
+ snprintf(buf, sizeof(buf), "DIGIDOC_OCSP_RESPONDER_CERT_%d", i);
+ else
+ snprintf(buf, sizeof(buf), "DIGIDOC_OCSP_RESPONDER_CERT_%d_%d", i, nIdx);
+ p1 = ConfigItem_lookup(buf);
+ ddocDebug(3, "findResponderByCNAndHashAndIndex", "Read cert key: %s file: %s", buf, (p1 ? p1 : "NULL"));
+ if(p1) {
+ if(checkFileExists(p1)) {
+ err = ReadCertificate(ppResp, p1);
+ } else {
+ p2 = ConfigItem_lookup("CA_CERT_PATH");
+ if(p2) {
+#ifdef WIN32
+ snprintf(buf, sizeof(buf), "%s\\%s", p2, p1);
+#else
+ snprintf(buf, sizeof(buf), "%s/%s", p2, p1);
+#endif
+ if(checkFileExists(buf))
+ err = ReadCertificate(ppResp, buf);
+ ddocDebug(3, "findResponderByCNAndHashAndIndex", "Read cert: %s rc: %d got: %s", buf, err, (*ppResp ? "OK" : "NULL"));
+ }
+ }
+ } // if p1
+ return err;
+}
+
+
+//--------------------------------------------------
+// Finds Responders certificate by CN
+// ppResp - address of found cert
+// szCN - Responder certs common name
+// hash - responder certs hash in base64 form
+// szCertSerial - specific serial number to search
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int findResponder(X509** ppResp, const char* szCN,
+ const char* szHash, char* szCertSerial)
+{
+ int err = ERR_OK, i, j;
+ char buf[300], szSerial[100];
+ const char *p1, *p2;
+ time_t t1, t2;
+ X509 *x509;
+
+ RETURN_IF_NULL_PARAM(ppResp);
+ // initialize
+ *ppResp = NULL;
+ err = findResponderIndex(&i, szCN, szHash, NULL);
+ ddocDebug(3, "findResponder", "CN: %s hash: %s index: %d, search notary: %s",
+ (szCN ? szCN : "NULL"), (szHash ? szHash : "NULL"), i,
+ (szCertSerial ? szCertSerial : "LATEST"));
+ RETURN_IF_NOT(err == ERR_OK, err);
+ j = 0;
+ t1 = t2 = 0;
+ do {
+ x509 = 0;
+ p1 = p2 = 0;
+ // compose search key
+ if(!j)
+ snprintf(buf, sizeof(buf), "DIGIDOC_OCSP_RESPONDER_CERT_%d", i);
+ else
+ snprintf(buf, sizeof(buf), "DIGIDOC_OCSP_RESPONDER_CERT_%d_%d", i, j);
+ p1 = ConfigItem_lookup(buf);
+ ddocDebug(3, "findResponder", "Read cert key: %s file: %s", buf, (p1 ? p1 : "NULL"));
+ if(p1) {
+ // check cache first
+ x509 = Cert_find(buf);
+ if(!x509) { // if not found in cache
+ if(checkFileExists(p1)) {
+
+ err = ReadCertificate(&x509, p1);
+ if(x509)
+ t2 = getCertNotAfterTimeT(x509);
+ ddocDebug(3, "findResponder", "Read cert: %s rc: %d not-after: %ld", p1, err, (unsigned long)t2);
+ } else {
+ p2 = ConfigItem_lookup("CA_CERT_PATH");
+ RETURN_IF_NOT(p2 != NULL, ERR_CONF_LINE);
+#ifdef WIN32
+ snprintf(buf, sizeof(buf), "%s\\%s", p2, p1);
+#else
+ snprintf(buf, sizeof(buf), "%s/%s", p2, p1);
+#endif
+ err = ReadCertificate(&x509, buf);
+ if(x509)
+ t2 = getCertNotAfterTimeT(x509);
+ ddocDebug(3, "findResponder", "Read cert: %s rc: %d not-after: %ld", buf, err, (unsigned long)t2);
+ } // else
+ } // !x509
+ if(!err && x509) { // if cert read successfully
+ if(szCertSerial) { // check for specific notary cert serial
+ szSerial[0] = 0;
+ ReadCertSerialNumber(szSerial, sizeof(szSerial), x509);
+ if(!strcmp(szSerial, szCertSerial)) {
+ *ppResp = x509;
+ ddocDebug(4, "findResponder", "assigning CA 1");
+ return ERR_OK;
+ }
+ }
+ if(!t1 || t2 > t1) { // first cert to check
+ t1 = t2;
+ ddocDebug(4, "findResponder", "assigning CA 2");
+ *ppResp = x509;
+ }
+ }
+ } // if p1
+ j++;
+ } while(x509 || j < 10); // until any potential cert found and I have tried to find one of the multiple certs
+ RETURN_IF_NOT(err == ERR_OK, ERR_CERT_READ);
+ ddocDebug(3, "findResponder", "CN: %s hash: %s index: %d, search notary: %s",
+ (szCN ? szCN : "NULL"), (szHash ? szHash : "NULL"), err, (*ppResp ? "OK" : "NULL"));
+ return err;
+}
+
+//--------------------------------------------------
+// Finds Responder certificates CA certs CN
+// caCN - buffer for responders CA CN
+// len - length of buffer for CA CN
+// szCN - responder certs common name
+// hash - responder certs hash in base64 form
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int findResponderCA(char* caCN, int len, const char* szCN, const char* hash)
+{
+ int err = ERR_OK, i=0;
+ char buf[50];
+ const char* p;
+
+ // initialize
+ RETURN_IF_NULL_PARAM(caCN);
+ caCN[0] = 0;
+ ddocDebug(3, "findResponderCA", "CA cn: %s, cn-l: %d", caCN, len);
+ err = findResponderIndex(&i, szCN, hash, NULL);
+ ddocDebug(3, "findResponderCA", "Resp idx: %d", i);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ snprintf(buf, sizeof(buf), "DIGIDOC_OCSP_RESPONDER_CERT_%d_CA", i);
+ p = ConfigItem_lookup(buf);
+ ddocDebug(3, "findResponderCA", "Lookup: %s found: %s len: %d", buf, p, len);
+ RETURN_IF_NOT(p != NULL, ERR_OCSP_RESP_NOT_TRUSTED);
+ strncpy(caCN, p, len);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Finds CA certificate of the given certificate
+// ppCA - address of found CA
+// pCert - certificate whose CA we are looking for
+// return error code or 0 for success
+// deprecated use findCAForCertificateAndSigTime()
+//--------------------------------------------------
+DIGIDOC_DEPRECATED EXP_OPTION int findCAForCertificate(X509** ppCA, const X509* pCert)
+{
+ return findCAForCertificateAndSigTime(ppCA, pCert, 0);
+}
+
+//--------------------------------------------------
+// Finds CA certificate of the given certificate
+// ppCA - address of found CA
+// pCert - certificate whose CA we are looking for
+// tSigTime - signature timestamp
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int findCAForCertificateAndSigTime(X509** ppCA, const X509* pCert, time_t tSigTime)
+{
+ int err = ERR_OK;
+ DigiDocMemBuf mbuf1, mbuf2;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ // read cert issuers CN
+ err = ddocCertGetIssuerCN((X509*)pCert, &mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, ERR_PKCS_CERT_DECODE);
+ RETURN_IF_NOT(mbuf1.pMem, ERR_PKCS_CERT_DECODE); // PR. fix crash
+ err = readAuthorityKeyIdentifier((X509*)pCert, &mbuf2);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ err = findCAForCNAndSigTime(ppCA, (const char*)mbuf1.pMem, &mbuf2, tSigTime);
+ ddocMemBuf_free(&mbuf1);
+ ddocMemBuf_free(&mbuf2);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ return err;
+}
+
+//--------------------------------------------------
+// Finds CA chain
+// ppChain - address of cert pointer array
+// nMaxChain - index of last cert in returned array - 0 based
+// szCN - CN of the first CA cert (not the child cert!)
+// pCert - certificate to search ca-s for
+// return error code or 0 for success
+// deprecated use findCAChainForCNAndSigTime()
+//--------------------------------------------------
+DIGIDOC_DEPRECATED EXP_OPTION int findCAChainForCN(X509** ppChain, int* nMaxChain, const char* szCN, X509* pCert)
+{
+ return findCAChainForCNAndSigTime(ppChain, nMaxChain, szCN, pCert, 0);
+}
+
+//--------------------------------------------------
+// Finds CA chain
+// ppChain - address of cert pointer array
+// nMaxChain - index of last cert in returned array - 0 based
+// szCN - CN of the first CA cert (not the child cert!)
+// pCert - certificate to search ca-s for
+// tSigTime - signature timestamp
+// return error code or 0 for success
+//--------------------------------------------------
+EXP_OPTION int findCAChainForCNAndSigTime(X509** ppChain, int* nMaxChain, const char* szCN, X509* pCert, time_t tSigTime)
+{
+ int err = ERR_OK, i;
+ char oldcn[300], buf3[100];
+ X509 * caCerts[NUM_SEARCH_CAS];
+ DigiDocMemBuf mbuf1, mbuf2, mbuf3;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ mbuf3.pMem = 0;
+ mbuf3.nLen = 0;
+ RETURN_IF_NULL_PARAM(ppChain);
+ RETURN_IF_NULL_PARAM(nMaxChain);
+ RETURN_IF_NULL_PARAM(szCN);
+ // initialize
+ for(i = 0; i < NUM_SEARCH_CAS; i++)
+ caCerts[i] = 0;
+ for(i = 0; i < NUM_SEARCH_CAS; i++)
+ ppChain[i] = NULL;
+ i = 0;
+ memset(oldcn, 0, sizeof(oldcn));
+ strncpy(oldcn, szCN, sizeof(oldcn));
+ *nMaxChain = -1;
+ if(pCert != NULL) {
+ err = readAuthorityKeyIdentifier(pCert, &mbuf2);
+ ddocEncodeBase64(&mbuf2, &mbuf3);
+ memset(buf3, 0, sizeof(buf3));
+ ReadCertSerialNumber(buf3, sizeof(buf3), pCert);
+ ddocDebug(3, "findCAChainForCN", "Subj cert nr: %s, auth-key: %s", buf3, (char*)mbuf3.pMem);
+ ddocMemBuf_free(&mbuf3);
+ }
+ do {
+ if(caCerts[i]) { // for first ca it is null
+ err = readAuthorityKeyIdentifier(caCerts[i], &mbuf2);
+ ddocEncodeBase64(&mbuf2, &mbuf3);
+ ddocDebug(3, "findCAChainForCN", "CA cert: %d, auth-key: %s", i, (char*)mbuf3.pMem);
+ ddocMemBuf_free(&mbuf3);
+ if(err)
+ return err;
+ }
+ err = findCAForCNAndSigTime(&caCerts[i], oldcn, &mbuf2, tSigTime);
+ ddocMemBuf_free(&mbuf2);
+ ddocDebug(3, "findCAChainForCN", "Read CA for CN: %s idx: %d rc: %d", oldcn, i, err);
+ SET_LAST_ERROR_IF_NOT(err == ERR_OK, err);
+ if (caCerts[i] && !err) {
+ err = ddocCertGetIssuerCN(caCerts[i], &mbuf1);
+ ddocDebug(3, "findCAChainForCN", "Issuer: %s old was: %s, rc: %d",
+ (const char*)mbuf1.pMem, oldcn, err);
+ SET_LAST_ERROR_IF_NOT(err == ERR_OK, err);
+ }
+ if(caCerts[i] && !err && mbuf1.pMem && !strcmp((const char*)mbuf1.pMem, oldcn) && i == 0) {
+ ppChain[0] = caCerts[0];
+ *nMaxChain = 0;
+ return err;
+ } else
+ if(!err && mbuf1.pMem && strcmp((const char*)mbuf1.pMem, oldcn)) {
+ i++;
+ if(!err)
+ strncpy(oldcn, (const char*)mbuf1.pMem, sizeof(oldcn) );
+ ddocMemBuf_free(&mbuf1);
+ } else {
+ ddocMemBuf_free(&mbuf1);
+ break;
+ }
+ } while (err == ERR_OK);
+ *nMaxChain = i;
+ ddocDebug(3, "findCAChainForCN", "Found: %d certs", (*nMaxChain) + 1);
+ // now reverse the chain such that the root CA is at the top - is it necessary??? // PR fix index
+ for(i = 0; i <= *nMaxChain; i++)
+ ppChain[i] = caCerts[(*nMaxChain) - i];
+ return err;
+}
+
+//------------------------------------------
+// Get a notary confirmation for signature
+// pSigDoc - signed document pointer
+// pSigInfo - signature to notarize
+// returns error code
+//------------------------------------------
+EXP_OPTION int notarizeSignature(SignedDoc* pSigDoc, SignatureInfo* pSigInfo)
+{
+ return notarizeSignatureWithIp(pSigDoc, pSigInfo, 0);
+}
+
+//------------------------------------------
+// Selects correct OCSP URL for this certificate
+// issuerDN - certificate issuer DN
+// ppOcspUrl - returned OCSP url or NULL if not found
+// returns error code or ERR_OK
+//------------------------------------------
+int ddocSelectOcspUrl(char* issuerDN, char** ppOcspUrl)
+{
+ int err = ERR_OK, i;
+ char buf1[100], *p;
+
+ RETURN_IF_NULL_PARAM(ppOcspUrl);
+ // get default OCSP URL
+ *ppOcspUrl = (char*)ConfigItem_lookup("DIGIDOC_OCSP_URL");
+ // if possible find OCSP URL by signers CA
+ ddocDebug(3, "ddocSelectOcspUrl", "signers CA: %s", (issuerDN ? issuerDN : "NULL"));
+ if(issuerDN) {
+ buf1[0] = 0;
+ findCN(issuerDN, buf1, sizeof(buf1));
+ ddocDebug(3, "ddocSelectOcspUrl", "signers CA CN: %s", buf1);
+ findResponderIndex(&i, NULL, NULL, buf1);
+ if(i > 0) {
+ snprintf(buf1, sizeof(buf1), "DIGIDOC_OCSP_RESPONDER_CERT_%d_URL", i);
+ p = (char*)ConfigItem_lookup(buf1);
+ if(p) {
+ *ppOcspUrl = p;
+ ddocDebug(3, "ddocSelectOcspUrl", "Selected OCSP URL: %s", p);
+ }
+ }
+ buf1[0] = 0;
+ }
+ if(!(*ppOcspUrl)) {
+ ddocDebug(1, "ddocSelectOcspUrl", "ERR112 ocsp url: %s", (*ppOcspUrl ? *ppOcspUrl : "NULL"));
+ SET_LAST_ERROR(ERR_UNKNOWN_CA);
+ err = ERR_UNKNOWN_CA;
+ } else {
+ ddocDebug(3, "ddocSelectOcspUrl", "Selected OCSP URL: %s", *ppOcspUrl);
+ }
+ return err;
+}
+
+int ddocFindCaChainForCert(X509* pCert,
+ X509** caCerts, int *nCerts,
+ char* szCA, int caLen)
+{
+ int err = ERR_OK, i;
+ DigiDocMemBuf mbuf1, mbuf2;
+
+ RETURN_IF_NULL_PARAM(caCerts);
+ RETURN_IF_NULL_PARAM(nCerts);
+ RETURN_IF_NULL_PARAM(szCA);
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ for(i = 0; i < NUM_SEARCH_CAS; i++)
+ caCerts[i] = 0;
+ szCA[0] = 0;
+ err = ddocCertGetIssuerDN(pCert, &mbuf1);
+ err = ddocCertGetSubjectDN(pCert, &mbuf2);
+ ddocDebug(3, "ddocFindCaChainForCert", "Find chain for: %s issuer: %s",
+ (char*)mbuf2.pMem, (char*)mbuf1.pMem);
+ if(!err) {
+ err = findCN((char*)mbuf1.pMem, szCA, caLen);
+ ddocDebug(3, "ddocFindCaChainForCert", "Find chain for CN: %s", szCA);
+ if(!err) {
+ err = findCAChainForCNAndSigTime(caCerts, nCerts, szCA, pCert, 0);
+ ddocDebug(3, "ddocFindCaChainForCert", "Chain length: %d, err: %d", *nCerts, err);
+ }
+ }
+ ddocMemBuf_free(&mbuf1);
+ ddocMemBuf_free(&mbuf2);
+ return err;
+}
+
+int ddocFindOcspCnCaAndCerts(OCSP_RESPONSE* pResp, int *nType,
+ X509** caCerts, int *nCerts,
+ char* szCN, int cnLen,
+ char* szCA, int caLen)
+{
+ int err = ERR_OK, i;
+ DigiDocMemBuf mbuf1;
+
+ RETURN_IF_NULL_PARAM(pResp);
+ RETURN_IF_NULL_PARAM(nType);
+ RETURN_IF_NULL_PARAM(caCerts);
+ RETURN_IF_NULL_PARAM(nCerts);
+ RETURN_IF_NULL_PARAM(szCN);
+ RETURN_IF_NULL_PARAM(szCA);
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ for(i = 0; i <= NUM_SEARCH_CAS; i++)
+ caCerts[i] = 0;
+ szCN[0] = szCA[0] = 0;
+ // find responder id type and value
+ ddocDebug(3, "ddocFindOcspCnCaAndCerts", "OCSP: %s", (pResp ? "OK" : "NO"));
+ err = ddocGetOcspRespIdTypeAndValue(pResp, nType, &mbuf1);
+ if((*nType) == RESPID_NAME_TYPE) {
+ err = findCN((char*)mbuf1.pMem, szCN, cnLen);
+ if (!err)
+ err = findResponderCA(szCA, caLen, szCN, NULL);
+ }
+ else if((*nType) == RESPID_KEY_TYPE) {
+ i = sizeof(szCN);
+ encode((const byte*)mbuf1.pMem, mbuf1.nLen, (byte*)szCN, &i);
+ if (!err)
+ err = findResponderCA(szCA, caLen, NULL, szCN);
+ }
+ else {
+ SET_LAST_ERROR(ERR_OCSP_WRONG_RESPID);
+ err = ERR_OCSP_WRONG_RESPID;
+ }
+ ddocDebug(3, "ddocFindOcspCnCaAndCerts", "Responder CN: %s CA: %s, RC: %d", szCN, szCA, err);
+ // find CA chain
+ if(err == ERR_OK)
+ err = findCAChainForCNAndSigTime(caCerts, nCerts, szCA, NULL, 0);
+ ddocDebug(3, "ddocFindOcspCnCaAndCerts", "Chain length: %d, err: %d", *nCerts, err);
+ // cleanup
+ ddocMemBuf_free(&mbuf1);
+ return err;
+}
+
+//------------------------------------------
+// Get a notary confirmation for signature
+// pSigDoc - signed document pointer
+// pSigInfo - signature to notarize
+// ip - callers ip address if known
+// returns error code
+//------------------------------------------
+EXP_OPTION int notarizeSignatureWithIp(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, unsigned long ip)
+{
+ NotaryInfo* pNotInfo;
+ int err = ERR_OK, nCAs = NUM_SEARCH_CAS, i, j, err2 = 0, nType;
+ X509* caCerts[NUM_SEARCH_CAS+1];
+ X509* pNotCert, *pSigCert = 0, *pSigCa = 0;
+ //AM 24.09.08 szCA size from 30 to 100 for Portuguese ID card
+ char szCN[200], szCA[100];
+ char *pkcs12file, *pkcs12passwd, *ocspUrl;
+ char *proxyHost, *proxyPort, *proxyUser, *proxyPass;
+ OCSP_RESPONSE *pResp = 0;
+ CertValue *pCertValue = 0;
+
+ // PR. index fix
+ for(i = 0; i < NUM_SEARCH_CAS; i++)
+ caCerts[i] = 0;
+ if(ConfigItem_lookup_bool("SIGN_OCSP", 1)) {
+ pkcs12file = (char*)ConfigItem_lookup("DIGIDOC_PKCS_FILE");
+ RETURN_IF_NOT(pkcs12file, ERR_OCSP_PKCS12_NO_FILE);
+ pkcs12passwd = (char*)ConfigItem_lookup("DIGIDOC_PKCS_PASSWD");
+ //RETURN_IF_NOT(pkcs12passwd, ERR_OCSP_PKCS12_NO_PASSWD);
+ } else {
+ pkcs12file = pkcs12passwd = NULL;
+ }
+ if(ConfigItem_lookup_bool("USE_PROXY", 1)) {
+ proxyHost = (char*)ConfigItem_lookup("DIGIDOC_PROXY_HOST");
+ RETURN_IF_NOT(proxyHost, ERR_WRONG_URL_OR_PROXY);
+ proxyPort = (char*)ConfigItem_lookup("DIGIDOC_PROXY_PORT");
+ RETURN_IF_NOT(proxyPort, ERR_WRONG_URL_OR_PROXY);
+ proxyUser = (char*)ConfigItem_lookup("DIGIDOC_PROXY_USER");
+ proxyPass = (char*)ConfigItem_lookup("DIGIDOC_PROXY_PASS");
+ ddocDebug(4, "notarizeSignature", "proxy: %s port : %s", proxyHost, proxyPort);
+ } else {
+ proxyHost = proxyPort = proxyUser = proxyPass = NULL;
+ }
+ err = ddocSelectOcspUrl((char*)ddocSigInfo_GetSignersCert_IssuerName(pSigInfo), &ocspUrl);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ // get signers ca certs
+ pSigCert = ddocSigInfo_GetSignersCert(pSigInfo);
+ err = ddocFindCaChainForCert(pSigCert, caCerts, &nCAs, szCA, sizeof(szCA));
+ RETURN_IF_NOT(nCAs >= 0, ERR_SIGNERS_CERT_NOT_TRUSTED);
+ pSigCa = caCerts[nCAs];
+ // get OCSP confirmation
+ ddocDebug(3, "notarizeSignatureWithIp", "Getting OCSP confirmation");
+ err = getConfirmationWithIpEx(pSigDoc, pSigInfo, (const X509 **)caCerts, NULL,
+ pkcs12file, pkcs12passwd, ocspUrl,
+ proxyHost, proxyPort, proxyUser, proxyPass, ip);
+ // release ca certs
+ nCAs=10;
+ for(i = 0; i < NUM_SEARCH_CAS; i++) {
+ if(caCerts[i] && caCerts[i] != pSigCa) {
+ X509_free(caCerts[i]);
+ caCerts[i] = 0;
+ }
+ }
+ // continue with the rest
+ RETURN_IF_NOT(err == ERR_OK, err);
+ pNotInfo = getNotaryWithSigId(pSigDoc, pSigInfo->szId);
+ RETURN_IF_NOT(pNotInfo != NULL, ERR_NOTARY_SIG_MATCH);
+ // get OCSP response
+ pResp = ddocNotInfo_GetOCSPResponse_Value(pNotInfo);
+ RETURN_IF_NOT(pResp != NULL, ERR_NOTARY_SIG_MATCH);
+ // find CN from responder-id, right CA and CA certs chain
+ err = ddocFindOcspCnCaAndCerts(pResp, &nType, (X509**)caCerts, &nCAs,
+ szCN, sizeof(szCN), szCA, sizeof(szCA));
+ // find usable responder cert by trying all of them
+ // until verification with one succedes
+ if(err == ERR_OK) {
+ j = 0;
+ do {
+ pNotCert = 0;
+ err2 = ERR_OK;
+ if(nType == RESPID_NAME_TYPE)
+ findResponderByCNAndHashAndIndex(&pNotCert, szCN, NULL, j);
+ else if(nType == RESPID_KEY_TYPE)
+ findResponderByCNAndHashAndIndex(&pNotCert, NULL, szCN, j);
+ ddocDebug(1, "notarizeSignatureWithIp", "Find notary: %s idx: %d cert: %s", szCN, j, (pNotCert ? "OK" : "NULL"));
+ if(pNotCert) {
+ err2 = finalizeAndVerifyNotary2(pSigDoc, pSigInfo,
+ pNotInfo, (const X509**)&caCerts, (const X509*)pNotCert, (const X509*)pSigCa);
+ ddocDebug(1, "notarizeSignatureWithIp", "Verifying notary: %d", err);
+ j++;
+ if(err2) {
+ // VS: release ownership before deletion
+ pCertValue = ddocSigInfo_GetOrCreateCertValueOfType(pSigInfo, CERTID_VALUE_RESPONDERS_CERT);
+ if(pCertValue && pCertValue->pCert == pNotCert) {
+ ddocDebug(1, "notarizeSignatureWithIp", "Release notary cert err2: %d", err2);
+ pCertValue->pCert = NULL;
+ }
+ X509_free(pNotCert);
+ }
+ }
+ } while(pNotCert && err2 != ERR_OK);
+ }
+ if(pSigCa)
+ X509_free(pSigCa);
+ if(err2)
+ err = err2;
+ else
+ clearErrors();
+ for(i = 0; i < NUM_SEARCH_CAS; i++)
+ if(caCerts[i])
+ X509_free(caCerts[i]);
+ if(pResp)
+ OCSP_RESPONSE_free(pResp);
+ // test if not cert is ok
+ pCertValue = ddocSigInfo_GetOrCreateCertValueOfType(pSigInfo, CERTID_VALUE_RESPONDERS_CERT);
+ ddocDebug(3, "notarizeSignatureWithIp", "End Notary: cert-val: %s cert: %s",
+ ((pCertValue && pCertValue->pCert) ? "OK" : "NULL"), (pNotCert ? "OK" : "NULL"));
+ // please note that we cannot free pNotCert here because we gave ownership to pNotInf!
+ return err;
+}
+
+//--------------------------------------------------
+// Signs the document and gets configrmation
+// pSigDoc - signed document pointer
+// ppSigInfo - address of new signature pointer
+// pin - smart card PIN
+// manifest - manifest / resolution (NULL)
+// city - signers city (NULL)
+// state - signers state (NULL)
+// zip - signers postal code (NULL)
+// country - signers country (NULL)
+//--------------------------------------------------
+EXP_OPTION int signDocument(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo,
+ const char* pin, const char* manifest,
+ const char* city, const char* state,
+ const char* zip, const char* country)
+{
+ return signDocumentWithSlot(pSigDoc, ppSigInfo, pin, manifest,
+ city, state, zip, country,
+ ConfigItem_lookup_int("DIGIDOC_SIGNATURE_SLOT", 0), 1, 1);
+}
+
+//--------------------------------------------------
+// Signs the document and gets configrmation
+// pSigDoc - signed document pointer
+// ppSigInfo - address of new signature pointer
+// pin - smart card PIN
+// manifest - manifest / resolution (NULL)
+// city - signers city (NULL)
+// state - signers state (NULL)
+// zip - signers postal code (NULL)
+// country - signers country (NULL)
+//--------------------------------------------------
+EXP_OPTION int signDocumentWithSlot(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo,
+ const char* pin, const char* manifest,
+ const char* city, const char* state,
+ const char* zip, const char* country,
+ int nSlot, int nOcsp, int nSigner)
+{
+ return signDocumentWithSlotAndSigner(pSigDoc, ppSigInfo, pin, manifest,
+ city, state, zip, country, nSlot, nOcsp, nSigner, NULL);
+}
+
+//--------------------------------------------------
+// Signs the document and gets configrmation
+// pSigDoc - signed document pointer
+// ppSigInfo - address of new signature pointer
+// pin - smart card PIN
+// manifest - manifest / resolution (NULL)
+// city - signers city (NULL)
+// state - signers state (NULL)
+// zip - signers postal code (NULL)
+// country - signers country (NULL)
+// nSigner - 1=PKCS11, 2=CNG (Microsoft CAPI)
+// szPkcs12FileName - PKCS#12 file name to be used for signing (required if nSigner=3)
+//--------------------------------------------------
+EXP_OPTION int signDocumentWithSlotAndSigner(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo,
+ const char* pin, const char* manifest,
+ const char* city, const char* state,
+ const char* zip, const char* country,
+ int nSlot, int nOcsp, int nSigner,
+ const char* szPkcs12FileName)
+{
+ int err = ERR_OK;
+ SignatureInfo* pSigInfo = NULL;
+
+ RETURN_IF_NULL_PARAM(pSigDoc);
+ RETURN_IF_NULL_PARAM(ppSigInfo);
+ if(nSigner == 3)
+ RETURN_IF_NULL_PARAM(szPkcs12FileName)
+ if(!pSigDoc->szFormatVer ||
+ strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_3_VER) ||
+ !pSigDoc->szFormat ||
+ strcmp(pSigDoc->szFormat, DIGIDOC_XML_1_1_NAME)) {
+ SET_LAST_ERROR(ERR_UNSUPPORTED_FORMAT);
+ return ERR_UNSUPPORTED_FORMAT;
+ }
+ clearErrors();
+
+ ddocDebug(1, "signDocument", "Creating new digital signature");
+ RETURN_IF_NOT(err == ERR_OK, err);
+
+ // add new signature with default id
+ err = SignatureInfo_new(&pSigInfo, pSigDoc, NULL);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ *ppSigInfo = pSigInfo;
+ // automatically calculate doc-info elements for this signature
+ addAllDocInfos(pSigDoc, *ppSigInfo);
+ // add signature production place
+ if (city || state || zip || country)
+ err = setSignatureProductionPlace(*ppSigInfo, city, state, zip, country);
+ // add user roles
+ if (manifest)
+ err = addSignerRole(*ppSigInfo, 0, manifest, -1, 0);
+ ddocDebug(1, "signDocument", "Calc signature");
+ // now sign the doc
+ if(nSigner == 1 || !nSigner)
+ err = calculateSignatureWithEstID(pSigDoc, *ppSigInfo, nSlot, pin);
+#ifdef WIN32
+ if(nSigner == 2)
+ err = calculateSigInfoSignatureWithCSPEstID(pSigDoc, *ppSigInfo, 0, pin);
+#endif
+ if(nSigner == 3)
+ err = calculateSignatureWithPkcs12(pSigDoc, *ppSigInfo, szPkcs12FileName, pin);
+ if(err == ERR_PKCS_LOGIN) return err;
+ RETURN_IF_NOT(err == ERR_OK, ERR_PKCS_SIGN_DATA);
+ if(nOcsp)
+ err = notarizeSignature(pSigDoc, *ppSigInfo);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Verify this notary
+// pSigDoc - signed document pointer
+// pNotInfo - notary to verify
+// returns error code
+//--------------------------------------------------
+int verifyNotary(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, NotaryInfo* pNotInfo)
+{
+ int err = ERR_OK, nCAs = NUM_SEARCH_CAS, i, err2 = 0;
+ X509 * caCerts[NUM_SEARCH_CAS];
+ X509* pNotCert = 0, *pCaCert = 0;
+ const DigiDocMemBuf *pMBuf = 0;
+ char buf1[300], buf2[300], szNotSerial[100];
+ int mustFreeNotaryCert = 0;
+
+ for (i = 0; i < NUM_SEARCH_CAS; i++)
+ caCerts[i] = 0;
+ // get responder certs serial nr
+ szNotSerial[0] = 0;
+ if(ddocSigInfo_GetOCSPRespondersCert(pSigInfo))
+ err = ReadCertSerialNumber(szNotSerial, sizeof(szNotSerial),
+ ddocSigInfo_GetOCSPRespondersCert(pSigInfo));
+ // find responder cert and it's CA cert
+ pMBuf = ddocNotInfo_GetResponderId(pNotInfo);
+ RETURN_IF_NULL(pMBuf);
+ memset(buf2, 0, sizeof(buf2));
+ // use responders cert from ddoc
+ //pNotCert = ddocSigInfo_GetOCSPRespondersCert(pSigInfo);
+
+ if(pNotInfo->nRespIdType == RESPID_NAME_TYPE) {
+ err = findCN((char*)pMBuf->pMem, buf1, sizeof(buf1));
+ ddocDebug(3, "verifyNotary", "Responder text: %s", buf1);
+ if (!err) {
+ err = findResponderCA(buf2, sizeof(buf2), buf1, NULL);
+ ddocDebug(3, "verifyNotary", "Responder CA: %s", buf2);
+ }
+ if(!err) {
+ err = findResponder(&pNotCert, buf1, NULL, (strlen(szNotSerial) ? szNotSerial : NULL));
+ ddocDebug(3, "verifyNotary", "Responder %s cert: %s, err: %d", buf1,
+ (pNotCert ? "OK" : "NULL"), err);
+ }
+ }
+ else if(pNotInfo->nRespIdType == RESPID_KEY_TYPE) {
+ i = sizeof(buf1);
+ encode((const byte*)pMBuf->pMem, pMBuf->nLen, (byte*)buf1, &i);
+ ddocDebug(3, "verifyNotary", "Responder bin: %s", buf1);
+ if (!err) {
+ err = findResponderCA(buf2, sizeof(buf2), NULL, buf1);
+ ddocDebug(3, "verifyNotary", "Responder CA: %s", buf2);
+ }
+ if(!err) {
+ err = findResponder(&pNotCert, NULL, buf1, (strlen(szNotSerial) ? szNotSerial : NULL));
+ ddocDebug(3, "verifyNotary", "Responder %s cert: %s, err: %d", buf1,
+ (pNotCert ? "OK" : "NULL"), err);
+ }
+ }
+ else {
+ SET_LAST_ERROR(ERR_OCSP_WRONG_RESPID);
+ err = ERR_OCSP_WRONG_RESPID;
+ }
+ if (!err) {
+ ddocDebug(3, "verifyNotary", "Find ca chain for: %s", buf2);
+ err = findCAChainForCNAndSigTime((X509**)caCerts, &nCAs, buf2, pNotCert, 0);
+ ddocDebug(3, "verifyNotary", "CA chain for: %s, ca-s: %d, rc: %d", buf2, nCAs+1, err);
+ }
+ // use specific error code for responders cert not found!
+ if(err) {
+ SET_LAST_ERROR(ERR_OCSP_RESP_NOT_TRUSTED);
+ err = ERR_OCSP_RESP_NOT_TRUSTED;
+ }
+ ddocDebug(3, "verifyNotary", "Chain length: %d, err: %d", nCAs+1, err);
+ if(pNotCert) { // #23784 - dont use responders cert in signature, use local copy
+ err = ddocSigInfo_SetOCSPRespondersCert(pSigInfo, pNotCert);
+ ddocDebug(3, "verifyNotary", "assigned notary cert from local store");
+ } else {
+ mustFreeNotaryCert = 1;
+
+ }
+ if (!err) {
+ ddocDebug(3, "verifyNotary", "Verifying Notary %s - cert: %s CA-s: %d", pNotInfo->szId, ((pNotCert) ? "OK" : "NULL"),nCAs+1);
+ err = findCAForCertificateAndSigTime(&pCaCert, ddocSigInfo_GetSignersCert(pSigInfo), 0);
+ err = verifyNotaryInfoCERT2(pSigDoc, pSigInfo, pNotInfo,
+ (const X509**)caCerts, ConfigItem_lookup("CA_CERT_PATH"),
+ pNotCert, pCaCert);
+ ddocDebug(3, "verifyNotary", "Verifying Notary %s - %s", pNotInfo->szId, ((!err) ? "OK" : "ERROR"));
+ }
+ if (mustFreeNotaryCert) {
+ ddocDebug(3, "verifyNotary", "freed notary cert, hopefully all is OK");
+ X509_free(pNotCert);
+ }
+ if (!err) {
+ err = isCertSignedByCERT(ddocSigInfo_GetOCSPRespondersCert(pSigInfo), caCerts[nCAs]);
+ if(err) {
+ err2 = isCertSignedByCERT(ddocSigInfo_GetOCSPRespondersCert(pSigInfo), caCerts[nCAs - 1]);
+ if(!err2) clearErrors(); else err = err2;
+ }
+ ddocDebug(3, "verifyNotary", "\tCertificate trusted - %s", ((!err) ? "OK" : "ERROR"));
+ }
+ // verify notary digest
+ if (!err) {
+ err = verifyNotaryDigest(pSigDoc, pNotInfo);
+ ddocDebug(3, "verifyNotary", "\tNotary digest - %s", ((!err) ? "OK" : "ERROR"));
+ }
+ for (i = 0; i < NUM_SEARCH_CAS; i++) {
+ if(caCerts[i]) {
+ X509_free(caCerts[i]);
+ caCerts[i] = 0;
+ }
+ }
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+
+//--------------------------------------------------
+// Verify this signature and it's notary
+// pSigDoc - signed document pointer
+// pSigInfo - signature to verify
+// szFileName - input digidoc filename
+// returns error code
+//--------------------------------------------------
+EXP_OPTION int verifySignatureAndNotary(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, const char* szFileName)
+{
+ int err1 = ERR_OK, err2 = ERR_OK, k;
+ X509* pCA = 0;
+ NotaryInfo* pNotInfo;
+ time_t tProdAt = 0;
+
+ pNotInfo = getNotaryWithSigId(pSigDoc, pSigInfo->szId);
+ if(pNotInfo)
+ ddocNotInfo_GetProducedAt_timet(pNotInfo, &tProdAt);
+ err1 = findCAForCertificateAndSigTime(&pCA, ddocSigInfo_GetSignersCert(pSigInfo), tProdAt);
+ ddocDebug(3, "verifySignatureAndNotary", "Sig: %s find ca: %d, CA: %s sig-time: %ld", pSigInfo->szId, err1, (pCA ? "OK" : "NULL"), (unsigned long)tProdAt);
+ //RETURN_IF_NOT(err == ERR_OK, err);
+ //RETURN_IF_NOT(pCA, ERR_SIGNERS_CERT_NOT_TRUSTED);
+ if(!pCA) {
+ err1 = ERR_SIGNERS_CERT_NOT_TRUSTED;
+ SET_LAST_ERROR(err1);
+ }
+ if(pCA)
+ err2 = verifySignatureInfoCERT(pSigDoc, pSigInfo, pCA, szFileName, 1);
+ if(err2) {
+ SET_LAST_ERROR(err2);
+ err1 = err2;
+ }
+ if (pNotInfo) {
+ err2 = verifyNotary(pSigDoc, pSigInfo, pNotInfo);
+ if(err2) {
+ SET_LAST_ERROR(err2);
+ if(!err1) err1 = err2;
+ }
+ ddocDebug(3, "verifySignatureAndNotary", "verify notary: %d", err2);
+ } else {
+ ddocDebug(3, "verifySignatureAndNotary", "\tSignature has no OCSP confirmation!\n");
+ SET_LAST_ERROR(ERR_NO_OCSP);
+ err2 = ERR_NO_OCSP;
+ if(!err1) err1 = err2;
+ }
+ if((k = getCountOfSignerRoles(pSigInfo, 0)) > 1) {
+ ddocDebug(1, "verifySignatureInfo", "Number of roles: %d, Currently supports max 1 roles", k);
+ SET_LAST_ERROR(ERR_MAX_1_ROLES);
+ err2 = ERR_MAX_1_ROLES;
+ if(!err1) err1 = err2;
+ }
+ //} else
+ // SET_LAST_ERROR(err2);
+ if (pCA)
+ X509_free(pCA);
+ if(pSigInfo->nErr1) // restore possibly cleared parsing err
+ SET_LAST_ERROR(pSigInfo->nErr1);
+ ddocDebug(3, "verifySignatureAndNotary", "Sig: %s err: %d haserr: %d", pSigInfo->szId, err1, hasUnreadErrors());
+ return checkUnknownErr();
+}
+
+//--------------------------------------------------
+// Extract common name from cert DN or responder id
+// src - DN
+// dest - buffer for CN
+// destLen - size of output buffer in bytes
+//--------------------------------------------------
+int findCN(char* src, char* dest, int destLen)
+{
+ char* p1, *p2;
+ int n;
+
+ p1 = strstr(src, "CN=");
+ if(p1) {
+ p1 += 3; // start of CN field
+ // find start of next field
+ p2 = strchr(p1, '=');
+ if(!p2) // if not found then this was the last field
+ p2 = strchr(p1, 0);
+ // if we have found = of next field then move back until before field name
+ if(p2 && *p2 == '=')
+ while(p2 > p1 && isalpha(*(p2-1))) p2--;
+ // remove possible field separators
+ while(p2 > p1 &&
+ (*(p2-1) == ' ' || *(p2-1) == ',' || *(p2-1) == '/'))
+ p2--;
+ if(p2) {
+ n = (int)(p2-p1);
+ if(n >= destLen) n = destLen - 1;
+ strncpy(dest, p1, n);
+ dest[n] = 0;
+ return ERR_OK;
+ }
+ }
+ SET_LAST_ERROR_RETURN_CODE(ERR_CERT_INVALID);
+}
+
+//------------------------------------------
+// Verify certificate by OCSP
+// pCert - certificate to check
+// ppResp - address to return OCSP response. Use NULL if
+// you don't want OCSP response to be returned
+// returns error code
+//------------------------------------------
+EXP_OPTION int ddocVerifyCertByOCSP(X509* pCert, OCSP_RESPONSE **ppResp)
+{
+ return ddocVerifyCertByOCSPWithIp(pCert, ppResp, 0);
+}
+
+//------------------------------------------
+// Verify certificate by OCSP
+// pCert - certificate to check
+// ppResp - address to return OCSP response. Use NULL if
+// you don't want OCSP response to be returned
+// returns error code
+//------------------------------------------
+EXP_OPTION int ddocVerifyCertByOCSPWithIp(X509* pCert, OCSP_RESPONSE **ppResp, unsigned long ip)
+{
+ int err = ERR_OK, nCAs = NUM_SEARCH_CAS, i, j, err2 = ERR_OK, nType;
+ X509 * caCerts[NUM_SEARCH_CAS];
+ X509 *pNotCert = 0;
+ char *pkcs12file, *pkcs12passwd;
+ char *proxyHost, *proxyPort;
+ char szCN[100], szCA[100], *ocspUrl;
+ OCSP_RESPONSE *pResp = NULL;
+ DigiDocMemBuf mbuf1;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ // check if OCSP must be signed
+ if(ConfigItem_lookup_bool("SIGN_OCSP", 1)) {
+ pkcs12file = (char*)ConfigItem_lookup("DIGIDOC_PKCS_FILE");
+ RETURN_IF_NOT(pkcs12file, ERR_OCSP_PKCS12_NO_FILE);
+ pkcs12passwd = (char*)ConfigItem_lookup("DIGIDOC_PKCS_PASSWD");
+ RETURN_IF_NOT(pkcs12passwd, ERR_OCSP_PKCS12_NO_PASSWD);
+ } else {
+ pkcs12file = pkcs12passwd = NULL;
+ }
+ // check proxy usage
+ if(ConfigItem_lookup_bool("USE_PROXY", 1)) {
+ proxyHost = (char*)ConfigItem_lookup("DIGIDOC_PROXY_HOST");
+ RETURN_IF_NOT(proxyHost, ERR_WRONG_URL_OR_PROXY);
+ proxyPort = (char*)ConfigItem_lookup("DIGIDOC_PROXY_PORT");
+ RETURN_IF_NOT(proxyPort, ERR_WRONG_URL_OR_PROXY);
+ ddocDebug(4, "ddocVerifyCertByOCSPWithIp", "proxy: %s port : %s", proxyHost, proxyPort);
+ } else {
+ proxyHost = proxyPort = NULL;
+ }
+ // send OCSP request and don't verify result immediately
+ err = ddocCertGetIssuerDN(pCert, &mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ err = ddocSelectOcspUrl((char*)mbuf1.pMem, &ocspUrl);
+ ddocMemBuf_free(&mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ // find cert oweners CA cert chain
+ err = ddocFindCaChainForCert(pCert, (X509**)caCerts, &nCAs, szCA, sizeof(szCA));
+ // if possible find OCSP URL by signers CA
+ ddocDebug(3, "ddocVerifyCertByOCSPWithIp", "OCSP URL: %s CA: %s chain: %d",
+ (ocspUrl ? ocspUrl : "NULL"), szCA, nCAs);
+ err = verifyCertificateByOCSPWithIp(pCert, (const X509 **)caCerts, NULL, ocspUrl,
+ proxyHost, proxyPort, pkcs12file, pkcs12passwd, &pResp, ip);
+ ddocDebug(3, "ddocVerifyCertByOCSPWithIp", "OCSP verification - RC: %d, resp: %s", err, (pResp ? "OK" : "NULL"));
+ // release cert CA chain, PR. index fix
+ for(i = 0; i < NUM_SEARCH_CAS; i++) {
+ if(caCerts[i]) {
+ X509_free(caCerts[i]);
+ caCerts[i] = 0;
+ }
+ }
+ // verify OCSP response
+ // find CN from responder-id, right CA and CA certs chain
+ if(!err)
+ err = ddocFindOcspCnCaAndCerts(pResp, &nType, (X509**)caCerts, &nCAs,
+ szCN, sizeof(szCN), szCA, sizeof(szCA));
+ // find usable responder cert by trying all of them
+ // until verification with one succedes
+ if(err == ERR_OK) {
+ j = 0;
+ do {
+ pNotCert = 0;
+ err2 = ERR_OK;
+ if(nType == RESPID_NAME_TYPE)
+ findResponderByCNAndHashAndIndex(&pNotCert, szCN, NULL, j);
+ else if(nType == RESPID_KEY_TYPE)
+ findResponderByCNAndHashAndIndex(&pNotCert, NULL, szCN, j);
+ ddocDebug(1, "ddocVerifyCertByOCSPWithIp", "Find notary: %s idx: %d cert: %s", szCN, j, (pNotCert ? "OK" : "NULL"));
+ if(pNotCert)
+ err2 = verifyOCSPResponse(pResp, (const X509**)&caCerts,
+ NULL, (const X509*)pNotCert);
+ ddocDebug(1, "ddocVerifyCertByOCSPWithIp", "Verifying notary: %d", err);
+ j++;
+ if(pNotCert)
+ X509_free(pNotCert);
+ } while(pNotCert && err2 != ERR_OK);
+ }
+ if(err2)
+ err = err2;
+ else
+ clearErrors();
+ for(i = 0; i < NUM_SEARCH_CAS; i++)
+ if(caCerts[i])
+ X509_free(caCerts[i]);
+ // return OCSP response if requested
+ if(pResp) {
+ if(ppResp)
+ *ppResp = pResp;
+ else
+ OCSP_RESPONSE_free(pResp);
+ }
+ return err;
+}
+
+//------------------------------------------
+// Reads an arbitrary file into memory buffer
+// szFileName - file name and path
+// pData - memory buffer object
+// returns error code
+//------------------------------------------
+EXP_OPTION int ddocReadFile(const char* szFileName, DigiDocMemBuf* pData)
+{
+ int err = ERR_OK;
+ long l1;
+ FILE *hFile;
+ char buf1[2050];
+#ifdef WIN32
+ wchar_t *convFileName = 0;
+ int i= 0;
+ err = utf82unicode((const char*)szFileName, (char**)&convFileName, &i);
+ ddocDebug(3, "ddocReadFile", "file: %s, conv-file: %s len: %d", szFileName, convFileName, i);
+#endif
+
+ RETURN_IF_NULL_PARAM(szFileName);
+ RETURN_IF_NULL_PARAM(pData);
+ pData->pMem = 0;
+ pData->nLen = 0;
+#ifdef WIN32
+ hFile = _wfopen(convFileName, L"rb");
+#else
+ hFile = fopen(szFileName, "rb");
+#endif
+ RETURN_IF_NOT(hFile, ERR_FILE_READ);
+ do {
+ l1 = fread(buf1, 1, 2048, hFile);
+ err = ddocMemAppendData(pData, buf1, (long)l1);
+ } while(l1 == 2048 && !err);
+ fclose(hFile);
+ return err;
+}
+
+//------------------------------------------
+// Writes an arbitrary file into memory buffer
+// szFileName - file name and path
+// pData - memory buffer object
+// returns error code
+//------------------------------------------
+EXP_OPTION int ddocWriteFile(const char* szFileName, DigiDocMemBuf* pData)
+{
+ int err = ERR_OK;
+ FILE *hFile;
+#ifdef WIN32
+ wchar_t *convFileName = 0;
+ int i= 0;
+ err = utf82unicode((const char*)szFileName, (char**)&convFileName, &i);
+ ddocDebug(3, "ddocReadFile", "file: %s, conv-file: %s len: %d", szFileName, convFileName, i);
+#endif
+
+ RETURN_IF_NULL_PARAM(szFileName);
+ RETURN_IF_NULL_PARAM(pData);
+#ifdef WIN32
+ hFile = _wfopen(convFileName, L"wb");
+#else
+ hFile = fopen(szFileName, "wb");
+#endif
+ RETURN_IF_NOT(hFile, ERR_FILE_WRITE);
+ if(hFile)
+ fwrite(pData->pMem, 1, pData->nLen, hFile);
+ fclose(hFile);
+ return err;
+}
+
diff --git a/libdigidoc/DigiDocConfig.h b/libdigidoc/DigiDocConfig.h
new file mode 100644
index 0000000..7e4d3e4
--- /dev/null
+++ b/libdigidoc/DigiDocConfig.h
@@ -0,0 +1,425 @@
+#ifndef __DIGI_DOC_CFG_H__
+#define __DIGI_DOC_CFG_H__
+//==================================================
+// FILE: DigiDocCfonfig.h
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for configuration management
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 08.01.2004 Veiko Sinivee
+// Creation
+// 20.03.2004 Added functions createOrReplacePrivateConfigItem()
+// writeConfigFile() and writePrivateConfigFile()
+// 20.03.2004 changed function notarizeSignature to check for PKCS12 arguments
+//==================================================
+
+#include <libdigidoc/DigiDocDefs.h>
+#include <libdigidoc/DigiDocLib.h>
+#include <time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#include <openssl/x509.h>
+
+
+// item type
+#define ITEM_TYPE_UNKNOWN 0
+#define ITEM_TYPE_GLOBAL 1
+#define ITEM_TYPE_PRIVATE 2
+
+// used to mark modified items to then store all together in private config file
+#define ITEM_STATUS_UNKNOWN 0
+#define ITEM_STATUS_OK 1
+#define ITEM_STATUS_MODIFIED 2
+
+ // holds one configuration item
+ typedef struct ConfigItem_st {
+ char* szKey; // items key
+ char* szValue; // items value
+ int nType; // items type (system wide or private)
+ int nStatus; // item status - clean/modified
+ } ConfigItem;
+
+ // holds one certificate item
+ typedef struct CertificateItem_st {
+ char* szKey; // items key
+ X509* pCert; // certificate
+ } CertificateItem;
+
+ // array of configration items
+ typedef struct ConfigurationStore_st {
+ int nItems;
+ ConfigItem** pItems;
+ int nCerts;
+ CertificateItem** pCerts;
+ } ConfigurationStore;
+
+ //--------------------------------------------------
+ // Returns true (not 0) if config store structure has been inited
+ //--------------------------------------------------
+ EXP_OPTION int isConfigInited();
+
+ //--------------------------------------------------
+ // Initializes configuration store
+ // szConfigFile - name of config file. Use NULL for default
+ //--------------------------------------------------
+ EXP_OPTION int initConfigStore(const char* szConfigFile);
+
+ //--------------------------------------------------
+ // Cleans memory of configuration store
+ // pConfStore - configuration collection (use NULL for default)
+ //--------------------------------------------------
+ EXP_OPTION void cleanupConfigStore(ConfigurationStore *pConfStore);
+
+ //--------------------------------------------------
+ // Adds a new configration item
+ // pConfStore - configuration collection (use NULL for default)
+ // key - items key
+ // value - items value
+ // type - item type
+ // status - item status
+ // returns ERR_OK on success
+ //--------------------------------------------------
+ EXP_OPTION int addConfigItem(ConfigurationStore *pConfStore, const char* key, const char* value, int type, int status);
+
+ //--------------------------------------------------
+ // Read ca and ocsp responder certs from files and cache in memory
+ //--------------------------------------------------
+ int initCertificateItems();
+
+ //--------------------------------------------------
+ // Deletes configration item
+ // key - items key
+ // returns ERR_OK on success
+ //--------------------------------------------------
+ EXP_OPTION int ConfigItem_delete(const char* key);
+
+ //--------------------------------------------------
+ // Adds a new private configration item or modifies
+ // pConfStore - configuration collection (use NULL for default)
+ // an existing one
+ // key - items key
+ // value - items value
+ // returns ERR_OK on success
+ //--------------------------------------------------
+ EXP_OPTION int createOrReplacePrivateConfigItem(ConfigurationStore *pConfStore, const char* key, const char* value);
+
+ //--------------------------------------------------
+ // Finds a new configration items value by key
+ // key - items key
+ // returns value of config item or NULL if not found
+ //--------------------------------------------------
+ EXP_OPTION const char* ConfigItem_lookup(const char* key);
+
+ //--------------------------------------------------
+ // Finds a new configration items value by key from the store
+ // key - items key
+ // pConfStore - store to search in
+ // returns value of config item or NULL if not found
+ //--------------------------------------------------
+ EXP_OPTION const char* ConfigItem_lookup_fromStore(ConfigurationStore *pConfStore, const char* key);
+
+ //--------------------------------------------------
+ // Finds a all configration items that start with this prefix
+ // pConfStore - collection of found items
+ // prefix - item keys prefix
+ // returns error code or ERR_OK
+ //--------------------------------------------------
+ int ConfigItem_findByPrefix(ConfigurationStore *pConfStore, const char* prefix);
+
+ //--------------------------------------------------
+ // Finds a numeric configration items value by key
+ // key - items key
+ // defValue - default value to be returned
+ // returns value of config item or defValue if not found
+ //--------------------------------------------------
+ EXP_OPTION int ConfigItem_lookup_int(const char* key, int defValue);
+
+ //--------------------------------------------------
+ // Finds a bolean configration items value by key
+ // key - items key
+ // defValue - default value to be returned
+ // returns value of config item or defValue if not found
+ //--------------------------------------------------
+ EXP_OPTION int ConfigItem_lookup_bool(const char* key, int defValue);
+
+ //--------------------------------------------------
+ // Finds a new configration items value by key
+ // key - items key
+ // returns value of config item or NULL if not found
+ //--------------------------------------------------
+ EXP_OPTION const char* ConfigItem_lookup_str(const char* key, const char* defValue);
+
+ //--------------------------------------------------
+ // Reads and parses configuration file
+ // fileName - configuration file name
+ // type - type of config file global/private
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int readConfigFile(const char* fileName, int type);
+
+ //--------------------------------------------------
+ // Writes a configuration file
+ // fileName - configuration file name
+ // type - type of config file global/private
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int writeConfigFile(const char* fileName, int type);
+
+ //--------------------------------------------------
+ // Saves all private config items in correct file
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int writePrivateConfigFile();
+
+ //--------------------------------------------------
+ // Sets a new name for private config file. Can be
+ // used to override default of env(HOME)/.digidoc.conf
+ // Use NULL to restore default value
+ //--------------------------------------------------
+ EXP_OPTION void setPrivateConfigFile(const char* fileName);
+
+ //--------------------------------------------------
+ // Finds CA certificate of the given certificate
+ // ppCA - address of found CA
+ // pCert - certificate whose CA we are looking for
+ // return error code or 0 for success
+ // deprecated use findCAForCertificateAndSigTime()
+ //--------------------------------------------------
+ DIGIDOC_DEPRECATED EXP_OPTION int findCAForCertificate(X509** ppCA, const X509* pCert);
+
+ //--------------------------------------------------
+ // Finds CA certificate of the given certificate
+ // ppCA - address of found CA
+ // pCert - certificate whose CA we are looking for
+ // tSigTime - signature timestamp
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int findCAForCertificateAndSigTime(X509** ppCA, const X509* pCert, time_t tSigTime);
+
+ //--------------------------------------------------
+ // Finds CA certificate by CN
+ // ppCA - address of found CA
+ // szCN - CA certs common name
+ // pHash - authority-key-identifier to search for CA
+ // return error code or 0 for success
+ // deprecated use findCAForCNAndSigTime()
+ //--------------------------------------------------
+ DIGIDOC_DEPRECATED EXP_OPTION int findCAForCN(X509** ppCA, const char* szCN, DigiDocMemBuf *pHash);
+
+ //--------------------------------------------------
+ // Finds CA certificate by CN
+ // ppCA - address of found CA
+ // szCN - CA certs common name
+ // pHash - authority-key-identifier to search for CA
+ // tSigTime - signing time or 0
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int findCAForCNAndSigTime(X509** ppCA, const char* szCN, DigiDocMemBuf *pHash, time_t tSigTime);
+
+ //--------------------------------------------------
+ // Finds CA chain
+ // ppChain - address of cert pointer array
+ // nMaxChain - index of last cert in returned array - 0 based
+ // szCN - CN of the first CA cert (not the child cert!)
+ // pCert - certificate to search ca-s for
+ // return error code or 0 for success
+ // deprecated use findCAChainForCNAndSigTime()
+ //--------------------------------------------------
+ DIGIDOC_DEPRECATED EXP_OPTION int findCAChainForCN(X509** ppChain, int* nMaxChain, const char* szCN, X509* pCert);
+
+ //--------------------------------------------------
+ // Finds CA chain
+ // ppChain - address of cert pointer array
+ // nMaxChain - index of last cert in returned array - 0 based
+ // szCN - CN of the first CA cert (not the child cert!)
+ // pCert - certificate to search ca-s for
+ // tSigTime - signature timestamp
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int findCAChainForCNAndSigTime(X509** ppChain, int* nMaxChain, const char* szCN, X509* pCert, time_t tSigTime);
+
+ //--------------------------------------------------
+ // Finds Responders certificate by CN
+ // ppResp - address of found cert
+ // szCN - Responder certs common name
+ // hash - responder certs hash in base64 form
+ // szCertSerial - specific serial number to search
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int findResponder(X509** ppResp, const char* szCN,
+ const char* szHash, char* szCertSerial);
+
+ //--------------------------------------------------
+ // Finds Responders certificate by CN and index
+ // ppResp - address of found cert
+ // szCN - Responder certs common name
+ // hash - responder certs hash in base64
+ // nIdx - index of the certificate for this respnder. Starts at 0
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int findResponderByCNAndHashAndIndex(X509** ppResp, const char* szCN,
+ const char* hash, int nIdx);
+
+ //--------------------------------------------------
+ // Finds Responder certificates CA certs CN
+ // caCN - buffer for responders CA CN
+ // len - length of buffer for CA CN
+ // szCN - responder certs common name
+ // hash - responder certs hash in base64 form
+ // return error code or 0 for success
+ //--------------------------------------------------
+ EXP_OPTION int findResponderCA(char* caCN, int len, const char* szCN, const char* hash);
+
+ //------------------------------------------
+ // Get a notary confirmation for signature
+ // pSigDoc - signed document pointer
+ // pSigInfo - signature to notarize
+ // returns error code
+ //------------------------------------------
+ EXP_OPTION int notarizeSignature(SignedDoc* pSigDoc, SignatureInfo* pSigInfo);
+
+ //------------------------------------------
+ // Get a notary confirmation for signature
+ // pSigDoc - signed document pointer
+ // pSigInfo - signature to notarize
+ // ip - callers ip address if known
+ // returns error code
+ //------------------------------------------
+ EXP_OPTION int notarizeSignatureWithIp(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, unsigned long ip);
+
+ //--------------------------------------------------
+ // Signs the document and gets configrmation
+ // pSigDoc - signed document pointer
+ // ppSigInfo - address of new signature pointer
+ // pin - smart card PIN
+ // manifest - manifest / resolution (NULL)
+ // city - signers city (NULL)
+ // state - signers state (NULL)
+ // zip - signers postal code (NULL)
+ // country - signers country (NULL)
+ //--------------------------------------------------
+ EXP_OPTION int signDocument(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo,
+ const char* pin, const char* manifest,
+ const char* city, const char* state,
+ const char* zip, const char* country);
+
+ //--------------------------------------------------
+ // Signs the document and gets configrmation
+ // pSigDoc - signed document pointer
+ // ppSigInfo - address of new signature pointer
+ // pin - smart card PIN
+ // manifest - manifest / resolution (NULL)
+ // city - signers city (NULL)
+ // state - signers state (NULL)
+ // zip - signers postal code (NULL)
+ // country - signers country (NULL)
+ // signs with PKCS11
+ //--------------------------------------------------
+ EXP_OPTION int signDocumentWithSlot(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo,
+ const char* pin, const char* manifest,
+ const char* city, const char* state,
+ const char* zip, const char* country,
+ int nSlot, int nOcsp, int nSigner);
+
+ //--------------------------------------------------
+ // Signs the document and gets configrmation
+ // pSigDoc - signed document pointer
+ // ppSigInfo - address of new signature pointer
+ // pin - smart card PIN
+ // manifest - manifest / resolution (NULL)
+ // city - signers city (NULL)
+ // state - signers state (NULL)
+ // zip - signers postal code (NULL)
+ // country - signers country (NULL)
+ // nSigner - 1=PKCS11, 2=CNG (Microsoft CAPI), 3=PKCS#12
+ // szPkcs12FileName - PKCS#12 file name to be used for signing (required if nSigner=3)
+ //--------------------------------------------------
+ EXP_OPTION int signDocumentWithSlotAndSigner(SignedDoc* pSigDoc, SignatureInfo** ppSigInfo,
+ const char* pin, const char* manifest,
+ const char* city, const char* state,
+ const char* zip, const char* country,
+ int nSlot, int nOcsp, int nSigner,
+ const char* szPkcs12FileName);
+
+ //--------------------------------------------------
+ // Verify this notary
+ // pSigDoc - signed document pointer
+ // pNotInfo - notary to verify
+ // returns error code
+ //--------------------------------------------------
+ int verifyNotary(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, NotaryInfo* pNotInfo);
+
+ //--------------------------------------------------
+ // Verify this signature and it's notary
+ // pSigDoc - signed document pointer
+ // pSigInfo - signature to verify
+ // szFileName - input digidoc filename
+ // returns error code
+ //--------------------------------------------------
+ EXP_OPTION int verifySignatureAndNotary(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, const char* szFileName);
+
+ //--------------------------------------------------
+ // Extract common name from cert DN or responder id
+ // src - DN
+ // dest - buffer for CN
+ // destLen - size of output buffer in bytes
+ //--------------------------------------------------
+ int findCN(char* src, char* dest, int destLen);
+
+ //------------------------------------------
+ // Verify certificate by OCSP
+ // pCert - certificate to check
+ // ppResp - address to return OCSP response. Use NULL if
+ // you don't want OCSP response to be returned
+ // returns error code
+ //------------------------------------------
+ EXP_OPTION int ddocVerifyCertByOCSP(X509* pCert, OCSP_RESPONSE **ppResp);
+
+ //------------------------------------------
+ // Verify certificate by OCSP
+ // pCert - certificate to check
+ // ppResp - address to return OCSP response. Use NULL if
+ // you don't want OCSP response to be returned
+ // returns error code
+ //------------------------------------------
+ EXP_OPTION int ddocVerifyCertByOCSPWithIp(X509* pCert, OCSP_RESPONSE **ppResp, unsigned long ip);
+
+ //------------------------------------------
+ // Reads an arbitrary file into memory buffer
+ // szFileName - file name and path
+ // pData - memory buffer object
+ // returns error code
+ //------------------------------------------
+ EXP_OPTION int ddocReadFile(const char* szFileName, DigiDocMemBuf* pData);
+
+ //------------------------------------------
+ // Writes an arbitrary file into memory buffer
+ // szFileName - file name and path
+ // pData - memory buffer object
+ // returns error code
+ //------------------------------------------
+ EXP_OPTION int ddocWriteFile(const char* szFileName, DigiDocMemBuf* pData);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif // __DIGI_DOC_CFG_H__
diff --git a/libdigidoc/DigiDocConvert.c b/libdigidoc/DigiDocConvert.c
new file mode 100644
index 0000000..d81b070
--- /dev/null
+++ b/libdigidoc/DigiDocConvert.c
@@ -0,0 +1,1373 @@
+//==================================================
+// FILE: DigiDocEnc.c
+// PROJECT: Digi Doc Encryption
+// DESCRIPTION: DigiDoc character conversion routines
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 22.09.2004 Veiko Sinivee
+// Creation
+//==================================================
+
+#include <libdigidoc/DigiDocDebug.h>
+#include <libdigidoc/DigiDocConvert.h>
+#include <libdigidoc/DigiDocError.h>
+#include <libdigidoc/DigiDocMem.h>
+#include <libdigidoc/DigiDocGen.h>
+
+#ifdef WIN32
+ #include <windows.h>
+#endif
+#include <libxml/globals.h>
+#include <libxml/xmlerror.h>
+#include <libxml/parser.h>
+#include <libxml/parserInternals.h> /* only for xmlNewInputFromFile() */
+#include <libxml/tree.h>
+#include <libxml/debugXML.h>
+#include <libxml/xmlmemory.h>
+#include <libxml/c14n.h>
+#include <ctype.h>
+#include <memory.h>
+
+
+
+//==========< general fucntions >============
+
+//--------------------------------------------------
+// Helper function that converts ISO Latin1 to UTF8
+// ascii - input data in ISO Latin1
+// utf8out - output buffer for UTF8 text
+// outlen - output buffer length
+// returns output buffer
+//--------------------------------------------------
+EXP_OPTION char* ascii2utf8(const char* ascii, char* utf8out, int* outlen)
+{
+ int inlen = strlen(ascii);
+ memset(utf8out, 0, *outlen);
+ isolat1ToUTF8((unsigned char*)utf8out, outlen, (const unsigned char*)ascii, &inlen);
+ return utf8out;
+}
+
+//--------------------------------------------------
+// Helper function that converts UTF8 to ISO Latin1
+// utf8in - input data in UTF8
+// asciiout - output buffer for ISO Latin1 text
+// outlen - output buffer length
+// returns output buffer
+//--------------------------------------------------
+EXP_OPTION char* utf82ascii(const char* utf8in, char* asciiout, int* outlen)
+{
+ int inlen = strlen(utf8in);
+ memset(asciiout, 0, *outlen);
+ UTF8Toisolat1((unsigned char*)asciiout, outlen, (const unsigned char*)utf8in, &inlen);
+ return asciiout;
+}
+
+int hex2char(char c)
+{
+ static char unidigits[] = "0123456789ABCDEF";
+ unsigned int i, k = 0;
+ for(i = 0; i < sizeof(unidigits); i++) {
+ if(unidigits[i] == c) {
+ k = i;
+ break;
+ }
+ }
+ return k;
+}
+
+
+struct u2w {
+ long uni;
+ unsigned char cp1252; // cp 1252 charset
+ unsigned char cp1257; // baltic charset
+ unsigned char utf8_1; // UTF8 1. byte
+ unsigned char utf8_2; // UTF8 2. byte
+};
+
+struct u2w uni2cp1252 [] = {
+ { 8364, 128, 0, 0, 0 }, // euro sign
+ { 8218, 130, 0, 0, 0 }, // SINGLE LOW-9 QUOTATION MARK
+ { 402, 131, 0, 0, 0 }, // LATIN SMALL LETTER F WITH HOOK
+ { 8222, 132, 0, 0, 0 }, // DOUBLE LOW-9 QUOTATION MARK
+ { 8230, 133, 0, 0, 0 }, // HORIZONTAL ELLIPSIS
+ { 8224, 134, 0, 0, 0 }, // DAGGER
+ { 8225, 135, 0, 0, 0 }, // DOUBLE DAGGER
+ { 710, 136, 0, 0, 0 }, // MODIFIER LETTER CIRCUMFLEX ACCENT
+ { 8240, 137, 0, 0, 0 }, // PER MILLE SIGN
+ { 352, 138, 208, 197, 160 }, // LATIN CAPITAL LETTER S WITH CARON
+ { 8249, 139, 0, 0, 0 }, // SINGLE LEFT-POINTING ANGLE QUOTATION MARK
+ { 338, 140, 0, 0, 0 }, // LATIN CAPITAL LIGATURE OE
+ { 381, 142, 222, 197, 189 }, // LATIN CAPITAL LETTER Z WITH CARON
+ { 8216, 145, 0, 0, 0 }, // LEFT SINGLE QUOTATION MARK
+ { 8217, 146, 0, 0, 0 }, // RIGHT SINGLE QUOTATION MARK
+ { 8220, 147, 0, 0, 0 }, // LEFT DOUBLE QUOTATION MARK
+ { 8221, 148, 0, 0, 0 }, // RIGHT DOUBLE QUOTATION MARK
+ { 8226, 149, 0, 0, 0 }, // BULLET
+ { 8211, 150, 0, 0, 0 }, // EN DASH
+ { 8212, 151, 0, 0, 0 }, // EM DASH
+ { 732, 152, 0, 0, 0 }, // SMALL TILDE
+ { 8482, 153, 0, 0, 0 }, // TRADE MARK SIGN
+ { 353, 154, 240, 197, 161 }, // LATIN SMALL LETTER S WITH CARON
+ { 8250, 155, 0, 0, 0 }, // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
+ { 339, 156, 0, 0, 0 }, // LATIN SMALL LIGATURE OE
+ { 382, 158, 254, 197, 190 }, // LATIN SMALL LETTER Z WITH CARON
+ { 376, 159, 0, 0, 0 }, // LATIN CAPITAL LETTER Y WITH DIAERESIS
+ { 196, 196, 196, 195, 132}, // Capital A with umlaut
+ { 214, 214, 214, 195, 150}, // Calital O with umlaut
+ { 220, 220, 220, 195, 156}, // Capital U with umlaut
+ { 213, 213, 213, 195, 149}, // Capital O with tilde
+ { 228, 228, 228, 195, 164}, // small a with umlaut
+ { 246, 246, 246, 195, 132}, // small o with umlaut
+ { 245, 245, 245, 195, 181}, // small o with tilde
+ { 252, 252, 252, 195, 188}, // small u with umlaut
+
+ { 0, 0, 0, 0, 0 } // table end marker
+};
+
+int isUmlaut(unsigned char c)
+{
+ int i;
+ for(i = 0; uni2cp1252[i].uni; i++) {
+ if(uni2cp1252[i].cp1252 == c) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int hasUmlauts(const char* str)
+{
+ int i;
+ for(i = 0; str[i]; i++) {
+ if(isUmlaut((unsigned char)str[i]))
+ return 1;
+ }
+ return 0;
+}
+
+int uni2char(long c)
+{
+ int i, k = 0x20; // use space for all undisplayable unicode chars
+ for(i = 0; uni2cp1252[i].uni; i++) {
+ if(uni2cp1252[i].uni == c) {
+ if(uni2cp1252[i].cp1257)
+ k = uni2cp1252[i].cp1257;
+ else
+ k = uni2cp1252[i].cp1252;
+ break;
+ }
+ }
+ return k;
+}
+
+int uni2utf8(long c, int utfidx)
+{
+ int i, k = 0x20; // use space for all undisplayable unicode chars
+ for(i = 0; uni2cp1252[i].uni; i++) {
+ if(uni2cp1252[i].uni == c) {
+ if(uni2cp1252[i].utf8_1) {
+ if(utfidx)
+ k = uni2cp1252[i].utf8_2;
+ else
+ k = uni2cp1252[i].utf8_1;
+ }
+ else
+ k = uni2cp1252[i].cp1252;
+ break;
+ }
+ }
+ return k;
+}
+
+
+EXP_OPTION void unicode2ascii(const char* uni, char* dest)
+{
+ int len, i, j, k;
+ long c;
+
+ RETURN_VOID_IF_NULL(uni);
+ RETURN_VOID_IF_NULL(dest);
+
+ len = strlen(uni);
+ memset(dest, 0, len+1);
+ for(i = j = 0; i < len; i++) {
+ if(uni[i] == '\\' && uni[i+1] == 'x') {
+ if(uni[i+2] == '0' && uni[i+3] == '0') {
+ if(uni[i+4] >= 'A' && uni[i+4] <= 'Z') { // simple char in form \x00A
+ dest[j] = (unsigned char)uni[i+4];
+ i += 4;
+ j++;
+ continue;
+ } else {
+ i += 3;
+ continue;
+ }
+ }
+ if(uni[i+2] == '0' && uni[i+3] != '0') { // more complex char like \x0}1
+ c = 0;
+ // first pos
+ k = uni[i+2];
+ k = (((k >= '0') && (k <= '9')) ? k - '0' : k);
+ k *= 4096;
+ c += k;
+ // second pos
+ k = uni[i+3];
+ k = (((k >= '0') && (k <= '9')) ? k - '0' : k);
+ k *= 256;
+ c += k;
+ // third pos
+ k = uni[i+4];
+ k = (((k >= '0') && (k <= '9')) ? k - '0' : k);
+ c += k;
+ if(c >= 0 && c <= 9) c+= '0';
+ // get corresponding cp1252 char
+ if(c > 256) {
+#ifdef WIN32
+ dest[j] = (unsigned char)uni2char(c);
+ j++;
+#else
+ dest[j] = uni2utf8(c, 0);
+ j++;
+ dest[j] = uni2utf8(c, 1);
+ j++;
+#endif
+ } else {
+ dest[j] = (unsigned char)c;
+ j++;
+ }
+ i += 4;
+ continue;
+ }
+ if(uni[i+2] != '0' && uni[i+3] != '0') { // hex char code like \xC4
+ c = hex2char(uni[i+2]) * 16 + hex2char(uni[i+3]);
+ if(c > 256) {
+#ifdef WIN32
+ dest[j] = (unsigned char)uni2char(c);
+ j++;
+#else
+ dest[j] = uni2utf8(c, 0);
+ j++;
+ dest[j] = uni2utf8(c, 1);
+ j++;
+#endif
+ } else {
+ dest[j] = (unsigned char)c;
+ j++;
+ }
+ i += 3;
+ continue;
+ }
+ } else {
+ dest[j] = uni[i];
+ j++;
+ }
+ }
+}
+
+typedef struct xmlsym_st {
+ char sym;
+ char* escape;
+} xmlsym;
+
+int g_xmlsyms = 6, g_xmlsyms2 = 7;
+xmlsym g_xmlsym[] = {
+ { '\n', "&#xA;" },
+ { '\r', "&#xD;" },
+ { '<', "&lt;" },
+ { '>', "&gt;" },
+ { '"', "&quot;" },
+ { '&', "&amp;" }, // VS: test if really necessary!
+ { '&', "&#38;" }
+};
+
+int findEscape(const char* src, char* sym)
+{
+ int i;
+
+ *sym = 0;
+ for(i = 0; i < g_xmlsyms; i++) {
+ if(!strncmp(g_xmlsym[i].escape, src, strlen(g_xmlsym[i].escape))) {
+ *sym = g_xmlsym[i].sym;
+ return strlen(g_xmlsym[i].escape);
+ }
+ }
+ return 0;
+}
+
+char findSym(const char* sym, int len)
+{
+ int i;
+
+ for(i = 0; i < g_xmlsyms2; i++) {
+ if(!strncmp(g_xmlsym[i].escape, sym, len)) {
+ return g_xmlsym[i].sym;
+ }
+ }
+ return 0;
+}
+
+//--------------------------------------------------
+// Converts xml symbols to corresponding escapes
+// src - string with xml special sybols
+// returns string with esacpes
+//--------------------------------------------------
+char* escape2xmlsym(const char* src)
+{
+ char* dest = 0, c;
+ int i, j, l, k;
+
+ l = strlen(src);
+ dest = (char*)malloc(l+1);
+ SET_LAST_ERROR_RETURN_IF_NOT(dest, ERR_BAD_ALLOC, NULL);
+ memset(dest, 0, l+1);
+ for(i = j = 0; i < l; i++, j++) {
+ if(src[i] == '&') {
+ k = findEscape(src + i, &c);
+ if(k && c) {
+ dest[j] = c;
+ i += k - 1;
+ }
+ else
+ dest[j] = src[i];
+ }
+ else
+ dest[j] = src[i];
+ }
+ ddocDebug(4, "escape2xmlsym", "%s --> %s", src, dest);
+ return dest;
+}
+
+
+//--------------------------------------------------
+// Converts xml symbols to corresponding escapes
+// src - string with xml special sybols
+// returns string with esacpes
+//--------------------------------------------------
+char* unescapeXmlsym(const char* src)
+{
+ char* dest = 0, c;
+ int i, j, l, k;
+
+ l = strlen(src);
+ dest = (char*)malloc(l+1);
+ SET_LAST_ERROR_RETURN_IF_NOT(dest, ERR_BAD_ALLOC, NULL);
+ memset(dest, 0, l+1);
+ for(i = j = 0; i < l; i++, j++) {
+ if(src[i] == '&') {
+ if(src[i+1] == ';') k = 1;
+ if(src[i+2] == ';') k = 2;
+ if(src[i+3] == ';') k = 3;
+ if(src[i+4] == ';') k = 4;
+ c = findSym(src + i, k);
+ if(k && c) {
+ dest[j] = c;
+ i += k;
+ }
+ else
+ dest[j] = src[i];
+ }
+ else
+ dest[j] = src[i];
+ }
+ ddocDebug(4, "unescapeXmlsym", "%s --> %s", src, dest);
+ return dest;
+}
+
+char g_hexChars[] = "0123456789ABCDEF";
+
+//--------------------------------------------------
+// Decodes a single hex digit
+// h - hex digit
+// return binary value
+//--------------------------------------------------
+byte h2b(char h)
+{
+ int i;
+ for(i = 0; i < 16; i++) {
+ if(g_hexChars[i] == h || g_hexChars[i] == toupper(h))
+ return (byte)i;
+ }
+ // if not found then return an error
+ ddocDebug(1, "h2b", "Invalid hex byte: %c", h);
+ SET_LAST_ERROR(ERR_BAD_PARAM);
+ return 0; // MSTERN: incorrect, VS - yes return -1 if not found. This is an error code
+}
+
+//--------------------------------------------------
+// Converts a hex number (string) to binary value
+// hex - hex number
+// bin - buffer for binary value
+// len - buffer length
+//--------------------------------------------------
+EXP_OPTION void hex2bin(const char* hex, byte* bin, int* len)
+{
+ int i, l;
+ byte b;
+
+ RETURN_VOID_IF_NULL(hex);
+ RETURN_VOID_IF_NULL(bin);
+ RETURN_VOID_IF_NULL(len);
+ memset(bin, 0, *len);
+ l = strlen(hex);
+ for(i = 0; i < l; i += 2) {
+ b = (byte) ((h2b(hex[i]) << 4) | h2b(hex[i+1]));
+ bin[i/2] = b;
+ }
+ *len = i / 2;
+}
+
+//--------------------------------------------------
+// Converts a single byte to two hex characters
+// b - binary value
+// dest - destination buffer
+//--------------------------------------------------
+void b2h(byte b, char* dest)
+{
+ dest[0] = g_hexChars[(b & 0xF0) >> 4];
+ dest[1] = g_hexChars[b & 0x0F];
+}
+
+//--------------------------------------------------
+// Converts a binary value to hex string
+// bin - binary value
+// blen - binary value length
+// hex - buffer for hex string
+// len - buffer length
+//--------------------------------------------------
+EXP_OPTION void bin2hex(const byte* bin, int blen, char* hex, int* len)
+{
+ int i;
+ byte b;
+
+ RETURN_VOID_IF_NULL(hex);
+ RETURN_VOID_IF_NULL(bin);
+ RETURN_VOID_IF_NULL(len);
+ memset(hex, 0, *len);
+ for(i = 0; i < blen; i++) {
+ b = bin[i];
+ hex[i*2] = g_hexChars[(b & 0xF0) >> 4];
+ hex[i*2+1] = g_hexChars[b & 0x0F];
+ }
+ *len = i / 2;
+}
+
+//============================================================
+// Encodes input data in hex format.
+// pMBufSrc - input data
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocBin2Hex(const DigiDocMemBuf* pMBufSrc, DigiDocMemBuf* pMBufDest)
+{
+ int err = ERR_OK, n;
+
+ RETURN_IF_NULL(pMBufSrc);
+ RETURN_IF_NULL(pMBufDest);
+ pMBufDest->pMem = 0;
+ pMBufDest->nLen = 0;
+ // alloc mem for result
+ if(pMBufSrc->pMem && pMBufSrc->nLen) {
+ err = ddocMemSetLength(pMBufDest, pMBufSrc->nLen * 2 + 10);
+ n = pMBufSrc->nLen * 2 + 10;
+ if(err) return err;
+ bin2hex((const byte*)pMBufSrc->pMem, pMBufSrc->nLen, (char*)pMBufDest->pMem, &n);
+ pMBufDest->nLen = n;
+ }
+ return err;
+}
+
+//--------------------------------------------------
+// Converts correct filename to incorrect encoding
+// used in formats 1.0, 1.1 and 1.2
+// src - input data
+// dest - buffer for converted data
+// len - length of destination buffer
+//--------------------------------------------------
+EXP_OPTION void convFNameToWin(const char* src, char* dest, int len)
+{
+ int i, j;
+ for(i = j = 0; src[i] && (j < len - 1); i++, j++) {
+ if(((unsigned char)src[i]) == 197 && ((unsigned char)src[i+1]) == 161) {
+ dest[j] = (unsigned char)195; dest[j+1] = (unsigned char)176; j++, i++; continue;
+ } else if(((unsigned char)src[i]) == 197 && ((unsigned char)src[i+1]) == 160) {
+ dest[j] = (unsigned char)195; dest[j+1] = (unsigned char)144; j++, i++; continue;
+ } else if(((unsigned char)src[i]) == 197 && ((unsigned char)src[i+1]) == 190) {
+ dest[j] = (unsigned char)195; dest[j+1] = (unsigned char)190; j++, i++; continue;
+ } else if(((unsigned char)src[i]) == 197 && ((unsigned char)src[i+1]) == 189) {
+ dest[j] = (unsigned char)195; dest[j+1] = (unsigned char)158; j++, i++; continue;
+ } else {
+ dest[j] = src[i];
+ }
+ }
+ dest[j] = 0;
+}
+
+//--------------------------------------------------
+// Converts bad UTF-8 filename used in formats 1.0,
+// 1.1 and 1.2 to correct encoding
+// src - input data
+// dest - buffer for converted data
+// len - length of destination buffer
+//--------------------------------------------------
+EXP_OPTION void convWinToFName(const char* src, char* dest, int len)
+{
+ int i, j;
+ for(i = j = 0; src[i] && (j < len - 1); i++, j++) {
+ if(((unsigned char)src[i]) == 195 && ((unsigned char)src[i+1]) == 176) {
+ dest[j] = (unsigned char)197; dest[j+1] = (unsigned char)161; j++, i++; continue;
+ } else if(((unsigned char)src[i]) == 195 && ((unsigned char)src[i+1]) == 144) {
+ dest[j] = (unsigned char)197; dest[j+1] = (unsigned char)160; j++, i++; continue;
+ } else if(((unsigned char)src[i]) == 195 && ((unsigned char)src[i+1]) == 190) {
+ dest[j] = (unsigned char)197; dest[j+1] = (unsigned char)190; j++, i++; continue;
+ } else if(((unsigned char)src[i]) == 195 && ((unsigned char)src[i+1]) == 158) {
+ dest[j] = (unsigned char)197; dest[j+1] = (unsigned char)189; j++, i++; continue;
+ } else {
+ dest[j] = src[i];
+ }
+ }
+ dest[j] = 0;
+}
+
+
+//==========< only win32 fucntions >============
+
+#ifdef WIN32
+
+//--------------------------------------------------
+// Converts input OEM charset data to 16 bit unicode.
+// oem - 8 bit oem charset input data
+// unicode - address of pointer for allocated unicode string. Caller must free() !
+// outlen - address of length variable for unicode string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int oem2unicode(const char* oem, char** unicode, int* outlen)
+{
+ int len;
+
+ *unicode = 0;
+ // convert oem to unicode
+ if(!oem || !strlen(oem))
+ return ERR_OK;
+ ddocDebug(4, "oem2unicode", "Convert: \'%s\' len: %d", oem, strlen(oem));
+ len = MultiByteToWideChar(CP_ACP, 0, oem, -1, NULL, 0) * 2 + 10;
+ ddocDebug(5, "oem2unicode", "Alloc: %d", len);
+ *unicode = (char*)malloc(len);
+ RETURN_IF_BAD_ALLOC(*unicode);
+ memset(*unicode, 0, len);
+ *outlen = MultiByteToWideChar(CP_ACP, 0, oem, -1, (LPWSTR)(*unicode), len);
+ if(!(*outlen)) {
+ SET_LAST_ERROR(ERR_CHARSET_CONVERT);
+ return ERR_CHARSET_CONVERT;
+ }
+ else
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Converts input 16 bit unicode data to UTF8.
+// unicode - 16 bit unicode input data
+// utf8 - address of pointer for allocated utf8 string. Caller must free() !
+// outlen - address of length variable for utf8 string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int unicode2utf8(const char* unicode, char** utf8, int* outlen)
+{
+ int len;
+
+ *utf8 = 0;
+ // now convert unicode to UTF8
+ if(!unicode || !strlen(unicode))
+ return ERR_OK;
+ len = WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)unicode, -1, NULL, 0, NULL, NULL) + 10;
+ ddocDebug(5, "unicode2utf8", "Alloc: %d", len);
+ *utf8 = (char*)malloc(len);
+ RETURN_IF_BAD_ALLOC(*utf8);
+ memset(*utf8, 0, len);
+ *outlen = WideCharToMultiByte(CP_UTF8, 0, (LPWSTR)unicode, -1, *utf8, len, NULL, NULL);
+ ddocDebug(5, "unicode2utf8", "Convert: \'%s\' len: %d", *utf8, strlen(*utf8));
+ if(!(*outlen)) {
+ SET_LAST_ERROR(ERR_CHARSET_CONVERT);
+ return ERR_CHARSET_CONVERT;
+ }
+ else
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Converts input OEM charset data to UTF-8
+// oem - 8 bit oem charset input data
+// utf8 - address of buffer allocated utf8 string.
+// len - size of buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int oem2utf8(const char* oem, char* utf8, int len)
+{
+ int err = ERR_OK, len1, len2;
+ char *pTmp1 = 0, *pTmp2 = 0;
+
+ ddocDebug(5, "oem2utf8", "oem2utf8");
+ // Kaido: 2.1.13 - initialize return value
+ *utf8 = 0;
+ // convert oem to unicode
+ if(!oem || !strlen(oem))
+ return ERR_OK;
+ err = oem2unicode(oem, &pTmp1, &len1);
+ if(err) return err;
+ // now convert unicode to UTF8
+ err = unicode2utf8(pTmp1, &pTmp2, &len2);
+ if(len2 < len)
+ memcpy(utf8, pTmp2, len2);
+ else
+ err = ERR_CHARSET_CONVERT;
+ if(pTmp1)
+ free(pTmp1);
+ if(pTmp2)
+ free(pTmp2);
+ return err;
+}
+
+//--------------------------------------------------
+// Converts input UTF-8 data to 16 bit unicode data.
+// utf8 - UTF-8 input data
+// unicode - address of pointer for allocated unicode string. Caller must free() !
+// outlen - address of length variable for unicode string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int utf82unicode(const char* utf8, char** unicode, int* outlen)
+{
+ int len;
+
+ *unicode = 0;
+ // convert unicode to UTF-8
+ if(!utf8 || !strlen(utf8))
+ return ERR_OK;
+ ddocDebug(5, "utf82unicode", "Convert: \'%s\' len: %d", utf8, strlen(utf8));
+ len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0) * 2 + 10;
+ ddocDebug(5, "utf82unicode", "Alloc: %d", len);
+ *unicode = (char*)malloc(len);
+ RETURN_IF_BAD_ALLOC(*unicode);
+ memset(*unicode, 0, len);
+ *outlen = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, (LPWSTR)(*unicode), len);
+ ddocDebug(5, "utf82unicode", "Converted: \'%s\' to \'%s\' len: %d", utf8, *unicode, *outlen);
+ if(!(*outlen)) {
+ SET_LAST_ERROR(ERR_CHARSET_CONVERT);
+ return ERR_CHARSET_CONVERT;
+ }
+ else
+ return ERR_OK;
+}
+
+//--------------------------------------------------
+// Converts input 16 bit unicode data to oem charset data.
+// unicode - 16 bit unicode input data
+// oem - address of pointer for allocated oem string. Caller must free() !
+// outlen - address of length variable for oem string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int unicode2oem(const char* unicode, char** oem, int* outlen)
+{
+ int len;
+
+ *oem = 0;
+ if(!unicode || !strlen(unicode))
+ return ERR_OK;
+ // now convert unicode to OEM
+ len = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)unicode, -1, NULL, 0, NULL, NULL) + 10;
+ ddocDebug(5, "unicode2oem", "Alloc: %d", len);
+ *oem = (char*)malloc(len);
+ RETURN_IF_BAD_ALLOC(*oem);
+ memset(*oem, 0, len);
+ *outlen = WideCharToMultiByte(CP_ACP, 0, (LPWSTR)unicode, -1, *oem, len, NULL, NULL);
+ ddocDebug(5, "unicode2oem", "Convert: \'%s\' len: %d", *oem, strlen(*oem));
+ if(!(*outlen)) {
+ SET_LAST_ERROR(ERR_CHARSET_CONVERT);
+ return ERR_CHARSET_CONVERT;
+ }
+ else
+ return ERR_OK;
+}
+
+
+//--------------------------------------------------
+// Converts input UTF-8 data to OEM charset data
+// utf8 - UTF-8 input data
+// oem - address of buffer for oem string.
+// len - size of buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int utf82oem(const char* utf8, char* oem, int len)
+{
+ int err = ERR_OK, len1, len2;
+ char *pTmp1 = 0, *pTmp2 = 0;
+
+ // Kaido: 2.1.13 - initialize return value
+ *oem = 0;
+ // convert utf8 to unicode
+ if(!utf8 || !strlen(utf8))
+ return ERR_OK;
+ memset(oem, 0, len);
+ err = utf82unicode(utf8, &pTmp1, &len1);
+ if(err) return err;
+ // now convert unicode to OEM
+ err = unicode2oem(pTmp1, &pTmp2, &len2);
+ if(len2 < len)
+ memcpy(oem, pTmp2, len2);
+ else
+ err = ERR_CHARSET_CONVERT;
+ if(pTmp1)
+ free(pTmp1);
+ if(pTmp2)
+ free(pTmp2);
+ return err;
+}
+
+//--------------------------------------------------
+// Converts input UTF-8 data to OEM charset data
+// pSigDoc - signed doc object
+// pDf - data file obejct
+// outFileName - output buffer
+// len - length of output buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getDataFileFileName(SignedDoc* pSigDoc, DataFile* pDf, char* outFileName, int len)
+{
+ int err = ERR_OK;
+ RETURN_IF_NULL_PARAM(pSigDoc);
+ RETURN_IF_NULL_PARAM(pDf);
+ RETURN_IF_NULL_PARAM(outFileName);
+
+ // Kaido: 2.1.13 - initialize return value
+ *outFileName = 0;
+ if(!strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_3_VER) ) {
+ //utf82oem(pDf->szFileName, buf1, 300);
+ //convFNameToWin(buf1, outFileName, len);
+ strncpy(outFileName, pDf->szFileName, len);
+ } else {
+ convWinToFName(pDf->szFileName, outFileName, len);
+ }
+ return err;
+}
+
+
+#endif
+
+
+//--------------------------------------------------
+// Converts input data to UTF-8
+// src - input data
+// returns converted string or NULL. Caller must free it.
+//--------------------------------------------------
+EXP_OPTION int ddocConvertInput(const char* src, char** dest)
+{
+ int l1, err = ERR_OK;
+
+ *dest = 0;
+ l1 = strlen(src) * 2 + 3;
+ *dest = (char*)malloc(l1);
+ if(*dest) {
+ memset(*dest, 0, l1);
+#ifdef WIN32
+ RETURN_IF_NULL(*dest);
+ err = oem2utf8(src, *dest, l1);
+#else
+ strncpy(*dest, src, l1);
+#endif
+ }
+ return err;
+}
+
+//--------------------------------------------------
+// Releases mem-block allocated by lib. In win32
+// this must be done since the mem was allocated by dll
+// and must also be released by dll that allocated it.
+// p - mem to be freed
+//--------------------------------------------------
+EXP_OPTION void freeLibMem(void* p)
+{
+ if(p)
+ free(p);
+}
+
+
+//--------------------------------------------------
+// Converts a filename according to platform rules
+// dest - destination buffer
+// destlen - destination buffer length
+// src - source filename
+// returns error code or ERR_OK
+//--------------------------------------------------
+int ddocConvertFileName(char* dest, int destlen, const char* src)
+{
+ int err = ERR_OK;
+
+ RETURN_IF_NULL_PARAM(dest);
+ RETURN_IF_NULL_PARAM(src);
+
+ *dest = 0; // initialize
+#ifdef WIN32
+ err = utf82oem(src, dest, destlen);
+#else
+ SET_LAST_ERROR_IF_NOT((int)strlen(src) < destlen, ERR_BUF_LEN);
+ strncpy(dest, src, destlen);
+#endif
+ return err;
+}
+
+//==========< Base64 functions >================
+
+
+//============================================================
+// Encode a byte array in Base64 format.
+// raw - input data
+// rawlen - length of input data
+// buf - destination buffer
+// buflen - destination buffer length (will be modified by catual number of bytes)
+//============================================================
+EXP_OPTION void encode(const byte* raw, int rawlen, byte* buf, int* buflen)
+{
+ EVP_ENCODE_CTX ectx;
+
+ RETURN_VOID_IF_NULL(raw);
+ RETURN_VOID_IF_NULL(buf);
+ RETURN_VOID_IF_NULL(buflen);
+
+ memset(buf, 0, *buflen);
+ EVP_EncodeInit(&ectx);
+ EVP_EncodeUpdate(&ectx, buf, buflen, (byte*)raw, rawlen);
+ EVP_EncodeFinal(&ectx, (unsigned char*)strchr((const char*)buf, 0), buflen);
+ *buflen = strlen((const char*)buf);
+ while(buf[*buflen-1] == '\n' || buf[*buflen-1] == '\r' || buf[*buflen-1] == '-') {
+ if(buf[*buflen-1] == '-')
+ ddocDebug(1, "encode", "Found - at the end of base64 code: %s", buf);
+
+ buf[*buflen-1] = 0;
+ *buflen = *buflen - 1;
+ }
+ *buflen = strlen((const char*)buf);
+}
+
+
+byte* breakToLinesOf64(byte* raw, int rawlen)
+{
+ int i, l1, j;
+ byte* p = raw;
+
+ // if it's not divide in lines
+ l1 = rawlen;
+ j = l1 + (l1/64) * 3;
+ p = (byte*)malloc(j);
+ if (!p) return NULL;
+ memset(p, 0, j);
+ for(i = j = 0; i < l1; i += 64) {
+ strncpy(strchr((const char*)p,0), (const char*)raw+i, ((i+64<l1) ? 64 : l1-i));
+ if(i + 64 < l1)
+ strncat((char*)p, "\n", j - strlen((char*)p));
+ }
+ l1 = strlen((const char*)p);
+ return p;
+}
+
+//============================================================
+// Decodes input data in Base64 format.
+// raw - input data
+// rawlen - length of input data
+// buf - destination buffer
+// buflen - destination buffer length (will be modified by catual number of bytes)
+//============================================================
+EXP_OPTION void decode(const byte* raw, int rawlen, byte* buf, int* buflen)
+{
+ EVP_ENCODE_CTX ectx;
+ int l1 = 0;
+ byte* p;
+
+ RETURN_VOID_IF_NULL(raw);
+ RETURN_VOID_IF_NULL(buf);
+ RETURN_VOID_IF_NULL(buflen);
+
+ memset(buf, 0, *buflen);
+ *buflen = 0;
+ EVP_DecodeInit(&ectx);
+ if((!strstr((const char*)raw, "\n") ||
+ !strstr((const char*)raw, "\r")) &&
+ strlen((const char*)raw) > 64) {
+ p = breakToLinesOf64((byte*)raw, rawlen);
+ l1 = strlen((const char*)p);
+ EVP_DecodeUpdate(&ectx, (unsigned char*)buf, &l1,
+ (unsigned char*)p,
+ strlen((const char*)p));
+ *buflen += l1;
+ free(p);
+ }
+ else
+ EVP_DecodeUpdate(&ectx, buf, buflen, (byte*)raw, rawlen);
+ EVP_DecodeFinal(&ectx, buf, &l1);
+ *buflen += l1;
+}
+
+
+//============================================================
+// Helper function to determine if this is a base64 char
+//============================================================
+int isb64char(int c)
+{
+ return ( (c >= 'A' && c <= 'Z') ||
+ (c >= 'a' && c <= 'z') ||
+ (c >= '0' && c <= '9') ||
+ (c == '+') ||
+ (c == '/') ||
+ (c == '=')
+ );
+}
+
+//============================================================
+// Decodes input data in Base64 format.
+// pMBufSrc - input data
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocDecodeBase64(DigiDocMemBuf* pMBufSrc, DigiDocMemBuf* pMBufDest)
+{
+ int err = ERR_OK, n;
+ long lPos1 = 0, lPos2 = 0;
+ EVP_ENCODE_CTX ectx;
+ char buf1[70];
+ RETURN_IF_NULL(pMBufSrc);
+ RETURN_IF_NULL(pMBufDest);
+
+ pMBufDest->pMem = 0;
+ pMBufDest->nLen = 0;
+ // alloc mem for result - it will get smaller so original length must be enough
+ err = ddocMemSetLength(pMBufDest, pMBufSrc->nLen);
+ if(err) return err;
+ EVP_DecodeInit(&ectx);
+ // decode base64
+ while(lPos1 < pMBufSrc->nLen) {
+ // copy next input row
+ memset(buf1, 0, sizeof(buf1));
+ n = 0;
+ while(n < 64 && lPos1 < pMBufSrc->nLen) {
+ if(isb64char(((char*)pMBufSrc->pMem)[lPos1])) {
+ buf1[n] = ((char*)pMBufSrc->pMem)[lPos1];
+ n++;
+ }
+ lPos1++;
+ }
+ strncat(buf1, "\n", sizeof(buf1) - strlen(buf1));
+ // decode this chunk
+ n = pMBufDest->nLen - lPos2;
+ EVP_DecodeUpdate(&ectx, (unsigned char*)((char*)pMBufDest->pMem + lPos2), &n,
+ (unsigned char*)buf1, strlen((const char*)buf1));
+ lPos2 += n;
+ }
+ memset(buf1, 0, sizeof(buf1));
+ n = sizeof(buf1);
+ EVP_DecodeFinal(&ectx, (unsigned char*)buf1, &n);
+ lPos2 += n;
+ pMBufDest->nLen = lPos2;
+ return err;
+}
+
+
+//============================================================
+// Decodes input data in Base64 format.
+// data - input data
+// len - length of input data. Use -1 for zero terminated strings
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocDecodeBase64Data(void* data, long len, DigiDocMemBuf* pMBufDest)
+{
+ DigiDocMemBuf mbuf1;
+
+ mbuf1.pMem = data;
+ if(len == -1)
+ mbuf1.nLen = strlen((const char*)data);
+ else
+ mbuf1.nLen = len;
+ return ddocDecodeBase64(&mbuf1, pMBufDest);
+}
+
+
+//============================================================
+// Encodes input data in Base64 format.
+// pMBufSrc - input data
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocEncodeBase64(const DigiDocMemBuf* pMBufSrc, DigiDocMemBuf* pMBufDest)
+{
+ int err = ERR_OK, nLen;
+ EVP_ENCODE_CTX ectx;
+
+ RETURN_IF_NULL(pMBufSrc);
+ RETURN_IF_NULL(pMBufDest);
+
+ pMBufDest->pMem = 0;
+ pMBufDest->nLen = 0;
+ // alloc mem for result
+ err = ddocMemSetLength(pMBufDest, pMBufSrc->nLen * 2 + 10);
+ if(err) return err;
+ EVP_EncodeInit(&ectx);
+ // encode base64
+ nLen = pMBufDest->nLen;
+ EVP_EncodeUpdate(&ectx, (unsigned char*)pMBufDest->pMem, &nLen,
+ (byte*)pMBufSrc->pMem, pMBufSrc->nLen);
+ pMBufDest->nLen = nLen;
+ nLen = (pMBufSrc->nLen * 2 + 10) - pMBufDest->nLen;
+ EVP_EncodeFinal(&ectx, (unsigned char*)pMBufDest->pMem + pMBufDest->nLen, &nLen);
+ pMBufDest->nLen += nLen; //strlen((const char*)pMBufDest->pMem);
+ return err;
+}
+
+//==========< conversion fucntions >================
+
+//--------------------------------------------------
+// Decodes an ASN1 generalized time
+// tm - ASN1 generalized time
+// y - year
+// M - month
+// d - day of month
+// h - hour
+// m - minute
+// s - second
+// returns error code or ERR_OK
+//--------------------------------------------------
+int decodeGeneralizedTime(ASN1_GENERALIZEDTIME *tm,
+ int* y, int* M, int* d,
+ int* h, int* m, int* s)
+{
+ char *v = NULL;
+ int gmt=0;
+ int i, err = ERR_OK;
+
+ RETURN_IF_NULL_PARAM(tm);
+ RETURN_IF_NULL_PARAM(y);
+ RETURN_IF_NULL_PARAM(M);
+ RETURN_IF_NULL_PARAM(d);
+ RETURN_IF_NULL_PARAM(h);
+ RETURN_IF_NULL_PARAM(m);
+ RETURN_IF_NULL_PARAM(s);
+
+ i=tm->length;
+ v=(char *)tm->data;
+ if (i < 12)
+ err = ERR_TIMESTAMP_DECODE;
+ if (v[i-1] == 'Z') gmt=1;
+ for (i=0; i<12; i++)
+ if ((v[i] > '9') || (v[i] < '0'))
+ err = ERR_TIMESTAMP_DECODE;
+ *y= (v[0]-'0')*1000+(v[1]-'0')*100 + (v[2]-'0')*10+(v[3]-'0');
+ *M= (v[4]-'0')*10+(v[5]-'0');
+ if ((*M > 12) || (*M < 1))
+ err = ERR_TIMESTAMP_DECODE;
+ *d= (v[6]-'0')*10+(v[7]-'0');
+ *h= (v[8]-'0')*10+(v[9]-'0');
+ *m= (v[10]-'0')*10+(v[11]-'0');
+ if ( (v[12] >= '0') && (v[12] <= '9') &&
+ (v[13] >= '0') && (v[13] <= '9'))
+ *s= (v[12]-'0')*10+(v[13]-'0');
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+//--------------------------------------------------
+// Decodes an ASN1 UTC time
+// tm - ASN1 generalized time
+// y - year
+// M - month
+// d - day of month
+// h - hour
+// m - minute
+// s - second
+// returns error code or ERR_OK
+//--------------------------------------------------
+int decodeUTCTime(ASN1_UTCTIME *tm,
+ int* y, int* M, int* d,
+ int* h, int* m, int* s)
+{
+ char *v;
+ int gmt=0;
+ int i, err = 0;
+
+ RETURN_IF_NULL_PARAM(tm);
+ RETURN_IF_NULL_PARAM(y);
+ RETURN_IF_NULL_PARAM(M);
+ RETURN_IF_NULL_PARAM(d);
+ RETURN_IF_NULL_PARAM(h);
+ RETURN_IF_NULL_PARAM(m);
+ RETURN_IF_NULL_PARAM(s);
+
+ i=tm->length;
+ v=(char *)tm->data;
+
+ if (i < 10)
+ err = ERR_TIMESTAMP_DECODE;
+ if (v[i-1] == 'Z') gmt=1;
+ for (i=0; i<10; i++)
+ if ((v[i] > '9') || (v[i] < '0'))
+ err = ERR_TIMESTAMP_DECODE;
+ *y= (v[0]-'0')*10+(v[1]-'0');
+ if (*y < 50) *y+=100;
+ *M= (v[2]-'0')*10+(v[3]-'0');
+ if ((*M > 12) || (*M < 1))
+ err = ERR_TIMESTAMP_DECODE;
+ *d= (v[4]-'0')*10+(v[5]-'0');
+ *h= (v[6]-'0')*10+(v[7]-'0');
+ *m= (v[8]-'0')*10+(v[9]-'0');
+ if ( (v[10] >= '0') && (v[10] <= '9') &&
+ (v[11] >= '0') && (v[11] <= '9'))
+ *s= (v[10]-'0')*10+(v[11]-'0');
+
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+//==========================================================
+// converts ASN1 time to time_t
+//==========================================================
+int asn1time2time_t(ASN1_TIME* tm, time_t* pT)
+{
+ int err = ERR_OK;
+ struct tm tm1;
+ //int dmz=0;
+
+ RETURN_IF_NULL_PARAM(tm);
+ RETURN_IF_NULL_PARAM(pT);
+ _tzset();
+ memset(&tm1, 0, sizeof(tm1));
+ if(tm->type == V_ASN1_UTCTIME)
+ err = decodeUTCTime(tm, &tm1.tm_year, &tm1.tm_mon,
+ &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min, &tm1.tm_sec);
+ if(tm->type == V_ASN1_GENERALIZEDTIME)
+ err = decodeGeneralizedTime(tm, &tm1.tm_year, &tm1.tm_mon,
+ &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min, &tm1.tm_sec);
+ tm1.tm_year -= 1900;
+ tm1.tm_mon -= 1;
+ tm1.tm_isdst = _daylight;
+ (*pT) = mktime(&tm1);
+ /*
+ if(_daylight!=0) {
+ if(_timezone<0){
+ dmz = (_timezone / 3600) - _daylight;
+ }else{
+ dmz = (_timezone / 3600) + _daylight;
+ }
+ }else{
+ dmz=_timezone / 3600;
+ }
+ (*pT) = (*pT) - (dmz * 3600);
+ */
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+
+//==========================================================
+// converts ASN1 time to time_t
+//==========================================================
+int asn1time2time_t_local(ASN1_TIME* tm, time_t* pT)
+{
+ int err = ERR_OK;
+ struct tm tm1;
+ int dmz=0;
+
+ RETURN_IF_NULL_PARAM(tm);
+ RETURN_IF_NULL_PARAM(pT);
+ _tzset();
+ memset(&tm1, 0, sizeof(tm1));
+ if(tm->type == V_ASN1_UTCTIME)
+ err = decodeUTCTime(tm, &tm1.tm_year, &tm1.tm_mon,
+ &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min, &tm1.tm_sec);
+ if(tm->type == V_ASN1_GENERALIZEDTIME)
+ err = decodeGeneralizedTime(tm, &tm1.tm_year, &tm1.tm_mon,
+ &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min, &tm1.tm_sec);
+ if(tm1.tm_year > 1900)
+ tm1.tm_year -= 1900;
+ tm1.tm_mon -= 1;
+ tm1.tm_isdst = _daylight;
+ (*pT) = mktime(&tm1);
+ if(_daylight != 0) {
+ if(_timezone<0){
+ dmz = (_timezone / 3600) - _daylight;
+ }else{
+ dmz = (_timezone / 3600) + _daylight;
+ }
+ }else{
+ dmz=_timezone / 3600;
+ }
+ (*pT) = (*pT) - (dmz * 3600);
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+//==========================================================
+// converts ASN1 time to string
+//==========================================================
+int asn1time2strYear(const SignedDoc* pSigDoc, ASN1_TIME* tm, char* buf, int year, int len)
+{
+ int err = ERR_OK;
+ struct tm tm1, tm2;
+ time_t t2;
+ int dmz=0;
+
+ RETURN_IF_NULL_PARAM(tm);
+ RETURN_IF_NULL_PARAM(buf);
+ //RETURN_IF_NULL_PARAM(pSigDoc);
+ _tzset();
+ memset(&tm1, 0, sizeof(tm1));
+ if(tm->type == V_ASN1_UTCTIME)
+ err = decodeUTCTime(tm, &tm1.tm_year, &tm1.tm_mon,
+ &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min, &tm1.tm_sec);
+ if(tm->type == V_ASN1_GENERALIZEDTIME)
+ err = decodeGeneralizedTime(tm, &tm1.tm_year, &tm1.tm_mon,
+ &tm1.tm_mday, &tm1.tm_hour, &tm1.tm_min, &tm1.tm_sec);
+
+ // V 1.76 - in format 1.3 we use CCYY-MM-DDTHH:MM:SSZ
+ if(!pSigDoc || (pSigDoc &&
+ !strcmp(pSigDoc->szFormatVer, DIGIDOC_XML_1_3_VER) )) {
+ snprintf(buf, len, "%04d-%02d-%02dT%02d:%02d:%02dZ",
+ year + tm1.tm_year, tm1.tm_mon, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ } else
+ // in version 1.0 we use format CCYY.MM.DDTHH:MM:SS-TZ
+ if(pSigDoc && !strcmp(pSigDoc->szFormat, SK_XML_1_NAME) && !strcmp(pSigDoc->szFormatVer, SK_XML_1_VER)) {
+ tm1.tm_year -= 1900 - year;
+ tm1.tm_mon -= 1;
+ tm1.tm_isdst = _daylight;
+ t2 = mktime(&tm1);
+ if (err == ERR_OK) {
+ if (_daylight!=0) {
+ if (_timezone<0) {
+ dmz = (_timezone / 3600) - _daylight;
+ } else {
+ dmz = (_timezone / 3600) + _daylight;
+ }
+ } else {
+ dmz=_timezone / 3600;
+ }
+ t2 -= (dmz * 3600);
+ ddocLocalTime(&t2, &tm2, 1);
+ snprintf(buf, len, "%04d.%02d.%02dT%02d:%02d:%02d%+03d:00",
+ tm2.tm_year + 1900, tm2.tm_mon + 1,
+ tm2.tm_mday, tm2.tm_hour, tm2.tm_min,
+ tm2.tm_sec, dmz * -1);
+ ddocDebug(5, "asn1time2strYear",
+ "ASN1 time: %s, tz: %d, string: %s\n", tm->data, dmz * -1, buf);
+ }
+ } else { // in version 1.1 we use format CCYY.MM.DDTHH:MM:SSZ and allways UTC time
+ snprintf(buf, len, "%04d.%02d.%02dT%02d:%02d:%02dZ",
+ year + tm1.tm_year, tm1.tm_mon, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ }
+
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+//==========================================================
+// converts ASN1 time to string
+//==========================================================
+int asn1time2str(const SignedDoc* pSigDoc, ASN1_TIME* tm, char* buf, int len)
+{
+ return asn1time2strYear(pSigDoc, tm, buf, 0, len);
+}
+
+
+
+//==============================================================================
+// converts ASN1_GENERALIZEDTOME object to string
+//==============================================================================
+int str2asn1time(const SignedDoc* pSigDoc, const char* str, ASN1_GENERALIZEDTIME* asn1tm)
+{
+ char buf[50];
+ int rc, dmz = 0;
+ struct tm tm1, tm2;
+ time_t t2;
+
+
+ RETURN_IF_NULL_PARAM(str);
+ RETURN_IF_NULL_PARAM(asn1tm);
+ _tzset();
+ memset(&tm1, 0, sizeof(tm1));
+ // in version 1.0 we use format CCYY.MM.DDTHH:MM:SS-TZ
+ if(!strcmp(pSigDoc->szFormat, SK_XML_1_NAME) && !strcmp(pSigDoc->szFormatVer, SK_XML_1_VER)) {
+ sscanf(str, "%04d.%02d.%04dT%02d:%02d:%02d%3d:00",
+ &(tm1.tm_year), &(tm1.tm_mon), &(tm1.tm_mday),
+ &(tm1.tm_hour), &(tm1.tm_min), &(tm1.tm_sec), &dmz);
+ tm1.tm_year -= 1900;
+ tm1.tm_mon -= 1;
+ tm1.tm_isdst = _daylight;
+ t2 = mktime(&tm1);
+ t2 -= (dmz * 3600);
+ ddocLocalTime(&t2, &tm2, 1);
+ snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d%02dZ",
+ tm2.tm_year + 1900, tm2.tm_mon + 1, tm2.tm_mday,
+ tm2.tm_hour, tm2.tm_min, tm2.tm_sec);
+ } else { // in version 1.1 we use format CCYY.MM.DDTHH:MM:SSZ and allways UTC time
+ sscanf(str, "%04d.%02d.%04dT%02d:%02d:%02dZ",
+ &(tm1.tm_year), &(tm1.tm_mon), &(tm1.tm_mday),
+ &(tm1.tm_hour), &(tm1.tm_min), &(tm1.tm_sec));
+ snprintf(buf, sizeof(buf), "%04d%02d%02d%02d%02d%02dZ",
+ tm1.tm_year, tm1.tm_mon, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ }
+ rc = ASN1_GENERALIZEDTIME_set_string(asn1tm, buf);
+ //printf("String: %s, tz: %d, ASN1 time: %s\n", str, dmz, asn1tm->data);
+ return ERR_OK;
+}
+
+//===================================================================
+// converts time_t to timestamp string
+// t - time_t input value
+// szTimestamp - output buffer
+// len - length of buffer
+// returns error code or ERR_OK
+//===================================================================
+EXP_OPTION int time_t2str(time_t t, char* szTimestamp, int len)
+{
+ struct tm tm1;
+
+ RETURN_IF_NULL_PARAM(szTimestamp);
+ ddocLocalTime(&t, &tm1, 0);
+ snprintf(szTimestamp, len, "%04d-%02d-%02dT%02d:%02d:%02dZ",
+ tm1.tm_year + 1900, tm1.tm_mon + 1,
+ tm1.tm_mday, tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ return ERR_OK;
+}
+
+//===================================================================
+// converts string to time_t
+// szTimestamp - input buffer
+// pT - address time_t output value
+// returns error code or ERR_OK
+//===================================================================
+EXP_OPTION int str2time_t(char* szTimestamp, time_t* pT)
+{
+ struct tm tm1;
+ time_t t1 = 0;
+ //int dmz = 0;
+
+ RETURN_IF_NULL_PARAM(szTimestamp);
+ RETURN_IF_NULL_PARAM(pT);
+ _tzset();
+ memset(&tm1, 0, sizeof(tm1));
+ sscanf(szTimestamp, "%04d.%02d.%04dT%02d:%02d:%02dZ",
+ &(tm1.tm_year), &(tm1.tm_mon), &(tm1.tm_mday),
+ &(tm1.tm_hour), &(tm1.tm_min), &(tm1.tm_sec) /*, &dmz*/);
+ tm1.tm_year -= 1900;
+ tm1.tm_mon -= 1;
+ tm1.tm_isdst = _daylight;
+ t1 = mktime(&tm1);
+ //t1 -= (dmz * 3600);
+ (*pT) = t1;
+ return ERR_OK;
+}
+
diff --git a/libdigidoc/DigiDocConvert.h b/libdigidoc/DigiDocConvert.h
new file mode 100644
index 0000000..d82886c
--- /dev/null
+++ b/libdigidoc/DigiDocConvert.h
@@ -0,0 +1,303 @@
+#ifndef __DIGIDOC_CONVERT_H__
+#define __DIGIDOC_CONVERT_H__
+//==================================================
+// FILE: DigiDocEnc.h
+// PROJECT: Digi Doc Encryption
+// DESCRIPTION: DigiDoc character conversion routines
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 22.09.2004 Veiko Sinivee
+// Creation
+//==================================================
+
+#include <libdigidoc/DigiDocLib.h>
+#include <libdigidoc/DigiDocDefs.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//==========< general functions >============
+
+//--------------------------------------------------
+// Decodes a single hex digit
+// h - hex digit
+// return binary value
+//--------------------------------------------------
+byte h2b(char h);
+
+//--------------------------------------------------
+// Converts a single byte to two hex characters
+// b - binary value
+// dest - destination buffer
+//--------------------------------------------------
+void b2h(byte b, char* dest);
+
+//--------------------------------------------------
+// Converts correct filename to incorrect encoding
+// used in formats 1.0, 1.1 and 1.2
+// src - input data
+// dest - buffer for converted data
+// len - length of destination buffer
+//--------------------------------------------------
+EXP_OPTION void convFNameToWin(const char* src, char* dest, int len);
+
+//--------------------------------------------------
+// Converts bad UTF-8 filename used in formats 1.0,
+// 1.1 and 1.2 to correct encoding
+// src - input data
+// dest - buffer for converted data
+// len - length of destination buffer
+//--------------------------------------------------
+EXP_OPTION void convWinToFName(const char* src, char* dest, int len);
+
+// Converts a hex number (string) to binary value
+EXP_OPTION void hex2bin(const char* hex, byte* bin, int* len);
+
+// Converts a binary value to hex string
+EXP_OPTION void bin2hex(const byte* bin, int blen, char* hex, int* len);
+
+//============================================================
+// Encodes input data in hex format.
+// pMBufSrc - input data
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocBin2Hex(const DigiDocMemBuf* pMBufSrc, DigiDocMemBuf* pMBufDest);
+
+// Helper function that converts ISO Latin1 to UTF8
+EXP_OPTION char* ascii2utf8(const char* ascii, char* utf8out, int* outlen);
+
+// Helper function that converts UTF8 to ISO Latin1
+EXP_OPTION char* utf82ascii(const char* utf8in, char* asciiout, int* outlen);
+
+// converts string from unicode to ascii
+EXP_OPTION void unicode2ascii(const char* uni, char* dest);
+// converts unicode escapes string to UTF8
+EXP_OPTION void unicodeEscapes2utf8(const char* uni, char* dest);
+
+
+char* escape2xmlsym(const char* src);
+
+
+int hasUmlauts(const char* str);
+int str2asn1time(const SignedDoc* pSigDoc, const char* str, ASN1_GENERALIZEDTIME* asn1tm);
+
+//--------------------------------------------------
+// Converts xml symbols to corresponding escapes
+// src - string with xml special sybols
+// returns string with esacpes
+//--------------------------------------------------
+char* escape2xmlsym(const char* src);
+
+char* unescapeXmlsym(const char* src);
+
+//--------------------------------------------------
+// Converts input data to UTF-8
+// src - input data
+// returns converted string or NULL. Caller must free it.
+//--------------------------------------------------
+EXP_OPTION int ddocConvertInput(const char* src, char** dest);
+
+// Base64 encode some data
+EXP_OPTION void encode(const byte* raw, int rawlen, byte* buf, int* buflen);
+// Base64 decode some data
+EXP_OPTION void decode(const byte* raw, int rawlen, byte* buf, int* buflen);
+
+
+//============================================================
+// Decodes input data in Base64 format.
+// pMBufSrc - input data
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocDecodeBase64(DigiDocMemBuf* pMBufSrc, DigiDocMemBuf* pMBufDest);
+
+//============================================================
+// Decodes input data in Base64 format.
+// data - input data
+// len - length of input data. Use -1 for zero terminated strings
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocDecodeBase64Data(void* data, long lLen, DigiDocMemBuf* pMBufDest);
+
+//============================================================
+// Encodes input data in Base64 format.
+// pMBufSrc - input data
+// pMBufDest - destination buffer
+//============================================================
+EXP_OPTION int ddocEncodeBase64(const DigiDocMemBuf* pMBufSrc, DigiDocMemBuf* pMBufDest);
+
+//=======< time convesrion >=======================
+
+//--------------------------------------------------
+// Decodes an ASN1 generalized time
+// tm - ASN1 generalized time
+// y - year
+// M - month
+// d - day of month
+// h - hour
+// m - minute
+// s - second
+// returns error code or ERR_OK
+//--------------------------------------------------
+int decodeGeneralizedTime(ASN1_GENERALIZEDTIME *tm,
+ int* y, int* M, int* d,
+ int* h, int* m, int* s);
+
+//--------------------------------------------------
+// Decodes an ASN1 UTC time
+// tm - ASN1 generalized time
+// y - year
+// M - month
+// d - day of month
+// h - hour
+// m - minute
+// s - second
+// returns error code or ERR_OK
+//--------------------------------------------------
+int decodeUTCTime(ASN1_UTCTIME *tm,
+ int* y, int* M, int* d,
+ int* h, int* m, int* s);
+
+//==========================================================
+// converts ASN1 time to time_t
+//==========================================================
+int asn1time2time_t(ASN1_TIME* tm, time_t* pT);
+
+int asn1time2time_t_local(ASN1_TIME* tm, time_t* pT);
+
+//==========================================================
+// converts ASN1 time to string
+//==========================================================
+int asn1time2strYear(const SignedDoc* pSigDoc, ASN1_TIME* tm, char* buf, int year, int len);
+
+//==========================================================
+// converts ASN1 time to string
+//==========================================================
+int asn1time2str(const SignedDoc* pSigDoc, ASN1_TIME* tm, char* buf, int len);
+
+//===================================================================
+// converts time_t to timestamp string
+// t - time_t input value
+// szTimestamp - output buffer
+// len - length of buffer
+// returns error code or ERR_OK
+//===================================================================
+ EXP_OPTION int time_t2str(time_t t, char* szTimestamp, int len);
+
+//===================================================================
+// converts string to time_t
+// szTimestamp - input buffer
+// pT - address time_t output value
+// returns error code or ERR_OK
+//===================================================================
+EXP_OPTION int str2time_t(char* szTimestamp, time_t* pT);
+
+//--------------------------------------------------
+// Converts a filename according to platform rules
+// dest - destination buffer
+// destlen - destination buffer length
+// src - source filename
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int ddocConvertFileName(char* dest, int destlen, const char* src);
+
+//==========< only win32 fucntions >============
+
+#ifdef WIN32
+
+//--------------------------------------------------
+// Converts input OEM charset data to 16 bit unicode.
+// oem - 8 bit oem charset input data
+// unicode - address of pointer for allocated unicode string. Caller must free() !
+// outlen - address of length variable for unicode string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int oem2unicode(const char* oem, char** unicode, int* outlen);
+
+//--------------------------------------------------
+// Converts input 16 bit unicode data to UTF8.
+// unicode - 16 bit unicode input data
+// utf8 - address of pointer for allocated utf8 string. Caller must free() !
+// outlen - address of length variable for utf8 string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int unicode2utf8(const char* unicode, char** utf8, int* outlen);
+
+//--------------------------------------------------
+// Converts input OEM charset data to UTF-8
+// oem - 8 bit oem charset input data
+// utf8 - address of buffer allocated utf8 string.
+// len - size of buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int oem2utf8(const char* oem, char* utf8, int len);
+
+//--------------------------------------------------
+// Converts input UTF-8 data to 16 bit unicode data.
+// utf8 - UTF-8 input data
+// unicode - address of pointer for allocated unicode string. Caller must free() !
+// outlen - address of length variable for unicode string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int utf82unicode(const char* utf8, char** unicode, int* outlen);
+
+//--------------------------------------------------
+// Converts input 16 bit unicode data to oem charset data.
+// unicode - 16 bit unicode input data
+// oem - address of pointer for allocated oem string. Caller must free() !
+// outlen - address of length variable for oem string
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int unicode2oem(const char* unicode, char** oem, int* outlen);
+
+//--------------------------------------------------
+// Converts input UTF-8 data to OEM charset data
+// utf8 - UTF-8 input data
+// oem - address of buffer for oem string.
+// len - size of buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int utf82oem(const char* utf8, char* oem, int len);
+
+//--------------------------------------------------
+// Converts input UTF-8 data to OEM charset data
+// pSigDoc - signed doc object
+// pDf - data file obejct
+// outFileName - output buffer
+// len - length of output buffer
+// returns error code or ERR_OK
+//--------------------------------------------------
+EXP_OPTION int getDataFileFileName(SignedDoc* pSigDoc, DataFile* pDf, char* outFileName, int len);
+
+#endif // WIN32
+
+//--------------------------------------------------
+// Releases mem-block allocated by lib. In win32
+// this must be done since the mem was allocated by dll
+// and must also be released by dll that allocated it.
+// p - mem to be freed
+//--------------------------------------------------
+EXP_OPTION void freeLibMem(void* p);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif // __DIGIDOC_CONVERT_H__
+
+
+
diff --git a/libdigidoc/DigiDocCsp.c b/libdigidoc/DigiDocCsp.c
new file mode 100644
index 0000000..ee0081b
--- /dev/null
+++ b/libdigidoc/DigiDocCsp.c
@@ -0,0 +1,2229 @@
+//==================================================
+// FILE: DigiDocCsp.c
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for creating
+// and reading signed documents.
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 20.10.2004 Changed createOCSPRequest, added SignedDoc parameeter
+// 10.02.2004 Changed decodeCertificateData
+// ReadCertSerialNumber
+// ReadCertificate
+// NotaryInfo_new
+// 01.02.2004 Aare Amenberg
+// from comments "Functions from EstIDLib.c"
+// functions from EstIdLib.c file
+// 20.11.2003 Aare Amenberg
+// removed tes2.resp file creating
+// 29.10.2003 Created by AA
+//
+//==================================================
+#ifdef WIN32
+
+#define WIN32_PKCS 1
+
+#include <windows.h>
+#include <wincrypt.h>
+#include <libdigidoc/DigiDocDefs.h>
+#include <libdigidoc/DigiDocLib.h>
+#include <libdigidoc/DigiDocCert.h>
+#include <libdigidoc/DigiDocMem.h>
+#include <libdigidoc/DigiDocConfig.h>
+#include <libdigidoc/DigiDocOCSP.h>
+#include <libdigidoc/DigiDocObj.h>
+#include <libdigidoc/DigiDocGen.h>
+#include <libdigidoc/DigiDocVerify.h>
+#include <libdigidoc/DigiDocConvert.h>
+#include <libdigidoc/DigiDocDebug.h>
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <memory.h>
+#include <string.h>
+#include <assert.h>
+#include <malloc.h>
+#include <direct.h>
+
+#include <fcntl.h>
+#include <time.h>
+
+
+#include <openssl/sha.h>
+#include <openssl/rsa.h>
+#include <openssl/evp.h>
+#include <openssl/objects.h>
+#include <openssl/x509.h>
+#include <openssl/x509v3.h>
+#include <openssl/err.h>
+#include <openssl/pem.h>
+#include <openssl/ssl.h>
+#include <openssl/ocsp.h>
+#include <openssl/pkcs12.h>
+
+#include <libxml/globals.h>
+#include <libxml/xmlerror.h>
+#include <libxml/parser.h>
+#include <libxml/parserInternals.h> /* only for xmlNewInputFromFile() */
+#include <libxml/tree.h>
+#include <libxml/debugXML.h>
+#include <libxml/xmlmemory.h>
+#include <libxml/c14n.h>
+
+#include "DigiCrypt.h"
+#include "DigiDocCert.h"
+
+#include "DigiDocCsp.h"
+
+CSProvider * cCSProvider;
+CSProvider * knownCSProviders[3];
+
+
+//AARE01102003
+typedef struct StoreHandle_st {
+ HCERTSTORE hHandle;
+ BOOL fRoot;
+} StoreHandle;
+
+
+BOOL Digi_OpenStore(StoreHandle *hStore);
+void Digi_CloseStore(StoreHandle *hStore);
+BOOL Digi_IsValidResponderCert(PCCERT_CONTEXT pCert);
+
+X509 * Digi_FindX509CopyFromStore(StoreHandle *hStore, X509 *pX509cert);
+X509 *Digi_FindResponderCert(StoreHandle *hStore, X509 *poSignerCert);
+char *Digi_GetName(X509_NAME *pName);
+BOOL Digi_CheckEnhancedKeyUsage(PCCERT_CONTEXT pCert, char *psValue);
+X509 *Digi_FindCertByResponse(StoreHandle *hStore, OCSP_RESPONSE *poResponse);
+PCCERT_CONTEXT Digi_FindCertBySubject(StoreHandle *hStore,char *psCN, BOOL bCheckValid, const char* szSerialNr, BOOL bCA);
+BOOL Digi_CompareCN(char *psSub1, char *psSub2);
+X509 **Digi_MakeCertList(X509 *poX509Main, StoreHandle *hStore);
+X509 **Digi_MakeCertListLow(X509 *poX509Main, StoreHandle *hStore);
+BOOL Digi_CheckResponderCertByResponse(X509 *poX509Responder, OCSP_RESPONSE *poResponse);
+
+void Digi_FreeCertList(X509 **caCerts);
+BOOL Digi_IsCert1SubjectDNEqualCert2IssuerDN(X509 *pCert1, X509 *pCert2);
+int ReadTestAare(char *pkcs12file);
+int Test_ReadCertData(X509 *poX509);
+int Test_ReadCertDataC(PCCERT_CONTEXT pCert);
+
+// Reads a certificate from pkcs12 container
+EXP_OPTION int Digi_readCertificateByPKCS12OnlyCertHandle(const char *pkcs12file, const char * passwd, X509 **x509);
+int Digi_getConfirmationWithCertSearch(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, char* pkcs12File, char* password,
+ char* notaryURL, char* proxyHost, char* proxyPort);
+//int Digi_setNotaryCertificate(NotaryInfo* pNotary, X509* notCert);
+int Digi_verifyNotaryInfoWithCertSearch(const SignedDoc* pSigDoc, const NotaryInfo* pNotInfo);
+
+// verifies this one signature
+int Digi_verifySignatureInfo(const SignedDoc* pSigDoc, const SignatureInfo* pSigInfo,
+ const char* szDataFile);
+// verifies the whole document (returns on first err)
+int Digi_verifySigDoc(const SignedDoc* pSigDoc, const char* szDataFile);
+int Digi_verifySigDocWithCertSearch(const SignedDoc* pSigDoc, const char* szDataFile);
+int Digi_verifyNotaryInfoCERT(const SignedDoc* pSigDoc,
+ const NotaryInfo* pNotInfo,
+ const X509** caCerts,
+ const X509* notCert,
+ const X509* pSigCA);
+//int Digi_initializeNotaryInfoWithOCSP(SignedDoc* pSigDoc, NotaryInfo* pNotary,
+// OCSP_RESPONSE* resp, X509* notCert, int initDigest);
+
+
+// verifies signed doc
+int verifySigDoc_ByCertStore(const SignedDoc* pSigDoc, const char* szDataFile);
+// Verifies this signature
+int verifySignatureInfo_ByCertStore(const SignedDoc* pSigDoc,
+ const SignatureInfo* pSigInfo, const char* szDataFile);
+// Verfies NotaryInfo signature
+int verifyNotaryInfo_ByCertStore(const SignedDoc* pSigDoc, const NotaryInfo* pNotInfo);
+
+// resolves certificate chain from MS CertStore upto root cert
+int resolveCertChain_ByCertStore(CertItem* pListStart);
+
+int GetAllCertificatesFromStore(const CertSearchStore *sS, CertItem **certList, int *numberOfCerts);
+void prepareString(const char * strIN,char * strOUT);
+void reverseArray(unsigned char *array, unsigned long arrayLen);
+
+extern int setup_verifyCERT(X509_STORE **newX509_STORE, const char *CApath, const X509** certs);
+
+extern X509_ALGOR* setSignAlgorithm(const EVP_MD * type);
+
+extern EXP_OPTION int signOCSPRequestPKCS12(OCSP_REQUEST *req, const char* filename, const char* passwd);
+
+
+extern LPBYTE getDefaultKeyName(CSProvider * cProvider);
+//extern CERT_PUBLIC_KEY_INFO * getCardKeyInfo(const char * ppContainerName);
+extern int GetCertificateFromStore(const CertSearchStore *sS, X509 **x509);
+extern int GetSignedHashWithEstIdCSPkey(const char * dataToBeSigned,unsigned long dataLen,unsigned char *pbKeyBlob, unsigned long *pbKeyBlobLen,unsigned char *hash, unsigned long *hashLen, unsigned char * hashedSignature,unsigned long * sigLen);
+extern int GetSignedHashWithKeyAndCSP(char *psKeyName, char *psCSPName, const char * dataToBeSigned,unsigned long dataLen,unsigned char *pbKeyBlob, unsigned long *pbKeyBlobLen,unsigned char *hash, unsigned long *hashLen, unsigned char * hashedSignature,unsigned long * sigLen, const char*
+);
+extern X509 * findIssuerCertificatefromStore(X509 *x509);
+X509* Digi_FindDirectCA(X509 *poX509Main, StoreHandle *hStore);
+
+X509* Digi_FindCertBySubjectAndHash(StoreHandle *hStore, char *psCN, BOOL bCheckValid, const char* szSerialNr, BOOL bCA, DigiDocMemBuf *pHash);
+
+//==========< macros >====================
+
+#define SET_LAST_ERROR(code) (addError((code), __FILE__, __LINE__, ""))
+#define SET_LAST_ERROR_IF_NOT(expr, code) { if(!(expr)) addError((code), __FILE__, __LINE__, #expr); }
+#define SET_LAST_ERROR_RETURN(code, retVal) { SET_LAST_ERROR(code); return (retVal); }
+#define SET_LAST_ERROR_RETURN_IF_NOT(expr, code, retVal) { if(!(expr)) { addError((code), __FILE__, __LINE__, #expr); return (retVal); } }
+#define SET_LAST_ERROR_RETURN_VOID_IF_NOT(expr, code) { if(!(expr)) { addError((code), __FILE__, __LINE__, #expr); return; } }
+#define RETURN_IF_NOT(expr, code) SET_LAST_ERROR_RETURN_IF_NOT((expr), (code), (code));
+#define RETURN_IF_NULL(p) RETURN_IF_NOT((p), ERR_NULL_POINTER);
+#define RETURN_VOID_IF_NULL(p) SET_LAST_ERROR_RETURN_VOID_IF_NOT((p), ERR_NULL_POINTER);
+#define RETURN_OBJ_IF_NULL(p, obj) SET_LAST_ERROR_RETURN_IF_NOT((p), ERR_NULL_POINTER, (obj));
+#define SET_LAST_ERROR_RETURN_CODE(code) { SET_LAST_ERROR(code); return (code); }
+
+//========================================
+
+
+BOOL Digi_OpenStore(StoreHandle *hStore)
+{
+ BOOL fRes = FALSE;
+ if (hStore != NULL) {
+ memset(hStore,0,sizeof(StoreHandle));
+ hStore->hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG,L"CA");
+ if (hStore->hHandle != NULL)
+ fRes = TRUE;
+ }
+ return(fRes);
+}
+
+void Digi_CloseStore(StoreHandle *hStore)
+{
+if (hStore != NULL && hStore->hHandle)
+ CertCloseStore(hStore->hHandle,CERT_CLOSE_STORE_FORCE_FLAG);
+hStore->hHandle = NULL;
+hStore->fRoot = FALSE;
+}
+
+
+X509 * Digi_FindX509CopyFromStore(StoreHandle *hStore, X509 *pX509cert) {
+ X509 *pResultCert = NULL;
+ char* certBlob;
+ int certBlobLen;
+ PCCERT_CONTEXT pCertFindContext = NULL;
+ PCCERT_CONTEXT pCertContext = NULL;
+ char *psValue = "1.3.6.1.5.5.7.3.9";
+
+ if (hStore == NULL || pX509cert == NULL) return(pResultCert);
+
+ certBlobLen = i2d_X509(pX509cert, NULL) + 1000;
+ certBlob = malloc(certBlobLen);
+
+ encodeCert(pX509cert,certBlob,&certBlobLen);
+ if (!certBlob) return(pResultCert);
+
+ pCertFindContext = CertCreateCertificateContext(X509_ASN_ENCODING|PKCS_7_ASN_ENCODING,certBlob,certBlobLen);
+ if (!pCertFindContext) return(pResultCert);
+
+ pCertContext = CertFindCertificateInStore(hStore->hHandle, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
+ 0, CERT_FIND_EXISTING, pCertFindContext, NULL);
+
+ if (pCertContext) { //cert found
+ if (Digi_CheckEnhancedKeyUsage(pCertContext,psValue) != TRUE) return(pResultCert);
+ ddocDecodeX509Data(&pResultCert,pCertContext->pbCertEncoded,pCertContext->cbCertEncoded);
+ } else {
+ char schultz[300];
+ snprintf(schultz, sizeof(schultz), "CertFindCertificateInStore open failed with 0x%0lx ", GetLastError());
+ return(pResultCert);
+ }
+
+ if (certBlob) free(certBlob);
+
+ return pResultCert;
+}
+
+
+
+X509 *Digi_FindResponderCert(StoreHandle *hStore, X509 *poSignerCert)
+{
+X509 *poResultCert = NULL;
+FILETIME oResultTime;
+X509 *poX509;
+BOOL fSet;
+PCCERT_CONTEXT pCert = NULL;
+X509_NAME *poX509SignerName = NULL;
+X509_NAME *poX509CurrentName = NULL;
+
+poX509SignerName = X509_get_issuer_name(poSignerCert);
+while (pCert = CertEnumCertificatesInStore(hStore->hHandle, pCert))
+ {
+ fSet = FALSE;
+ //get handle
+ //AA100204
+ ddocDecodeX509Data(&poX509, pCert->pbCertEncoded,pCert->cbCertEncoded);
+ if (poX509 != NULL)
+ {
+ //get current cert issuer
+ poX509CurrentName = X509_get_issuer_name(poX509);
+ //TEST
+ //psTemp = Digi_GetName(poX509CurrentName);
+ //Digi_CheckEnhancedKeyUsage(pCert,"1.3.6.1.5.5");
+ //Test_ReadCertData(poX509);
+ //END TEST
+ // if issuer match
+ if (poX509SignerName != NULL && poX509CurrentName != NULL && X509_NAME_cmp(poX509SignerName, poX509CurrentName) == 0)
+ {
+ // check date
+ // NULL, if current time
+ if (Digi_IsValidResponderCert(pCert) == TRUE)
+ {
+ if (poResultCert == NULL)
+ fSet = TRUE;
+ else
+ {
+ if (CompareFileTime(&pCert->pCertInfo->NotBefore, &oResultTime) > 0)
+ fSet = TRUE;
+ }
+ if (fSet == TRUE)
+ {
+ //delete previous if exists
+ if (poResultCert != NULL)
+ X509_free(poResultCert);
+ //set result value
+ poResultCert = poX509;
+ memmove(&oResultTime,&pCert->pCertInfo->NotBefore,sizeof(FILETIME));
+ }
+ }
+ }
+ }
+ if (poX509 != NULL && fSet == FALSE)
+ X509_free(poX509);
+ }
+
+
+return(poResultCert);
+}
+
+int Test_ReadCertDataC(PCCERT_CONTEXT pCert)
+{
+int iRes = 0;
+X509 *poX509 = NULL;
+if (pCert != NULL);
+ //AA100204
+ ddocDecodeX509Data(&poX509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+if (poX509 != NULL)
+ iRes = Test_ReadCertData(poX509);
+return(iRes);
+}
+
+
+
+int Test_ReadCertData(X509 *poX509)
+{
+ int iRes;
+ DigiDocMemBuf mbuf1;
+ DigiDocMemBuf mbuf2;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ // get issuer DN
+ iRes = ddocCertGetIssuerDN(poX509, &mbuf1);
+ iRes = ddocMemAppendData(&mbuf1, "\n", -1);
+ // get subject DN
+ iRes = ddocCertGetSubjectDN(poX509, &mbuf2);
+ iRes = ddocMemAppendData(&mbuf1, (const char*)mbuf2.pMem, mbuf2.nLen);
+ // display it
+ MessageBox(NULL,(const char*)mbuf1.pMem,"TEST",0);
+ ddocMemBuf_free(&mbuf1);
+ ddocMemBuf_free(&mbuf2);
+ return(0);
+}
+
+BOOL Digi_IsValidResponderCert(PCCERT_CONTEXT pCert)
+{
+BOOL fIsValid = FALSE;
+char *psValue = "1.3.6.1.5.5.7.3.9";
+if (pCert != NULL)
+ {
+ fIsValid = Digi_CheckEnhancedKeyUsage(pCert,psValue);
+ if (fIsValid == TRUE)
+ {
+ if (CertVerifyTimeValidity(NULL,pCert->pCertInfo) != 0)
+ fIsValid = FALSE;
+ }
+ }
+return(fIsValid);
+}
+
+
+BOOL Digi_CheckEnhancedKeyUsage(PCCERT_CONTEXT pCert, char *psValue)
+{
+BOOL fRes = FALSE;
+DWORD dwFlags = CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG;
+PCERT_ENHKEY_USAGE pUsage = NULL;
+//DWORD cUsageIdentifier - number of elements in rgpszUsageIdentifier
+//LPSTR *rgpszUsageIdentifier - array;
+DWORD cbUsage = 0;
+BOOL fCallRes;
+int iI;
+char *psValueCurrent;
+fCallRes = CertGetEnhancedKeyUsage(pCert,dwFlags,NULL, &cbUsage);
+if (fCallRes == TRUE)
+ {
+ pUsage = (PCERT_ENHKEY_USAGE)malloc(cbUsage);
+ fCallRes = CertGetEnhancedKeyUsage(pCert,dwFlags,pUsage, &cbUsage);
+ if (fCallRes == TRUE)
+ {
+ for (iI=0; iI < (int)pUsage->cUsageIdentifier;++iI)
+ {
+ psValueCurrent = pUsage->rgpszUsageIdentifier[iI];
+ if (psValueCurrent != NULL && psValue != NULL)
+ {
+ if (strstr(psValueCurrent,psValue) != NULL)
+ {
+ fRes = TRUE;
+ break;
+ }
+ }
+ }
+ }
+ }
+if (pUsage != NULL)
+ free(pUsage);
+return(fRes);
+}
+
+
+X509 *Digi_FindCertByResponse(StoreHandle *hStore, OCSP_RESPONSE *poResponse)
+{
+ X509 *poX509 = NULL;
+ PCCERT_CONTEXT pCert = NULL;
+ OCSP_RESPID *rid = NULL;
+ OCSP_BASICRESP *br = NULL;
+ OCSP_RESPDATA *rd = NULL;
+ int iLen;
+ char sCN[255];
+
+ if (poResponse != NULL) {
+ if ((br = OCSP_response_get1_basic(poResponse)) == NULL)
+ return(poX509);
+ rd = br->tbsResponseData;
+ rid = rd->responderId;
+ if (rid->type != V_OCSP_RESPID_NAME) {
+ if(br) OCSP_BASICRESP_free(br);
+ return(poX509);
+ }
+ iLen = X509_NAME_get_text_by_NID(rid->value.byName,NID_commonName,sCN,sizeof(sCN));
+ if (iLen > 0) //VS: 18.03.2006 - use only currently valid cert for new notary
+ pCert = Digi_FindCertBySubject(hStore, sCN, TRUE, 0, TRUE);
+ if(pCert != NULL)
+ //AA100204
+ ddocDecodeX509Data(&poX509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ }
+ if(br) OCSP_BASICRESP_free(br);
+ return(poX509);
+}
+
+
+
+//Added by AA 09/10/2003
+BOOL Digi_CheckResponderCertByResponse(X509 *poX509Responder, OCSP_RESPONSE *poResponse)
+{
+BOOL fRes = FALSE;
+OCSP_RESPID *rid = NULL;
+OCSP_BASICRESP *br = NULL;
+OCSP_RESPDATA *rd = NULL;
+int iLen;
+char sCNResp[255];
+char sCNCert[255];
+if (poResponse != NULL)
+ {
+ if ((br = OCSP_response_get1_basic(poResponse)) == NULL)
+ return(fRes);
+ rd = br->tbsResponseData;
+ rid = rd->responderId;
+ if (rid->type != V_OCSP_RESPID_NAME)
+ return(fRes);
+ iLen = X509_NAME_get_text_by_NID(rid->value.byName,NID_commonName,sCNResp,sizeof(sCNResp));
+ if (iLen > 0)
+ {
+ iLen = X509_NAME_get_text_by_NID(X509_get_subject_name(poX509Responder),NID_commonName, sCNCert,sizeof(sCNCert));
+ if (iLen > 0)
+ {
+ fRes = Digi_CompareCN(sCNResp,sCNCert);
+ }
+ }
+ }
+return(fRes);
+}
+
+//VS: 18.03.2006 - use only currently valid cert for new notary
+PCCERT_CONTEXT Digi_FindCertBySubject(StoreHandle *hStore, char *psCN, BOOL bCheckValid, const char* szSerialNr, BOOL bCA)
+{
+ PCCERT_CONTEXT pCert = NULL;
+ BOOL fFind = FALSE;
+ X509 *poX509;
+ char sSerial[255];
+ time_t tNow;
+ DigiDocMemBuf mbuf;
+
+ mbuf.pMem = 0;
+ mbuf.nLen = 0;
+
+ if (hStore == NULL || psCN == NULL)
+ return(pCert);
+ Digi_CloseStore(hStore);
+ hStore->hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, (bCA ? L"CA" : L"My"));
+ if (hStore->hHandle == NULL)
+ return(pCert);
+ //get signer issuer
+ while (fFind == FALSE && (pCert = CertEnumCertificatesInStore(hStore->hHandle,pCert)))
+ {
+ //AA100204
+ ddocDecodeX509Data(&poX509, pCert->pbCertEncoded,pCert->cbCertEncoded);
+ if (poX509 != NULL)
+ {
+ //iLen = X509_NAME_get_text_by_NID(X509_get_subject_name(poX509),NID_commonName, sSubject,255);
+
+ ddocCertGetSubjectCN(poX509, &mbuf);
+
+ if(mbuf.nLen > 0) {
+ fFind = Digi_CompareCN((char*)mbuf.pMem, psCN);
+ if(fFind) {
+ if(szSerialNr) { //VS: 18.03.2006 - look for a cert with specific serial nr
+ ReadCertSerialNumber(sSerial, sizeof(sSerial)-1, poX509);
+ fFind = !strcmp(szSerialNr, sSerial);
+ } else if(bCheckValid) { //VS: 18.03.2006 - use only currently valid cert for new notary
+ time(&tNow);
+ fFind = !isCertValid(poX509, tNow);
+ }
+ }
+ }
+ X509_free(poX509);
+ }
+ }
+ if (fFind == FALSE)
+ pCert = NULL;
+ return(pCert);
+}
+
+X509* Digi_FindCertBySubjectAndHash(StoreHandle *hStore, char *psCN, BOOL bCheckValid, const char* szSerialNr, BOOL bCA, DigiDocMemBuf *pHash)
+{
+ PCCERT_CONTEXT pCert = NULL;
+ BOOL fFind = FALSE;
+ X509 *poX509 = NULL, *pSCert = NULL;
+ char sSerial[255];
+ time_t tNow;
+ DigiDocMemBuf mbuf1, mbuf2, mbuf3; //, mbuf4, mbuf5;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ mbuf2.pMem = 0;
+ mbuf2.nLen = 0;
+ mbuf3.pMem = 0;
+ mbuf3.nLen = 0;
+ /*mbuf4.pMem = 0;
+ mbuf4.nLen = 0;
+ mbuf5.pMem = 0;
+ mbuf5.nLen = 0;*/
+ if (hStore == NULL || psCN == NULL)
+ return NULL;
+ Digi_CloseStore(hStore);
+ hStore->hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, (bCA ? L"CA" : L"My"));
+ if (hStore->hHandle == NULL)
+ return NULL;
+ ddocEncodeBase64(pHash, &mbuf3);
+ ddocDebug(3, "Digi_FindCertBySubjectAndHash", "Find CN: %s serial: %s subj-hash: %s", psCN, szSerialNr, (char*)mbuf3.pMem);
+ ddocMemBuf_free(&mbuf3);
+ //get signer issuer
+ while (fFind == FALSE && (pCert = CertEnumCertificatesInStore(hStore->hHandle,pCert)))
+ {
+ //AA100204
+ ddocDecodeX509Data(&poX509, pCert->pbCertEncoded,pCert->cbCertEncoded);
+ if (poX509 != NULL)
+ {
+ //iLen = X509_NAME_get_text_by_NID(X509_get_subject_name(poX509),NID_commonName, sSubject,255);
+ ddocCertGetSubjectCN(poX509, &mbuf1);
+ if(mbuf1.nLen > 0) {
+ fFind = Digi_CompareCN((char*)mbuf1.pMem, psCN);
+ if(fFind) {
+ if(szSerialNr) { //VS: 18.03.2006 - look for a cert with specific serial nr
+ ReadCertSerialNumber(sSerial, sizeof(sSerial)-1, poX509);
+ fFind = !strcmp(szSerialNr, sSerial);
+ } else if(bCheckValid) { //VS: 18.03.2006 - use only currently valid cert for new notary
+ time(&tNow);
+ fFind = !isCertValid(poX509, tNow);
+ }
+ }
+ if(fFind && pHash && poX509) {
+ readSubjectKeyIdentifier(poX509, &mbuf2);
+ ddocEncodeBase64(&mbuf2, &mbuf3);
+ //readAuthorityKeyIdentifier(poX509, &mbuf4);
+ //ddocEncodeBase64(&mbuf4, &mbuf5);
+ if(!ddocMemCompareMemBufs(pHash, &mbuf2)) {
+ pSCert = poX509;
+ fFind = TRUE;
+ //break;
+ }
+ else
+ fFind = FALSE;
+ }
+ }
+ //ddocDebug(3, "Digi_FindCertBySubjectAndHash", "Compare CN: %s serial: %s subj-hash: %s auth-hash: %s rc: %d", (char*)mbuf1.pMem, sSerial, (char*)mbuf3.pMem, (char*)mbuf5.pMem, fFind);
+ ddocDebug(3, "Digi_FindCertBySubjectAndHash", "Compare CN: %s serial: %s subj-hash: %s rc: %d", (char*)mbuf1.pMem, sSerial, (char*)mbuf3.pMem, fFind);
+ if(!pSCert) {
+ X509_free(poX509);
+ poX509 = NULL;
+ }
+ ddocMemBuf_free(&mbuf1);
+ ddocMemBuf_free(&mbuf2);
+ ddocMemBuf_free(&mbuf3);
+ //ddocMemBuf_free(&mbuf4);
+ //ddocMemBuf_free(&mbuf5);
+ }
+ }
+ if(fFind == FALSE)
+ pCert = NULL;
+ ddocMemBuf_free(&mbuf1);
+ ddocMemBuf_free(&mbuf2);
+ ddocMemBuf_free(&mbuf3);
+ //ddocMemBuf_free(&mbuf4);
+ //ddocMemBuf_free(&mbuf5);
+ return pSCert;
+}
+
+//----------------------------------------------------
+// Returns a list of certificates based on the
+// search criteria
+// szCN - CN of certs to search for
+// tValid - check validity on the given date (if not 0)
+// szSerialNr - serach for certs with this serial nr
+// pMBuf - public key hash to search
+//----------------------------------------------------
+X509 **Digi_FindCACerts(StoreHandle *hStore, const char* szCN, time_t tValid,
+ const char* szSerialNr, DigiDocMemBuf* pMBuf)
+{
+ int iMaxCerts = 512;
+ int iRes = 0, l1, l2;
+ X509 **caCerts = NULL;
+ X509 *poX509;
+ PCCERT_CONTEXT pCert = NULL;
+ BOOL fAdd;
+ char buf1[255], buf2[100];
+ DigiDocMemBuf mbuf1;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ //ddocDebug(3, "Digi_FindCACerts", "CN: %s tValid: %ld serial: %s,
+ // open CA store
+ if(!hStore) return NULL;
+ Digi_CloseStore(hStore);
+ hStore->hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG,L"CA");
+ if (hStore->hHandle == NULL) {
+ return NULL;
+ }
+
+ // alloc list and initalize all positions to NULL
+ caCerts = (X509**)malloc(sizeof(void*) * (iMaxCerts+1));
+ if(caCerts == NULL) {
+ return(caCerts);
+ }
+ memset(caCerts,0,sizeof(void*) * (iMaxCerts+1));
+
+
+ if(hStore->hHandle != NULL) {
+ while(pCert= CertEnumCertificatesInStore(hStore->hHandle, pCert)) {
+ fAdd = FALSE;
+ ddocDecodeX509Data(&poX509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ if(poX509 != NULL) {
+ // check CN
+ if(szCN) {
+ buf1[0] = 0;
+ X509_NAME_get_text_by_NID(X509_get_subject_name(poX509), NID_commonName, buf1, sizeof(buf1));
+ fAdd = Digi_CompareCN((char*)szCN, buf1);
+ }
+ // check serial nr
+ if(szSerialNr) {
+ buf1[0] = 0;
+ ReadCertSerialNumber(buf1, sizeof(buf1)-1, poX509);
+ fAdd = !strcmp(szSerialNr, (const char*)buf1);
+ }
+ // check pubkey hash
+ if(pMBuf) {
+ ddocCertGetPubkeyDigest(poX509, &mbuf1);
+ l1 = sizeof(buf1);
+ l2 = sizeof(buf2);
+ bin2hex((const byte*)mbuf1.pMem, mbuf1.nLen, buf1, &l1);
+ bin2hex((const byte*)pMBuf->pMem, pMBuf->nLen, buf2, &l2);
+ ddocDebug(3, "Digi_FindCACerts", "Compare cert-hash: %s with searched-hash %s", buf1, buf2);
+ fAdd = !ddocMemCompareMemBufs(&mbuf1, pMBuf);
+ ddocMemBuf_free(&mbuf1);
+ }
+ if(tValid)
+ fAdd = !isCertValid(poX509, tValid);
+ }
+ // if any of the conditiones matched then add cert to list
+ if (fAdd == TRUE) {
+ caCerts[iRes] = poX509;
+ ++iRes;
+ }
+ else
+ X509_free(poX509);
+ }
+ }
+ // if no certs found then free the array
+ caCerts[iRes] = NULL;
+ if(iRes == 0) {
+ free(caCerts);
+ caCerts = NULL;
+ }
+ return(caCerts);
+}
+
+
+X509 **Digi_MakeCertList(X509 *poX509Main, StoreHandle *hStore)
+{
+X509 **caCerts = NULL;
+memset(hStore,0,sizeof(StoreHandle));
+hStore->hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG,L"CA");
+if (hStore->hHandle != NULL)
+ {
+ caCerts = Digi_MakeCertListLow(poX509Main, hStore);
+ if (caCerts == NULL)
+ {
+ CertCloseStore(hStore->hHandle,CERT_CLOSE_STORE_FORCE_FLAG);
+ hStore->hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG,L"ROOT");
+ if (hStore->hHandle != NULL)
+ {
+ hStore->fRoot = TRUE;
+ caCerts = Digi_MakeCertListLow(poX509Main, hStore);
+ }
+ }
+ }
+return(caCerts);
+}
+
+
+X509 **Digi_MakeCertListLow(X509 *poX509Main, StoreHandle *hStore)
+{
+int iMaxCerts = 512;
+int iRes = 0;
+X509 **caCerts = NULL;
+X509 *poX509;
+PCCERT_CONTEXT pCert = NULL;
+BOOL fAdd;
+if (poX509Main == NULL)
+ return(caCerts);
+caCerts = (X509**)malloc(sizeof(void*) * (iMaxCerts+1));
+if (caCerts == NULL)
+ return(caCerts);
+memset(caCerts,0,sizeof(void*) * (iMaxCerts+1));
+
+if (hStore->hHandle != NULL)
+ {
+ while( pCert= CertEnumCertificatesInStore( hStore->hHandle,pCert))
+ {
+ fAdd = FALSE;
+ ddocDecodeX509Data(&poX509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ //TEST
+ //Test_ReadCertData(poX509);
+ //ENDTEST
+ if (poX509 != NULL)
+ fAdd = Digi_IsCert1SubjectDNEqualCert2IssuerDN(poX509,poX509Main);
+ if (fAdd == TRUE)
+ {
+ caCerts[iRes] = poX509;
+ ++iRes;
+ }
+ else
+ X509_free(poX509);
+ }
+ }
+//Added by AA 2004/03/15
+caCerts[iRes] = NULL;
+if (iRes == 0)
+ {
+ free(caCerts);
+ caCerts = NULL;
+ }
+return(caCerts);
+}
+
+
+X509* Digi_FindDirectCA(X509 *poX509Main, StoreHandle *hStore)
+{
+ X509 *poX509;
+ PCCERT_CONTEXT pCert = NULL;
+
+ if (poX509Main == NULL)
+ return NULL;
+
+ if (hStore->hHandle != NULL) {
+ while(pCert = CertEnumCertificatesInStore( hStore->hHandle, pCert)) {
+ ddocDecodeX509Data(&poX509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ if(poX509 != NULL) {
+ if(Digi_IsCert1SubjectDNEqualCert2IssuerDN(poX509, poX509Main)) {
+ return poX509;
+ }
+ }
+ else
+ X509_free(poX509);
+ }
+ }
+ return NULL;
+}
+
+void Digi_FreeCertList(X509 **caCerts)
+{
+int iMaxCerts = 512;
+int i;
+if (caCerts != NULL)
+ {
+ for(i = 0; i < iMaxCerts; i++)
+ {
+ if(caCerts[i] != NULL)
+ X509_free(caCerts[i]);
+ }
+ free(caCerts);
+ }
+}
+
+
+BOOL Digi_CompareCN(char *psSub1, char *psSub2)
+{
+ BOOL fRes = FALSE;
+ if (psSub1 != NULL && psSub2 != NULL )
+ {
+ if (strlen(psSub1) > 0 || strlen(psSub2) > 0)
+ {
+ if (strcmp(psSub1,psSub2) == 0)
+ fRes = TRUE;
+ }
+ }
+ return(fRes);
+}
+
+
+int countCerts(const X509** certs)
+{
+ int i = 0;
+ while(certs && certs[i])
+ i++;
+ return i;
+}
+
+BOOL Digi_IsCert1SubjectDNEqualCert2IssuerDN(X509 *pCert1, X509 *pCert2)
+{
+BOOL fEqual = FALSE;
+unsigned long ulHash1;
+unsigned long ulHash2;
+ulHash1 = X509_subject_name_hash(pCert1);
+ulHash2 = X509_issuer_name_hash(pCert2);
+if (ulHash1 == ulHash2)
+ fEqual = TRUE;
+return(fEqual);
+}
+
+
+//29/09/2003
+//31/05/2006 - (g_current_TSAProfile->g_bAddTimeStamp) enables timestamping
+int Digi_getConfirmationWithCertSearch(SignedDoc* pSigDoc, SignatureInfo* pSigInfo,
+ char* pkcs12File, char *password,
+ char* notaryURL, char* proxyHost, char* proxyPort)
+{
+ int err = ERR_OK, err2 = ERR_OK, i, l1;
+ StoreHandle hStore;
+ NotaryInfo* pNotInf = NULL;
+ X509 *pNotCert = NULL, *pNotCertFound = NULL, *pSigCa = 0;
+ X509 **caCerts = NULL;
+ X509 **respCerts = NULL;
+ const DigiDocMemBuf *pMBuf = 0;
+ char szCN[255], buf1[100];
+
+ // set default values from config file
+ if(ConfigItem_lookup_bool("SIGN_OCSP", 1)) {
+ if(!pkcs12File || !strlen(pkcs12File))
+ pkcs12File = (char*)ConfigItem_lookup("DIGIDOC_PKCS_FILE");
+ if(!password || !strlen(password))
+ password = (char*)ConfigItem_lookup("DIGIDOC_PKCS_PASSWD");
+ }
+ if(!notaryURL || !strlen(notaryURL))
+ notaryURL = (char*)ConfigItem_lookup("DIGIDOC_OCSP_URL");
+ if(ConfigItem_lookup_bool("USE_PROXY", 1)) {
+ proxyHost = (char*)ConfigItem_lookup("DIGIDOC_PROXY_HOST");
+ RETURN_IF_NOT(proxyHost, ERR_WRONG_URL_OR_PROXY);
+ proxyPort = (char*)ConfigItem_lookup("DIGIDOC_PROXY_PORT");
+ RETURN_IF_NOT(proxyPort, ERR_WRONG_URL_OR_PROXY);
+ }
+ if (Digi_OpenStore(&hStore) == FALSE)
+ SET_LAST_ERROR_RETURN_CODE(ERR_CERT_STORE_READ);
+ // we need to find some CA-s of signer before asking for
+ // confirmation in order to be able to construct certid
+ // we need this because of users direct CA
+ respCerts = Digi_MakeCertListLow(ddocSigInfo_GetSignersCert(pSigInfo), &hStore);
+ if(respCerts) {
+ for(i = 0; respCerts[i]; i++) // find lowest (middle) ca - direct ca of signers cert
+ pSigCa = respCerts[i];
+ }
+ // VS: ver 1.5.33 - make this decision lower if confirmation can still be retrieved
+ //if(!respCerts) SET_LAST_ERROR_RETURN_CODE(ERR_SIGNERS_CERT_NOT_TRUSTED);
+ err = getConfirmation(pSigDoc, pSigInfo, respCerts, NULL,
+ pkcs12File, password,
+ notaryURL, proxyHost, proxyPort);
+ //Digi_FreeCertList(respCerts);
+ if(respCerts) {
+ for(i = 0; respCerts[i]; i++) {
+ if(respCerts[i] && respCerts[i] != pSigCa) {
+ X509_free(respCerts[i]);
+ respCerts[i] = 0;
+ }
+ }
+ }
+ if(err) return err;
+ pNotInf = pSigInfo->pNotary;
+ pMBuf = ddocNotInfo_GetResponderId(pNotInf);
+ RETURN_IF_NOT(pMBuf != NULL, ERR_NOTARY_SIG_MATCH);
+ if(pNotInf->nRespIdType == RESPID_NAME_TYPE) {
+ szCN[0] = 0;
+ if(pMBuf && pMBuf->pMem)
+ findCN((char*)pMBuf->pMem, szCN, sizeof(szCN));
+ pMBuf = NULL; // don't look for pubkey hash
+ ddocDebug(3, "Digi_getConfirmationWithCertSearch", "Find OCSP resp CA-s by key %s", szCN);
+ } else if(pNotInf->nRespIdType == RESPID_KEY_TYPE) {
+ // look for pubkey hash in Digi_FindCACerts
+ pMBuf = &(pNotInf->mbufRespId);
+ szCN[0] = 0;
+ l1 = sizeof(buf1);
+ bin2hex((const byte*)pNotInf->mbufRespId.pMem, pNotInf->mbufRespId.nLen, buf1, &l1);
+ ddocDebug(3, "Digi_getConfirmationWithCertSearch", "Find OCSP resp CA-s by hash %s", buf1);
+ }
+
+
+ RETURN_IF_NOT(pNotInf != NULL, ERR_NOTARY_SIG_MATCH);
+ // find a list of potential responder certificates
+ // search only by responder id = CN. Should I check also validity on current time ?
+ respCerts = Digi_FindCACerts(&hStore, (szCN[0] ? szCN : NULL), 0, 0, (DigiDocMemBuf*)pMBuf);
+ clearErrors();
+
+ if(!err && respCerts) {
+ i = 0;
+ do {
+ pNotCert = respCerts[i];
+ // get the next potential notary cert
+ if(pNotCert) {
+ // find CA certs for it
+ Digi_CloseStore(&hStore);
+ caCerts = Digi_MakeCertList(pNotCert, &hStore);
+
+ if (caCerts != NULL) {
+ err2 = finalizeAndVerifyNotary2(pSigDoc, pSigInfo, pNotInf, (const X509**)caCerts, (const X509*)pNotCert, pSigCa);
+ // if this didn't verify then free the cert and mark the slot as freed
+ if(err2) {
+ // remove certid and certvalue created for verification
+ removeNotaryInfoCert(pSigInfo);
+ // mark slot as freed (was done above)
+ respCerts[i] = 0;
+ }
+ // found one cert, save it for later
+ if(!err2) {
+ // if one cert was already found
+ // then pick the freshes one - one were not-after-date is latest
+ if(pNotCertFound) {
+ if(getCertNotAfterTimeT(pNotCert) > getCertNotAfterTimeT(pNotCertFound)) {
+ // release older cert
+ X509_free(pNotCertFound);
+ pNotCertFound = pNotCert;
+ }
+ }
+ pNotCertFound = pNotCert;
+ }
+ // else don't free, give ownership to new Notary!
+ // mark the slot as freed
+ respCerts[i] = 0;
+ }
+ else {
+ err = ERR_CERT_STORE_READ;
+ //fprintf(hFile, "No CA-s found, err: %d\n", err);
+ }
+ // free CA certs
+ Digi_FreeCertList(caCerts);
+ }
+ i++;
+ } while(pNotCert);
+ // free the remaining responder certs
+ Digi_FreeCertList(respCerts);
+ }
+
+ // else clear verifying errors
+ clearErrors();
+ // final check with the selected responders certificate
+ if(pNotCertFound) {
+ Digi_CloseStore(&hStore);
+ caCerts = Digi_MakeCertList(pNotCertFound, &hStore);
+ err = finalizeAndVerifyNotary2(pSigDoc, pSigInfo, pNotInf, (const X509**)caCerts, (const X509*)pNotCertFound, pSigCa);
+ Digi_FreeCertList(caCerts);
+ }
+ else
+ err = ERR_OCSP_CERT_NOTFOUND;
+ //fprintf(hFile, "OCSP finalize RC: %d\n", err);
+ // reset original signature content
+ if(pSigInfo->mbufOrigContent.pMem)
+ ddocMemBuf_free(&(pSigInfo->mbufOrigContent));
+ Digi_CloseStore(&hStore);
+ if(err != ERR_OK)
+ SET_LAST_ERROR(err);
+ return(err);
+}
+
+//--------------------------------------------------
+// Verfies NotaryInfo signature
+// pSigDoc - signed doc object
+// pNotInfo - NotaryInfo object
+// caFiles - array of CA file names terminated with NULL
+// CApath - path to (directory) all certs
+// notCertFile - Notary (e.g. OCSP responder) cert file
+//--------------------------------------------------
+int Digi_verifyNotaryInfoWithCertSearch(const SignedDoc* pSigDoc, const NotaryInfo* pNotInfo)
+{
+ X509** caCerts = NULL;
+ X509* notCert = NULL;
+ X509* cert = NULL, *pSigCA = NULL, *pSigCert = NULL;
+ StoreHandle hStore;
+ SignatureInfo *pSigInfo = NULL;
+ int err = ERR_OK;
+
+ if(pNotInfo)
+ pSigInfo = ddocGetSignatureForNotary(pSigDoc, pNotInfo);
+ if(pSigInfo != NULL) {
+ cert = ddocSigInfo_GetOCSPRespondersCert(pSigInfo);
+ }
+ caCerts = Digi_MakeCertList(cert,&hStore);
+ if(caCerts == NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_CERT_STORE_READ);
+ //siin leitakse responderi cert vastavalt kirjeldusele
+ //notCert = Digi_FindResponderCert(&hStore,cert);
+ //08.03.2005 leitakse responderi koopia win certstoorest
+ if(!err) {
+ notCert = Digi_FindX509CopyFromStore(&hStore,cert);
+ pSigCert = ddocSigInfo_GetSignersCert(pSigInfo);
+ pSigCA = Digi_FindDirectCA(pSigCert, &hStore);
+ if((!notCert || !pSigCA) && hStore.fRoot == 1) { // try also CA store
+ Digi_CloseStore(&hStore);
+ memset(&hStore,0,sizeof(StoreHandle));
+ hStore.hHandle = CertOpenStore(CERT_STORE_PROV_SYSTEM,0,(HCRYPTPROV)NULL,
+ CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG,L"CA");
+ if(!notCert)
+ notCert = Digi_FindX509CopyFromStore(&hStore,cert);
+ if(!pSigCA)
+ pSigCA = Digi_FindDirectCA(pSigCert, &hStore);
+ }
+ if (notCert)
+ err = Digi_verifyNotaryInfoCERT(pSigDoc, pNotInfo, (const X509**)caCerts, notCert, pSigCA);
+ else
+ err = ERR_OCSP_CERT_NOTFOUND;
+ }
+ Digi_CloseStore(&hStore);
+ Digi_FreeCertList(caCerts);
+ //AM 23.05.08 where notCert is freed?
+ if(notCert)
+ X509_free(notCert);
+ if(pSigCA)
+ X509_free(pSigCA);
+ if (err != ERR_OK) SET_LAST_ERROR(err);
+ return err;
+}
+
+//============================================================
+// Verifies the whole document, but returns on first error
+// Use the functions defined earlier to verify all contents
+// step by step.
+// pSigDoc - signed doc data
+//
+//============================================================
+int Digi_verifySigDocWithCertSearch(const SignedDoc* pSigDoc, const char* szDataFile)
+
+{
+ SignatureInfo* pSigInfo;
+ NotaryInfo* pNotInfo;
+ int i, d, err = ERR_OK;
+
+ RETURN_IF_NULL(pSigDoc);
+ //assert(pSigDoc);
+ d = getCountOfSignatures(pSigDoc);
+ for(i = 0; i < d; i++) {
+ pSigInfo = getSignature(pSigDoc, i);
+ err = Digi_verifySignatureInfo(pSigDoc, pSigInfo, szDataFile);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ pNotInfo = pSigInfo->pNotary;
+ err = Digi_verifyNotaryInfoWithCertSearch(pSigDoc, pNotInfo);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ }
+ return err;
+}
+
+
+//--------------------------------------------------
+// Reads a certificate from pkcs12 conteiner
+//--------------------------------------------------
+// AA 18/09/2003
+EXP_OPTION int Digi_readCertificateByPKCS12OnlyCertHandle(const char *pkcs12file, const char * passwd, X509 **x509)
+{
+ int err = ERR_OK;
+ EVP_PKEY *pkey;
+ // VS: 26.01.2010 - initialize
+ (*x509) = 0;
+ //AM 16.09.08 DigiDocClient calling it with empty strings even ocsp request signing is off
+ if(!strcmp(pkcs12file, ""))
+ return ERR_OK;
+ err = ReadCertificateByPKCS12(x509,pkcs12file,passwd,&pkey);
+ //AM 22.05.08 pKey should be freed
+ if(err == 0 && pkey)
+ EVP_PKEY_free(pkey);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ return ERR_OK;
+}
+
+//============================================================
+// Verifies this signature
+// pSigDoc - signed doc data
+// pSigInfo - signature info object
+// signerCA - direct signer CA certs filename
+// szDateFile - name of the digidoc file
+// bUseCA - use CA certs or not 1/0
+// from original file and use it for hash function.
+// This is usefull if the file has been generated by
+// another library and possibly formats these elements
+// differently.
+//============================================================
+int Digi_verifySignatureInfo(const SignedDoc* pSigDoc, const SignatureInfo* pSigInfo, const char* szDataFile)
+{
+ char buf2[100], *p1 = 0;
+ X509* pCaCert = 0;
+ int err = ERR_OK, k = 0;
+ StoreHandle hStore;
+ DigiDocMemBuf mbuf1;
+
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ buf2[0] = 0;
+ if(!Digi_OpenStore(&hStore))
+ return ERR_CERT_STORE_READ;
+ //p1 = ddocSigInfo_GetSignersCert_IssuerName(pSigInfo);
+ p1 = (char*)ddocSigInfo_GetSignersCert_IssuerNameAndHash(pSigInfo, &mbuf1);
+ //strncpy(buf1, ddocSigInfo_GetSignersCert_IssuerName(pSigInfo), sizeof(buf1));
+ if(p1)
+ findCN((char*)p1, buf2, sizeof(buf2));
+ pCaCert = Digi_FindCertBySubjectAndHash(&hStore, buf2, FALSE, 0, TRUE, &mbuf1);
+ if(!pCaCert) {
+ ddocDebug(1, "Digi_verifySignatureInfo", "ERR112 cert: %s", buf2);
+ //AM 02.03.09 teadmata olek kui leia CA serti
+ return ERR_UNKNOWN_CA;
+ }
+ err = verifySignatureInfoCERT(pSigDoc, pSigInfo, pCaCert,
+ szDataFile, (pCaCert != NULL));
+ if(pCaCert)
+ X509_free(pCaCert);
+ Digi_CloseStore(&hStore);
+ ddocMemBuf_free(&mbuf1);
+ if((k = getCountOfSignerRoles(pSigInfo, 0)) > 1) {
+ ddocDebug(1, "Digi_verifySignatureInfo", "Number of roles: %d, Currently supports max 1 roles", k);
+ SET_LAST_ERROR(ERR_MAX_1_ROLES);
+ err = ERR_MAX_1_ROLES;
+ }
+ return err;
+}
+
+
+//============================================================
+// Verifies the whole document, but returns on first error
+// Use the functions defined earlier to verify all contents
+// step by step.
+// pSigDoc - signed doc data
+//
+//============================================================
+
+int Digi_verifySigDoc(const SignedDoc* pSigDoc, const char* szDataFile)
+
+{
+ SignatureInfo* pSigInfo;
+ NotaryInfo* pNotInfo;
+ int i, d, err = ERR_OK;
+
+ RETURN_IF_NULL_PARAM(pSigDoc);
+ //assert(pSigDoc);
+ d = getCountOfSignatures(pSigDoc);
+ for(i = 0; i < d; i++) {
+ pSigInfo = getSignature(pSigDoc, i);
+ err = Digi_verifySignatureInfo(pSigDoc, pSigInfo, szDataFile);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ }
+ d = getCountOfNotaryInfos(pSigDoc);
+ for(i = 0;i < d; i++) {
+ pNotInfo = getNotaryInfo(pSigDoc, i);
+ err = Digi_verifyNotaryInfoWithCertSearch(pSigDoc, pNotInfo);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ }
+ return ERR_OK;
+}
+
+
+//--------------------------------------------------
+// Verfies NotaryInfo signature
+// pSigDoc - signed doc object
+// pNotInfo - NotaryInfo object
+// caCerts - CA certificate pointer array terminated with NULL
+// CApath - path to (directory) all certs
+// notCertFile - Notary (e.g. OCSP responder) cert file
+//--------------------------------------------------
+int Digi_verifyNotaryInfoCERT(const SignedDoc* pSigDoc,
+ const NotaryInfo* pNotInfo,
+ const X509** caCerts,
+ const X509* notCert,
+ const X509* pSigCA)
+{
+ SignatureInfo* pSigInfo = NULL;
+ pSigInfo = ddocGetSignatureForNotary(pSigDoc, pNotInfo);
+ RETURN_IF_NOT(pSigInfo != NULL, ERR_NOTARY_NO_SIGNATURE);
+ return verifyNotaryInfoCERT2(pSigDoc, pSigInfo, pNotInfo, caCerts, 0, notCert, pSigCA);
+}
+
+
+//====================================================================
+// Finds issuer certificate of given certificate
+// returns NULL if not found or any error occures
+// The stores "My","CA" and "Root" will be scanned.
+//====================================================================
+EXP_OPTION X509 * findIssuerCertificatefromMsStore(X509 *x509){
+ return findIssuerCertificatefromStore(x509);
+
+}
+
+//Functions from EstIDLib.c
+
+
+//============================================================
+// Calculates and stores a signature for this SignatureInfo object
+// Uses EstEID card as CSP to sign the info
+// pSigInfo - signature info object
+//============================================================
+EXP_OPTION int calculateSigInfoSignatureWithCSPEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, int iByKeyContainer, const char* szPin)
+{
+ int err = ERR_OK, l1;
+ PCCERT_CONTEXT pCert;
+ char buf1[300];
+ unsigned long sigLen;
+ int digLen, len=0;
+ char sigDig[300],signature[2084], *p1;
+ char *psKeyName = NULL;
+ char *psCSPName = NULL;
+ //long tmpSerial;
+ //HCRYPTPROV hProvider;
+ DWORD dwRes;
+ X509 *pX509;
+ DigiDocMemBuf *pMBuf1;
+
+ ddocDebug(3, "calculateSigInfoSignatureWithCSPEstID", "Sign id: %s", pSigInfo->szId);
+ pCert = DigiCrypt_FindContext((BOOL) iByKeyContainer, &dwRes);
+ if(pCert == NULL) {
+ if (dwRes == dDigiCrypt_Error_NotFoundCSP)
+ err = ERR_CSP_NO_CARD_DATA;
+ if(dwRes == dDigiCrypt_Error_UserCancel)
+ err = ERR_CSP_USER_CANCEL;
+ if (dwRes == dDigiCrypt_Error_NoDefaultKey)
+ err = ERR_CSP_NODEFKEY_CONTAINER;
+ if (dwRes == dDIgiCrypt_Error_NotFoundCert)
+ err = ERR_CSP_CERT_FOUND;
+
+ SET_LAST_ERROR_RETURN_CODE(err);
+ }
+ psKeyName = DigiCrypt_FindContext_GetKeyName();
+ psCSPName = DigiCrypt_FindContext_GetCSPName();
+ //AA100204
+ ddocDecodeX509Data(&pX509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ err = setSignatureCert(pSigInfo, pX509);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ //AA-Viimase minuti jama
+ createTimestamp(pSigDoc, sigDig, sizeof(sigDig));
+ setString(&(pSigInfo->szTimeStamp), sigDig, -1);
+ // Signed properties digest
+ // now calculate signed properties digest
+ err = calculateSignedPropertiesDigest(pSigDoc, pSigInfo);
+ // TODO: replace later
+ pMBuf1 = ddocDigestValue_GetDigestValue(pSigInfo->pSigPropDigest);
+ ddocSigInfo_SetSigPropRealDigest(pSigInfo, (const char*)pMBuf1->pMem, pMBuf1->nLen);
+ // signature type & val
+ ddocSignatureValue_new(&(pSigInfo->pSigValue), 0, SIGN_RSA_NAME, 0, 0);
+ // calc signed-info digest
+ l1 = sizeof(buf1);
+ err = calculateSignedInfoDigest(pSigDoc, pSigInfo, (byte*)buf1, &l1);
+ err = ddocSigInfo_SetSigInfoRealDigest(pSigInfo, buf1, l1);
+ sigLen = sizeof(signature);
+ memset(signature, 0, sizeof(signature));
+ p1 = createXMLSignedInfo(pSigDoc, pSigInfo);
+ len = strlen(p1);
+
+ // sign the <SignedInfo> hash with CSP
+ digLen = sizeof(sigDig);
+ err = GetSignedHashWithKeyAndCSP(psKeyName,psCSPName, p1, len, NULL, NULL, sigDig, &digLen,&signature[0],&sigLen,szPin);
+ if(p1)
+ free(p1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ // set signature value
+ ddocSigInfo_SetSignatureValue(pSigInfo, signature, (int)sigLen);
+ ddocDebug(3, "calculateSigInfoSignatureWithCSPEstID", "End signing Sign id: %s, rc: %d", pSigInfo->szId, err);
+ return ERR_OK;
+}
+
+
+
+X509* findCertificate(const CertSearch * cS){
+ //debugPrint("findCertificate");
+ X509* poCert = NULL;
+ if(cS==NULL){
+ return NULL;
+ }else if(cS->searchType==CERT_SEARCH_BY_X509){
+ ReadCertificate(&poCert,cS->x509FileName);
+ return(poCert);
+ }else if(cS->searchType==CERT_SEARCH_BY_PKCS12){
+ X509 * x509=NULL;
+ EVP_PKEY * pKey=NULL;
+ int err=0;
+ err=ReadCertificateByPKCS12(&x509,cS->pkcs12FileName,cS->pswd,&pKey);
+ EVP_PKEY_free(pKey);
+ if(err==ERR_OK){
+ return x509;
+ }else{
+ SET_LAST_ERROR(err);
+ return NULL;
+ }
+ }else if(cS->searchType==CERT_SEARCH_BY_STORE){
+ #ifdef WIN32_CSP
+ X509 * x509=NULL;
+ int err=0;
+ RETURN_OBJ_IF_NULL(cS->certSearchStore, NULL);
+ err=GetCertificateFromStore(cS->certSearchStore,&x509);
+ //debugPrint("return from findCertificate (MS Store)");
+ if(err==ERR_OK){
+ return x509;
+ }else{
+ SET_LAST_ERROR(err);
+ return NULL;
+ }
+ #else
+ return NULL;
+ #endif
+ }else{
+ return NULL;
+ }
+}
+
+EXP_OPTION int findAllCertificates(const CertSearchStore *sS, X509 ***certsArray, int *numberOfCerts){
+ #ifdef WIN32_CSP
+ int rc=0,i;
+ X509 **array;
+ CertItem *certItem, *certItem2;
+ rc=GetAllCertificatesFromStore(sS,&certItem,numberOfCerts);
+ if(rc==ERR_OK){
+ array=malloc(sizeof(X509*)*(*numberOfCerts));
+ RETURN_IF_BAD_ALLOC(array);
+ for(i=0;i< *numberOfCerts ;i++){
+ array[i]=certItem->pCert;
+ certItem2=certItem;
+ certItem=certItem->nextItem;
+ free(certItem2);
+ }
+ *certsArray=array;
+ }
+ if (rc != ERR_OK) SET_LAST_ERROR(rc);
+ return rc;
+ #else
+ SET_LAST_ERROR_RETURN_CODE(ERR_UNSUPPORTED_CERT_SEARCH);
+ #endif // WIN32_CSP
+}
+
+/***********************************************************************/
+//=========================================================================
+// Returns pointer to current CSP. If current CSP was not initialized (i.e
+// NULL ) and input parameter is TRUE then active CSP is asked from
+// function getActiveProvider() and if CSP is "EST ID CSP" then
+// signature flag in CSP structure will turned to true
+//=========================================================================
+EXP_OPTION CSProvider * getCurrentCSProvider(BOOL tryToFindIfMissing){
+ if(tryToFindIfMissing==FALSE){
+ return cCSProvider;
+ }
+ // so tryToFindIfMissing was true, we need to find out if not found yet
+ if(cCSProvider==NULL ){
+ //cCSProvider=getActiveProvider();
+ if(cCSProvider!=NULL){
+ if(strcmp(cCSProvider->CSPName,EST_EID_CSP)==0)
+ cCSProvider->at_sig=TRUE;
+ else
+ cCSProvider->at_sig=FALSE;
+ }
+ }
+ return cCSProvider;
+
+}
+EXP_OPTION void setCurrentCSProvider(CSProvider * newProvider){
+ cCSProvider=newProvider;
+}
+
+
+
+//=====================================================
+EXP_OPTION CertSearchStore* CertSearchStore_new()
+{
+ CertSearchStore* certSearch;
+ certSearch=(CertSearchStore*)malloc(sizeof(CertSearchStore));
+ memset(certSearch, 0, sizeof(CertSearchStore));
+ return certSearch;
+}
+
+EXP_OPTION void CertSearchStore_free(CertSearchStore* certSearchStore){
+ int i=0;
+ RETURN_VOID_IF_NULL(certSearchStore);
+ if (certSearchStore->subDNCriterias) {
+ for(; i < certSearchStore->numberOfSubDNCriterias ; i++ ){
+ if(certSearchStore->subDNCriterias[i] != NULL){
+ free(certSearchStore->subDNCriterias[i]);
+ }
+ }
+ free(certSearchStore->subDNCriterias);
+ }
+ certSearchStore->numberOfSubDNCriterias=0;
+ if (certSearchStore->issDNCriterias) {
+ for(; i < certSearchStore->numberOfIssDNCriterias ; i++ ){
+ if(certSearchStore->issDNCriterias[i] != NULL){
+ free(certSearchStore->issDNCriterias[i]);
+ }
+ }
+ free(certSearchStore->issDNCriterias);
+ }
+ certSearchStore->numberOfIssDNCriterias=0;
+ if(certSearchStore->storeName != NULL){
+ free(certSearchStore->storeName);
+ }
+ if(certSearchStore->publicKeyInfo){
+ free(certSearchStore->publicKeyInfo);
+ }
+ free(certSearchStore);
+ certSearchStore=NULL;
+}
+
+
+EXP_OPTION CertSearch* CertSearch_new(){
+ CertSearch* certSearch;
+ certSearch=(CertSearch*)malloc(sizeof(CertSearch));
+ memset(certSearch, 0, sizeof(CertSearch));
+ return certSearch;
+}
+
+EXP_OPTION void CertSearch_free(CertSearch* certSearch){
+ if(certSearch->certSearchStore != NULL){
+ CertSearchStore_free(certSearch->certSearchStore);
+ }
+ if(certSearch->pkcs12FileName != NULL){
+ free(certSearch->pkcs12FileName);
+ }
+ if(certSearch->pswd != NULL){
+ free(certSearch->pswd);
+ }
+ if(certSearch->x509FileName != NULL){
+ free(certSearch->x509FileName);
+ }
+ if(certSearch->keyFileName != NULL){
+ free(certSearch->keyFileName);
+ }
+ free(certSearch);
+ certSearch=NULL;
+
+}
+
+EXP_OPTION void CertSearch_setX509FileName(CertSearch* certSearch, const char* str)
+{
+ if(certSearch && str) {
+ setString((char**)&certSearch->x509FileName, str, -1);
+ }
+}
+
+EXP_OPTION void CertSearch_setKeyFileName(CertSearch* certSearch, const char* str)
+{
+ if(certSearch && str) {
+ setString((char**)&certSearch->keyFileName, str, -1);
+ }
+}
+
+EXP_OPTION void CertSearch_setPkcs12FileName(CertSearch* certSearch, const char* str)
+{
+ if(certSearch && str) {
+ setString((char**)&certSearch->pkcs12FileName, str, -1);
+ }
+}
+
+EXP_OPTION void CertSearch_setPasswd(CertSearch* certSearch, const char* str)
+{
+ if(certSearch && str) {
+ setString((char**)&certSearch->pswd, str, -1);
+ }
+}
+
+
+
+// Frees cert handles and items in this list.
+// WARNING! when caller does not own the first cert in chain,
+// then pass pListStart->nextItem instead of pListStart itself.
+EXP_OPTION void CertList_free(CertItem* pListStart) {
+ if (pListStart) {
+ CertItem* pItem = pListStart;
+ CertItem* pTmp;
+ while (pItem) {
+ pTmp = pItem->nextItem;
+ X509_free((X509*)pItem->pCert);
+ free(pItem);
+ pItem = pTmp;
+ }
+ }
+}
+
+//=====================================================================
+// reads certificate from system store
+// IN CertSearchStore *sS - search criterias
+// OUT x509 certificate
+//=====================================================================
+int GetAllCertificatesFromStore(const CertSearchStore *sS, CertItem ** certList, int *numberOfCerts)
+{
+ int retCode=ERR_OK;
+/*
+ int retCode1=ERR_UNSUPPORTED_CERT_SEARCH; // Unknown search type
+ int retCode2=ERR_CSP_OPEN_STORE; // Can not open system store
+ int retCode3=ERR_CSP_CERT_FOUND; // Certificate not found from store, probably cetificate not registered
+ int retCode4=ERR_INCORRECT_CERT_SEARCH; // search type Sub DN but mismatch of parameters
+ int retCode5=ERR_PKCS_CERT_DECODE;
+*/
+
+ int i=0,certCounter=0;
+ int initSize=10;
+ X509 *x509;
+ CertItem *certFirst,*certCurrent,*certIt;
+ BOOL certFound=FALSE;
+ BOOL useSerial=FALSE;
+ BOOL useSubDN=FALSE;
+ BOOL useIssDN=FALSE;
+ HCERTSTORE hCertStore = NULL;
+ PCCERT_CONTEXT pCert=NULL;
+ char defaultName[]="My";
+ char* storeName;
+ char buf[4000];
+ char buf1[4000];
+ long tmpSerial;
+ int err;
+ DigiDocMemBuf mbuf1;
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+
+ RETURN_IF_NOT(numberOfCerts !=NULL, ERR_NULL_SER_NUM_POINTER);
+
+ if((sS->searchType&(CERT_STORE_SEARCH_BY_SERIAL|CERT_STORE_SEARCH_BY_SUBJECT_DN|CERT_STORE_SEARCH_BY_ISSUER_DN)) == 0)
+ SET_LAST_ERROR_RETURN_CODE(ERR_UNSUPPORTED_CERT_SEARCH);
+
+ if((sS->searchType&CERT_STORE_SEARCH_BY_SERIAL) != 0){
+ useSerial=TRUE;
+ }
+ if((sS->searchType&CERT_STORE_SEARCH_BY_SUBJECT_DN) != 0){
+ useSubDN=TRUE;
+ if(sS->numberOfSubDNCriterias<1)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ if (sS->subDNCriterias == NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ for(i=0;i<sS->numberOfSubDNCriterias;i++){
+ if(sS->subDNCriterias[i]==NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ }
+ }
+ if((sS->searchType&CERT_STORE_SEARCH_BY_ISSUER_DN) != 0){
+ useIssDN=TRUE;
+ if(sS->numberOfIssDNCriterias<1)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+
+ if (sS->issDNCriterias == NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ for(i=0;i<sS->numberOfIssDNCriterias;i++){
+ if(sS->issDNCriterias[i]==NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ }
+ }
+ if(sS->storeName!=NULL){
+ storeName=sS->storeName;
+ }else{
+ storeName=defaultName;
+ }
+ certFirst = malloc(sizeof(CertItem));
+ RETURN_IF_BAD_ALLOC(certFirst);
+ // memset(certFirst,0,sizeof(certFirst)); <-- Andrus: fills with zeros only first 32 bits
+ memset(certFirst,0,sizeof(CertItem));
+ *certList=certFirst;
+ certCurrent=certFirst;
+ /////******************** start task ***********************************
+ while(TRUE){
+ hCertStore=CertOpenSystemStore(0,storeName);
+ if(!hCertStore){
+ retCode=ERR_CSP_OPEN_STORE;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+
+ while(TRUE){
+ pCert = CertEnumCertificatesInStore( hCertStore,pCert);
+ if(!pCert)
+ break;
+ //AA100204
+ ddocDecodeX509Data(&x509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ RETURN_IF_NOT(x509 != NULL, ERR_PKCS_CERT_DECODE);
+
+ // if serial is a criteria check it
+ if(useSerial){
+ //AA-viimase minuti jama
+ //ReadCertSerialNumber(&tmpSerial,x509);
+ ReadCertSerialNumber(buf,sizeof(buf),x509);
+ tmpSerial = atol(buf);
+ if(tmpSerial == sS->certSerial){
+ certFound=TRUE;
+ }else{
+ certFound=FALSE;
+ X509_free(x509);
+ continue;
+ }
+ }//if(useSerial){
+
+ // if issuer name is a criteria check it
+ if(useIssDN){
+ int len=0;
+ X509_NAME * x509name;
+ x509name = X509_get_issuer_name(x509);
+ len=sizeof(buf);
+ memset(buf,0,len);
+ memset(buf1,0,sizeof(buf1));
+
+ //AM 26.09.08
+ //X509_NAME_oneline(x509name,buf,len);
+ err = ddocCertGetIssuerDN(x509, &mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ len=strlen((char*)mbuf1.pMem);
+ prepareString((char*)mbuf1.pMem,buf1);
+ for(i=0;i<sS->numberOfIssDNCriterias;i++){
+ memset(buf,0,sizeof(buf));
+ prepareString(sS->issDNCriterias[i],buf);
+ if(strstr(buf1,buf)){
+ certFound=TRUE;
+ }else{
+ certFound=FALSE;
+ //X509_free(x509); <-- Andrus: free operation performed in the end of useIssDN block
+ break;
+ }
+ }
+ if(!certFound){
+ X509_free(x509);
+ continue;
+ }
+ }//if(useIssDN){
+
+ // if subject name is a criteria check it
+ if(useSubDN){
+ int len=0;
+ X509_NAME * x509name;
+ x509name = X509_get_subject_name(x509);
+ len=sizeof(buf);
+ memset(buf,0,len);
+ memset(buf1,0,sizeof(buf1));
+
+ //AM 26.09.08
+ //X509_NAME_oneline(x509name,buf,len);
+ err = ddocCertGetSubjectDN(x509, &mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ len=strlen((char*)mbuf1.pMem);
+ prepareString((char*)mbuf1.pMem,buf1);
+ for(i=0;i<sS->numberOfSubDNCriterias;i++){
+ memset(buf,0,sizeof(buf));
+ prepareString(sS->subDNCriterias[i],buf);
+ if(strstr(buf1,buf)){
+ certFound=TRUE;
+ }else{
+ certFound=FALSE;
+ break;
+ }
+ }
+ // did we find ?
+ if(!certFound){
+ X509_free(x509);
+ continue;
+ }
+ }//if(useSubDN){
+ ddocMemBuf_free(&mbuf1);
+ // did we find ?
+ if(certFound){
+ certCounter++;
+ if(certCounter==1){
+ certFirst->pCert=x509;
+ continue;
+ }
+ certIt = malloc(sizeof(CertItem));
+ RETURN_IF_BAD_ALLOC(certIt);
+ // memset(certIt,0,sizeof(certIt)); <-- Andrus: fills with zeros only first 32 bits
+ memset(certIt,0,sizeof(CertItem));
+ certIt->pCert=x509;
+ certCurrent->nextItem=certIt;
+ certCurrent=certIt;
+ }else{
+ X509_free(x509);
+ continue;
+ }
+ }//while(pCertt=CertEnumCertificatesInStore(hCertStore,pCert))
+ *numberOfCerts=certCounter;
+ if( certCounter<1 ){
+ retCode = ERR_CSP_CERT_FOUND;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ break;
+ }//while(TRUE){
+ /////******************** close and free objects ***********************************
+ if(pCert) {CertFreeCertificateContext(pCert); }
+ if(hCertStore) {CertCloseStore(hCertStore,CERT_CLOSE_STORE_FORCE_FLAG);hCertStore=0;}
+ return retCode;
+ /////*******************************************************************************
+}
+//==========================================================
+// removes all spaces and tabs and makes all characters uppercase
+//==========================================================
+void prepareString(const char * strIN,char * strOUT){
+ int len=0;
+ int i=0;
+ int tempLen=0;
+ len=strlen(strIN);
+
+ if(len==0){
+ return;
+ }
+ for (;i<len ; i++) {
+ if((strIN[i] == ' ') || (strIN[i] == '\t')){
+ continue;
+ }else if( strIN[i]>0x60 && strIN[i]<0x7B ){
+ strOUT[tempLen++] = (strIN[i]-0x20);
+ }else {
+ strOUT[tempLen++] = strIN[i];
+ }
+ }
+}
+
+//=====================================================================
+// reads certificate from system store
+// IN CertSearchStore *sS - search criterias
+// OUT x509 certificate
+//=====================================================================
+int GetCertificateFromStore(const CertSearchStore *sS, X509 **cert){
+ int retCode=ERR_OK;
+ int retCode1=ERR_UNSUPPORTED_CERT_SEARCH; // Unknown search type
+ int retCode2=ERR_CSP_OPEN_STORE; // Can not open system store
+ int retCode3=ERR_CSP_CERT_FOUND; // Certificate not found from store, probably cetificate not registered
+ int retCode4=ERR_INCORRECT_CERT_SEARCH; // search type Sub DN but mismatch of parameters
+ int retCode5=ERR_PKCS_CERT_DECODE;
+
+ int i=0;
+ X509 *x509;
+ BOOL certFound=FALSE;
+ BOOL useKeyInfo=FALSE;
+ BOOL useSerial=FALSE;
+ BOOL useSubDN=FALSE;
+ BOOL useIssDN=FALSE;
+ HCERTSTORE hCertStore = NULL;
+ CERT_PUBLIC_KEY_INFO* pKeyInfo;
+ PCCERT_CONTEXT pCert=NULL;
+ char defaultName[]="My";
+ char* storeName;
+ char buf[3000];
+ char buf1[3000];
+ long tmpSerial;
+ int err=0;
+ DigiDocMemBuf mbuf1;
+ mbuf1.pMem = 0;
+ mbuf1.nLen = 0;
+ //---------------------------------
+ // TODO: it's just a test - remove it
+ //---------------------------------
+ /*
+ char* pSelArr[] = {"Good reader", "Better reader", "The best reader", NULL};
+ int iRes = runDigiDocDialogUnit(pSelArr, "Please select smartcard reader:");
+ if (iRes != -1) {
+ // handle picked element
+ char resultAsText[128];
+ //sprintf(resultAsText, "Selected item with index=%d", iRes);
+ MessageBox(NULL, resultAsText, "DigiDoc", MB_OK|MB_ICONEXCLAMATION);
+ } else {
+ // if possible, handle Cancel operation
+ }
+ */
+ //---------------------------------
+ // End of TODO
+ //---------------------------------
+ if((sS->searchType&(CERT_STORE_SEARCH_BY_SERIAL|CERT_STORE_SEARCH_BY_SUBJECT_DN|CERT_STORE_SEARCH_BY_ISSUER_DN|CERT_STORE_SEARCH_BY_KEY_INFO)) == 0)
+ SET_LAST_ERROR_RETURN_CODE(ERR_UNSUPPORTED_CERT_SEARCH);
+ if((sS->searchType&CERT_STORE_SEARCH_BY_KEY_INFO) != 0){
+ useKeyInfo=TRUE;
+ pKeyInfo=sS->publicKeyInfo;
+ if(pKeyInfo==NULL){
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ }
+ }
+ if((sS->searchType&CERT_STORE_SEARCH_BY_SERIAL) != 0){
+ useSerial=TRUE;
+ }
+ if((sS->searchType&CERT_STORE_SEARCH_BY_SUBJECT_DN) != 0){
+ useSubDN=TRUE;
+ if(sS->numberOfSubDNCriterias<1)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ if (sS->subDNCriterias == NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ for(i=0;i<sS->numberOfSubDNCriterias;i++){
+ if(sS->subDNCriterias[i]==NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ }
+ }
+ if((sS->searchType&CERT_STORE_SEARCH_BY_ISSUER_DN) != 0){
+ useIssDN=TRUE;
+ if(sS->numberOfIssDNCriterias<1)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ if (sS->issDNCriterias == NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ for(i=0;i<sS->numberOfIssDNCriterias;i++){
+ if(sS->issDNCriterias[i]==NULL)
+ SET_LAST_ERROR_RETURN_CODE(ERR_INCORRECT_CERT_SEARCH);
+ }
+ }
+ if(sS->storeName!=NULL){
+ storeName=sS->storeName;
+ }else{
+ storeName=&defaultName[0];
+ }
+ /////******************** start task ***********************************
+ while(TRUE){
+ hCertStore=CertOpenSystemStore(0,storeName);
+ if(!hCertStore){
+ retCode = ERR_CSP_OPEN_STORE;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ if(useKeyInfo){
+ pCert=CertFindCertificateInStore(hCertStore,X509_ASN_ENCODING|PKCS_7_ASN_ENCODING,0,CERT_FIND_PUBLIC_KEY,pKeyInfo,NULL );
+ if(pCert){
+ //AA100204
+ ddocDecodeX509Data(&x509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ certFound=TRUE;
+ //memcpy(cert,x509,sizeof(x509));
+ //X509_free(x509);
+ *cert=x509;
+ break;
+ }
+ }//if(useSerial){
+ while( pCert= CertEnumCertificatesInStore( hCertStore,pCert)){
+ //AA100204
+ ddocDecodeX509Data(&x509,pCert->pbCertEncoded,pCert->cbCertEncoded);
+ RETURN_IF_NOT(x509 != NULL, ERR_PKCS_CERT_DECODE);
+ if(useSerial){
+ //AA-Viimase minuti jama
+ //ReadCertSerialNumber(&tmpSerial,x509);
+ ReadCertSerialNumber(buf,sizeof(buf),x509);
+ tmpSerial = atol(buf);
+ if(tmpSerial == sS->certSerial){
+ certFound=TRUE;
+ }else{
+ certFound=FALSE;
+ X509_free(x509);
+ continue;
+ }
+ }//if(useSerial){
+ if(useIssDN){
+ int len=0;
+ X509_NAME * x509name;
+ x509name = X509_get_issuer_name(x509);
+ len=sizeof(buf);
+ memset(buf,0,len);
+ memset(buf1,0,sizeof(buf1));
+
+ //AM 26.09.08
+ //X509_NAME_oneline(x509name,buf,len);
+ err = ddocCertGetIssuerDN(x509, &mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ len=strlen((char*)mbuf1.pMem);
+ prepareString((char*)mbuf1.pMem,buf1);
+
+ for(i=0;i<sS->numberOfIssDNCriterias;i++){
+ memset(buf,0,sizeof(buf));
+ prepareString(sS->issDNCriterias[i],buf);
+ if(strstr(buf1,buf)){
+ certFound=TRUE;
+ }else{
+ certFound=FALSE;
+ X509_free(x509);
+ break;
+ }
+ }
+ if(!certFound){
+ X509_free(x509);
+ continue;
+ }
+ }//if(useIssDN){
+
+ if(useSubDN){
+ int len=0;
+ X509_NAME * x509name;
+ x509name = X509_get_subject_name(x509);
+ len=sizeof(buf);
+ memset(buf,0,len);
+ memset(buf1,0,sizeof(buf1));
+
+ //AM 26.09.08
+ //X509_NAME_oneline(x509name,buf,len);
+ err = ddocCertGetSubjectDN(x509, &mbuf1);
+ RETURN_IF_NOT(err == ERR_OK, err);
+ len=strlen((char*)mbuf1.pMem);
+ prepareString((char*)mbuf1.pMem,buf1);
+
+ for(i=0;i<sS->numberOfSubDNCriterias;i++){
+ memset(buf,0,sizeof(buf));
+ prepareString(sS->subDNCriterias[i],buf);
+ if(strstr(buf1,buf)){
+ certFound=TRUE;
+ }else{
+ certFound=FALSE;
+ break;
+ }
+ }
+ // did we find ?
+ if(!certFound){
+ X509_free(x509);
+ continue;
+ }
+ }//if(useSubDN){
+ ddocMemBuf_free(&mbuf1);
+ // did we find ?
+ if(certFound){
+ break;
+ }else{
+ X509_free(x509);
+ continue;
+ }
+ }//while(pCertt=CertEnumCertificatesInStore(hCertStore,pCert))
+ if( certFound ){
+ //memcpy(cert,x509,sizeof(x509));
+ //X509_free(x509);
+ *cert=x509;
+ }else{
+ retCode=ERR_CSP_CERT_FOUND;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ break;
+ }//while(TRUE){
+
+ /////******************** close and free objects ***********************************
+ if(pCert) {CertFreeCertificateContext(pCert); }
+ if(hCertStore) {CertCloseStore(hCertStore,CERT_CLOSE_STORE_FORCE_FLAG);hCertStore=0;}
+ return retCode;
+ /////*******************************************************************************
+}
+//=======================================================
+//Asks and returns key name or NULL if can not be found.
+//Key name must be freed. Name will be like "AUT_VIISAKAS,VILLU,19901012020"
+//IN cProvider - crypto provider name, "EstEID Card CSP" in
+// EstID's case.
+//=======================================================
+LPBYTE getDefaultKeyName(CSProvider * cCSP){
+ BOOL fRes;
+ HCRYPTPROV hProv = 0;
+ LPBYTE pbContName = NULL;//string, key name to be stored
+ DWORD dwContName;
+ if(cCSP==NULL){
+ cCSP=getCurrentCSProvider(TRUE);
+ }
+ if(cCSP==NULL){
+ return NULL;
+ }
+ if(cCSP->rsa_full){
+ fRes = CryptAcquireContext(&hProv,NULL,cCSP->CSPName, PROV_RSA_FULL, 0);
+ }else{
+ fRes = CryptAcquireContext(&hProv,NULL,cCSP->CSPName, PROV_RSA_SIG, 0);
+ }
+ if (RCRYPT_FAILED(fRes)){ return NULL; }
+ // asks keypair name, in auth case it is AUT_<name, given name, code>
+ // first size and the the keyname itself
+ fRes = CryptGetProvParam(hProv,PP_CONTAINER,NULL,&dwContName,0);
+ if (RCRYPT_FAILED(fRes)){ return NULL; }
+ //pbContName =(LPBYTE) LocalAlloc(0,dwContName);
+ pbContName =(LPBYTE) malloc(dwContName);
+ if(pbContName != NULL ){
+ fRes = CryptGetProvParam(hProv,PP_CONTAINER,pbContName,&dwContName,0);
+ }
+ //in pbContName-s there is now ASCII string
+ fRes = CryptReleaseContext(hProv,0);
+ if (RCRYPT_FAILED(fRes)){ return NULL; }
+ hProv =0;
+ return pbContName;
+
+}
+
+//========================================================================
+// Returns issuer certificate context
+//========================================================================
+const CERT_CONTEXT * findCertFromStore(const CERT_CONTEXT *cert, const char *storeName)
+{
+ HCERTSTORE hCertStore = NULL;
+ const CERT_CONTEXT *issuer = NULL;
+ DWORD flag=CERT_STORE_SIGNATURE_FLAG;
+ hCertStore=CertOpenSystemStore(0,storeName);
+ if(!hCertStore){
+ return NULL;
+ }
+ issuer = CertGetIssuerCertificateFromStore(hCertStore,cert,NULL,&flag);
+ CertCloseStore(hCertStore,0);
+ return issuer;
+}
+
+//=========================================================================
+X509 * findIssuerCertificatefromStore(X509 *x509)
+{
+ const CERT_CONTEXT *cert = NULL;
+ const CERT_CONTEXT *issuer = NULL;
+ char * storeNames[] = {"CA","Root","My"};
+
+ unsigned char certBlob[5000];
+ int i, certBlobLen = sizeof(certBlob);
+ X509 *x509issuer = NULL;
+
+ RETURN_OBJ_IF_NULL(x509, NULL);
+ //encode(
+ memset(certBlob,0,sizeof(certBlob));
+ encodeCert(x509,(char *)certBlob,&certBlobLen);
+ cert = CertCreateCertificateContext(X509_ASN_ENCODING|PKCS_7_ASN_ENCODING,certBlob,certBlobLen);
+ if(cert == NULL){
+ return NULL;
+ }
+ for( i=0;i<3;i++){
+ issuer=findCertFromStore(cert,storeNames[i]);
+ if(issuer){
+ break;
+ }
+ }
+ if(issuer){
+ //AA100204
+ ddocDecodeX509Data(&x509issuer,issuer->pbCertEncoded,issuer->cbCertEncoded);
+ CertFreeCertificateContext(issuer);
+ }
+ CertFreeCertificateContext(cert);
+
+ return x509issuer;
+
+}
+
+
+//=====================================================================
+// hashes and signes data with EstId card, returns also public_key_blob
+// which can be used in order to verify signature
+// IN dataToBeSigned - source data buffer
+// IN dataLen - how many bytes will be read from source buffer
+// OUT pbKeyBlob - public key buffer( corresponding private key was used to sign.
+// OUT pbKeyBlobLen - public key length in buffer
+// OUT hash - output data buffer for hash
+// OUT hashLen - data length in output buffer
+// OUT hashedSignature - output data buffer for hashed and signed data
+// OUT sigLen - data length in output buffer
+// IN szPin - PIN2 [optional]
+//=====================================================================
+int GetSignedHashWithKeyAndCSP( char *psKeyName, char *psCSPName,
+ const char * dataToBeSigned,unsigned long dataLen,
+ unsigned char *pbKeyBlob, unsigned long *pbKeyBlobLen,
+ unsigned char *hash, unsigned long *hashLen,
+ unsigned char * hashedSignature,unsigned long * sigLen,
+ const char* szPin)
+{
+ int retCode=ERR_OK, l1;
+ HCRYPTPROV hProv = 0;
+ HCRYPTHASH sha1 = 0;
+ HCRYPTKEY hKey = 0;
+ PCCERT_CONTEXT pCert=NULL;
+ BOOL fRes;
+ DWORD dwRes;
+ char *p1 = 0;
+
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "key: %s csp: %s, pin-len: %d", psKeyName, psCSPName, (szPin ? strlen(szPin) : 0));
+ // debug
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "data to sign: \'%s\' len: %d tlen: %d", dataToBeSigned, dataLen, strlen(dataToBeSigned));
+ //////******************** start task *************************************
+ while(TRUE){
+ //
+ //sprintf(sTemp,"CSP=%s \nCON=%s\n%d",psCSPName,psKeyName,DigiCrypt_FindContext_GetCSPType(psCSPName));
+ //MessageBox(NULL,sTemp,"TEST",MB_OK);
+ //
+ fRes=CryptAcquireContext(&hProv,psKeyName,psCSPName,DigiCrypt_FindContext_GetCSPType(psCSPName),0);//CRYPT_VERIFYCONTEXT);
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "CryptAcquireContext: \'%s\' rc: %d", psKeyName, fRes);
+
+ if(fRes==FALSE){
+ dwRes = GetLastError();
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "error in CryptAcquireContext: %ld hex: %x", dwRes, dwRes);
+ retCode=ERR_CSP_NO_CARD_DATA;
+ break;
+
+ }
+ fRes=CryptCreateHash(hProv,CALG_SHA1,0,0,&sha1);
+ if(fRes==FALSE){
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "CryptCreateHash RC (bool): %d", (int)fRes);
+ retCode=ERR_CSP_NO_HASH_START;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ // start hash
+ fRes=CryptHashData(sha1,dataToBeSigned,dataLen,0);
+
+ if(fRes==FALSE){
+ retCode=ERR_CSP_NO_HASH;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ if(hash!=NULL){
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "caling CryptGetHashParam hash: %s len: %ld", hash, *hashLen);
+ fRes=CryptGetHashParam(sha1,HP_HASHVAL, hash,hashLen ,0);
+ if(fRes==FALSE){
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "CryptGetHashParam RC (bool): %d", (int)fRes);
+ retCode=ERR_CSP_NO_HASH_RESULT;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ // debug
+ l1 = *hashLen * 2 + 10;
+ p1 = (char*)malloc(l1);
+ if(p1) {
+ memset(p1, 0, l1);
+ encode((const byte*)hash, *hashLen, (byte*)p1, &l1);
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "hash: %s len: %d", p1, l1);
+ free(p1);
+ p1 = 0;
+ }
+ }
+
+ if(hashedSignature != NULL) {
+ //use by standard way is not allways possible -- AT_SIGNATURE -- main thing is that cert is ok nor the keyspec
+ //instead of that we should use CryptAcquireCertificatePrivateKey function. But then we must change basic context of this function.
+ //workaround -- we try with both keyspecs
+ // set PIN2 for signing if possible
+ if(szPin && strlen(szPin)) {
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "Setting PIN len: %d", strlen(szPin));
+ fRes = CryptSetProvParam(hProv, PP_SIGNATURE_PIN, (const BYTE*)szPin, 0 );
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "PIN setting: %d", fRes);
+ }
+ fRes=CryptSignHash(sha1,AT_SIGNATURE ,NULL,0, hashedSignature,sigLen);
+ if(fRes==FALSE)
+ {
+ dwRes = GetLastError();
+ //try again with keyspec AT_KEYEXCHANGE
+ if(dwRes==0x8009000d) // wrong keyspec
+ {
+ fRes=CryptSignHash(sha1,AT_KEYEXCHANGE ,NULL,0, NULL,sigLen); //*sigLen should be 128... this can be avoided whi
+ fRes=CryptSignHash(sha1,AT_KEYEXCHANGE ,NULL,0, hashedSignature,sigLen);
+ if(fRes==FALSE)
+ {
+ dwRes = GetLastError();
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "error in CryptSignHash: %ld", dwRes);
+ retCode=ERR_CSP_SIGN;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ } else if(dwRes == 0x8010006e) {
+ ddocDebug(2, "GetSignedHashWithKeyAndCSP", "user cancelled signing");
+ retCode=ERR_CSP_USER_CANCEL;
+ SET_LAST_ERROR(ERR_CSP_USER_CANCEL);
+ break;
+ }
+ else
+ {
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "error in signing: %uld hex: %x", dwRes, dwRes);
+ retCode=ERR_CSP_SIGN;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ }
+ } else
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "hashed signature is NULL");
+
+ // we must switsh end and begining
+ // because windows uses little-endian but verification
+ // assumes big-endian
+ reverseArray(hashedSignature, *sigLen);
+
+ if(pbKeyBlob!=NULL){
+ fRes=CryptGetUserKey(hProv,AT_KEYEXCHANGE,&hKey);
+ if(fRes==FALSE){
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "error in CryptGetUserKey");
+ retCode=ERR_CSP_OPEN_KEY;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ fRes=CryptExportKey(hKey,0,PUBLICKEYBLOB,0,pbKeyBlob,pbKeyBlobLen);
+ if(fRes==FALSE){
+ ddocDebug(1, "GetSignedHashWithKeyAndCSP", "error in CryptExportKey");
+ retCode=ERR_CSP_READ_KEY;
+ SET_LAST_ERROR(retCode);
+ break;
+ }
+ }
+
+ break;
+ }//while(TRUE)
+ ///********************** free objects ************************************
+ if(hKey){
+ CryptDestroyKey(hKey);hKey=0;
+ }
+ if(sha1){
+ CryptDestroyHash(sha1);sha1= 0;
+ }
+ if(hProv){
+ CryptReleaseContext(hProv,0);
+ }
+ ddocDebug(3, "GetSignedHashWithKeyAndCSP", "end of signing RC: %d", retCode);
+ return retCode;
+ /////*******************************************************************************
+}
+
+//===============================================================
+// This function is used to change order in a massive. Last byte
+// becomes first and so on.
+// IN/OUT array - massive to be changed
+// IN arrayLen - array's length
+//===============================================================
+void reverseArray(unsigned char *array, unsigned long arrayLen)
+{
+ int ri, rj;
+ unsigned char t;
+
+ for (ri = 0, rj = arrayLen - 1; ri < rj; ++ri, --rj) {
+ t = array[ri];
+ array[ri] = array[rj];
+ array[rj] = t;
+ }
+}
+
+
+
+#endif
diff --git a/libdigidoc/DigiDocCsp.h b/libdigidoc/DigiDocCsp.h
new file mode 100644
index 0000000..c285c29
--- /dev/null
+++ b/libdigidoc/DigiDocCsp.h
@@ -0,0 +1,132 @@
+#ifndef __DIGIDOCCSP_H__
+#define __DIGIDOCCSP_H__
+
+//==================================================
+// FILE: DigDocCsp.h
+// PROJECT: Digi Doc
+// DESCRIPTION: CSP Functions
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 1.0 09.05.2002 Veiko Sinivee
+//==================================================
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define EST_EID_CSP "EstEID Card CSP"
+
+typedef struct CSProvider_st {
+ char* CSPName;
+ int rsa_full; // if FALSE RSA_SIG will be used
+ int at_sig; //// if FALSE AT_KEYEXCHANGE will be used
+} CSProvider;
+
+// general structure for a list of certificates
+typedef struct CertItem_st {
+ X509* pCert;
+ struct CertItem_st* nextItem;
+} CertItem;
+
+
+typedef struct CertSearchStore_st {
+ int searchType;
+ char* storeName; // default is "My"
+ long certSerial;
+ int numberOfSubDNCriterias;
+ char** subDNCriterias;
+ int numberOfIssDNCriterias;
+ char** issDNCriterias;
+ void* publicKeyInfo;
+} CertSearchStore;
+
+typedef struct CertSearch_st {
+ int searchType;
+ char* x509FileName;
+ char* keyFileName;
+ char* pkcs12FileName;
+ char * pswd;
+ CertSearchStore* certSearchStore;
+} CertSearch;
+
+
+//=====================================================================
+// Hashes and signes data with EstId card, returns also cert
+// which can be used in order to verify signature
+// IN dataToBeSigned - source data buffer
+// IN dataLen - how many bytes will be read from source buffer
+// OUT cert - cert buffer( corresponding private key was used to sign.), migth be NULL if this parameter is not needed.
+// OUT certLen - cert length in buffer, migth be NULL if cert parameter is not needed.
+// OUT keyBlob - public key's buffer, migth be NULL if this parameter is not needed.
+// OUT keyBlobLen - public key's length in buffer, migth be NULL if keyBlob parameter is not needed.
+// OUT hash - hash buffer, migth be NULL if this parameter is not needed.
+// OUT hashLen - hash length in buffer, migth be NULL if hash parameter is not needed.
+// OUT sign - output data buffer for hashed and signed data
+// OUT sigLen - data length in output buffer
+//=====================================================================
+int GetSignParametersWithEstIdCSP(byte * dataToBeSigned,unsigned long dataLen,
+ X509 **x509, int *needCert,
+ byte *keyBlob, unsigned long *keyBlobLen,
+ byte *hash, unsigned long *hashLen,
+ byte *sign,unsigned long *sigLen);
+
+
+
+//EXP_OPTION int calculateSigInfoSignatureWithEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo,
+// int slot, const char* passwd);
+
+
+//Added parameter iByKeyContainer by A.Amenberg 06062003
+EXP_OPTION int calculateSigInfoSignatureWithCSPEstID(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, int iByKeyContainer, const char* szPin);
+
+EXP_OPTION X509 * findIssuerCertificatefromMsStore(X509 *x509);
+
+
+EXP_OPTION CertSearchStore* CertSearchStore_new();
+EXP_OPTION void CertSearchStore_free(CertSearchStore* certSearchStore);
+
+EXP_OPTION CertSearch* CertSearch_new();
+EXP_OPTION void CertSearch_free(CertSearch* certSearch);
+EXP_OPTION void CertList_free(CertItem* pListStart);
+EXP_OPTION void CertSearch_setX509FileName(CertSearch* certSearch, const char* str);
+EXP_OPTION void CertSearch_setKeyFileName(CertSearch* certSearch, const char* str);
+EXP_OPTION void CertSearch_setPkcs12FileName(CertSearch* certSearch, const char* str);
+EXP_OPTION void CertSearch_setPasswd(CertSearch* certSearch, const char* str);
+
+
+//
+EXP_OPTION CSProvider * getCurrentCSProvider(BOOL tryToFindIfMissing);
+EXP_OPTION X509* findCertificate(const CertSearch * cS);
+EXP_OPTION int findAllCertificates(const CertSearchStore *sS, X509 ***certsArray, int *numberOfCerts);
+
+EXP_OPTION int Digi_readCertificateByPKCS12OnlyCertHandle(const char *pkcs12file, const char * passwd, X509 **x509);
+EXP_OPTION int Digi_getConfirmationWithCertSearch(SignedDoc* pSigDoc, SignatureInfo* pSigInfo, char* pkcs12File, char* password,
+ char* notaryURL, char* proxyHost, char* proxyPort);
+EXP_OPTION int Digi_setNotaryCertificate(NotaryInfo* pNotary, X509* notCert);
+EXP_OPTION int Digi_verifyNotaryInfoWithCertSearch(const SignedDoc* pSigDoc, const NotaryInfo* pNotInfo);
+
+// verifies this one signature
+EXP_OPTION int Digi_verifySignatureInfo(const SignedDoc* pSigDoc, const SignatureInfo* pSigInfo,
+ const char* szDataFile);
+// verifies the whole document (returns on first err)
+EXP_OPTION int Digi_verifySigDoc(const SignedDoc* pSigDoc, const char* szDataFile);
+EXP_OPTION int Digi_verifySigDocWithCertSearch(const SignedDoc* pSigDoc, const char* szDataFile);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif \ No newline at end of file
diff --git a/libdigidoc/DigiDocDebug.c b/libdigidoc/DigiDocDebug.c
new file mode 100644
index 0000000..0c7e3b8
--- /dev/null
+++ b/libdigidoc/DigiDocDebug.c
@@ -0,0 +1,170 @@
+//==================================================
+// FILE: DigiDocDebug.h
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for debug output
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 10.08.2004 Veiko Sinivee
+// Creation
+//==================================================
+
+#include <libdigidoc/DigiDocDebug.h>
+#include <libdigidoc/DigiDocConfig.h>
+#include <libdigidoc/DigiDocLib.h>
+
+#if defined(GNUCPP) || !defined(WIN32)
+ #include <unistd.h>
+ #define _mkdir mkdir
+ #define _rmdir rmdir
+ #define _unlink unlink
+ #define _tzset tzset
+ #define _getcwd getcwd
+#endif
+
+
+//-----------------------------------------
+// Formats debug output
+// level - debug level to output this message on
+// func - name of the function
+// format - message format and arguments
+//-----------------------------------------
+EXP_OPTION void ddocDebug(int level, const char* func, const char* format, ...)
+{
+ time_t tNow;
+ struct tm tm1;
+ int nLevel = ConfigItem_lookup_int("DEBUG_LEVEL", 1);
+ const char * szDebugFile = ConfigItem_lookup("DEBUG_FILE");
+ va_list args;
+ FILE* hFile = 0;
+
+ if(level <= nLevel) {
+ time(&tNow);
+ ddocLocalTime(&tNow, &tm1, 1);
+ va_start(args, format);
+ if(szDebugFile && ((hFile = fopen(szDebugFile, "ab")) != NULL)) {
+ fprintf(hFile, "%s\t[%04d-%02d-%02d %02d:%02d:%02d] ",
+ func, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ vfprintf(hFile, format, args);
+ fprintf(hFile, "\n");
+ fclose(hFile);
+ } else {
+ fprintf(stderr, "%s\t[%04d-%02d-%02d %02d:%02d:%02d] ",
+ func, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ vfprintf(stderr, format, args);
+ fprintf(stderr, "\n");
+ }
+ }
+}
+
+//-----------------------------------------
+// Writes debug data in a file
+// level - debug level to write on
+// szFileName - target file name
+// pMemBuf - buffer for log data
+//-----------------------------------------
+EXP_OPTION int ddocDebugWriteFile(int level, const char* szFileName, DigiDocMemBuf *pMemBuf)
+{
+ int err = ERR_OK;
+ FILE* hFile;
+ int nLevel = ConfigItem_lookup_int("DEBUG_LEVEL", 1);
+
+ RETURN_IF_NULL_PARAM(szFileName);
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ if(level <= nLevel) {
+ if((hFile = fopen(szFileName, "ab")) != NULL) {
+ fwrite(pMemBuf->pMem, 1, pMemBuf->nLen, hFile);
+ fclose(hFile);
+ }
+ }
+ return err;
+}
+
+//-----------------------------------------
+// Formats debug output
+// level - debug level to output this message on
+// func - name of the function
+// msg - message format and arguments
+// args - va_list struct
+//-----------------------------------------
+EXP_OPTION void ddocDebugVaArgs(int level, const char* func, const char* msg, va_list args)
+{
+ time_t tNow;
+ struct tm tm1;
+ int nLevel = ConfigItem_lookup_int("DEBUG_LEVEL", 1);
+ const char * szDebugFile = ConfigItem_lookup("DEBUG_FILE");
+ FILE* hFile = 0;
+
+ if(level <= nLevel) {
+ time(&tNow);
+ ddocLocalTime(&tNow, &tm1, 1);
+ if(szDebugFile && ((hFile = fopen(szDebugFile, "ab")) != NULL)) {
+ fprintf(hFile, "%s\t[%04d-%02d-%02d %02d:%02d:%02d] ",
+ func, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ vfprintf(hFile, msg, args);
+ fprintf(hFile, "\n");
+ fclose(hFile);
+ } else {
+ fprintf(stderr, "%s\t[%04d-%02d-%02d %02d:%02d:%02d] ",
+ func, tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday,
+ tm1.tm_hour, tm1.tm_min, tm1.tm_sec);
+ vfprintf(stderr, msg, args);
+ fprintf(stderr, "\n");
+ }
+ }
+}
+
+//-----------------------------------------
+// Deletes the log file if it exists.
+//-----------------------------------------
+EXP_OPTION void ddocDebugTruncateLog()
+{
+ char * szDebugFile = (char*)ConfigItem_lookup("DEBUG_FILE");
+ if(szDebugFile && checkFileExists(szDebugFile)) {
+ _unlink(szDebugFile);
+ }
+}
+
+//-----------------------------------------
+// Reads the contents of the log file
+// pMemBuf - buffer for log data
+//-----------------------------------------
+EXP_OPTION int ddocDebugReadLog(DigiDocMemBuf *pMemBuf)
+{
+ char * szDebugFile = (char*)ConfigItem_lookup("DEBUG_FILE");
+ FILE *hFile;
+ int err = ERR_OK, l2, l1;
+ char buf1[1025];
+
+ RETURN_IF_NULL_PARAM(pMemBuf);
+ pMemBuf->pMem = 0;
+ pMemBuf->nLen = 0;
+ if(szDebugFile) {
+ if((hFile = fopen(szDebugFile, "rt")) != NULL) {
+ l1 = sizeof(buf1);
+ do {
+ l2 = fread(buf1, 1, l1, hFile);
+ err = ddocMemAppendData(pMemBuf, buf1, l2);
+ } while(l2 > 0);
+ fclose(hFile);
+ }
+ }
+ else
+ err = ERR_FILE_READ;
+ return err;
+}
+
diff --git a/libdigidoc/DigiDocDebug.h b/libdigidoc/DigiDocDebug.h
new file mode 100644
index 0000000..366bce7
--- /dev/null
+++ b/libdigidoc/DigiDocDebug.h
@@ -0,0 +1,75 @@
+#ifndef __DIGIDOC_DEBUG_H__
+#define __DIGIDOC_DEBUG_H__
+//==================================================
+// FILE: DigiDocDebug.h
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for debug output
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 10.08.2004 Veiko Sinivee
+// Creation
+//==================================================
+
+#include <libdigidoc/DigiDocMem.h>
+#include <libdigidoc/DigiDocDefs.h>
+#include <stdarg.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//-----------------------------------------
+// Formats debug output
+// level - debug level to output this message on
+// func - name of the function
+// format - message format and arguments
+//-----------------------------------------
+EXP_OPTION void ddocDebug(int level, const char* func, const char* format, ...);
+
+//-----------------------------------------
+// Formats debug output
+// level - debug level to output this message on
+// func - name of the function
+// msg - message format and arguments
+// args - va_list struct
+//-----------------------------------------
+EXP_OPTION void ddocDebugVaArgs(int level, const char* func, const char* msg, va_list args);
+
+//-----------------------------------------
+// Deletes the log file if it exists.
+//-----------------------------------------
+EXP_OPTION void ddocDebugTruncateLog();
+
+//-----------------------------------------
+// Reads the contents of the log file
+// pMemBuf - buffer for log data
+//-----------------------------------------
+EXP_OPTION int ddocDebugReadLog(DigiDocMemBuf *pMemBuf);
+
+//-----------------------------------------
+// Writes debug data in a file
+// level - debug level to write on
+// szFileName - target file name
+// pMemBuf - buffer for log data
+//-----------------------------------------
+EXP_OPTION int ddocDebugWriteFile(int level, const char* szFileName, DigiDocMemBuf *pMemBuf);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // __DIGIDOC_DEBUG_H__
+
diff --git a/libdigidoc/DigiDocDefs.h b/libdigidoc/DigiDocDefs.h
new file mode 100644
index 0000000..713369c
--- /dev/null
+++ b/libdigidoc/DigiDocDefs.h
@@ -0,0 +1,180 @@
+#ifndef __DIGIDOC_DEFS_H__
+#define __DIGIDOC_DEFS_H__
+//==================================================
+// FILE: DigiDocDefs.h
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc global definitions.
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.ode
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 15.06.2005 Veiko Sinivee
+//==================================================
+
+
+#ifdef WIN32
+ #ifndef WIN32_LEAN_AND_MEAN
+ #define WIN32_LEAN_AND_MEAN
+ #endif
+ #include <windows.h>
+ #define WIN32_CSP
+ #ifdef _MSC_VER
+ #pragma warning( disable: 4100 4706 4204 4221 )
+ #endif
+ #ifdef digidoc_EXPORTS
+ #define EXP_OPTION __declspec(dllexport)
+ #else
+ #define EXP_OPTION __declspec(dllimport)
+ #endif
+ #define DIGIDOC_DEPRECATED __declspec(deprecated)
+#else
+ #if __GNUC__ >= 4
+ #define EXP_OPTION __attribute__ ((visibility("default")))
+ #define DIGIDOC_DEPRECATED __attribute__ ((__deprecated__))
+ #else
+ #define EXP_OPTION
+ #define DIGIDOC_DEPRECATED
+ #endif
+#endif
+
+#ifdef WIN32
+ //for _msize function
+ #define FILESEPARATOR "\\"
+ #include <malloc.h>
+ #include <direct.h>
+ #define snprintf _snprintf
+#else
+ #define FILESEPARATOR "/"
+ #define DIGI_DOC_LIB
+ #include <unistd.h>
+ #define _mkdir mkdir
+ #define _rmdir rmdir
+ #define _unlink unlink
+ #define _tzset tzset
+ #define _getcwd getcwd
+ #if defined(__FreeBSD__)
+ #define _timezone tzone
+ extern long int tzone; /* default for Estonia, but see initDigiDocLib() */
+ #define _daylight daylight
+ extern int daylight; /* default, but see initDigiDocLib() */
+ #else
+ #define _timezone timezone
+ #define _daylight daylight
+ #endif
+#endif
+
+#define WITH_BASE64_HASHING_HACK 1
+// VS: disabled ecdsa support for FC13 building
+//#define WITH_ECDSA 1
+
+//#define WITH_DEPRECATED_FUNCTIONS
+
+
+// old timestamp struct
+#define WITH_TIMETSTAMP_STRUCT
+
+#ifndef byte
+typedef unsigned char byte;
+#endif
+
+#define WITH_SHA256
+//==========< Digest types >=======================
+#ifdef WITH_SHA256
+#define SIGNATURE_LEN 144
+#else
+#define SIGNATURE_LEN 128
+#endif
+#define DIGEST_LEN 20
+#define DIGEST_SHA1 0
+#define DIGEST_SHA256 1
+#define DIGEST_LEN256 32
+#define CERT_DATA_LEN 4096
+#define X509_NAME_LEN 256
+#define SIGNATURE_RSA 0
+#define CONTENT_EMBEDDED "EMBEDDED"
+#define CONTENT_EMBEDDED_BASE64 "EMBEDDED_BASE64"
+#define X509_NAME_BUF_LEN 500
+
+//==========< Format types >=======================
+
+#define SK_PKCS7_1 "SK-PKCS#7-1.0"
+#define SK_XML_1_NAME "SK-XML"
+#define DIGIDOC_XML_1_1_NAME "DIGIDOC-XML"
+#define SK_XML_1_VER "1.0"
+#define DIGIDOC_XML_1_1_VER "1.1"
+#define DIGIDOC_XML_1_2_VER "1.2"
+#define DIGIDOC_XML_1_3_VER "1.3"
+#define SK_NOT_VERSION "OCSP-1.0"
+
+#define DIGEST_SHA1_NAME "sha1"
+#define DIGEST_SHA1_WRONG "sha1wrong"
+#define DIGEST_SHA256_NAME "sha256"
+#define SIGN_RSA_NAME "RSA"
+#ifdef WITH_ECDSA
+ #define SIGN_ECDSA_NAME "ECDSA"
+#endif
+#define OCSP_NONCE_NAME "OCSP Nonce"
+#define RESPID_NAME_VALUE "NAME"
+#define RESPID_KEY_VALUE "KEY HASH"
+#define OCSP_SIG_TYPE "sha1WithRSAEncryption"
+#define RESPID_NAME_TYPE 1
+#define RESPID_KEY_TYPE 2
+
+#define DIGEST_METHOD_SHA1 "http://www.w3.org/2000/09/xmldsig#sha1"
+#define DIGEST_METHOD_SHA256 "http://www.w3.org/2001/04/xmlenc#sha256"
+#define NAMESPACE_XML_DSIG "http://www.w3.org/2000/09/xmldsig#"
+#define NAMESPACE_XADES_111 "http://uri.etsi.org/01903/v1.1.1#"
+#define NAMESPACE_XADES_132 "http://uri.etsi.org/01903/v1.3.2#"
+#define NAMESPACE_XADES "http://uri.etsi.org/01903#"
+
+
+//==========< Format types >=======================
+
+#define CHARSET_ISO_8859_1 "ISO-8859-1"
+#define CHARSET_UTF_8 "UTF-8"
+
+
+//==========< language codes >=======================
+#define DDOC_LANG_ENGLISH 0
+#define DDOC_LANG_ESTONIAN 1
+#define DDOC_NUM_LANGUAGES 2
+#define SUPPORTED_VERSION_COUNT 4
+
+//==========< file formats >=======================
+
+#define FILE_FORMAT_ASN1 0
+#define FILE_FORMAT_PEM 1
+//#define FILE_FORMAT_
+
+//============< OCSP paramaters >==================
+
+#define OCSP_REQUEST_SIGN_NO 1
+#define OCSP_REQUEST_SIGN_CSP 2
+#define OCSP_REQUEST_SIGN_X509 3
+#define OCSP_REQUEST_SIGN_PKCS11_WIN 4
+#define OCSP_REQUEST_SIGN_PKCS12 5
+
+//================== Cert search constants =========
+#define CERT_SEARCH_BY_STORE 1
+#define CERT_SEARCH_BY_X509 2
+#define CERT_SEARCH_BY_PKCS12 3
+
+// thes can be XOR'ed, then all criterias are used
+#define CERT_STORE_SEARCH_BY_SERIAL 0x01
+#define CERT_STORE_SEARCH_BY_SUBJECT_DN 0x02
+#define CERT_STORE_SEARCH_BY_ISSUER_DN 0x04
+#define CERT_STORE_SEARCH_BY_KEY_INFO 0x08
+
+#define FILE_BUFSIZE 1024*16
+
+#endif // __DIGIDOC_DEFS_H__
diff --git a/libdigidoc/DigiDocDfExtract.c b/libdigidoc/DigiDocDfExtract.c
new file mode 100644
index 0000000..28345e9
--- /dev/null
+++ b/libdigidoc/DigiDocDfExtract.c
@@ -0,0 +1,405 @@
+//==================================================
+// FILE: DigiDocDfExtract.c
+// PROJECT: Digi Doc
+// DESCRIPTION: Digi Doc functions for extracting <DataFile> contents
+// AUTHOR: Veiko Sinivee, S|E|B IT Partner Estonia
+//==================================================
+// Copyright (C) AS Sertifitseerimiskeskus
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+// GNU Lesser General Public Licence is available at
+// http://www.gnu.org/copyleft/lesser.html
+//==========< HISTORY >=============================
+// 03.03.2008 Veiko Sinivee
+// Creation
+//==================================================
+
+#include <libdigidoc/DigiDocDefs.h>
+#include <libdigidoc/DigiDocError.h>
+#include <libdigidoc/DigiDocDebug.h>
+#include <libdigidoc/DigiDocConvert.h>
+#include <libdigidoc/DigiDocMem.h>
+#include <libdigidoc/DigiDocLib.h>
+#include <libdigidoc/DigiDocObj.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <memory.h>
+#include <string.h>
+#include <ctype.h>
+
+#ifdef WIN32
+ #define snprintf _snprintf
+ #include <wchar.h>
+#endif
+
+#define ST_START 0
+#define ST_XML 1
+#define ST_TAG_NM 2
+#define ST_TAG_WS 3
+#define ST_ATTR_NM 4
+#define ST_ATTR_WS 5
+#define ST_ATTR_CON 6
+#define ST_CON 7
+#define ST_DF_START 8
+#define ST_DF_CON 9
+#define ST_DF_TAG 10
+#define ST_DF_END 11
+#define ST_DF_END_END 12
+
+
+//--------------------------------------------------
+// Reads in signed XML document and extracts the desired data file
+// pSigDoc - signed document object if exists. Can be NULL
+// szFileName - digidoc filename
+// szDataFileName - name of the file where to store embedded data.
+// szDocId - DataFile Id atribute value
+// szCharset - convert DataFile content to charset
+//--------------------------------------------------
+EXP_OPTION int ddocExtractDataFile(SignedDoc* pSigDoc, const char* szFileName,
+ const char* szDataFileName, const char* szDocId,
+ const char* szCharset)
+{
+ FILE *fIn = 0, *fOut = 0;
+ int err = ERR_OK, i, nRead, lt, la, lc, j, ld, lb, l, eState = 0, fs = 0;
+ long len, lExtr = 0, lSize = 0;
+ char chars[1050], tag[100], attr[100], con[1030], dec[70], b64line[70];