softhsm-2.0.0/0000775000175000017500000000000012552220146010176 500000000000000softhsm-2.0.0/README.md0000664000175000017500000000774612533040716011415 00000000000000# SoftHSM version 2 SoftHSM is part of the OpenDNSSEC project. Read more at www.opendnssec.org. ## Introduction OpenDNSSEC handles and stores its cryptographic keys via the PKCS#11 interface. This interface specifies how to communicate with cryptographic devices such as HSM:s (Hardware Security Modules) and smart cards. The purpose of these devices is, among others, to generate cryptographic keys and sign information without revealing private-key material to the outside world. They are often designed to perform well on these specific tasks compared to ordinary processes in a normal computer. A potential problem with the use of the PKCS#11 interface is that it might limit the wide spread use of OpenDNSSEC, since a potential user might not be willing to invest in a new hardware device. To counter this effect, OpenDNSSEC is providing a software implementation of a generic cryptographic device with a PKCS#11 interface, the SoftHSM. SoftHSM is designed to meet the requirements of OpenDNSSEC, but can also work together with other cryptographic products because of the PKCS#11 interface. ## Developers - Rickard Bellgrim (.SE, The Internet Infrastructure Foundation, www.iis.se) - Francis Dupont (ISC, www.isc.org) - René Post (XPT Software and Consulting, www.xpt.nl) - Roland van Rijswijk (SURFnet bv, www.surfnet.nl) ## Dependencies SoftHSM depends on a cryptographic library, Botan or OpenSSL. Minimum required versions: - Botan 1.10.0 - OpenSSL 1.0.0 If you are using Botan, make sure that it has support for GNU MP (--with-gnump). This will improve the performance when doing public key operations. There is a migration tool for converting token databases from SoftHSMv1 into the new type of tokens. If this tool is built, then SQLite3 is required (>= 3.4.2). ## Installation ### Configure Configure the installation/compilation scripts: ./configure Options: --disable-non-paged-memory Disable non-paged memory for secure storage (default enabled) --disable-ecc Disable support for ECC (default enabled) --disable-gost Disable support for GOST (default enabled) --disable-visibility Disable hidden visibilty link mode [enabled] --with-crypto-backend Select crypto backend (openssl|botan) --with-openssl=PATH Specify prefix of path of OpenSSL --with-botan=PATH Specify prefix of path of Botan --with-migrate Build the migration tool. Used when migrating a SoftHSM v1 token database. Requires SQLite3 --with-objectstore-backend-db Build with database object store (SQLite3) --with-sqlite3=PATH Specify prefix of path of SQLite3 For more options: ./configure --help ### Compile Compile the source code using the following command: make ### Install Library Install the library using the follow command: sudo make install ### Configure The default location of the config file is /etc/softhsm2.conf. This location can be change by setting the environment variable. export SOFTHSM2_CONF=/home/user/config.file Details on the configuration can be found in "man softhsm2.conf". Create the token directory you defined in your config file: mkdir ### Initialize Tokens Use either softhsm2-util or the PKCS#11 interface. The SO PIN can e.g. be used to re-initialize the token and the user PIN is handed out to the application so it can interact with the token. softhsm2-util --init-token --slot 0 --label "My token 1" Type in SO PIN and user PIN. Once a token has been initialized, more slots will be added automatically with a new uninitialized token. ### Link Link to this library and use the PKCS#11 interface. ## Backup All of the tokens and their objects are stored in the location given by softhsm2.conf. Backup can thus be done as a regular file copy. ## Building from the repository If the code is downloaded directly from the code repository, you have to prepare the configuration scripts before continuing with the real README. 1. You need to install automake, autoconf, libtool, etc. 2. Run the command 'sh autogen.sh' 3. Continue reading this README. softhsm-2.0.0/OSX-NOTES.md0000664000175000017500000001353212533040716012005 00000000000000# Building SoftHSMv2 on Mac OS X 10.8.5 (Mountain Lion) This document contains instructions for building SoftHSMv2 from the command line on Mac OS X 10.8.5. This may work for other version of OS X, but that has not been verified. ## Command Line Tools We assume that XCode has been installed. To find out where Xcode keeps the C++ compiler type the following at the command line: $ xcode-select --print-path /Applications/Xcode.app/Contents/Developer The gcc compiler in this case can be found at /Applications/Xcode.app/Contents/Developer/usr/bin/gcc Alternatively if you don't want to install XCode you could install command line tools for os x that can be downloaded from apple. E.g. currently the following package for the mountain lion release of OS X is available for download. command_line_tools_os_x_mountain_lion_for_xcode__october_2013.dmg This dmg file is still 100MB but at least orders of magnitude smaller than installing all of XCode. ## Homebrew The libraries that come as part of OS X are rather old. We need to use more recent versions of these libraries to avoid unexpected failures during building and running. There is a community supported command line package manager for installing the dependencies we need. It's called homebrew. First we'll need to install it as follows: $ ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go/install)" Now we need to install some dependencies $ brew install automake $ brew install openssl $ brew install sqlite $ brew install cppunit Because both openssl and sqlite are pre-installed on the system, the new downloads are stored in an alternative location. /usr/local/opt During configure the paths to the newly installed libraries needs to be passed in so configure can actually find the libraries. We'll show how to do that later. ## Cloning SoftHSMv2 We now need to clone SoftHSMv2 from github. $ git clone https://github.com/opendnssec/SoftHSMv2.git $ cd SoftHSMv2 I needed to change a line in configure.ac in order to prevent some errors during configure. Instead of the line: AM_INIT_AUTOMAKE(foreign) I'm using AM_INIT_AUTOMAKE([foreign subdir-objects]) After changing this we can configure the build. ## Configuring the build Start by installing autoconf in the source directory by executing the autogen.sh script. $ sh ./autogen.sh If all went well a configure script should have been generated. To find out the options available for building issue the following command: $ ./configure --help In the example below I will enable the optional token object store database backend. $ ./configure --with-objectstore-backend-db \ --with-openssl=/usr/local/opt/openssl \ --with-sqlite3=/usr/local/opt/sqlite Now if for some reason the compilers are not found, do the following at the command line. $ export CC="xcrun gcc" $ export CPP="xcrun cpp" $ export CXX="xcrun g++" $ ./configure --with-objectstore-backend-db \ --with-openssl=/usr/local/opt/openssl \ --with-sqlite3=/usr/local/opt/sqlite By exporting these environment variables we are instructing configure to use the compilers stored inside the installed XCode.app. ## Building and Testing SoftHSMv2 Now we can build SoftHSMv2 by just executing make. $ make And we can check that it works by running all tests. $ make check To try a specific test, e.g. to check just the PKCS#11 test cases use the following make command: $ make -C src/lib/test check Then change src/lib/test/softhsm2.conf so it contains the following lines. # SoftHSM v2 configuration file directories.tokendir = ./tokens objectstore.backend = db We are now ready to run the tests again. $ make -C src/lib/test check Because the object store backend was changed from file to db we have used sqlite for storing the token objects. Verify this by looking in the sub-folders of src/lib/test/tokens There you should find a database file named sqlite3.db ## Performance The file backend currently exhibits the best performance. It is normally at least twice as fast as the database backend. The idea behind storing token objects in a database is that it has advantages when a large number (> 100K) of keys are stored in a token. A database allows for selectively querying and loading in only a subset of the keys into memory. The file based storage backend reads in the complete contents of the token. Also because the database is only a single file, we should not hit any system limitations w.r.t. the number of files that can be stored in a file system. The database backend uses transactions to write changes to the token database. For modifiable attributes this will require a round trip to the database every time an attribute has been read as another process may have modified the given attribute. The database backend uses approximately 20% less memory because it will only load in object attributes on demand. For non-mutable attributes that is not a problem because once an object with its attributes is created those attributes won't change. On the other hand the mutable attributes of the object are always read when the object is accessed, making it slower because this will require a roundtrip to the database for every mutable attribute. Note that most attributes are non-mutable and especially the key material is non-mutable. So once this (encrypted !) material has been read into memory it will remain cached (encrypted !). Currently the query functionality for only retrieving a subset of the objects is not yet implemented. Therefore the database solution has no advantages w.r.t. the file based solution for large number of files other than the 20% less memory usage mentioned before. For applications that need the highest speed possible and only read/use the token, a solution would be to copy the whole of the token database to a ramdisk. This should only be used when the application doesn't modify the token, because a power-cycle of the host will wipe out the ramdisk. softhsm-2.0.0/configure0000775000175000017500000226160612552216617012052 00000000000000#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for SoftHSM 2.0.0. # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1 test -n \"\${ZSH_VERSION+set}\${BASH_VERSION+set}\" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO ECHO=\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO\$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test \"X\`printf %s \$ECHO\`\" = \"X\$ECHO\" \\ || test \"X\`print -r -- \$ECHO\`\" = \"X\$ECHO\" ) || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, $0: including any error possibly output before this $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" SHELL=${CONFIG_SHELL-/bin/sh} test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='SoftHSM' PACKAGE_TARNAME='softhsm' PACKAGE_VERSION='2.0.0' PACKAGE_STRING='SoftHSM 2.0.0' PACKAGE_BUGREPORT='' PACKAGE_URL='' ac_unique_file="src/Makefile.am" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='am__EXEEXT_FALSE am__EXEEXT_TRUE LTLIBOBJS LIBOBJS CXXCPP OTOOL64 OTOOL LIPO NMEDIT DSYMUTIL MANIFEST_TOOL RANLIB ac_ct_AR AR DLLTOOL OBJDUMP LN_S NM ac_ct_DUMPBIN DUMPBIN LD FGREP SED host_os host_vendor host_cpu host build_os build_vendor build_cpu build LIBTOOL default_softhsm2_conf softhsmtokendir SQLITE3_LIBS SQLITE3_INCLUDES SQLITE3 BUILD_OBJECTSTORE_BACKEND_DB_FALSE BUILD_OBJECTSTORE_BACKEND_DB_TRUE BUILD_MIGRATE_FALSE BUILD_MIGRATE_TRUE YIELD_LIB WITH_BOTAN_FALSE WITH_BOTAN_TRUE WITH_OPENSSL_FALSE WITH_OPENSSL_TRUE CRYPTO_LIBS CRYPTO_INCLUDES BOTAN_VERSION_MINOR BOTAN_LIBS BOTAN_INCLUDES HAVE_CXX11 OPENSSL_LIBS OPENSSL_INCLUDES WITH_GOST_FALSE WITH_GOST_TRUE WITH_ECC_FALSE WITH_ECC_TRUE EGREP GREP CPP am__fastdepCXX_FALSE am__fastdepCXX_TRUE CXXDEPMODE ac_ct_CXX CXXFLAGS CXX am__fastdepCC_FALSE am__fastdepCC_TRUE CCDEPMODE am__nodep AMDEPBACKSLASH AMDEP_FALSE AMDEP_TRUE am__quote am__include DEPDIR OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC VERSION_INFO AM_BACKSLASH AM_DEFAULT_VERBOSITY AM_DEFAULT_V AM_V am__untar am__tar AMTAR am__leading_dot SET_MAKE AWK mkdir_p MKDIR_P INSTALL_STRIP_PROGRAM STRIP install_sh MAKEINFO AUTOHEADER AUTOMAKE AUTOCONF ACLOCAL VERSION PACKAGE CYGPATH_W am__isrc INSTALL_DATA INSTALL_SCRIPT INSTALL_PROGRAM target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_silent_rules enable_dependency_tracking enable_pedantic enable_strict enable_64bit enable_ecc enable_gost enable_fips with_crypto_backend with_openssl with_botan enable_non_paged_memory with_migrate with_objectstore_backend_db with_sqlite3 enable_visibility enable_shared enable_static with_pic enable_fast_install with_gnu_ld with_sysroot enable_libtool_lock ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CXX CXXFLAGS CCC CPP CXXCPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures SoftHSM 2.0.0 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/softhsm] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF Program names: --program-prefix=PREFIX prepend PREFIX to installed program names --program-suffix=SUFFIX append SUFFIX to installed program names --program-transform-name=PROGRAM run sed PROGRAM on installed program names System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of SoftHSM 2.0.0:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --enable-silent-rules less verbose build output (undo: "make V=1") --disable-silent-rules verbose build output (undo: "make V=0") --enable-dependency-tracking do not reject slow dependency extractors --disable-dependency-tracking speeds up one-time build --enable-pedantic enable pedantic compile mode [enabled] --enable-strict enable strict compile mode [enabled] --enable-64bit enable 64-bit compiling [disabled] --enable-ecc Enable support for ECC (default enabled) --enable-gost Enable support for GOST (default enabled) --enable-fips Enable support for FIPS 140-2 mode (default disabled) --disable-non-paged-memory Disable non-paged memory for secure storage (default enabled) --disable-visibility disable hidden visibilty link mode [enabled] --enable-shared[=PKGS] build shared libraries [default=yes] --enable-static[=PKGS] build static libraries [default=yes] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] --disable-libtool-lock avoid locking (might break parallel builds) Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --with-crypto-backend Select crypto backend (openssl|botan) --with-openssl=PATH Specify prefix of path of OpenSSL --with-botan=PATH Specify prefix of path of Botan --with-migrate Build the migration tool. Requires SQLite3. --with-objectstore-backend-db Build with object store backend database (SQLite3). --with-sqlite3=PATH Specify prefix of path of SQLite3 --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use both] --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot=DIR Search for dependent libraries within DIR (or the compiler's sysroot if not specified). Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CXX C++ compiler command CXXFLAGS C++ compiler flags CPP C preprocessor CXXCPP C++ preprocessor Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to the package provider. _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF SoftHSM configure 2.0.0 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_cxx_try_compile LINENO # ---------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_compile # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link # ac_fn_c_check_func LINENO FUNC VAR # ---------------------------------- # Tests whether FUNC exists, setting the cache variable VAR accordingly ac_fn_c_check_func () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case declares $2. For example, HP-UX 11i declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, which can conflict with char $2 (); below. Prefer to if __STDC__ is defined, since exists even on freestanding compilers. */ #ifdef __STDC__ # include #else # include #endif #undef $2 /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char $2 (); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ #if defined __stub_$2 || defined __stub___$2 choke me #endif int main () { return $2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_func # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists, giving a warning if it cannot be compiled using # the include files in INCLUDES and setting the cache variable VAR # accordingly. ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_cxx_try_link LINENO # ------------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_cxx_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_link # ac_fn_cxx_try_run LINENO # ------------------------ # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_cxx_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_run # ac_fn_cxx_try_cpp LINENO # ------------------------ # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_cxx_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_cxx_preproc_warn_flag$ac_cxx_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_cpp cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by SoftHSM $as_me 2.0.0, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers config.h" am__api_version='1.14' ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Find a good install program. We prefer a C program (faster), # so one script is as good as another. But avoid the broken or # incompatible versions: # SysV /etc/install, /usr/sbin/install # SunOS /usr/etc/install # IRIX /sbin/install # AIX /bin/install # AmigaOS /C/install, which installs bootblocks on floppy discs # AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag # AFS /usr/afsws/bin/install, which mishandles nonexistent args # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" # OS/2's system install, which has a completely different semantic # ./install, which can be erroneously created by make from ./install.sh. # Reject install programs that cannot install multiple files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 $as_echo_n "checking for a BSD-compatible install... " >&6; } if test -z "$INSTALL"; then if ${ac_cv_path_install+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. # Account for people who put trailing slashes in PATH elements. case $as_dir/ in #(( ./ | .// | /[cC]/* | \ /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ /usr/ucb/* ) ;; *) # OSF1 and SCO ODT 3.0 have their own names for install. # Don't use installbsd from OSF since it installs stuff as root # by default. for ac_prog in ginstall scoinst install; do for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then if test $ac_prog = install && grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # AIX install. It has an incompatible calling convention. : elif test $ac_prog = install && grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then # program-specific install script used by HP pwplus--don't use. : else rm -rf conftest.one conftest.two conftest.dir echo one > conftest.one echo two > conftest.two mkdir conftest.dir if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && test -s conftest.one && test -s conftest.two && test -s conftest.dir/conftest.one && test -s conftest.dir/conftest.two then ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" break 3 fi fi fi done done ;; esac done IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir fi if test "${ac_cv_path_install+set}" = set; then INSTALL=$ac_cv_path_install else # As a last resort, use the slow shell script. Don't cache a # value for INSTALL within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. INSTALL=$ac_install_sh fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 $as_echo "$INSTALL" >&6; } # Use test -z because SunOS4 sh mishandles braces in ${var-val}. # It thinks the first close brace ends the variable substitution. test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 $as_echo_n "checking whether build environment is sane... " >&6; } # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$*" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$*" != "X $srcdir/configure conftest.file" \ && test "$*" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". as_fn_error $? "ls -t appears to fail. Make sure there is not a broken alias in your environment" "$LINENO" 5 fi if test "$2" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$2" = conftest.file ) then # Ok. : else as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi rm -f conftest.file test "$program_prefix" != NONE && program_transform_name="s&^&$program_prefix&;$program_transform_name" # Use a double $ so make ignores it. test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. # By default was `s,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: 'missing' script is too old or missing" >&5 $as_echo "$as_me: WARNING: 'missing' script is too old or missing" >&2;} fi if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. if test "$cross_compiling" != no; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a thread-safe mkdir -p" >&5 $as_echo_n "checking for a thread-safe mkdir -p... " >&6; } if test -z "$MKDIR_P"; then if ${ac_cv_path_mkdir+:} false; then : $as_echo_n "(cached) " >&6 else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in mkdir gmkdir; do for ac_exec_ext in '' $ac_executable_extensions; do as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext" || continue case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir (GNU coreutils) '* | \ 'mkdir (coreutils) '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext break 3;; esac done done done IFS=$as_save_IFS fi test -d ./--version && rmdir ./--version if test "${ac_cv_path_mkdir+set}" = set; then MKDIR_P="$ac_cv_path_mkdir -p" else # As a last resort, use the slow shell script. Don't cache a # value for MKDIR_P within a source directory, because that will # break other packages using the cache if that directory is # removed, or if the value is a relative name. MKDIR_P="$ac_install_sh -d" fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 $as_echo "$MKDIR_P" >&6; } for ac_prog in gawk mawk nawk awk do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AWK="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 $as_echo "$AWK" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AWK" && break done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF # GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; *) eval ac_cv_prog_make_${ac_make}_set=no;; esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } SET_MAKE= else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null # Check whether --enable-silent-rules was given. if test "${enable_silent_rules+set}" = set; then : enableval=$enable_silent_rules; fi case $enable_silent_rules in # ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=1;; esac am_make=${MAKE-make} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 $as_echo_n "checking whether $am_make supports nested variables... " >&6; } if ${am_cv_make_support_nested_variables+:} false; then : $as_echo_n "(cached) " >&6 else if $as_echo 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit' | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 $as_echo "$am_cv_make_support_nested_variables" >&6; } if test $am_cv_make_support_nested_variables = yes; then AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AM_BACKSLASH='\' if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." am__isrc=' -I$(srcdir)' # test to see if srcdir already configured if test -f $srcdir/config.status; then as_fn_error $? "source directory already configured; run \"make distclean\" there first" "$LINENO" 5 fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi # Define the identity of the package. PACKAGE='softhsm' VERSION='2.0.0' cat >>confdefs.h <<_ACEOF #define PACKAGE "$PACKAGE" _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION "$VERSION" _ACEOF # Some tools Automake needs. ACLOCAL=${ACLOCAL-"${am_missing_run}aclocal-${am__api_version}"} AUTOCONF=${AUTOCONF-"${am_missing_run}autoconf"} AUTOMAKE=${AUTOMAKE-"${am_missing_run}automake-${am__api_version}"} AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"} MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"} # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # mkdir_p='$(MKDIR_P)' # We need awk for the "check" target. The system "awk" is bad on # some platforms. # Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AMTAR='$${TAR-tar}' # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar pax cpio none' am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 fi fi case "$prefix" in NONE) case "$sysconfdir" in '${prefix}/etc') sysconfdir=/etc ac_configure_args="$ac_configure_args --sysconfdir=$sysconfdir" { $as_echo "$as_me:${as_lineno-$LINENO}: sysconfdir set to $sysconfdir" >&5 $as_echo "$as_me: sysconfdir set to $sysconfdir" >&6;} ;; esac case "$localstatedir" in '${prefix}/var') localstatedir=/var ac_configure_args="$ac_configure_args --localstatedir=$localstatedir" { $as_echo "$as_me:${as_lineno-$LINENO}: localstate set to $localstatedir" >&5 $as_echo "$as_me: localstate set to $localstatedir" >&6;} ;; esac ;; esac # Version info for the library VERSION_INFO="2:0:1" # Checks for compilers ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC understands -c and -o together" >&5 $as_echo_n "checking whether $CC understands -c and -o together... " >&6; } if ${am_cv_prog_cc_c_o+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if { echo "$as_me:$LINENO: $CC -c conftest.$ac_ext -o conftest2.$ac_objext" >&5 ($CC -c conftest.$ac_ext -o conftest2.$ac_objext) >&5 2>&5 ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&5 (exit $ac_status); } \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 $as_echo "$am_cv_prog_cc_c_o" >&6; } if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu DEPDIR="${am__leading_dot}deps" ac_config_commands="$ac_config_commands depfiles" am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for style of include used by $am_make" >&5 $as_echo_n "checking for style of include used by $am_make... " >&6; } am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $_am_result" >&5 $as_echo "$_am_result" >&6; } rm -f confinc confmf # Check whether --enable-dependency-tracking was given. if test "${enable_dependency_tracking+set}" = set; then : enableval=$enable_dependency_tracking; fi if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi if test "x$enable_dependency_tracking" != xno; then AMDEP_TRUE= AMDEP_FALSE='#' else AMDEP_TRUE='#' AMDEP_FALSE= fi depcc="$CC" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CC_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CC_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CC_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CC_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 $as_echo "$am_cv_CC_dependencies_compiler_type" >&6; } CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then am__fastdepCC_TRUE= am__fastdepCC_FALSE='#' else am__fastdepCC_TRUE='#' am__fastdepCC_FALSE= fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test -z "$CXX"; then if test -n "$CCC"; then CXX=$CCC else if test -n "$ac_tool_prefix"; then for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CXX="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXX" >&5 $as_echo "$CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CXX" && break done fi if test -z "$CXX"; then ac_ct_CXX=$CXX for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CXX="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CXX" >&5 $as_echo "$ac_ct_CXX" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CXX" && break done if test "x$ac_ct_CXX" = x; then CXX="g++" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CXX=$ac_ct_CXX fi fi fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C++ compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } if ${ac_cv_cxx_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 $as_echo "$ac_cv_cxx_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GXX=yes else GXX= fi ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } if ${ac_cv_prog_cxx_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes else CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : else ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ac_cv_prog_cxx_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cxx_werror_flag=$ac_save_cxx_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 $as_echo "$ac_cv_prog_cxx_g" >&6; } if test "$ac_test_CXXFLAGS" = set; then CXXFLAGS=$ac_save_CXXFLAGS elif test $ac_cv_prog_cxx_g = yes; then if test "$GXX" = yes; then CXXFLAGS="-g -O2" else CXXFLAGS="-g" fi else if test "$GXX" = yes; then CXXFLAGS="-O2" else CXXFLAGS= fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu depcc="$CXX" am_compiler_list= { $as_echo "$as_me:${as_lineno-$LINENO}: checking dependency style of $depcc" >&5 $as_echo_n "checking dependency style of $depcc... " >&6; } if ${am_cv_CXX_dependencies_compiler_type+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_CXX_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n 's/^#*\([a-zA-Z0-9]*\))$/\1/p' < ./depcomp` fi am__universal=false case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_CXX_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_CXX_dependencies_compiler_type=none fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_CXX_dependencies_compiler_type" >&5 $as_echo "$am_cv_CXX_dependencies_compiler_type" >&6; } CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type if test "x$enable_dependency_tracking" != xno \ && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then am__fastdepCXX_TRUE= am__fastdepCXX_FALSE='#' else am__fastdepCXX_TRUE='#' am__fastdepCXX_FALSE= fi # Compiler flags # Check whether --enable-pedantic was given. if test "${enable_pedantic+set}" = set; then : enableval=$enable_pedantic; else enable_pedantic="yes" fi if test "${enable_pedantic}" = "yes"; then enable_strict="yes"; CFLAGS="${CFLAGS} -pedantic" fi # Check whether --enable-strict was given. if test "${enable_strict+set}" = set; then : enableval=$enable_strict; else enable_strict="yes" fi if test "${enable_strict}" = "yes"; then CFLAGS="${CFLAGS} -Wall -Wextra" CXXFLAGS="${CXXFLAGS} -Wall -Wextra" fi # Check whether --enable-64bit was given. if test "${enable_64bit+set}" = set; then : enableval=$enable_64bit; enable_64bit="${enableval}" else enable_64bit="no" fi if test "x$enable_64bit" = "xyes" then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can compile in 64-bit mode" >&5 $as_echo_n "checking if we can compile in 64-bit mode... " >&6; } tmp_CFLAGS=$CFLAGS CFLAGS="-m64" if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { return sizeof(void*) == 8 ? 0 : 1; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } CXXFLAGS="-m64 $CXXFLAGS" LDFLAGS="-m64 $LDFLAGS" CFLAGS="-m64 $tmp_CFLAGS" else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } as_fn_error $? "Don't know how to compile in 64-bit mode." "$LINENO" 5 CFLAGS=$tmp_CFLAGS fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi # Check for libraries (-ldl can be required by OpenSSL too) ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : $as_echo "#define HAVE_DLOPEN 1" >>confdefs.h else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : $as_echo "#define HAVE_DLOPEN 1" >>confdefs.h LIBS="$LIBS -ldl" else ac_fn_c_check_func "$LINENO" "LoadLibrary" "ac_cv_func_LoadLibrary" if test "x$ac_cv_func_LoadLibrary" = xyes; then : if test $ac_cv_func_LoadLibrary = yes; then $as_echo "#define HAVE_LOADLIBRARY 1" >>confdefs.h fi else as_fn_error $? "No dynamic library loading support" "$LINENO" 5 fi fi fi # Check for headers ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done for ac_header in pthread.h do : ac_fn_c_check_header_mongrel "$LINENO" "pthread.h" "ac_cv_header_pthread_h" "$ac_includes_default" if test "x$ac_cv_header_pthread_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_PTHREAD_H 1 _ACEOF fi done # What crypto backend to use and if we want to have support GOST # First check if we want to support ECC and GOST # Check whether --enable-ecc was given. if test "${enable_ecc+set}" = set; then : enableval=$enable_ecc; enable_ecc="${enableval}" else enable_ecc="yes" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ECC support" >&5 $as_echo_n "checking for ECC support... " >&6; } if test "x${enable_ecc}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } cat >>confdefs.h <<_ACEOF #define WITH_ECC /**/ _ACEOF else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x${enable_ecc}" = "xyes"; then WITH_ECC_TRUE= WITH_ECC_FALSE='#' else WITH_ECC_TRUE='#' WITH_ECC_FALSE= fi # Check whether --enable-gost was given. if test "${enable_gost+set}" = set; then : enableval=$enable_gost; enable_gost="${enableval}" else enable_gost="yes" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GOST support" >&5 $as_echo_n "checking for GOST support... " >&6; } if test "x${enable_gost}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } cat >>confdefs.h <<_ACEOF #define WITH_GOST /**/ _ACEOF else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x${enable_gost}" = "xyes"; then WITH_GOST_TRUE= WITH_GOST_FALSE='#' else WITH_GOST_TRUE='#' WITH_GOST_FALSE= fi # Second check for the FIPS 140-2 mode # Check whether --enable-fips was given. if test "${enable_fips+set}" = set; then : enableval=$enable_fips; enable_fips="${enableval}" else enable_fips="no" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FIPS 140-2 mode" >&5 $as_echo_n "checking for FIPS 140-2 mode... " >&6; } if test "x${enable_fips}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } cat >>confdefs.h <<_ACEOF #define WITH_FIPS /**/ _ACEOF else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x${enable_fips}" = "xyes"; then WITH_GOST_TRUE= WITH_GOST_FALSE='#' else WITH_GOST_TRUE='#' WITH_GOST_FALSE= fi # Then check what crypto library we want to use # Check whether --with-crypto-backend was given. if test "${with_crypto_backend+set}" = set; then : withval=$with_crypto_backend; crypto_backend="${withval}" else crypto_backend="openssl" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for crypto backend" >&5 $as_echo_n "checking for crypto backend... " >&6; } if test "x${crypto_backend}" = "xopenssl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: OpenSSL" >&5 $as_echo "OpenSSL" >&6; } if test "x${enable_fips}" = "xyes"; then # Check whether --with-openssl was given. if test "${with_openssl+set}" = set; then : withval=$with_openssl; OPENSSL_PATH="$withval" else OPENSSL_PATH="/usr/local" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the OpenSSL includes" >&5 $as_echo_n "checking what are the OpenSSL includes... " >&6; } OPENSSL_INCLUDES="-I$OPENSSL_PATH/include" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OPENSSL_INCLUDES" >&5 $as_echo "$OPENSSL_INCLUDES" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the OpenSSL libs" >&5 $as_echo_n "checking what are the OpenSSL libs... " >&6; } OPENSSL_LIBS="-L$OPENSSL_PATH/lib -lcrypto" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OPENSSL_LIBS" >&5 $as_echo "$OPENSSL_LIBS" >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $OPENSSL_INCLUDES" LIBS="$LIBS $OPENSSL_LIBS" for ac_header in openssl/ssl.h do : ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" if test "x$ac_cv_header_openssl_ssl_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_OPENSSL_SSL_H 1 _ACEOF else as_fn_error $? "Can't find OpenSSL headers" "$LINENO" 5 fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BN_init in -lcrypto" >&5 $as_echo_n "checking for BN_init in -lcrypto... " >&6; } if ${ac_cv_lib_crypto_BN_init+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lcrypto $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char BN_init (); int main () { return BN_init (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_crypto_BN_init=yes else ac_cv_lib_crypto_BN_init=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_crypto_BN_init" >&5 $as_echo "$ac_cv_lib_crypto_BN_init" >&6; } if test "x$ac_cv_lib_crypto_BN_init" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBCRYPTO 1 _ACEOF LIBS="-lcrypto $LIBS" else as_fn_error $? "Can't find OpenSSL library" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for OpenSSL version" >&5 $as_echo_n "checking for OpenSSL version... " >&6; } CHECK_OPENSSL_VERSION=0x010001000L ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main() { #ifndef OPENSSL_VERSION_NUMBER return -1; #endif #if OPENSSL_VERSION_NUMBER >= $CHECK_OPENSSL_VERSION return 0; #else return 1; #endif } _ACEOF if ac_fn_c_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: >= 1.0.1" >&5 $as_echo ">= 1.0.1" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: < 1.0.1" >&5 $as_echo "< 1.0.1" >&6; } as_fn_error $? "OpenSSL library too old (1.0.1 or later required)" "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS else # Check whether --with-openssl was given. if test "${with_openssl+set}" = set; then : withval=$with_openssl; OPENSSL_PATH="$withval" else OPENSSL_PATH="/usr/local" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the OpenSSL includes" >&5 $as_echo_n "checking what are the OpenSSL includes... " >&6; } OPENSSL_INCLUDES="-I$OPENSSL_PATH/include" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OPENSSL_INCLUDES" >&5 $as_echo "$OPENSSL_INCLUDES" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the OpenSSL libs" >&5 $as_echo_n "checking what are the OpenSSL libs... " >&6; } OPENSSL_LIBS="-L$OPENSSL_PATH/lib -lcrypto" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OPENSSL_LIBS" >&5 $as_echo "$OPENSSL_LIBS" >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $OPENSSL_INCLUDES" LIBS="$LIBS $OPENSSL_LIBS" for ac_header in openssl/ssl.h do : ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" if test "x$ac_cv_header_openssl_ssl_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_OPENSSL_SSL_H 1 _ACEOF else as_fn_error $? "Can't find OpenSSL headers" "$LINENO" 5 fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BN_init in -lcrypto" >&5 $as_echo_n "checking for BN_init in -lcrypto... " >&6; } if ${ac_cv_lib_crypto_BN_init+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lcrypto $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char BN_init (); int main () { return BN_init (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_crypto_BN_init=yes else ac_cv_lib_crypto_BN_init=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_crypto_BN_init" >&5 $as_echo "$ac_cv_lib_crypto_BN_init" >&6; } if test "x$ac_cv_lib_crypto_BN_init" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBCRYPTO 1 _ACEOF LIBS="-lcrypto $LIBS" else as_fn_error $? "Can't find OpenSSL library" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for OpenSSL version" >&5 $as_echo_n "checking for OpenSSL version... " >&6; } CHECK_OPENSSL_VERSION=0x010000000L ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main() { #ifndef OPENSSL_VERSION_NUMBER return -1; #endif #if OPENSSL_VERSION_NUMBER >= $CHECK_OPENSSL_VERSION return 0; #else return 1; #endif } _ACEOF if ac_fn_c_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: >= 1.0.0" >&5 $as_echo ">= 1.0.0" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: < 1.0.0" >&5 $as_echo "< 1.0.0" >&6; } as_fn_error $? "OpenSSL library too old (1.0.0 or later required)" "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi CRYPTO_INCLUDES=$OPENSSL_INCLUDES CRYPTO_LIBS=$OPENSSL_LIBS if test "x${enable_ecc}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for OpenSSL ECC support" >&5 $as_echo_n "checking for OpenSSL ECC support... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main() { EC_KEY *ec256, *ec384; ec256 = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); ec384 = EC_KEY_new_by_curve_name(NID_secp384r1); if (ec256 == NULL || ec384 == NULL) return 1; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: Found P256 and P384" >&5 $as_echo "Found P256 and P384" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: Cannot find P256 or P384" >&5 $as_echo "Cannot find P256 or P384" >&6; } as_fn_error $? "OpenSSL library has no ECC support" "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi if test "x${enable_gost}" = "xyes"; then if test "x${enable_fips}" = "xyes"; then as_fn_error $? "GOST is not FIPS approved" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for OpenSSL GOST support" >&5 $as_echo_n "checking for OpenSSL GOST support... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main() { ENGINE *e; EC_KEY *ek; ek = NULL; OPENSSL_config(NULL); e = ENGINE_by_id("gost"); if (e == NULL) return 1; if (ENGINE_init(e) <= 0) return 1; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: Found GOST engine" >&5 $as_echo "Found GOST engine" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: Cannot GOST engine" >&5 $as_echo "Cannot GOST engine" >&6; } as_fn_error $? "OpenSSL library has no GOST support" "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi if test "x${enable_fips}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for OpenSSL FIPS capable library" >&5 $as_echo_n "checking for OpenSSL FIPS capable library... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$CRYPTO_LIBS $LIBS" # check whether we can build an application which can # "reference the OpenSSL FIPS object module" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main() { return !FIPS_mode_set(1); } _ACEOF if ac_fn_c_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: Found working FIPS_mode_set()" >&5 $as_echo "Found working FIPS_mode_set()" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: FIPS_mode_set(1) failed" >&5 $as_echo "FIPS_mode_set(1) failed" >&6; } as_fn_error $? "OpenSSL library is not FIPS capable" "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # build missing fips_premain_dso tool if test "x${FIPSLD_CC}" != "x"; then THERE="`echo $CC | sed -e 's|[^/]*$||'`".. if test "x${FIPSLIBDIR}" != "x"; then PREMAIN_C="${FIPSLIBDIR}/fips_premain.c" elif test -f "${THERE}/fips/fips_premain.c"; then PREMAIN_C="${THERE}/fips/fips_premain.c" elif test -f "${THERE}/lib/fips_premain.c"; then PREMAIN_C="${THERE}/lib/fips_premain.c" else { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: can't find fips_premain.c" >&5 $as_echo "$as_me: WARNING: can't find fips_premain.c" >&2;} fi $FIPSLD_CC $CPPFLAGS -DFINGERPRINT_PREMAIN_DSO_LOAD \ -o src/lib/fips_premain_dso $PREMAIN_C $LIBS fi CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS else { $as_echo "$as_me:${as_lineno-$LINENO}: checking OpenSSL EVP interface for AES key wrapping" >&5 $as_echo_n "checking OpenSSL EVP interface for AES key wrapping... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main() { EVP_aes_128_wrap(); return 1; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: RFC 3394 is supported" >&5 $as_echo "RFC 3394 is supported" >&6; } $as_echo "#define HAVE_AES_KEY_WRAP 1" >>confdefs.h else { $as_echo "$as_me:${as_lineno-$LINENO}: result: RFC 3394 is not supported" >&5 $as_echo "RFC 3394 is not supported" >&6; } fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: checking OpenSSL EVP interface for AES key wrapping with pad" >&5 $as_echo_n "checking OpenSSL EVP interface for AES key wrapping with pad... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main() { EVP_aes_128_wrap_pad(); return 1; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: RFC 5649 is supported" >&5 $as_echo "RFC 5649 is supported" >&6; } $as_echo "#define HAVE_AES_KEY_WRAP_PAD 1" >>confdefs.h else { $as_echo "$as_me:${as_lineno-$LINENO}: result: RFC 5649 is not supported" >&5 $as_echo "RFC 5649 is not supported" >&6; } fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi cat >>confdefs.h <<_ACEOF #define WITH_OPENSSL /**/ _ACEOF elif test "x${crypto_backend}" = "xbotan"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: Botan" >&5 $as_echo "Botan" >&6; } # Check whether --with-botan was given. if test "${with_botan+set}" = set; then : withval=$with_botan; BOTAN_PATH="$withval" else BOTAN_PATH="/usr/local" fi BOTAN_VERSION_MINOR=10 as_ac_File=`$as_echo "ac_cv_file_$BOTAN_PATH/include/botan-1.10/botan/init.h" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $BOTAN_PATH/include/botan-1.10/botan/init.h" >&5 $as_echo_n "checking for $BOTAN_PATH/include/botan-1.10/botan/init.h... " >&6; } if eval \${$as_ac_File+:} false; then : $as_echo_n "(cached) " >&6 else test "$cross_compiling" = yes && as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5 if test -r "$BOTAN_PATH/include/botan-1.10/botan/init.h"; then eval "$as_ac_File=yes" else eval "$as_ac_File=no" fi fi eval ac_res=\$$as_ac_File { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_File"\" = x"yes"; then : BOTAN_VERSION_MINOR=10 else as_ac_File=`$as_echo "ac_cv_file_$BOTAN_PATH/include/botan-1.11/botan/init.h" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $BOTAN_PATH/include/botan-1.11/botan/init.h" >&5 $as_echo_n "checking for $BOTAN_PATH/include/botan-1.11/botan/init.h... " >&6; } if eval \${$as_ac_File+:} false; then : $as_echo_n "(cached) " >&6 else test "$cross_compiling" = yes && as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5 if test -r "$BOTAN_PATH/include/botan-1.11/botan/init.h"; then eval "$as_ac_File=yes" else eval "$as_ac_File=no" fi fi eval ac_res=\$$as_ac_File { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test \"x\$"$as_ac_File"\" = x"yes"; then : BOTAN_VERSION_MINOR=11 else as_fn_error $? "Cannot find Botan includes" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the Botan includes" >&5 $as_echo_n "checking what are the Botan includes... " >&6; } BOTAN_INCLUDES="-I$BOTAN_PATH/include/botan-1.$BOTAN_VERSION_MINOR" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $BOTAN_INCLUDES" >&5 $as_echo "$BOTAN_INCLUDES" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the Botan libs" >&5 $as_echo_n "checking what are the Botan libs... " >&6; } BOTAN_LIBS="-L$BOTAN_PATH/lib -lbotan-1.$BOTAN_VERSION_MINOR" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $BOTAN_LIBS" >&5 $as_echo "$BOTAN_LIBS" >&6; } if test "x${BOTAN_VERSION_MINOR}" = "x11"; then ax_cxx_compile_cxx11_required=true ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu ac_success=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX supports C++11 features by default" >&5 $as_echo_n "checking whether $CXX supports C++11 features by default... " >&6; } if ${ax_cv_cxx_compile_cxx11+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ template struct check { static_assert(sizeof(int) <= sizeof(T), "not big enough"); }; struct Base { virtual void f() {} }; struct Child : public Base { virtual void f() override {} }; typedef check> right_angle_brackets; int a; decltype(a) b; typedef check check_type; check_type c; check_type&& cr = static_cast(c); auto d = a; auto l = [](){}; _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : ax_cv_cxx_compile_cxx11=yes else ax_cv_cxx_compile_cxx11=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ax_cv_cxx_compile_cxx11" >&5 $as_echo "$ax_cv_cxx_compile_cxx11" >&6; } if test x$ax_cv_cxx_compile_cxx11 = xyes; then ac_success=yes fi if test x$ac_success = xno; then for switch in -std=c++11 -std=c++0x; do cachevar=`$as_echo "ax_cv_cxx_compile_cxx11_$switch" | $as_tr_sh` { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX supports C++11 features with $switch" >&5 $as_echo_n "checking whether $CXX supports C++11 features with $switch... " >&6; } if eval \${$cachevar+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_CXXFLAGS="$CXXFLAGS" CXXFLAGS="$CXXFLAGS $switch" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ template struct check { static_assert(sizeof(int) <= sizeof(T), "not big enough"); }; struct Base { virtual void f() {} }; struct Child : public Base { virtual void f() override {} }; typedef check> right_angle_brackets; int a; decltype(a) b; typedef check check_type; check_type c; check_type&& cr = static_cast(c); auto d = a; auto l = [](){}; _ACEOF if ac_fn_cxx_try_compile "$LINENO"; then : eval $cachevar=yes else eval $cachevar=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext CXXFLAGS="$ac_save_CXXFLAGS" fi eval ac_res=\$$cachevar { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } if eval test x\$$cachevar = xyes; then CXXFLAGS="$CXXFLAGS $switch" ac_success=yes break fi done fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test x$ax_cxx_compile_cxx11_required = xtrue; then if test x$ac_success = xno; then as_fn_error $? "*** A compiler with support for C++11 language features is required." "$LINENO" 5 fi else if test x$ac_success = xno; then HAVE_CXX11=0 { $as_echo "$as_me:${as_lineno-$LINENO}: No compiler with C++11 support was found" >&5 $as_echo "$as_me: No compiler with C++11 support was found" >&6;} else HAVE_CXX11=1 $as_echo "#define HAVE_CXX11 1" >>confdefs.h fi fi fi tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $BOTAN_INCLUDES" LIBS="$LIBS $BOTAN_LIBS" ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { using namespace Botan; LibraryInitializer::initialize(); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,10,0) #error "Botan version too old"; #endif ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: checking for Botan >= v1.10.0 ... yes" >&5 $as_echo "checking for Botan >= v1.10.0 ... yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: checking for Botan >= v1.10.0 ... no" >&5 $as_echo "checking for Botan >= v1.10.0 ... no" >&6; } as_fn_error $? "Missing the correct version of the Botan library" "$LINENO" 5 fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS CRYPTO_INCLUDES=$BOTAN_INCLUDES CRYPTO_LIBS=$BOTAN_LIBS if test "x${enable_ecc}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Botan ECC support" >&5 $as_echo_n "checking for Botan ECC support... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main() { Botan::LibraryInitializer::initialize(); const std::string name("secp256r1"); const Botan::OID oid(Botan::OIDS::lookup(name)); const Botan::EC_Group ecg(oid); try { #if BOTAN_VERSION_MINOR == 11 const std::vector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #else const Botan::SecureVector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #endif } catch(...) { return 1; } return 0; } _ACEOF if ac_fn_cxx_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: Found P256" >&5 $as_echo "Found P256" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: Cannot find P256" >&5 $as_echo "Cannot find P256" >&6; } as_fn_error $? " Botan library has no valid ECC support. Please upgrade to a later version of Botan, above or including version 1.10.6 or 1.11.5. Alternatively disable ECC support in SoftHSM with --disable-ecc " "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi if test "x${enable_fips}" = "xyes"; then as_fn_error $? "Botan does not support FIPS 140-2 mode" "$LINENO" 5 fi if test "x${enable_gost}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Botan GOST support" >&5 $as_echo_n "checking for Botan GOST support... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run test program while cross compiling See \`config.log' for more details" "$LINENO" 5; } else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include int main() { Botan::LibraryInitializer::initialize(); const std::string name("gost_256A"); const Botan::OID oid(Botan::OIDS::lookup(name)); const Botan::EC_Group ecg(oid); try { #if BOTAN_VERSION_MINOR == 11 const std::vector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #else const Botan::SecureVector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #endif } catch(...) { return 1; } return 0; } _ACEOF if ac_fn_cxx_try_run "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: Found GOST" >&5 $as_echo "Found GOST" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: Cannot find GOST" >&5 $as_echo "Cannot find GOST" >&6; } as_fn_error $? " Botan library has no valid GOST support. Please upgrade to a later version of Botan, above or including version 1.10.6 or 1.11.5. Alternatively disable GOST support in SoftHSM with --disable-gost " "$LINENO" 5 fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi if test "x${BOTAN_VERSION_MINOR}" = "x10"; then tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $BOTAN_INCLUDES" LIBS="$LIBS $BOTAN_LIBS" ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #ifndef BOTAN_HAS_ENGINE_GNU_MP #error "No GNU MP support"; #endif ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: checking for Botan GNU MP support... yes" >&5 $as_echo "checking for Botan GNU MP support... yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: checking for Botan GNU MP support... no" >&5 $as_echo "checking for Botan GNU MP support... no" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: ==================================================== Botan has not been built with GNU MP (--with-gnump). This will give negative impact on the performance. ====================================================" >&5 $as_echo "$as_me: WARNING: ==================================================== Botan has not been built with GNU MP (--with-gnump). This will give negative impact on the performance. ====================================================" >&2;} fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Botan RFC5649 support" >&5 $as_echo_n "checking for Botan RFC5649 support... " >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" $as_echo "#define HAVE_AES_KEY_WRAP 1" >>confdefs.h ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main() { using namespace Botan; SecureVector key(10); SymmetricKey kek("AABB"); Algorithm_Factory& af = global_state().algorithm_factory(); SecureVector x = rfc5649_keywrap(key, kek, af); return 1; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: Found AES key wrap with pad" >&5 $as_echo "Found AES key wrap with pad" >&6; } $as_echo "#define HAVE_AES_KEY_WRAP_PAD 1" >>confdefs.h else { $as_echo "$as_me:${as_lineno-$LINENO}: result: Cannot find AES key wrap with pad" >&5 $as_echo "Cannot find AES key wrap with pad" >&6; } fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS cat >>confdefs.h <<_ACEOF #define WITH_BOTAN /**/ _ACEOF else { $as_echo "$as_me:${as_lineno-$LINENO}: result: Unknown" >&5 $as_echo "Unknown" >&6; } as_fn_error $? "Crypto backend ${crypto_backend} not supported. Use openssl or botan." "$LINENO" 5 fi if test "x${crypto_backend}" = "xopenssl"; then WITH_OPENSSL_TRUE= WITH_OPENSSL_FALSE='#' else WITH_OPENSSL_TRUE='#' WITH_OPENSSL_FALSE= fi if test "x${crypto_backend}" = "xbotan"; then WITH_BOTAN_TRUE= WITH_BOTAN_FALSE='#' else WITH_BOTAN_TRUE='#' WITH_BOTAN_FALSE= fi # Non-paged memory for secure storage # Check whether --enable-non-paged-memory was given. if test "${enable_non_paged_memory+set}" = set; then : enableval=$enable_non_paged_memory; enable_non_paged_memory="${enableval}" else enable_non_paged_memory="yes" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-paged memory for secure storage" >&5 $as_echo_n "checking for non-paged memory for secure storage... " >&6; } if test "x${enable_non_paged_memory}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: enabled" >&5 $as_echo "enabled" >&6; } cat >>confdefs.h <<_ACEOF #define SENSITIVE_NON_PAGE /**/ _ACEOF for ac_header in sys/mman.h do : ac_fn_c_check_header_mongrel "$LINENO" "sys/mman.h" "ac_cv_header_sys_mman_h" "$ac_includes_default" if test "x$ac_cv_header_sys_mman_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_SYS_MMAN_H 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum size that may be locked into memory" >&5 $as_echo_n "checking the maximum size that may be locked into memory... " >&6; } MLOCK_SIZE="`ulimit -l`" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MLOCK_SIZE" >&5 $as_echo "$MLOCK_SIZE" >&6; } if test "x${MLOCK_SIZE}" != "xunlimited"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: ====================================================================== SoftHSM has been configured to store sensitive data in non-page RAM (i.e. memory that is not swapped out to disk). This is the default and most secure configuration. Your system, however, is not configured to support this model in non-privileged accounts (i.e. user accounts). You can check the setting on your system by running the following command in a shell: ulimit -l If this does not return \"unlimited\" and you plan to run SoftHSM from non-privileged accounts then you should edit the configuration file /etc/security/limits.conf (on most systems). You will need to add the following lines to this file: # * - memlock unlimited Alternatively, you can elect to disable this feature of SoftHSM by re-running configure with the option \"--disable-non-paged-memory\". Please be advised that this may seriously degrade the security of SoftHSM. ======================================================================" >&5 $as_echo "$as_me: WARNING: ====================================================================== SoftHSM has been configured to store sensitive data in non-page RAM (i.e. memory that is not swapped out to disk). This is the default and most secure configuration. Your system, however, is not configured to support this model in non-privileged accounts (i.e. user accounts). You can check the setting on your system by running the following command in a shell: ulimit -l If this does not return \"unlimited\" and you plan to run SoftHSM from non-privileged accounts then you should edit the configuration file /etc/security/limits.conf (on most systems). You will need to add the following lines to this file: # * - memlock unlimited Alternatively, you can elect to disable this feature of SoftHSM by re-running configure with the option \"--disable-non-paged-memory\". Please be advised that this may seriously degrade the security of SoftHSM. ======================================================================" >&2;} fi else { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5 $as_echo "disabled" >&6; } fi # If the user want to have the migration tool # Requires SQLite3 # Check whether --with-migrate was given. if test "${with_migrate+set}" = set; then : withval=$with_migrate; build_migrate="${withval}" else build_migrate="no" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if building with softhsm2-migrate" >&5 $as_echo_n "checking if building with softhsm2-migrate... " >&6; } if test "x${build_migrate}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } YIELD_LIB= # Solaris has sched_yield in librt, not in libpthread or libc. # Solaris 2.5.1, 2.6 has sched_yield in libposix4, not librt. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sched_yield in -lrt" >&5 $as_echo_n "checking for sched_yield in -lrt... " >&6; } if ${ac_cv_lib_rt_sched_yield+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lrt $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char sched_yield (); int main () { return sched_yield (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_rt_sched_yield=yes else ac_cv_lib_rt_sched_yield=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_sched_yield" >&5 $as_echo "$ac_cv_lib_rt_sched_yield" >&6; } if test "x$ac_cv_lib_rt_sched_yield" = xyes; then : YIELD_LIB=-lrt else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sched_yield in -lposix4" >&5 $as_echo_n "checking for sched_yield in -lposix4... " >&6; } if ${ac_cv_lib_posix4_sched_yield+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lposix4 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char sched_yield (); int main () { return sched_yield (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_posix4_sched_yield=yes else ac_cv_lib_posix4_sched_yield=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_posix4_sched_yield" >&5 $as_echo "$ac_cv_lib_posix4_sched_yield" >&6; } if test "x$ac_cv_lib_posix4_sched_yield" = xyes; then : YIELD_LIB=-lposix4 fi fi ac_fn_c_check_header_mongrel "$LINENO" "sched.h" "ac_cv_header_sched_h" "$ac_includes_default" if test "x$ac_cv_header_sched_h" = xyes; then : fi else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x${build_migrate}" = "xyes"; then BUILD_MIGRATE_TRUE= BUILD_MIGRATE_FALSE='#' else BUILD_MIGRATE_TRUE='#' BUILD_MIGRATE_FALSE= fi # If the user wants to have the database storage backend # Check whether --with-objectstore-backend-db was given. if test "${with_objectstore_backend_db+set}" = set; then : withval=$with_objectstore_backend_db; build_objectstore_backend_db="${withval}" else build_objectstore_backend_db="no" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if building database object store backend" >&5 $as_echo_n "checking if building database object store backend... " >&6; } if test "x${build_objectstore_backend_db}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } cat >>confdefs.h <<_ACEOF #define HAVE_OBJECTSTORE_BACKEND_DB 1 _ACEOF else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x${build_objectstore_backend_db}" = "xyes"; then BUILD_OBJECTSTORE_BACKEND_DB_TRUE= BUILD_OBJECTSTORE_BACKEND_DB_FALSE='#' else BUILD_OBJECTSTORE_BACKEND_DB_TRUE='#' BUILD_OBJECTSTORE_BACKEND_DB_FALSE= fi # Require SQLite3 if either building --with-migrate or --with-objectstore-backend-db { $as_echo "$as_me:${as_lineno-$LINENO}: checking if SQLite3 required" >&5 $as_echo_n "checking if SQLite3 required... " >&6; } if test "x${build_migrate}" = "xyes" -o "x${build_objectstore_backend_db}" = "xyes"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } # Check whether --with-sqlite3 was given. if test "${with_sqlite3+set}" = set; then : withval=$with_sqlite3; SQLITE3_PATH="$withval" for ac_prog in sqlite3 do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_SQLITE3+:} false; then : $as_echo_n "(cached) " >&6 else case $SQLITE3 in [\\/]* | ?:[\\/]*) ac_cv_path_SQLITE3="$SQLITE3" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $withval/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_SQLITE3="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi SQLITE3=$ac_cv_path_SQLITE3 if test -n "$SQLITE3"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SQLITE3" >&5 $as_echo "$SQLITE3" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$SQLITE3" && break done test -n "$SQLITE3" || SQLITE3="sqlite3" else SQLITE3_PATH="/usr/local" for ac_prog in sqlite3 do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_SQLITE3+:} false; then : $as_echo_n "(cached) " >&6 else case $SQLITE3 in [\\/]* | ?:[\\/]*) ac_cv_path_SQLITE3="$SQLITE3" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_SQLITE3="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi SQLITE3=$ac_cv_path_SQLITE3 if test -n "$SQLITE3"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SQLITE3" >&5 $as_echo "$SQLITE3" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$SQLITE3" && break done test -n "$SQLITE3" || SQLITE3="sqlite3" fi if ! test -x "$SQLITE3"; then as_fn_error $? "sqlite3 command not found" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the SQLite3 includes" >&5 $as_echo_n "checking what are the SQLite3 includes... " >&6; } SQLITE3_INCLUDES="-I$SQLITE3_PATH/include" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SQLITE3_INCLUDES" >&5 $as_echo "$SQLITE3_INCLUDES" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking what are the SQLite3 libs" >&5 $as_echo_n "checking what are the SQLite3 libs... " >&6; } SQLITE3_LIBS="-L$SQLITE3_PATH/lib -lsqlite3" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $SQLITE3_LIBS" >&5 $as_echo "$SQLITE3_LIBS" >&6; } tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $SQLITE3_INCLUDES" LIBS="$LIBS $SQLITE3_LIBS" for ac_header in sqlite3.h do : ac_fn_c_check_header_mongrel "$LINENO" "sqlite3.h" "ac_cv_header_sqlite3_h" "$ac_includes_default" if test "x$ac_cv_header_sqlite3_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_SQLITE3_H 1 _ACEOF else as_fn_error $? "Can't find SQLite3 headers" "$LINENO" 5 fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sqlite3_prepare_v2 in -lsqlite3" >&5 $as_echo_n "checking for sqlite3_prepare_v2 in -lsqlite3... " >&6; } if ${ac_cv_lib_sqlite3_sqlite3_prepare_v2+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsqlite3 $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char sqlite3_prepare_v2 (); int main () { return sqlite3_prepare_v2 (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_sqlite3_sqlite3_prepare_v2=yes else ac_cv_lib_sqlite3_sqlite3_prepare_v2=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sqlite3_sqlite3_prepare_v2" >&5 $as_echo "$ac_cv_lib_sqlite3_sqlite3_prepare_v2" >&6; } if test "x$ac_cv_lib_sqlite3_sqlite3_prepare_v2" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBSQLITE3 1 _ACEOF LIBS="-lsqlite3 $LIBS" else as_fn_error $? "Missing SQLite3 library v3.4.2 or greater" "$LINENO" 5 fi CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi # Set visibility flags so only PKCS#11 entry points are exported # Check whether --enable-visibility was given. if test "${enable_visibility+set}" = set; then : enableval=$enable_visibility; enable_visibility="${enableval}" else enable_visibility="yes" fi if test "${enable_visibility}" = "yes"; then CFLAGS="${CFLAGS} -fvisibility=hidden" CXXFLAGS="${CXXFLAGS} -fvisibility=hidden" $as_echo "#define CRYPTOKI_VISIBILITY 1" >>confdefs.h fi # Set full directory paths full_sysconfdir=`eval eval eval eval eval echo "${sysconfdir}" | sed "s#NONE#${prefix}#" | sed "s#NONE#${ac_default_prefix}#"` full_localstatedir=`eval eval eval eval eval echo "${localstatedir}" | sed "s#NONE#${prefix}#" | sed "s#NONE#${ac_default_prefix}#"` full_libdir=`eval eval eval eval eval echo "${libdir}" | sed "s#NONE#${prefix}#" | sed "s#NONE#${ac_default_prefix}#"` default_softhsm2_conf="`eval echo ${full_sysconfdir} | sed s,NONE,$ac_default_prefix,g`/softhsm2.conf" softhsmtokendir=${full_localstatedir}/lib/softhsm/tokens/ # Install the library in a sub-directory full_libdir="$full_libdir/softhsm" libdir=$full_libdir # For getConfigPath() for ac_func in getpwuid_r do : ac_fn_c_check_func "$LINENO" "getpwuid_r" "ac_cv_func_getpwuid_r" if test "x$ac_cv_func_getpwuid_r" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_GETPWUID_R 1 _ACEOF fi done # Define some variables for the code cat >>confdefs.h <<_ACEOF #define VERSION_MAJOR 2 _ACEOF cat >>confdefs.h <<_ACEOF #define VERSION_MINOR 0 _ACEOF cat >>confdefs.h <<_ACEOF #define MAX_PIN_LEN 255 _ACEOF cat >>confdefs.h <<_ACEOF #define MIN_PIN_LEN 4 _ACEOF cat >>confdefs.h <<_ACEOF #define DEFAULT_SOFTHSM2_CONF "$default_softhsm2_conf" _ACEOF cat >>confdefs.h <<_ACEOF #define DEFAULT_TOKENDIR "$softhsmtokendir" _ACEOF cat >>confdefs.h <<_ACEOF #define DEFAULT_OBJECTSTORE_BACKEND "file" _ACEOF cat >>confdefs.h <<_ACEOF #define DEFAULT_LOG_LEVEL "INFO" _ACEOF cat >>confdefs.h <<_ACEOF #define DEFAULT_PKCS11_LIB "$full_libdir/libsofthsm2.so" _ACEOF # Generate the libtool script and install script case `pwd` in *\ * | *\ *) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&5 $as_echo "$as_me: WARNING: Libtool does not cope well with whitespace in \`pwd\`" >&2;} ;; esac macro_version='2.4.2' macro_revision='1.3337' ltmain="$ac_aux_dir/ltmain.sh" # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac # Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\(["`$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to print strings" >&5 $as_echo_n "checking how to print strings... " >&6; } # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "" } case "$ECHO" in printf*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: printf" >&5 $as_echo "printf" >&6; } ;; print*) { $as_echo "$as_me:${as_lineno-$LINENO}: result: print -r" >&5 $as_echo "print -r" >&6; } ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: cat" >&5 $as_echo "cat" >&6; } ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed { ac_script=; unset ac_script;} if test -z "$SED"; then ac_path_SED_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_SED="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED case `"$ac_path_SED" --version 2>&1` in *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo '' >> "conftest.nl" "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_SED_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_SED="$ac_path_SED" ac_path_SED_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_SED_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_SED"; then as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 fi else ac_cv_path_SED=$SED fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 $as_echo "$ac_cv_path_SED" >&6; } SED="$ac_cv_path_SED" rm -f conftest.sed test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then ac_path_FGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in fgrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_FGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP case `"$ac_path_FGREP" --version 2>&1` in *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'FGREP' >> "conftest.nl" "$ac_path_FGREP" FGREP < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_FGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_FGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_FGREP"; then as_fn_error $? "no acceptable fgrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_FGREP=$FGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 $as_echo "$ac_cv_path_FGREP" >&6; } FGREP="$ac_cv_path_FGREP" test -z "$GREP" && GREP=grep # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5 $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if ${lt_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 $as_echo "$lt_cv_path_NM" >&6; } if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else if test -n "$ac_tool_prefix"; then for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DUMPBIN="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DUMPBIN" >&5 $as_echo "$DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$DUMPBIN" && break done fi if test -z "$DUMPBIN"; then ac_ct_DUMPBIN=$DUMPBIN for ac_prog in dumpbin "link -dump" do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DUMPBIN" >&5 $as_echo "$ac_ct_DUMPBIN" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_DUMPBIN" && break done if test "x$ac_ct_DUMPBIN" = x; then DUMPBIN=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DUMPBIN=$ac_ct_DUMPBIN fi fi case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5 $as_echo_n "checking the name lister ($NM) interface... " >&6; } if ${lt_cv_nm_interface+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&5) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&5 (eval echo "\"\$as_me:$LINENO: output\"" >&5) cat conftest.out >&5 if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 $as_echo "$lt_cv_nm_interface" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 $as_echo_n "checking whether ln -s works... " >&6; } LN_S=$as_ln_s if test "$LN_S" = "ln -s"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 $as_echo "no, using $LN_S" >&6; } fi # find the maximum length of command line arguments { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5 $as_echo_n "checking the maximum length of command line arguments... " >&6; } if ${lt_cv_sys_max_cmd_len+:} false; then : $as_echo_n "(cached) " >&6 else i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[ ]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac fi if test -n $lt_cv_sys_max_cmd_len ; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_max_cmd_len" >&5 $as_echo "$lt_cv_sys_max_cmd_len" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: none" >&5 $as_echo "none" >&6; } fi max_cmd_len=$lt_cv_sys_max_cmd_len : ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands some XSI constructs" >&5 $as_echo_n "checking whether the shell understands some XSI constructs... " >&6; } # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $xsi_shell" >&5 $as_echo "$xsi_shell" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the shell understands \"+=\"" >&5 $as_echo_n "checking whether the shell understands \"+=\"... " >&6; } lt_shell_append=no ( foo=bar; set foo baz; eval "$1+=\$2" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_shell_append" >&5 $as_echo "$lt_shell_append" >&6; } if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to $host format" >&5 $as_echo_n "checking how to convert $build file names to $host format... " >&6; } if ${lt_cv_to_host_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_host_file_cmd" >&5 $as_echo "$lt_cv_to_host_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to convert $build file names to toolchain format" >&5 $as_echo_n "checking how to convert $build file names to toolchain format... " >&6; } if ${lt_cv_to_tool_file_cmd+:} false; then : $as_echo_n "(cached) " >&6 else #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_to_tool_file_cmd" >&5 $as_echo "$lt_cv_to_tool_file_cmd" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5 $as_echo_n "checking for $LD option to reload object files... " >&6; } if ${lt_cv_ld_reload_flag+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_reload_flag='-r' fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 $as_echo "$lt_cv_ld_reload_flag" >&6; } reload_flag=$lt_cv_ld_reload_flag case $reload_flag in "" | " "*) ;; *) reload_flag=" $reload_flag" ;; esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in cygwin* | mingw* | pw32* | cegcc*) if test "$GCC" != yes; then reload_cmds=false fi ;; darwin*) if test "$GCC" = yes; then reload_cmds='$LTCC $LTCFLAGS -nostdlib ${wl}-r -o $output$reload_objs' else reload_cmds='$LD$reload_flag -o $output$reload_objs' fi ;; esac if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args. set dummy ${ac_tool_prefix}objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJDUMP="${ac_tool_prefix}objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJDUMP" >&5 $as_echo "$OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OBJDUMP"; then ac_ct_OBJDUMP=$OBJDUMP # Extract the first word of "objdump", so it can be a program name with args. set dummy objdump; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJDUMP="objdump" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJDUMP" >&5 $as_echo "$ac_ct_OBJDUMP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OBJDUMP" = x; then OBJDUMP="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJDUMP=$ac_ct_OBJDUMP fi else OBJDUMP="$ac_cv_prog_OBJDUMP" fi test -z "$OBJDUMP" && OBJDUMP=objdump { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5 $as_echo_n "checking how to recognize dependent libraries... " >&6; } if ${lt_cv_deplibs_check_method+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support # interlibrary dependencies. # 'none' -- dependencies not supported. # `unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. # 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # which responds to the $file_magic_cmd with a given extended regex. # If you have `file' or equivalent on your system and you're not sure # whether `pass_all' will *always* work, you probably want this one. case $host_os in aix[4-9]*) lt_cv_deplibs_check_method=pass_all ;; beos*) lt_cv_deplibs_check_method=pass_all ;; bsdi[45]*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib)' lt_cv_file_magic_cmd='/usr/bin/file -L' lt_cv_file_magic_test_file=/shlib/libc.so ;; cygwin*) # func_win32_libid is a shell function defined in ltmain.sh lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' ;; mingw* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. # func_win32_libid assumes BSD nm, so disallow it if using MS dumpbin. if ( test "$lt_cv_nm_interface" = "BSD nm" && file / ) >/dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[3-9]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF-[0-9][0-9]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]' lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|PA-RISC[0-9]\.[0-9]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[3-9]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [ML]SB (shared object|dynamic lib) M[0-9][0-9]* Version [0-9]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [0-9][0-9]*-bit [LM]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [0-9][0-9]*-bit [LM]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 $as_echo "$lt_cv_deplibs_check_method" >&6; } file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[\1]\/[\1]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dlltool", so it can be a program name with args. set dummy ${ac_tool_prefix}dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DLLTOOL="${ac_tool_prefix}dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DLLTOOL" >&5 $as_echo "$DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DLLTOOL"; then ac_ct_DLLTOOL=$DLLTOOL # Extract the first word of "dlltool", so it can be a program name with args. set dummy dlltool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DLLTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DLLTOOL="dlltool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DLLTOOL" >&5 $as_echo "$ac_ct_DLLTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DLLTOOL" = x; then DLLTOOL="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DLLTOOL=$ac_ct_DLLTOOL fi else DLLTOOL="$ac_cv_prog_DLLTOOL" fi test -z "$DLLTOOL" && DLLTOOL=dlltool { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to associate runtime and link libraries" >&5 $as_echo_n "checking how to associate runtime and link libraries... " >&6; } if ${lt_cv_sharedlib_from_linklib_cmd+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 $as_echo "$lt_cv_sharedlib_from_linklib_cmd" >&6; } sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO if test -n "$ac_tool_prefix"; then for ac_prog in ar do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_AR="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi AR=$ac_cv_prog_AR if test -n "$AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AR" >&5 $as_echo "$AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$AR" && break done fi if test -z "$AR"; then ac_ct_AR=$AR for ac_prog in ar do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_AR="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_AR" >&5 $as_echo "$ac_ct_AR" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_AR" && break done if test "x$ac_ct_AR" = x; then AR="false" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac AR=$ac_ct_AR fi fi : ${AR=ar} : ${AR_FLAGS=cru} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for archiver @FILE support" >&5 $as_echo_n "checking for archiver @FILE support... " >&6; } if ${lt_cv_ar_at_file+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&5' { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$lt_ar_try\""; } >&5 (eval $lt_ar_try) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 $as_echo "$lt_cv_ar_at_file" >&6; } if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args. set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_STRIP="${ac_tool_prefix}strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 $as_echo "$STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_STRIP"; then ac_ct_STRIP=$STRIP # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_STRIP="strip" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_STRIP" >&5 $as_echo "$ac_ct_STRIP" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_STRIP" = x; then STRIP=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac STRIP=$ac_ct_STRIP fi else STRIP="$ac_cv_prog_STRIP" fi test -z "$STRIP" && STRIP=: if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. set dummy ${ac_tool_prefix}ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RANLIB"; then ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi RANLIB=$ac_cv_prog_RANLIB if test -n "$RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 $as_echo "$RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_RANLIB"; then ac_ct_RANLIB=$RANLIB # Extract the first word of "ranlib", so it can be a program name with args. set dummy ranlib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_RANLIB"; then ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_RANLIB="ranlib" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB if test -n "$ac_ct_RANLIB"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 $as_echo "$ac_ct_RANLIB" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_RANLIB" = x; then RANLIB=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac RANLIB=$ac_ct_RANLIB fi else RANLIB="$ac_cv_prog_RANLIB" fi test -z "$RANLIB" && RANLIB=: # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Check for command to grab the raw symbol name followed by C symbol from nm. { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5 $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; } if ${lt_cv_sys_global_symbol_pipe+:} false; then : $as_echo_n "(cached) " >&6 else # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[BCDEGRST]' # Regexp to match symbols that can be accessed directly from C. sympat='\([_A-Za-z][_A-Za-z0-9]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[BCDT]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[ABCDEGRST]' fi ;; irix* | nonstopux*) symcode='[BCDEGRST]' ;; osf*) symcode='[BCDEGQRST]' ;; solaris*) symcode='[BDRT]' ;; sco3.2v5*) symcode='[DT]' ;; sysv4.2uw2*) symcode='[DT]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[ABDT]' ;; sysv4) symcode='[DFNSTU]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[ABCDGIRSTW]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([^ ]*\)[ ]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([^ ]*\) \(lib[^ ]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([^ ]*\) \([^ ]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK '"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[ ]\($symcode$symcode*\)[ ][ ]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Now try to grab the symbols. nlist=conftest.nm if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist\""; } >&5 (eval $NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$lt_prog_compiler_no_builtin_flag" if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&5 fi else echo "cannot find nm_test_var in $nlist" >&5 fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&5 fi else echo "$progname: failed program was:" >&5 cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done fi if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: failed" >&5 $as_echo "failed" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: ok" >&5 $as_echo "ok" >&6; } fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[@]FILE' >/dev/null; then nm_file_list_spec='@' fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for sysroot" >&5 $as_echo_n "checking for sysroot... " >&6; } # Check whether --with-sysroot was given. if test "${with_sysroot+set}" = set; then : withval=$with_sysroot; else with_sysroot=no fi lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${with_sysroot}" >&5 $as_echo "${with_sysroot}" >&6; } as_fn_error $? "The sysroot must be an absolute path." "$LINENO" 5 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${lt_sysroot:-no}" >&5 $as_echo "${lt_sysroot:-no}" >&6; } # Check whether --enable-libtool-lock was given. if test "${enable_libtool_lock+set}" = set; then : enableval=$enable_libtool_lock; fi test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '#line '$LINENO' "configure"' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) case `/usr/bin/file conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" ;; *) LD="${LD-ld} -m elf_i386" ;; esac ;; powerpc64le-*) LD="${LD-ld} -m elf32lppclinux" ;; powerpc64-*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*) LD="${LD-ld} -m elf64lppc" ;; powerpc-*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5 $as_echo_n "checking whether the C compiler needs -belf... " >&6; } if ${lt_cv_cc_needs_belf+:} false; then : $as_echo_n "(cached) " >&6 else ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_cc_needs_belf=yes else lt_cv_cc_needs_belf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 $as_echo "$lt_cv_cc_needs_belf" >&6; } if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}mt", so it can be a program name with args. set dummy ${ac_tool_prefix}mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_MANIFEST_TOOL="${ac_tool_prefix}mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MANIFEST_TOOL" >&5 $as_echo "$MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_MANIFEST_TOOL"; then ac_ct_MANIFEST_TOOL=$MANIFEST_TOOL # Extract the first word of "mt", so it can be a program name with args. set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_MANIFEST_TOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="mt" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_MANIFEST_TOOL" >&5 $as_echo "$ac_ct_MANIFEST_TOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_MANIFEST_TOOL" = x; then MANIFEST_TOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac MANIFEST_TOOL=$ac_ct_MANIFEST_TOOL fi else MANIFEST_TOOL="$ac_cv_prog_MANIFEST_TOOL" fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 $as_echo_n "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } if ${lt_cv_path_mainfest_tool+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 $as_echo "$lt_cv_path_mainfest_tool" >&6; } if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi case $host_os in rhapsody* | darwin*) if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args. set dummy ${ac_tool_prefix}dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_DSYMUTIL="${ac_tool_prefix}dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DSYMUTIL" >&5 $as_echo "$DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_DSYMUTIL"; then ac_ct_DSYMUTIL=$DSYMUTIL # Extract the first word of "dsymutil", so it can be a program name with args. set dummy dsymutil; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_DSYMUTIL="dsymutil" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_DSYMUTIL" >&5 $as_echo "$ac_ct_DSYMUTIL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_DSYMUTIL" = x; then DSYMUTIL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac DSYMUTIL=$ac_ct_DSYMUTIL fi else DSYMUTIL="$ac_cv_prog_DSYMUTIL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args. set dummy ${ac_tool_prefix}nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_NMEDIT="${ac_tool_prefix}nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $NMEDIT" >&5 $as_echo "$NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_NMEDIT"; then ac_ct_NMEDIT=$NMEDIT # Extract the first word of "nmedit", so it can be a program name with args. set dummy nmedit; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_NMEDIT="nmedit" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_NMEDIT" >&5 $as_echo "$ac_ct_NMEDIT" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_NMEDIT" = x; then NMEDIT=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac NMEDIT=$ac_ct_NMEDIT fi else NMEDIT="$ac_cv_prog_NMEDIT" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args. set dummy ${ac_tool_prefix}lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_LIPO="${ac_tool_prefix}lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LIPO" >&5 $as_echo "$LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_LIPO"; then ac_ct_LIPO=$LIPO # Extract the first word of "lipo", so it can be a program name with args. set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_LIPO="lipo" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_LIPO" >&5 $as_echo "$ac_ct_LIPO" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_LIPO" = x; then LIPO=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac LIPO=$ac_ct_LIPO fi else LIPO="$ac_cv_prog_LIPO" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args. set dummy ${ac_tool_prefix}otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL="${ac_tool_prefix}otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL" >&5 $as_echo "$OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL"; then ac_ct_OTOOL=$OTOOL # Extract the first word of "otool", so it can be a program name with args. set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL="otool" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL" >&5 $as_echo "$ac_ct_OTOOL" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL" = x; then OTOOL=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL=$ac_ct_OTOOL fi else OTOOL="$ac_cv_prog_OTOOL" fi if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args. set dummy ${ac_tool_prefix}otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OTOOL64="${ac_tool_prefix}otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OTOOL64" >&5 $as_echo "$OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_OTOOL64"; then ac_ct_OTOOL64=$OTOOL64 # Extract the first word of "otool64", so it can be a program name with args. set dummy otool64; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OTOOL64="otool64" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OTOOL64" >&5 $as_echo "$ac_ct_OTOOL64" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_OTOOL64" = x; then OTOOL64=":" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OTOOL64=$ac_ct_OTOOL64 fi else OTOOL64="$ac_cv_prog_OTOOL64" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5 $as_echo_n "checking for -single_module linker flag... " >&6; } if ${lt_cv_apple_cc_single_mod+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&5 $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&5 # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&5 fi rm -rf libconftest.dylib* rm -f conftest.* fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 $as_echo "$lt_cv_apple_cc_single_mod" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; } if ${lt_cv_ld_exported_symbols_list+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_ld_exported_symbols_list=yes else lt_cv_ld_exported_symbols_list=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 $as_echo "$lt_cv_ld_exported_symbols_list" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -force_load linker flag" >&5 $as_echo_n "checking for -force_load linker flag... " >&6; } if ${lt_cv_ld_force_load+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&5 $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&5 echo "$AR cru libconftest.a conftest.o" >&5 $AR cru libconftest.a conftest.o 2>&5 echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&5 elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&5 fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 $as_echo "$lt_cv_ld_force_load" >&6; } case $host_os in rhapsody* | darwin1.[012]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[91]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[012]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac for ac_header in dlfcn.h do : ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default " if test "x$ac_cv_header_dlfcn_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DLFCN_H 1 _ACEOF fi done func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf # Set options enable_dlopen=no enable_win32_dll=no # Check whether --enable-shared was given. if test "${enable_shared+set}" = set; then : enableval=$enable_shared; p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac else enable_shared=yes fi # Check whether --enable-static was given. if test "${enable_static+set}" = set; then : enableval=$enable_static; p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac else enable_static=yes fi # Check whether --with-pic was given. if test "${with_pic+set}" = set; then : withval=$with_pic; lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac else pic_mode=default fi test -z "$pic_mode" && pic_mode=default # Check whether --enable-fast-install was given. if test "${enable_fast_install+set}" = set; then : enableval=$enable_fast_install; p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac else enable_fast_install=yes fi # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' test -z "$LN_S" && LN_S="ln -s" if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5 $as_echo_n "checking for objdir... " >&6; } if ${lt_cv_objdir+:} false; then : $as_echo_n "(cached) " >&6 else rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 $as_echo "$lt_cv_objdir" >&6; } objdir=$lt_cv_objdir cat >>confdefs.h <<_ACEOF #define LT_OBJDIR "$lt_cv_objdir/" _ACEOF case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5 $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/${ac_tool_prefix}file; then lt_cv_path_MAGIC_CMD="$ac_dir/${ac_tool_prefix}file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5 $as_echo_n "checking for file... " >&6; } if ${lt_cv_path_MAGIC_CMD+:} false; then : $as_echo_n "(cached) " >&6 else case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR ac_dummy="/usr/bin$PATH_SEPARATOR$PATH" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/file; then lt_cv_path_MAGIC_CMD="$ac_dir/file" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac fi MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $MAGIC_CMD" >&5 $as_echo "$MAGIC_CMD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi else MAGIC_CMD=: fi fi fi ;; esac # Use C for the default configuration in the libtool script lt_save_CC="$CC" ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o objext=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then lt_prog_compiler_no_builtin_flag= if test "$GCC" = yes; then case $cc_basename in nvcc*) lt_prog_compiler_no_builtin_flag=' -Xcompiler -fno-builtin' ;; *) lt_prog_compiler_no_builtin_flag=' -fno-builtin' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5 $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_rtti_exceptions=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 $as_echo "$lt_cv_prog_compiler_rtti_exceptions" >&6; } if test x"$lt_cv_prog_compiler_rtti_exceptions" = xyes; then lt_prog_compiler_no_builtin_flag="$lt_prog_compiler_no_builtin_flag -fno-rtti -fno-exceptions" else : fi fi lt_prog_compiler_wl= lt_prog_compiler_pic= lt_prog_compiler_static= if test "$GCC" = yes; then lt_prog_compiler_wl='-Wl,' lt_prog_compiler_static='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) lt_prog_compiler_pic='-fPIC' ;; esac ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. lt_prog_compiler_can_build_shared=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic=-Kconform_pic fi ;; *) lt_prog_compiler_pic='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 lt_prog_compiler_wl='-Xlinker ' if test -n "$lt_prog_compiler_pic"; then lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) lt_prog_compiler_wl='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static='-Bstatic' else lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' ;; hpux9* | hpux10* | hpux11*) lt_prog_compiler_wl='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? lt_prog_compiler_static='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) lt_prog_compiler_wl='-Wl,' # PIC (with -KPIC) is the default. lt_prog_compiler_static='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; # Lahey Fortran 8.1. lf95*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='--shared' lt_prog_compiler_static='--static' ;; nagfor*) # NAG Fortran compiler lt_prog_compiler_wl='-Wl,-Wl,,' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; ccc*) lt_prog_compiler_wl='-Wl,' # All Alpha code is PIC. lt_prog_compiler_static='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-qpic' lt_prog_compiler_static='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='' ;; *Sun\ F* | *Sun*Fortran*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' lt_prog_compiler_wl='-Wl,' ;; *Intel*\ [CF]*Compiler*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fPIC' lt_prog_compiler_static='-static' ;; *Portland\ Group*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-fpic' lt_prog_compiler_static='-Bstatic' ;; esac ;; esac ;; newsos6) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic='-fPIC -shared' ;; osf3* | osf4* | osf5*) lt_prog_compiler_wl='-Wl,' # All OSF/1 code is PIC. lt_prog_compiler_static='-non_shared' ;; rdos*) lt_prog_compiler_static='-non_shared' ;; solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) lt_prog_compiler_wl='-Qoption ld ';; *) lt_prog_compiler_wl='-Wl,';; esac ;; sunos4*) lt_prog_compiler_wl='-Qoption ld ' lt_prog_compiler_pic='-PIC' lt_prog_compiler_static='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then lt_prog_compiler_pic='-Kconform_pic' lt_prog_compiler_static='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' ;; unicos*) lt_prog_compiler_wl='-Wl,' lt_prog_compiler_can_build_shared=no ;; uts4*) lt_prog_compiler_pic='-pic' lt_prog_compiler_static='-Bstatic' ;; *) lt_prog_compiler_can_build_shared=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic= ;; *) lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic=$lt_prog_compiler_pic fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 $as_echo "$lt_cv_prog_compiler_pic" >&6; } lt_prog_compiler_pic=$lt_cv_prog_compiler_pic # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } if ${lt_cv_prog_compiler_pic_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 $as_echo "$lt_cv_prog_compiler_pic_works" >&6; } if test x"$lt_cv_prog_compiler_pic_works" = xyes; then case $lt_prog_compiler_pic in "" | " "*) ;; *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; esac else lt_prog_compiler_pic= lt_prog_compiler_can_build_shared=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works=yes fi else lt_cv_prog_compiler_static_works=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 $as_echo "$lt_cv_prog_compiler_static_works" >&6; } if test x"$lt_cv_prog_compiler_static_works" = xyes; then : else lt_prog_compiler_static= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 $as_echo "$lt_cv_prog_compiler_c_o" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } runpath_var= allow_undefined_flag= always_export_symbols=no archive_cmds= archive_expsym_cmds= compiler_needs_object=no enable_shared_with_static_runtimes=no export_dynamic_flag_spec= export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' hardcode_automatic=no hardcode_direct=no hardcode_direct_absolute=no hardcode_libdir_flag_spec= hardcode_libdir_separator= hardcode_minus_L=no hardcode_shlibpath_var=unsupported inherit_rpath=no link_all_deplibs=unknown module_cmds= module_expsym_cmds= old_archive_from_new_cmds= old_archive_from_expsyms_cmds= thread_safe_flag_spec= whole_archive_flag_spec= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list include_expsyms= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. exclude_expsyms='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; linux* | k*bsd*-gnu | gnu*) link_all_deplibs=no ;; esac ld_shlibs=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[2-9]*) ;; *\ \(GNU\ Binutils\)\ [3-9]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [01].* | *\ 2.[0-9].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[3-9]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' export_dynamic_flag_spec='${wl}--export-all-symbols' allow_undefined_flag=unsupported always_export_symbols=no enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs=no fi ;; haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs=yes ;; interix[3-9]*) hardcode_direct=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 whole_archive_flag_spec= tmp_sharedflag='--shared' ;; xl[cC]* | bgxl[cC]* | mpixl[cC]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 whole_archive_flag_spec='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 whole_archive_flag_spec='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac archive_cmds='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself whole_archive_flag_spec='--whole-archive$convenience --no-whole-archive' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else ld_shlibs=no fi ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) ld_shlibs=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac ;; sunos4*) archive_cmds='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= hardcode_direct=yes hardcode_shlibpath_var=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else ld_shlibs=no fi ;; esac if test "$ld_shlibs" = no; then runpath_var= hardcode_libdir_flag_spec= export_dynamic_flag_spec= whole_archive_flag_spec= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) allow_undefined_flag=unsupported always_export_symbols=yes archive_expsym_cmds='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. hardcode_minus_L=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. hardcode_direct=unsupported fi ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds='' hardcode_direct=yes hardcode_direct_absolute=yes hardcode_libdir_separator=':' link_all_deplibs=yes file_list_spec='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L=yes hardcode_libdir_flag_spec='-L$libdir' hardcode_libdir_separator= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi link_all_deplibs=no else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. always_export_symbols=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag='-berok' # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag="-z nodefs" archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath_+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath_=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath_ fi hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag=' ${wl}-bernotok' allow_undefined_flag=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec='$convenience' fi archive_cmds_need_lc=yes # This is similar to how AIX traditionally builds its shared libraries. archive_expsym_cmds="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds='' ;; m68k) archive_cmds='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes ;; esac ;; bsdi[45]*) export_dynamic_flag_spec=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported always_export_symbols=yes file_list_spec='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' enable_shared_with_static_runtimes=yes exclude_expsyms='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1,DATA/'\'' | $SED -e '\''/^[AITW][ ]/s/.*[ ]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib old_postinstall_cmds='chmod 644 $oldlib' postlink_cmds='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper hardcode_libdir_flag_spec=' ' allow_undefined_flag=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. old_archive_from_new_cmds='true' # FIXME: Should let the user specify the lib program. old_archive_cmds='lib -OUT:$oldlib$oldobjs$old_deplibs' enable_shared_with_static_runtimes=yes ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc=no hardcode_direct=no hardcode_automatic=yes hardcode_shlibpath_var=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec='' fi link_all_deplibs=yes allow_undefined_flag="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" else ld_shlibs=no fi ;; dgux*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; hpux9*) if test "$GCC" = yes; then archive_cmds='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else archive_cmds='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes export_dynamic_flag_spec='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) archive_cmds='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $CC understands -b" >&5 $as_echo_n "checking if $CC understands -b... " >&6; } if ${lt_cv_prog_compiler__b+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler__b=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler__b=yes fi else lt_cv_prog_compiler__b=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 $as_echo "$lt_cv_prog_compiler__b" >&6; } if test x"$lt_cv_prog_compiler__b" = xyes; then archive_cmds='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi ;; esac fi if test "$with_gnu_ld" = no; then hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' hardcode_libdir_separator=: case $host_cpu in hppa*64*|ia64*) hardcode_direct=no hardcode_shlibpath_var=no ;; *) hardcode_direct=yes hardcode_direct_absolute=yes export_dynamic_flag_spec='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. hardcode_minus_L=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $host_os linker accepts -exported_symbol" >&5 $as_echo_n "checking whether the $host_os linker accepts -exported_symbol... " >&6; } if ${lt_cv_irix_exported_symbol+:} false; then : $as_echo_n "(cached) " >&6 else save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int foo (void) { return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : lt_cv_irix_exported_symbol=yes else lt_cv_irix_exported_symbol=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 $as_echo "$lt_cv_irix_exported_symbol" >&6; } if test "$lt_cv_irix_exported_symbol" = yes; then archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: inherit_rpath=yes link_all_deplibs=yes ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else archive_cmds='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi hardcode_libdir_flag_spec='-R$libdir' hardcode_direct=yes hardcode_shlibpath_var=no ;; newsos6) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: hardcode_shlibpath_var=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no hardcode_direct_absolute=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' export_dynamic_flag_spec='${wl}-E' else case $host_os in openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-R$libdir' ;; *) archive_cmds='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' hardcode_libdir_flag_spec='${wl}-rpath,$libdir' ;; esac fi else ld_shlibs=no fi ;; os2*) hardcode_libdir_flag_spec='-L$libdir' hardcode_minus_L=yes allow_undefined_flag=unsupported archive_cmds='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' old_archive_from_new_cmds='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi archive_cmds_need_lc='no' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then allow_undefined_flag=' ${wl}-expect_unresolved ${wl}\*' archive_cmds='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' else allow_undefined_flag=' -expect_unresolved \*' archive_cmds='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly hardcode_libdir_flag_spec='-rpath $libdir' fi archive_cmds_need_lc='no' hardcode_libdir_separator=: ;; solaris*) no_undefined_flag=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' archive_cmds='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' archive_cmds='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' archive_cmds='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi hardcode_libdir_flag_spec='-R$libdir' hardcode_shlibpath_var=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then whole_archive_flag_spec='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else whole_archive_flag_spec='-z allextract$convenience -z defaultextract' fi ;; esac link_all_deplibs=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. archive_cmds='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi hardcode_libdir_flag_spec='-L$libdir' hardcode_direct=yes hardcode_minus_L=yes hardcode_shlibpath_var=no ;; sysv4) case $host_vendor in sni) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. archive_cmds='$LD -G -o $lib $libobjs $deplibs $linker_flags' reload_cmds='$CC -r -o $output$reload_objs' hardcode_direct=no ;; motorola) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_direct=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' hardcode_shlibpath_var=no ;; sysv4.3*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no export_dynamic_flag_spec='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_shlibpath_var=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes ld_shlibs=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag='${wl}-z,text' archive_cmds_need_lc=no hardcode_shlibpath_var=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag='${wl}-z,text' allow_undefined_flag='${wl}-z,nodefs' archive_cmds_need_lc=no hardcode_shlibpath_var=no hardcode_libdir_flag_spec='${wl}-R,$libdir' hardcode_libdir_separator=':' link_all_deplibs=yes export_dynamic_flag_spec='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then archive_cmds='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else archive_cmds='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) archive_cmds='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' hardcode_libdir_flag_spec='-L$libdir' hardcode_shlibpath_var=no ;; *) ld_shlibs=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) export_dynamic_flag_spec='${wl}-Blargedynsym' ;; esac fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs" >&5 $as_echo "$ld_shlibs" >&6; } test "$ld_shlibs" = no && can_build_shared=no with_gnu_ld=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc" in x|xyes) # Assume -lc should be added archive_cmds_need_lc=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl pic_flag=$lt_prog_compiler_pic compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag allow_undefined_flag= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc=no else lt_cv_archive_cmds_need_lc=yes fi allow_undefined_flag=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 $as_echo "$lt_cv_archive_cmds_need_lc" >&6; } archive_cmds_need_lc=$lt_cv_archive_cmds_need_lc ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([A-Za-z]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[lt_foo]++; } if (lt_freq[lt_foo] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([A-Za-z]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib" sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action= if test -n "$hardcode_libdir_flag_spec" || test -n "$runpath_var" || test "X$hardcode_automatic" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, )" != no && test "$hardcode_minus_L" != no; then # Linking always hardcodes the temporary library directory. hardcode_action=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action" >&5 $as_echo "$hardcode_action" >&6; } if test "$hardcode_action" = relink || test "$inherit_rpath" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes fi ;; *) ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load" if test "x$ac_cv_func_shl_load" = xyes; then : lt_cv_dlopen="shl_load" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 $as_echo_n "checking for shl_load in -ldld... " >&6; } if ${ac_cv_lib_dld_shl_load+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char shl_load (); int main () { return shl_load (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_shl_load=yes else ac_cv_lib_dld_shl_load=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 $as_echo "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes; then : lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld" else ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes; then : lt_cv_dlopen="dlopen" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dl_dlopen=yes else ac_cv_lib_dl_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 $as_echo_n "checking for dlopen in -lsvld... " >&6; } if ${ac_cv_lib_svld_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dlopen (); int main () { return dlopen (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_svld_dlopen=yes else ac_cv_lib_svld_dlopen=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 $as_echo "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes; then : lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld" else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 $as_echo_n "checking for dld_link in -ldld... " >&6; } if ${ac_cv_lib_dld_dld_link+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dld_link (); int main () { return dld_link (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dld_dld_link=yes else ac_cv_lib_dld_dld_link=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 $as_echo "$ac_cv_lib_dld_dld_link" >&6; } if test "x$ac_cv_lib_dld_dld_link" = xyes; then : lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld" fi fi fi fi fi fi ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5 $as_echo_n "checking whether a program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self=no ;; esac else : # compilation failed lt_cv_dlopen_self=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 $as_echo "$lt_cv_dlopen_self" >&6; } if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5 $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; } if ${lt_cv_dlopen_self_static+:} false; then : $as_echo_n "(cached) " >&6 else if test "$cross_compiling" = yes; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF #line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; } _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_link\""; } >&5 (eval $ac_link) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&5 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlneed_uscore) lt_cv_dlopen_self_static=yes ;; x$lt_dlunknown|x*) lt_cv_dlopen_self_static=no ;; esac else : # compilation failed lt_cv_dlopen_self_static=no fi fi rm -fr conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 $as_echo "$lt_cv_dlopen_self_static" >&6; } fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi striplib= old_striplib= { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stripping libraries is possible" >&5 $as_echo_n "checking whether stripping libraries is possible... " >&6; } if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi ;; *) { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } ;; esac fi # Report which library types will actually be built { $as_echo "$as_me:${as_lineno-$LINENO}: checking if libtool supports shared libraries" >&5 $as_echo_n "checking if libtool supports shared libraries... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $can_build_shared" >&5 $as_echo "$can_build_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build shared libraries" >&5 $as_echo_n "checking whether to build shared libraries... " >&6; } test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[4-9]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_shared" >&5 $as_echo "$enable_shared" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to build static libraries" >&5 $as_echo_n "checking whether to build static libraries... " >&6; } # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes { $as_echo "$as_me:${as_lineno-$LINENO}: result: $enable_static" >&5 $as_echo "$enable_static" >&6; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu CC="$lt_save_CC" if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 $as_echo_n "checking how to run the C++ preprocessor... " >&6; } if test -z "$CXXCPP"; then if ${ac_cv_prog_CXXCPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CXXCPP needs to be expanded for CXXCPP in "$CXX -E" "/lib/cpp" do ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CXXCPP=$CXXCPP fi CXXCPP=$ac_cv_prog_CXXCPP else ac_cv_prog_CXXCPP=$CXXCPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CXXCPP" >&5 $as_echo "$CXXCPP" >&6; } ac_preproc_ok=false for ac_cxx_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_cxx_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu else _lt_caught_CXX_error=yes fi ac_ext=cpp ac_cpp='$CXXCPP $CPPFLAGS' ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_cxx_compiler_gnu archive_cmds_need_lc_CXX=no allow_undefined_flag_CXX= always_export_symbols_CXX=no archive_expsym_cmds_CXX= compiler_needs_object_CXX=no export_dynamic_flag_spec_CXX= hardcode_direct_CXX=no hardcode_direct_absolute_CXX=no hardcode_libdir_flag_spec_CXX= hardcode_libdir_separator_CXX= hardcode_minus_L_CXX=no hardcode_shlibpath_var_CXX=unsupported hardcode_automatic_CXX=no inherit_rpath_CXX=no module_cmds_CXX= module_expsym_cmds_CXX= link_all_deplibs_CXX=unknown old_archive_cmds_CXX=$old_archive_cmds reload_flag_CXX=$reload_flag reload_cmds_CXX=$reload_cmds no_undefined_flag_CXX= whole_archive_flag_spec_CXX= enable_shared_with_static_runtimes_CXX=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o objext_CXX=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC # save warnings/boilerplate of simple test code ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC compiler_CXX=$CC for cc_temp in $compiler""; do case $cc_temp in compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then lt_prog_compiler_no_builtin_flag_CXX=' -fno-builtin' else lt_prog_compiler_no_builtin_flag_CXX= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration # Check whether --with-gnu-ld was given. if test "${with_gnu_ld+set}" = set; then : withval=$with_gnu_ld; test "$withval" = no || with_gnu_ld=yes else with_gnu_ld=no fi ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 $as_echo_n "checking for ld used by $CC... " >&6; } case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [\\/]* | ?:[\\/]*) re_direlt='/[^/][^/]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5 $as_echo_n "checking for GNU ld... " >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5 $as_echo_n "checking for non-GNU ld... " >&6; } fi if ${lt_cv_path_LD+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &5 $as_echo "$LD" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5 $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; } if ${lt_cv_prog_gnu_ld+:} false; then : $as_echo_n "(cached) " >&6 else # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 &5 $as_echo "$lt_cv_prog_gnu_ld" >&6; } with_gnu_ld=$lt_cv_prog_gnu_ld # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then archive_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else whole_archive_flag_spec_CXX= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } ld_shlibs_CXX=yes case $host_os in aix3*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aix[4-9]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[23]|aix4.[23].*|aix[5-9]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. archive_cmds_CXX='' hardcode_direct_CXX=yes hardcode_direct_absolute_CXX=yes hardcode_libdir_separator_CXX=':' link_all_deplibs_CXX=yes file_list_spec_CXX='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[012]|aix4.[012].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 hardcode_direct_CXX=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking hardcode_minus_L_CXX=yes hardcode_libdir_flag_spec_CXX='-L$libdir' hardcode_libdir_separator_CXX= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi export_dynamic_flag_spec_CXX='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. always_export_symbols_CXX=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. allow_undefined_flag_CXX='-berok' # Determine the default libpath from the value encoded in an empty # executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath__CXX+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath__CXX fi hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" archive_expsym_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then hardcode_libdir_flag_spec_CXX='${wl}-R $libdir:/usr/lib:/lib' allow_undefined_flag_CXX="-z nodefs" archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else if ${lt_cv_aix_libpath__CXX+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : lt_aix_libpath_sed=' /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }' lt_cv_aix_libpath__CXX=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX="/usr/lib:/lib" fi fi aix_libpath=$lt_cv_aix_libpath__CXX fi hardcode_libdir_flag_spec_CXX='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. no_undefined_flag_CXX=' ${wl}-bernotok' allow_undefined_flag_CXX=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives whole_archive_flag_spec_CXX='$convenience' fi archive_cmds_need_lc_CXX=yes # This is similar to how AIX traditionally builds its shared # libraries. archive_expsym_cmds_CXX="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then allow_undefined_flag_CXX=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME archive_cmds_CXX='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else ld_shlibs_CXX=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. hardcode_libdir_flag_spec_CXX=' ' allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=yes file_list_spec_CXX='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. archive_cmds_CXX='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, CXX)='true' enable_shared_with_static_runtimes_CXX=yes # Don't use ranlib old_postinstall_cmds_CXX='chmod 644 $oldlib' postlink_cmds_CXX='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, CXX) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec_CXX='-L$libdir' export_dynamic_flag_spec_CXX='${wl}--export-all-symbols' allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=no enable_shared_with_static_runtimes_CXX=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... archive_expsym_cmds_CXX='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else ld_shlibs_CXX=no fi ;; esac ;; darwin* | rhapsody*) archive_cmds_need_lc_CXX=no hardcode_direct_CXX=no hardcode_automatic_CXX=yes hardcode_shlibpath_var_CXX=unsupported if test "$lt_cv_ld_force_load" = "yes"; then whole_archive_flag_spec_CXX='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' else whole_archive_flag_spec_CXX='' fi link_all_deplibs_CXX=yes allow_undefined_flag_CXX="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all archive_cmds_CXX="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" module_cmds_CXX="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" module_expsym_cmds_CXX="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" if test "$lt_cv_apple_cc_single_mod" != "yes"; then archive_cmds_CXX="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" archive_expsym_cmds_CXX="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi else ld_shlibs_CXX=no fi ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF ld_shlibs_CXX=no ;; freebsd-elf*) archive_cmds_need_lc_CXX=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions ld_shlibs_CXX=yes ;; haiku*) archive_cmds_CXX='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' link_all_deplibs_CXX=yes ;; hpux9*) hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' hardcode_libdir_separator_CXX=: export_dynamic_flag_spec_CXX='${wl}-E' hardcode_direct_CXX=yes hardcode_minus_L_CXX=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aCC*) archive_cmds_CXX='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then archive_cmds_CXX='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then hardcode_libdir_flag_spec_CXX='${wl}+b ${wl}$libdir' hardcode_libdir_separator_CXX=: case $host_cpu in hppa*64*|ia64*) ;; *) export_dynamic_flag_spec_CXX='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) hardcode_direct_CXX=no hardcode_shlibpath_var_CXX=no ;; *) hardcode_direct_CXX=yes hardcode_direct_absolute_CXX=yes hardcode_minus_L_CXX=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; aCC*) case $host_cpu in hppa*64*) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) archive_cmds_CXX='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) archive_cmds_CXX='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) archive_cmds_CXX='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; interix[3-9]*) hardcode_direct_CXX=no hardcode_shlibpath_var_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. archive_cmds_CXX='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' archive_expsym_cmds_CXX='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ archive_cmds_CXX='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi link_all_deplibs_CXX=yes ;; esac hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator_CXX=: inherit_rpath_CXX=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' archive_expsym_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac archive_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac archive_cmds_need_lc_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' whole_archive_flag_spec_CXX='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [1-5].* | *pgcpp\ [1-5].*) prelink_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' old_archive_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' archive_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' archive_expsym_cmds_CXX='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac hardcode_libdir_flag_spec_CXX='${wl}--rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' whole_archive_flag_spec_CXX='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' archive_expsym_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH hardcode_libdir_flag_spec_CXX='-rpath $libdir' hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' export_dynamic_flag_spec_CXX='${wl}--export-dynamic' archive_cmds_CXX='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then archive_expsym_cmds_CXX='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 no_undefined_flag_CXX=' -zdefs' archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' archive_expsym_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' hardcode_libdir_flag_spec_CXX='-R$libdir' whole_archive_flag_spec_CXX='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' compiler_needs_object_CXX=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; m88k*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= hardcode_libdir_flag_spec_CXX='-R$libdir' hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) ld_shlibs_CXX=yes ;; openbsd2*) # C++ shared libraries are fairly broken ld_shlibs_CXX=no ;; openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no hardcode_direct_absolute_CXX=yes archive_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then archive_expsym_cmds_CXX='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' export_dynamic_flag_spec_CXX='${wl}-E' whole_archive_flag_spec_CXX="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else ld_shlibs_CXX=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. archive_cmds_CXX='tempext=`echo $shared_ext | $SED -e '\''s/\([^()0-9A-Za-z{}]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath,$libdir' hardcode_libdir_separator_CXX=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) old_archive_cmds_CXX='$CC -Bstatic -o $oldlib $oldobjs' ;; *) old_archive_cmds_CXX='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; cxx*) case $host in osf3*) allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' ;; *) allow_undefined_flag_CXX=' -expect_unresolved \*' archive_cmds_CXX='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' archive_expsym_cmds_CXX='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' hardcode_libdir_flag_spec_CXX='-rpath $libdir' ;; esac hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then allow_undefined_flag_CXX=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) archive_cmds_CXX='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) archive_cmds_CXX='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac hardcode_libdir_flag_spec_CXX='${wl}-rpath ${wl}$libdir' hardcode_libdir_separator_CXX=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support ld_shlibs_CXX=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ archive_cmds_need_lc_CXX=yes no_undefined_flag_CXX=' -zdefs' archive_cmds_CXX='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' hardcode_libdir_flag_spec_CXX='-R$libdir' hardcode_shlibpath_var_CXX=no case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) whole_archive_flag_spec_CXX='-z allextract$convenience -z defaultextract' ;; esac link_all_deplibs_CXX=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. old_archive_cmds_CXX='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler archive_cmds_CXX='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. old_archive_cmds_CXX='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then no_undefined_flag_CXX=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then archive_cmds_CXX='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. archive_cmds_CXX='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' archive_expsym_cmds_CXX='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi hardcode_libdir_flag_spec_CXX='${wl}-R $wl$libdir' case $host_os in solaris2.[0-5] | solaris2.[0-5].*) ;; *) whole_archive_flag_spec_CXX='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7* | sco3.2v5.0.[024]*) no_undefined_flag_CXX='${wl}-z,text' archive_cmds_need_lc_CXX=no hardcode_shlibpath_var_CXX=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. no_undefined_flag_CXX='${wl}-z,text' allow_undefined_flag_CXX='${wl}-z,nodefs' archive_cmds_need_lc_CXX=no hardcode_shlibpath_var_CXX=no hardcode_libdir_flag_spec_CXX='${wl}-R,$libdir' hardcode_libdir_separator_CXX=':' link_all_deplibs_CXX=yes export_dynamic_flag_spec_CXX='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) archive_cmds_CXX='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' old_archive_cmds_CXX='$CC -Tprelink_objects $oldobjs~ '"$old_archive_cmds_CXX" reload_cmds_CXX='$CC -Tprelink_objects $reload_objs~ '"$reload_cmds_CXX" ;; *) archive_cmds_CXX='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' archive_expsym_cmds_CXX='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; *) # FIXME: insert proper C++ library support ld_shlibs_CXX=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 $as_echo "$ld_shlibs_CXX" >&6; } test "$ld_shlibs_CXX" = no && can_build_shared=no GCC_CXX="$GXX" LD_CXX="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... # Dependencies to place before and after the object being linked: predep_objects_CXX= postdep_objects_CXX= predeps_CXX= postdeps_CXX= compiler_lib_search_path_CXX= cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$compiler_lib_search_path_CXX"; then compiler_lib_search_path_CXX="${prev}${p}" else compiler_lib_search_path_CXX="${compiler_lib_search_path_CXX} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$postdeps_CXX"; then postdeps_CXX="${prev}${p}" else postdeps_CXX="${postdeps_CXX} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$predep_objects_CXX"; then predep_objects_CXX="$p" else predep_objects_CXX="$predep_objects_CXX $p" fi else if test -z "$postdep_objects_CXX"; then postdep_objects_CXX="$p" else postdep_objects_CXX="$postdep_objects_CXX $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling CXX test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken case $host_os in interix[3-9]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. predep_objects_CXX= postdep_objects_CXX= postdeps_CXX= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then postdeps_CXX='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then postdeps_CXX='-library=Cstd -library=Crun' fi ;; esac ;; esac case " $postdeps_CXX " in *" -lc "*) archive_cmds_need_lc_CXX=no ;; esac compiler_lib_search_dirs_CXX= if test -n "${compiler_lib_search_path_CXX}"; then compiler_lib_search_dirs_CXX=`echo " ${compiler_lib_search_path_CXX}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi lt_prog_compiler_wl_CXX= lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX= # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static_CXX='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support lt_prog_compiler_pic_CXX='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries lt_prog_compiler_pic_CXX='-DDLL_EXPORT' ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files lt_prog_compiler_pic_CXX='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all lt_prog_compiler_pic_CXX= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. lt_prog_compiler_static_CXX= ;; interix[3-9]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then lt_prog_compiler_pic_CXX=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) lt_prog_compiler_pic_CXX='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic_CXX='-fPIC -shared' ;; *) lt_prog_compiler_pic_CXX='-fPIC' ;; esac else case $host_os in aix[4-9]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor lt_prog_compiler_static_CXX='-Bstatic' else lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic_CXX='-DDLL_EXPORT' ;; dgux*) case $cc_basename in ec++*) lt_prog_compiler_pic_CXX='-KPIC' ;; ghcx*) # Green Hills C++ Compiler lt_prog_compiler_pic_CXX='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then lt_prog_compiler_pic_CXX='+Z' fi ;; aCC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) lt_prog_compiler_pic_CXX='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_static_CXX='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler lt_prog_compiler_wl_CXX='--backend -Wl,' lt_prog_compiler_pic_CXX='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-fPIC' lt_prog_compiler_static_CXX='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-fpic' lt_prog_compiler_static_CXX='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX='-non_shared' ;; xlc* | xlC* | bgxl[cC]* | mpixl[cC]*) # IBM XL 8.0, 9.0 on PPC and BlueGene lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-qpic' lt_prog_compiler_static_CXX='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' lt_prog_compiler_wl_CXX='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) lt_prog_compiler_pic_CXX='-W c,exportall' ;; *) ;; esac ;; netbsd* | netbsdelf*-gnu) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. lt_prog_compiler_pic_CXX='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) lt_prog_compiler_wl_CXX='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 lt_prog_compiler_pic_CXX='-pic' ;; cxx*) # Digital/Compaq C++ lt_prog_compiler_wl_CXX='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. lt_prog_compiler_pic_CXX= lt_prog_compiler_static_CXX='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' lt_prog_compiler_wl_CXX='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler lt_prog_compiler_pic_CXX='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x lt_prog_compiler_pic_CXX='-pic' lt_prog_compiler_static_CXX='-Bstatic' ;; lcc*) # Lucid lt_prog_compiler_pic_CXX='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) lt_prog_compiler_wl_CXX='-Wl,' lt_prog_compiler_pic_CXX='-KPIC' lt_prog_compiler_static_CXX='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 lt_prog_compiler_pic_CXX='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) lt_prog_compiler_can_build_shared_CXX=no ;; esac fi case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) lt_prog_compiler_pic_CXX= ;; *) lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 $as_echo_n "checking for $compiler option to produce PIC... " >&6; } if ${lt_cv_prog_compiler_pic_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5 $as_echo "$lt_cv_prog_compiler_pic_CXX" >&6; } lt_prog_compiler_pic_CXX=$lt_cv_prog_compiler_pic_CXX # # Check to make sure the PIC flag actually works. # if test -n "$lt_prog_compiler_pic_CXX"; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " >&6; } if ${lt_cv_prog_compiler_pic_works_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_pic_works_CXX=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_pic_works_CXX=yes fi fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5 $as_echo "$lt_cv_prog_compiler_pic_works_CXX" >&6; } if test x"$lt_cv_prog_compiler_pic_works_CXX" = xyes; then case $lt_prog_compiler_pic_CXX in "" | " "*) ;; *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; esac else lt_prog_compiler_pic_CXX= lt_prog_compiler_can_build_shared_CXX=no fi fi # # Check to make sure the static flag actually works. # wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\" { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } if ${lt_cv_prog_compiler_static_works_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_static_works_CXX=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&5 $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then lt_cv_prog_compiler_static_works_CXX=yes fi else lt_cv_prog_compiler_static_works_CXX=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5 $as_echo "$lt_cv_prog_compiler_static_works_CXX" >&6; } if test x"$lt_cv_prog_compiler_static_works_CXX" = xyes; then : else lt_prog_compiler_static_CXX= fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o_CXX=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 $as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5 $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if ${lt_cv_prog_compiler_c_o_CXX+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 echo "$as_me:$LINENO: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then lt_cv_prog_compiler_c_o_CXX=yes fi fi chmod u+w . 2>&5 $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 $as_echo "$lt_cv_prog_compiler_c_o_CXX" >&6; } hard_links="nottested" if test "$lt_cv_prog_compiler_c_o_CXX" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user { $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can lock with hard links" >&5 $as_echo_n "checking if we can lock with hard links... " >&6; } hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hard_links" >&5 $as_echo "$hard_links" >&6; } if test "$hard_links" = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&5 $as_echo "$as_me: WARNING: \`$CC' does not support \`-c -o', so \`make -j' may be unsafe" >&2;} need_locks=warn fi else need_locks=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the $compiler linker ($LD) supports shared libraries" >&5 $as_echo_n "checking whether the $compiler linker ($LD) supports shared libraries... " >&6; } export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms_CXX='_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*' case $host_os in aix[4-9]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then export_symbols_cmds_CXX='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else export_symbols_cmds_CXX='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && (substr(\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) export_symbols_cmds_CXX="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms_CXX='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' ;; esac ;; linux* | k*bsd*-gnu | gnu*) link_all_deplibs_CXX=no ;; *) export_symbols_cmds_CXX='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ld_shlibs_CXX" >&5 $as_echo "$ld_shlibs_CXX" >&6; } test "$ld_shlibs_CXX" = no && can_build_shared=no with_gnu_ld_CXX=$with_gnu_ld # # Do we need to explicitly link libc? # case "x$archive_cmds_need_lc_CXX" in x|xyes) # Assume -lc should be added archive_cmds_need_lc_CXX=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $archive_cmds_CXX in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether -lc should be explicitly linked in" >&5 $as_echo_n "checking whether -lc should be explicitly linked in... " >&6; } if ${lt_cv_archive_cmds_need_lc_CXX+:} false; then : $as_echo_n "(cached) " >&6 else $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$lt_prog_compiler_wl_CXX pic_flag=$lt_prog_compiler_pic_CXX compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$allow_undefined_flag_CXX allow_undefined_flag_CXX= if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1\""; } >&5 (eval $archive_cmds_CXX 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then lt_cv_archive_cmds_need_lc_CXX=no else lt_cv_archive_cmds_need_lc_CXX=yes fi allow_undefined_flag_CXX=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc_CXX" >&5 $as_echo "$lt_cv_archive_cmds_need_lc_CXX" >&6; } archive_cmds_need_lc_CXX=$lt_cv_archive_cmds_need_lc_CXX ;; esac fi ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking dynamic linker characteristics" >&5 $as_echo_n "checking dynamic linker characteristics... " >&6; } library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[4-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[01] | aix4.[01].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([^/]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[45]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([a-zA-Z]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | $GREP ';[c-zC-Z]:/' >/dev/null; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[.]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[23].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[01]* | freebsdelf3.[01]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[2-9]* | freebsdelf3.[2-9]* | \ freebsd4.[0-5] | freebsdelf4.[0-5] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[3-9]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH if ${lt_cv_shlibpath_overrides_runpath+:} false; then : $as_echo_n "(cached) " >&6 else lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl_CXX\"; \ LDFLAGS=\"\$LDFLAGS $hardcode_libdir_flag_spec_CXX\"" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_cxx_try_link "$LINENO"; then : if ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null; then : lt_cv_shlibpath_overrides_runpath=yes fi fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[89] | openbsd2.[89].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 $as_echo "$dynamic_linker" >&6; } test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to hardcode library paths into programs" >&5 $as_echo_n "checking how to hardcode library paths into programs... " >&6; } hardcode_action_CXX= if test -n "$hardcode_libdir_flag_spec_CXX" || test -n "$runpath_var_CXX" || test "X$hardcode_automatic_CXX" = "Xyes" ; then # We can hardcode non-existent directories. if test "$hardcode_direct_CXX" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, CXX)" != no && test "$hardcode_minus_L_CXX" != no; then # Linking always hardcodes the temporary library directory. hardcode_action_CXX=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. hardcode_action_CXX=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. hardcode_action_CXX=unsupported fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $hardcode_action_CXX" >&5 $as_echo "$hardcode_action_CXX" >&6; } if test "$hardcode_action_CXX" = relink || test "$inherit_rpath_CXX" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_commands="$ac_config_commands libtool" # Only expand once: # Generate the makefiles ac_config_files="$ac_config_files Makefile src/Makefile src/lib/Makefile src/lib/common/Makefile src/lib/common/softhsm2.conf src/lib/common/softhsm2.conf.5 src/lib/crypto/Makefile src/lib/crypto/test/Makefile src/lib/data_mgr/Makefile src/lib/data_mgr/test/Makefile src/lib/object_store/Makefile src/lib/object_store/test/Makefile src/lib/session_mgr/Makefile src/lib/session_mgr/test/Makefile src/lib/slot_mgr/Makefile src/lib/slot_mgr/test/Makefile src/lib/handle_mgr/Makefile src/lib/handle_mgr/test/Makefile src/lib/test/Makefile src/lib/test/softhsm2.conf src/lib/test/tokens/dummy src/bin/Makefile src/bin/common/Makefile src/bin/dump/Makefile src/bin/keyconv/Makefile src/bin/migrate/Makefile src/bin/util/Makefile" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs { $as_echo "$as_me:${as_lineno-$LINENO}: checking that generated files are newer than configure" >&5 $as_echo_n "checking that generated files are newer than configure... " >&6; } if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: done" >&5 $as_echo "done" >&6; } if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' else am__EXEEXT_TRUE='#' am__EXEEXT_FALSE= fi if test -z "${AMDEP_TRUE}" && test -z "${AMDEP_FALSE}"; then as_fn_error $? "conditional \"AMDEP\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCC_TRUE}" && test -z "${am__fastdepCC_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${am__fastdepCXX_TRUE}" && test -z "${am__fastdepCXX_FALSE}"; then as_fn_error $? "conditional \"am__fastdepCXX\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${WITH_ECC_TRUE}" && test -z "${WITH_ECC_FALSE}"; then as_fn_error $? "conditional \"WITH_ECC\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${WITH_GOST_TRUE}" && test -z "${WITH_GOST_FALSE}"; then as_fn_error $? "conditional \"WITH_GOST\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${WITH_GOST_TRUE}" && test -z "${WITH_GOST_FALSE}"; then as_fn_error $? "conditional \"WITH_GOST\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${WITH_OPENSSL_TRUE}" && test -z "${WITH_OPENSSL_FALSE}"; then as_fn_error $? "conditional \"WITH_OPENSSL\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${WITH_BOTAN_TRUE}" && test -z "${WITH_BOTAN_FALSE}"; then as_fn_error $? "conditional \"WITH_BOTAN\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_MIGRATE_TRUE}" && test -z "${BUILD_MIGRATE_FALSE}"; then as_fn_error $? "conditional \"BUILD_MIGRATE\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi if test -z "${BUILD_OBJECTSTORE_BACKEND_DB_TRUE}" && test -z "${BUILD_OBJECTSTORE_BACKEND_DB_FALSE}"; then as_fn_error $? "conditional \"BUILD_OBJECTSTORE_BACKEND_DB\" was never defined. Usually this means the macro was only invoked conditionally." "$LINENO" 5 fi : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by SoftHSM $as_me 2.0.0, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" config_commands="$ac_config_commands" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Configuration commands: $config_commands Report bugs to the package provider." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ SoftHSM config.status 2.0.0 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' INSTALL='$INSTALL' MKDIR_P='$MKDIR_P' AWK='$AWK' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # # INIT-COMMANDS # AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir" # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' macro_version='`$ECHO "$macro_version" | $SED "$delay_single_quote_subst"`' macro_revision='`$ECHO "$macro_revision" | $SED "$delay_single_quote_subst"`' enable_shared='`$ECHO "$enable_shared" | $SED "$delay_single_quote_subst"`' enable_static='`$ECHO "$enable_static" | $SED "$delay_single_quote_subst"`' pic_mode='`$ECHO "$pic_mode" | $SED "$delay_single_quote_subst"`' enable_fast_install='`$ECHO "$enable_fast_install" | $SED "$delay_single_quote_subst"`' SHELL='`$ECHO "$SHELL" | $SED "$delay_single_quote_subst"`' ECHO='`$ECHO "$ECHO" | $SED "$delay_single_quote_subst"`' PATH_SEPARATOR='`$ECHO "$PATH_SEPARATOR" | $SED "$delay_single_quote_subst"`' host_alias='`$ECHO "$host_alias" | $SED "$delay_single_quote_subst"`' host='`$ECHO "$host" | $SED "$delay_single_quote_subst"`' host_os='`$ECHO "$host_os" | $SED "$delay_single_quote_subst"`' build_alias='`$ECHO "$build_alias" | $SED "$delay_single_quote_subst"`' build='`$ECHO "$build" | $SED "$delay_single_quote_subst"`' build_os='`$ECHO "$build_os" | $SED "$delay_single_quote_subst"`' SED='`$ECHO "$SED" | $SED "$delay_single_quote_subst"`' Xsed='`$ECHO "$Xsed" | $SED "$delay_single_quote_subst"`' GREP='`$ECHO "$GREP" | $SED "$delay_single_quote_subst"`' EGREP='`$ECHO "$EGREP" | $SED "$delay_single_quote_subst"`' FGREP='`$ECHO "$FGREP" | $SED "$delay_single_quote_subst"`' LD='`$ECHO "$LD" | $SED "$delay_single_quote_subst"`' NM='`$ECHO "$NM" | $SED "$delay_single_quote_subst"`' LN_S='`$ECHO "$LN_S" | $SED "$delay_single_quote_subst"`' max_cmd_len='`$ECHO "$max_cmd_len" | $SED "$delay_single_quote_subst"`' ac_objext='`$ECHO "$ac_objext" | $SED "$delay_single_quote_subst"`' exeext='`$ECHO "$exeext" | $SED "$delay_single_quote_subst"`' lt_unset='`$ECHO "$lt_unset" | $SED "$delay_single_quote_subst"`' lt_SP2NL='`$ECHO "$lt_SP2NL" | $SED "$delay_single_quote_subst"`' lt_NL2SP='`$ECHO "$lt_NL2SP" | $SED "$delay_single_quote_subst"`' lt_cv_to_host_file_cmd='`$ECHO "$lt_cv_to_host_file_cmd" | $SED "$delay_single_quote_subst"`' lt_cv_to_tool_file_cmd='`$ECHO "$lt_cv_to_tool_file_cmd" | $SED "$delay_single_quote_subst"`' reload_flag='`$ECHO "$reload_flag" | $SED "$delay_single_quote_subst"`' reload_cmds='`$ECHO "$reload_cmds" | $SED "$delay_single_quote_subst"`' OBJDUMP='`$ECHO "$OBJDUMP" | $SED "$delay_single_quote_subst"`' deplibs_check_method='`$ECHO "$deplibs_check_method" | $SED "$delay_single_quote_subst"`' file_magic_cmd='`$ECHO "$file_magic_cmd" | $SED "$delay_single_quote_subst"`' file_magic_glob='`$ECHO "$file_magic_glob" | $SED "$delay_single_quote_subst"`' want_nocaseglob='`$ECHO "$want_nocaseglob" | $SED "$delay_single_quote_subst"`' DLLTOOL='`$ECHO "$DLLTOOL" | $SED "$delay_single_quote_subst"`' sharedlib_from_linklib_cmd='`$ECHO "$sharedlib_from_linklib_cmd" | $SED "$delay_single_quote_subst"`' AR='`$ECHO "$AR" | $SED "$delay_single_quote_subst"`' AR_FLAGS='`$ECHO "$AR_FLAGS" | $SED "$delay_single_quote_subst"`' archiver_list_spec='`$ECHO "$archiver_list_spec" | $SED "$delay_single_quote_subst"`' STRIP='`$ECHO "$STRIP" | $SED "$delay_single_quote_subst"`' RANLIB='`$ECHO "$RANLIB" | $SED "$delay_single_quote_subst"`' old_postinstall_cmds='`$ECHO "$old_postinstall_cmds" | $SED "$delay_single_quote_subst"`' old_postuninstall_cmds='`$ECHO "$old_postuninstall_cmds" | $SED "$delay_single_quote_subst"`' old_archive_cmds='`$ECHO "$old_archive_cmds" | $SED "$delay_single_quote_subst"`' lock_old_archive_extraction='`$ECHO "$lock_old_archive_extraction" | $SED "$delay_single_quote_subst"`' CC='`$ECHO "$CC" | $SED "$delay_single_quote_subst"`' CFLAGS='`$ECHO "$CFLAGS" | $SED "$delay_single_quote_subst"`' compiler='`$ECHO "$compiler" | $SED "$delay_single_quote_subst"`' GCC='`$ECHO "$GCC" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_pipe='`$ECHO "$lt_cv_sys_global_symbol_pipe" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_cdecl='`$ECHO "$lt_cv_sys_global_symbol_to_cdecl" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address" | $SED "$delay_single_quote_subst"`' lt_cv_sys_global_symbol_to_c_name_address_lib_prefix='`$ECHO "$lt_cv_sys_global_symbol_to_c_name_address_lib_prefix" | $SED "$delay_single_quote_subst"`' nm_file_list_spec='`$ECHO "$nm_file_list_spec" | $SED "$delay_single_quote_subst"`' lt_sysroot='`$ECHO "$lt_sysroot" | $SED "$delay_single_quote_subst"`' objdir='`$ECHO "$objdir" | $SED "$delay_single_quote_subst"`' MAGIC_CMD='`$ECHO "$MAGIC_CMD" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag='`$ECHO "$lt_prog_compiler_no_builtin_flag" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic='`$ECHO "$lt_prog_compiler_pic" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl='`$ECHO "$lt_prog_compiler_wl" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static='`$ECHO "$lt_prog_compiler_static" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o='`$ECHO "$lt_cv_prog_compiler_c_o" | $SED "$delay_single_quote_subst"`' need_locks='`$ECHO "$need_locks" | $SED "$delay_single_quote_subst"`' MANIFEST_TOOL='`$ECHO "$MANIFEST_TOOL" | $SED "$delay_single_quote_subst"`' DSYMUTIL='`$ECHO "$DSYMUTIL" | $SED "$delay_single_quote_subst"`' NMEDIT='`$ECHO "$NMEDIT" | $SED "$delay_single_quote_subst"`' LIPO='`$ECHO "$LIPO" | $SED "$delay_single_quote_subst"`' OTOOL='`$ECHO "$OTOOL" | $SED "$delay_single_quote_subst"`' OTOOL64='`$ECHO "$OTOOL64" | $SED "$delay_single_quote_subst"`' libext='`$ECHO "$libext" | $SED "$delay_single_quote_subst"`' shrext_cmds='`$ECHO "$shrext_cmds" | $SED "$delay_single_quote_subst"`' extract_expsyms_cmds='`$ECHO "$extract_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc='`$ECHO "$archive_cmds_need_lc" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes='`$ECHO "$enable_shared_with_static_runtimes" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec='`$ECHO "$export_dynamic_flag_spec" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec='`$ECHO "$whole_archive_flag_spec" | $SED "$delay_single_quote_subst"`' compiler_needs_object='`$ECHO "$compiler_needs_object" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds='`$ECHO "$old_archive_from_new_cmds" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds='`$ECHO "$old_archive_from_expsyms_cmds" | $SED "$delay_single_quote_subst"`' archive_cmds='`$ECHO "$archive_cmds" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds='`$ECHO "$archive_expsym_cmds" | $SED "$delay_single_quote_subst"`' module_cmds='`$ECHO "$module_cmds" | $SED "$delay_single_quote_subst"`' module_expsym_cmds='`$ECHO "$module_expsym_cmds" | $SED "$delay_single_quote_subst"`' with_gnu_ld='`$ECHO "$with_gnu_ld" | $SED "$delay_single_quote_subst"`' allow_undefined_flag='`$ECHO "$allow_undefined_flag" | $SED "$delay_single_quote_subst"`' no_undefined_flag='`$ECHO "$no_undefined_flag" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec='`$ECHO "$hardcode_libdir_flag_spec" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator='`$ECHO "$hardcode_libdir_separator" | $SED "$delay_single_quote_subst"`' hardcode_direct='`$ECHO "$hardcode_direct" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute='`$ECHO "$hardcode_direct_absolute" | $SED "$delay_single_quote_subst"`' hardcode_minus_L='`$ECHO "$hardcode_minus_L" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var='`$ECHO "$hardcode_shlibpath_var" | $SED "$delay_single_quote_subst"`' hardcode_automatic='`$ECHO "$hardcode_automatic" | $SED "$delay_single_quote_subst"`' inherit_rpath='`$ECHO "$inherit_rpath" | $SED "$delay_single_quote_subst"`' link_all_deplibs='`$ECHO "$link_all_deplibs" | $SED "$delay_single_quote_subst"`' always_export_symbols='`$ECHO "$always_export_symbols" | $SED "$delay_single_quote_subst"`' export_symbols_cmds='`$ECHO "$export_symbols_cmds" | $SED "$delay_single_quote_subst"`' exclude_expsyms='`$ECHO "$exclude_expsyms" | $SED "$delay_single_quote_subst"`' include_expsyms='`$ECHO "$include_expsyms" | $SED "$delay_single_quote_subst"`' prelink_cmds='`$ECHO "$prelink_cmds" | $SED "$delay_single_quote_subst"`' postlink_cmds='`$ECHO "$postlink_cmds" | $SED "$delay_single_quote_subst"`' file_list_spec='`$ECHO "$file_list_spec" | $SED "$delay_single_quote_subst"`' variables_saved_for_relink='`$ECHO "$variables_saved_for_relink" | $SED "$delay_single_quote_subst"`' need_lib_prefix='`$ECHO "$need_lib_prefix" | $SED "$delay_single_quote_subst"`' need_version='`$ECHO "$need_version" | $SED "$delay_single_quote_subst"`' version_type='`$ECHO "$version_type" | $SED "$delay_single_quote_subst"`' runpath_var='`$ECHO "$runpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_var='`$ECHO "$shlibpath_var" | $SED "$delay_single_quote_subst"`' shlibpath_overrides_runpath='`$ECHO "$shlibpath_overrides_runpath" | $SED "$delay_single_quote_subst"`' libname_spec='`$ECHO "$libname_spec" | $SED "$delay_single_quote_subst"`' library_names_spec='`$ECHO "$library_names_spec" | $SED "$delay_single_quote_subst"`' soname_spec='`$ECHO "$soname_spec" | $SED "$delay_single_quote_subst"`' install_override_mode='`$ECHO "$install_override_mode" | $SED "$delay_single_quote_subst"`' postinstall_cmds='`$ECHO "$postinstall_cmds" | $SED "$delay_single_quote_subst"`' postuninstall_cmds='`$ECHO "$postuninstall_cmds" | $SED "$delay_single_quote_subst"`' finish_cmds='`$ECHO "$finish_cmds" | $SED "$delay_single_quote_subst"`' finish_eval='`$ECHO "$finish_eval" | $SED "$delay_single_quote_subst"`' hardcode_into_libs='`$ECHO "$hardcode_into_libs" | $SED "$delay_single_quote_subst"`' sys_lib_search_path_spec='`$ECHO "$sys_lib_search_path_spec" | $SED "$delay_single_quote_subst"`' sys_lib_dlsearch_path_spec='`$ECHO "$sys_lib_dlsearch_path_spec" | $SED "$delay_single_quote_subst"`' hardcode_action='`$ECHO "$hardcode_action" | $SED "$delay_single_quote_subst"`' enable_dlopen='`$ECHO "$enable_dlopen" | $SED "$delay_single_quote_subst"`' enable_dlopen_self='`$ECHO "$enable_dlopen_self" | $SED "$delay_single_quote_subst"`' enable_dlopen_self_static='`$ECHO "$enable_dlopen_self_static" | $SED "$delay_single_quote_subst"`' old_striplib='`$ECHO "$old_striplib" | $SED "$delay_single_quote_subst"`' striplib='`$ECHO "$striplib" | $SED "$delay_single_quote_subst"`' compiler_lib_search_dirs='`$ECHO "$compiler_lib_search_dirs" | $SED "$delay_single_quote_subst"`' predep_objects='`$ECHO "$predep_objects" | $SED "$delay_single_quote_subst"`' postdep_objects='`$ECHO "$postdep_objects" | $SED "$delay_single_quote_subst"`' predeps='`$ECHO "$predeps" | $SED "$delay_single_quote_subst"`' postdeps='`$ECHO "$postdeps" | $SED "$delay_single_quote_subst"`' compiler_lib_search_path='`$ECHO "$compiler_lib_search_path" | $SED "$delay_single_quote_subst"`' LD_CXX='`$ECHO "$LD_CXX" | $SED "$delay_single_quote_subst"`' reload_flag_CXX='`$ECHO "$reload_flag_CXX" | $SED "$delay_single_quote_subst"`' reload_cmds_CXX='`$ECHO "$reload_cmds_CXX" | $SED "$delay_single_quote_subst"`' old_archive_cmds_CXX='`$ECHO "$old_archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' compiler_CXX='`$ECHO "$compiler_CXX" | $SED "$delay_single_quote_subst"`' GCC_CXX='`$ECHO "$GCC_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_no_builtin_flag_CXX='`$ECHO "$lt_prog_compiler_no_builtin_flag_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_pic_CXX='`$ECHO "$lt_prog_compiler_pic_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_wl_CXX='`$ECHO "$lt_prog_compiler_wl_CXX" | $SED "$delay_single_quote_subst"`' lt_prog_compiler_static_CXX='`$ECHO "$lt_prog_compiler_static_CXX" | $SED "$delay_single_quote_subst"`' lt_cv_prog_compiler_c_o_CXX='`$ECHO "$lt_cv_prog_compiler_c_o_CXX" | $SED "$delay_single_quote_subst"`' archive_cmds_need_lc_CXX='`$ECHO "$archive_cmds_need_lc_CXX" | $SED "$delay_single_quote_subst"`' enable_shared_with_static_runtimes_CXX='`$ECHO "$enable_shared_with_static_runtimes_CXX" | $SED "$delay_single_quote_subst"`' export_dynamic_flag_spec_CXX='`$ECHO "$export_dynamic_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' whole_archive_flag_spec_CXX='`$ECHO "$whole_archive_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' compiler_needs_object_CXX='`$ECHO "$compiler_needs_object_CXX" | $SED "$delay_single_quote_subst"`' old_archive_from_new_cmds_CXX='`$ECHO "$old_archive_from_new_cmds_CXX" | $SED "$delay_single_quote_subst"`' old_archive_from_expsyms_cmds_CXX='`$ECHO "$old_archive_from_expsyms_cmds_CXX" | $SED "$delay_single_quote_subst"`' archive_cmds_CXX='`$ECHO "$archive_cmds_CXX" | $SED "$delay_single_quote_subst"`' archive_expsym_cmds_CXX='`$ECHO "$archive_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' module_cmds_CXX='`$ECHO "$module_cmds_CXX" | $SED "$delay_single_quote_subst"`' module_expsym_cmds_CXX='`$ECHO "$module_expsym_cmds_CXX" | $SED "$delay_single_quote_subst"`' with_gnu_ld_CXX='`$ECHO "$with_gnu_ld_CXX" | $SED "$delay_single_quote_subst"`' allow_undefined_flag_CXX='`$ECHO "$allow_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' no_undefined_flag_CXX='`$ECHO "$no_undefined_flag_CXX" | $SED "$delay_single_quote_subst"`' hardcode_libdir_flag_spec_CXX='`$ECHO "$hardcode_libdir_flag_spec_CXX" | $SED "$delay_single_quote_subst"`' hardcode_libdir_separator_CXX='`$ECHO "$hardcode_libdir_separator_CXX" | $SED "$delay_single_quote_subst"`' hardcode_direct_CXX='`$ECHO "$hardcode_direct_CXX" | $SED "$delay_single_quote_subst"`' hardcode_direct_absolute_CXX='`$ECHO "$hardcode_direct_absolute_CXX" | $SED "$delay_single_quote_subst"`' hardcode_minus_L_CXX='`$ECHO "$hardcode_minus_L_CXX" | $SED "$delay_single_quote_subst"`' hardcode_shlibpath_var_CXX='`$ECHO "$hardcode_shlibpath_var_CXX" | $SED "$delay_single_quote_subst"`' hardcode_automatic_CXX='`$ECHO "$hardcode_automatic_CXX" | $SED "$delay_single_quote_subst"`' inherit_rpath_CXX='`$ECHO "$inherit_rpath_CXX" | $SED "$delay_single_quote_subst"`' link_all_deplibs_CXX='`$ECHO "$link_all_deplibs_CXX" | $SED "$delay_single_quote_subst"`' always_export_symbols_CXX='`$ECHO "$always_export_symbols_CXX" | $SED "$delay_single_quote_subst"`' export_symbols_cmds_CXX='`$ECHO "$export_symbols_cmds_CXX" | $SED "$delay_single_quote_subst"`' exclude_expsyms_CXX='`$ECHO "$exclude_expsyms_CXX" | $SED "$delay_single_quote_subst"`' include_expsyms_CXX='`$ECHO "$include_expsyms_CXX" | $SED "$delay_single_quote_subst"`' prelink_cmds_CXX='`$ECHO "$prelink_cmds_CXX" | $SED "$delay_single_quote_subst"`' postlink_cmds_CXX='`$ECHO "$postlink_cmds_CXX" | $SED "$delay_single_quote_subst"`' file_list_spec_CXX='`$ECHO "$file_list_spec_CXX" | $SED "$delay_single_quote_subst"`' hardcode_action_CXX='`$ECHO "$hardcode_action_CXX" | $SED "$delay_single_quote_subst"`' compiler_lib_search_dirs_CXX='`$ECHO "$compiler_lib_search_dirs_CXX" | $SED "$delay_single_quote_subst"`' predep_objects_CXX='`$ECHO "$predep_objects_CXX" | $SED "$delay_single_quote_subst"`' postdep_objects_CXX='`$ECHO "$postdep_objects_CXX" | $SED "$delay_single_quote_subst"`' predeps_CXX='`$ECHO "$predeps_CXX" | $SED "$delay_single_quote_subst"`' postdeps_CXX='`$ECHO "$postdeps_CXX" | $SED "$delay_single_quote_subst"`' compiler_lib_search_path_CXX='`$ECHO "$compiler_lib_search_path_CXX" | $SED "$delay_single_quote_subst"`' LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } # Quote evaled strings. for var in SHELL \ ECHO \ PATH_SEPARATOR \ SED \ GREP \ EGREP \ FGREP \ LD \ NM \ LN_S \ lt_SP2NL \ lt_NL2SP \ reload_flag \ OBJDUMP \ deplibs_check_method \ file_magic_cmd \ file_magic_glob \ want_nocaseglob \ DLLTOOL \ sharedlib_from_linklib_cmd \ AR \ AR_FLAGS \ archiver_list_spec \ STRIP \ RANLIB \ CC \ CFLAGS \ compiler \ lt_cv_sys_global_symbol_pipe \ lt_cv_sys_global_symbol_to_cdecl \ lt_cv_sys_global_symbol_to_c_name_address \ lt_cv_sys_global_symbol_to_c_name_address_lib_prefix \ nm_file_list_spec \ lt_prog_compiler_no_builtin_flag \ lt_prog_compiler_pic \ lt_prog_compiler_wl \ lt_prog_compiler_static \ lt_cv_prog_compiler_c_o \ need_locks \ MANIFEST_TOOL \ DSYMUTIL \ NMEDIT \ LIPO \ OTOOL \ OTOOL64 \ shrext_cmds \ export_dynamic_flag_spec \ whole_archive_flag_spec \ compiler_needs_object \ with_gnu_ld \ allow_undefined_flag \ no_undefined_flag \ hardcode_libdir_flag_spec \ hardcode_libdir_separator \ exclude_expsyms \ include_expsyms \ file_list_spec \ variables_saved_for_relink \ libname_spec \ library_names_spec \ soname_spec \ install_override_mode \ finish_eval \ old_striplib \ striplib \ compiler_lib_search_dirs \ predep_objects \ postdep_objects \ predeps \ postdeps \ compiler_lib_search_path \ LD_CXX \ reload_flag_CXX \ compiler_CXX \ lt_prog_compiler_no_builtin_flag_CXX \ lt_prog_compiler_pic_CXX \ lt_prog_compiler_wl_CXX \ lt_prog_compiler_static_CXX \ lt_cv_prog_compiler_c_o_CXX \ export_dynamic_flag_spec_CXX \ whole_archive_flag_spec_CXX \ compiler_needs_object_CXX \ with_gnu_ld_CXX \ allow_undefined_flag_CXX \ no_undefined_flag_CXX \ hardcode_libdir_flag_spec_CXX \ hardcode_libdir_separator_CXX \ exclude_expsyms_CXX \ include_expsyms_CXX \ file_list_spec_CXX \ compiler_lib_search_dirs_CXX \ predep_objects_CXX \ postdep_objects_CXX \ predeps_CXX \ postdeps_CXX \ compiler_lib_search_path_CXX; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in reload_cmds \ old_postinstall_cmds \ old_postuninstall_cmds \ old_archive_cmds \ extract_expsyms_cmds \ old_archive_from_new_cmds \ old_archive_from_expsyms_cmds \ archive_cmds \ archive_expsym_cmds \ module_cmds \ module_expsym_cmds \ export_symbols_cmds \ prelink_cmds \ postlink_cmds \ postinstall_cmds \ postuninstall_cmds \ finish_cmds \ sys_lib_search_path_spec \ sys_lib_dlsearch_path_spec \ reload_cmds_CXX \ old_archive_cmds_CXX \ old_archive_from_new_cmds_CXX \ old_archive_from_expsyms_cmds_CXX \ archive_cmds_CXX \ archive_expsym_cmds_CXX \ module_cmds_CXX \ module_expsym_cmds_CXX \ export_symbols_cmds_CXX \ prelink_cmds_CXX \ postlink_cmds_CXX; do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[\\\\\\\`\\"\\\$]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done ac_aux_dir='$ac_aux_dir' xsi_shell='$xsi_shell' lt_shell_append='$lt_shell_append' # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile' _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;; "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;; "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; "src/lib/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/Makefile" ;; "src/lib/common/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/common/Makefile" ;; "src/lib/common/softhsm2.conf") CONFIG_FILES="$CONFIG_FILES src/lib/common/softhsm2.conf" ;; "src/lib/common/softhsm2.conf.5") CONFIG_FILES="$CONFIG_FILES src/lib/common/softhsm2.conf.5" ;; "src/lib/crypto/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/crypto/Makefile" ;; "src/lib/crypto/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/crypto/test/Makefile" ;; "src/lib/data_mgr/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/data_mgr/Makefile" ;; "src/lib/data_mgr/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/data_mgr/test/Makefile" ;; "src/lib/object_store/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/object_store/Makefile" ;; "src/lib/object_store/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/object_store/test/Makefile" ;; "src/lib/session_mgr/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/session_mgr/Makefile" ;; "src/lib/session_mgr/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/session_mgr/test/Makefile" ;; "src/lib/slot_mgr/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/slot_mgr/Makefile" ;; "src/lib/slot_mgr/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/slot_mgr/test/Makefile" ;; "src/lib/handle_mgr/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/handle_mgr/Makefile" ;; "src/lib/handle_mgr/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/handle_mgr/test/Makefile" ;; "src/lib/test/Makefile") CONFIG_FILES="$CONFIG_FILES src/lib/test/Makefile" ;; "src/lib/test/softhsm2.conf") CONFIG_FILES="$CONFIG_FILES src/lib/test/softhsm2.conf" ;; "src/lib/test/tokens/dummy") CONFIG_FILES="$CONFIG_FILES src/lib/test/tokens/dummy" ;; "src/bin/Makefile") CONFIG_FILES="$CONFIG_FILES src/bin/Makefile" ;; "src/bin/common/Makefile") CONFIG_FILES="$CONFIG_FILES src/bin/common/Makefile" ;; "src/bin/dump/Makefile") CONFIG_FILES="$CONFIG_FILES src/bin/dump/Makefile" ;; "src/bin/keyconv/Makefile") CONFIG_FILES="$CONFIG_FILES src/bin/keyconv/Makefile" ;; "src/bin/migrate/Makefile") CONFIG_FILES="$CONFIG_FILES src/bin/migrate/Makefile" ;; "src/bin/util/Makefile") CONFIG_FILES="$CONFIG_FILES src/bin/util/Makefile" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # case $INSTALL in [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; esac ac_MKDIR_P=$MKDIR_P case $MKDIR_P in [\\/$]* | ?:[\\/]* ) ;; */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;; esac _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t s&@MKDIR_P@&$ac_MKDIR_P&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi # Compute "$ac_file"'s index in $config_headers. _am_arg="$ac_file" _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" || $as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$_am_arg" : 'X\(//\)[^/]' \| \ X"$_am_arg" : 'X\(//\)$' \| \ X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$_am_arg" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'`/stamp-h$_am_stamp_count ;; :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 $as_echo "$as_me: executing $ac_file commands" >&6;} ;; esac case $ac_file$ac_mode in "depfiles":C) test x"$AMDEP_TRUE" != x"" || { # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named 'Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`$as_dirname -- "$mf" || $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$mf" : 'X\(//\)[^/]' \| \ X"$mf" : 'X\(//\)$' \| \ X"$mf" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$mf" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running 'make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "$am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`$as_dirname -- "$file" || $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$file" : 'X\(//\)[^/]' \| \ X"$file" : 'X\(//\)$' \| \ X"$file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir=$dirpart/$fdir; as_fn_mkdir_p # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ;; "libtool":C) # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # The names of the tagged configurations supported by this script. available_tags="CXX " # ### BEGIN LIBTOOL CONFIG # Which release of libtool.m4 was used? macro_version=$macro_version macro_revision=$macro_revision # Whether or not to build shared libraries. build_libtool_libs=$enable_shared # Whether or not to build static libraries. build_old_libs=$enable_static # What type of objects to build. pic_mode=$pic_mode # Whether or not to optimize for fast installation. fast_install=$enable_fast_install # Shell to use when invoking shell scripts. SHELL=$lt_SHELL # An echo program that protects backslashes. ECHO=$lt_ECHO # The PATH separator for the build system. PATH_SEPARATOR=$lt_PATH_SEPARATOR # The host system. host_alias=$host_alias host=$host host_os=$host_os # The build system. build_alias=$build_alias build=$build build_os=$build_os # A sed program that does not truncate output. SED=$lt_SED # Sed that helps us avoid accidentally triggering echo(1) options like -n. Xsed="\$SED -e 1s/^X//" # A grep program that handles long lines. GREP=$lt_GREP # An ERE matcher. EGREP=$lt_EGREP # A literal string matcher. FGREP=$lt_FGREP # A BSD- or MS-compatible name lister. NM=$lt_NM # Whether we need soft or hard links. LN_S=$lt_LN_S # What is the maximum length of a command? max_cmd_len=$max_cmd_len # Object file suffix (normally "o"). objext=$ac_objext # Executable file suffix (normally ""). exeext=$exeext # whether the shell understands "unset". lt_unset=$lt_unset # turn spaces into newlines. SP2NL=$lt_lt_SP2NL # turn newlines into spaces. NL2SP=$lt_lt_NL2SP # convert \$build file names to \$host format. to_host_file_cmd=$lt_cv_to_host_file_cmd # convert \$build files to toolchain format. to_tool_file_cmd=$lt_cv_to_tool_file_cmd # An object symbol dumper. OBJDUMP=$lt_OBJDUMP # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method # Command to use when deplibs_check_method = "file_magic". file_magic_cmd=$lt_file_magic_cmd # How to find potential files when deplibs_check_method = "file_magic". file_magic_glob=$lt_file_magic_glob # Find potential files using nocaseglob when deplibs_check_method = "file_magic". want_nocaseglob=$lt_want_nocaseglob # DLL creation program. DLLTOOL=$lt_DLLTOOL # Command to associate shared and link libraries. sharedlib_from_linklib_cmd=$lt_sharedlib_from_linklib_cmd # The archiver. AR=$lt_AR # Flags to create an archive. AR_FLAGS=$lt_AR_FLAGS # How to feed a file listing to the archiver. archiver_list_spec=$lt_archiver_list_spec # A symbol stripping program. STRIP=$lt_STRIP # Commands used to install an old-style archive. RANLIB=$lt_RANLIB old_postinstall_cmds=$lt_old_postinstall_cmds old_postuninstall_cmds=$lt_old_postuninstall_cmds # Whether to use a lock for old archive extraction. lock_old_archive_extraction=$lock_old_archive_extraction # A C compiler. LTCC=$lt_CC # LTCC compiler flags. LTCFLAGS=$lt_CFLAGS # Take the output of nm and produce a listing of raw symbols and C names. global_symbol_pipe=$lt_lt_cv_sys_global_symbol_pipe # Transform the output of nm in a proper C declaration. global_symbol_to_cdecl=$lt_lt_cv_sys_global_symbol_to_cdecl # Transform the output of nm in a C name address pair. global_symbol_to_c_name_address=$lt_lt_cv_sys_global_symbol_to_c_name_address # Transform the output of nm in a C name address pair when lib prefix is needed. global_symbol_to_c_name_address_lib_prefix=$lt_lt_cv_sys_global_symbol_to_c_name_address_lib_prefix # Specify filename containing input files for \$NM. nm_file_list_spec=$lt_nm_file_list_spec # The root where to search for dependent libraries,and in which our libraries should be installed. lt_sysroot=$lt_sysroot # The name of the directory that contains temporary libtool files. objdir=$objdir # Used to examine libraries when file_magic_cmd begins with "file". MAGIC_CMD=$MAGIC_CMD # Must we lock files when doing compilation? need_locks=$lt_need_locks # Manifest tool. MANIFEST_TOOL=$lt_MANIFEST_TOOL # Tool to manipulate archived DWARF debug symbol files on Mac OS X. DSYMUTIL=$lt_DSYMUTIL # Tool to change global to local symbols on Mac OS X. NMEDIT=$lt_NMEDIT # Tool to manipulate fat objects and archives on Mac OS X. LIPO=$lt_LIPO # ldd/readelf like tool for Mach-O binaries on Mac OS X. OTOOL=$lt_OTOOL # ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4. OTOOL64=$lt_OTOOL64 # Old archive suffix (normally "a"). libext=$libext # Shared library suffix (normally ".so"). shrext_cmds=$lt_shrext_cmds # The commands to extract the exported symbol list from a shared archive. extract_expsyms_cmds=$lt_extract_expsyms_cmds # Variables whose values should be saved in libtool wrapper scripts and # restored at link time. variables_saved_for_relink=$lt_variables_saved_for_relink # Do we need the "lib" prefix for modules? need_lib_prefix=$need_lib_prefix # Do we need a version for libraries? need_version=$need_version # Library versioning type. version_type=$version_type # Shared library runtime path variable. runpath_var=$runpath_var # Shared library path variable. shlibpath_var=$shlibpath_var # Is shlibpath searched before the hard-coded library search path? shlibpath_overrides_runpath=$shlibpath_overrides_runpath # Format of library name prefix. libname_spec=$lt_libname_spec # List of archive names. First name is the real one, the rest are links. # The last name is the one that the linker finds with -lNAME library_names_spec=$lt_library_names_spec # The coded name of the library, if different from the real name. soname_spec=$lt_soname_spec # Permission mode override for installation of shared libraries. install_override_mode=$lt_install_override_mode # Command to use after installation of a shared archive. postinstall_cmds=$lt_postinstall_cmds # Command to use after uninstallation of a shared archive. postuninstall_cmds=$lt_postuninstall_cmds # Commands used to finish a libtool library installation in a directory. finish_cmds=$lt_finish_cmds # As "finish_cmds", except a single script fragment to be evaled but # not shown. finish_eval=$lt_finish_eval # Whether we should hardcode library paths into libraries. hardcode_into_libs=$hardcode_into_libs # Compile-time system search path for libraries. sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries. sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec # Whether dlopen is supported. dlopen_support=$enable_dlopen # Whether dlopen of programs is supported. dlopen_self=$enable_dlopen_self # Whether dlopen of statically linked programs is supported. dlopen_self_static=$enable_dlopen_self_static # Commands to strip libraries. old_striplib=$lt_old_striplib striplib=$lt_striplib # The linker used to build libraries. LD=$lt_LD # How to create reloadable object files. reload_flag=$lt_reload_flag reload_cmds=$lt_reload_cmds # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds # A language specific compiler. CC=$lt_compiler # Is the compiler the GNU compiler? with_gcc=$GCC # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds archive_expsym_cmds=$lt_archive_expsym_cmds # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds module_expsym_cmds=$lt_module_expsym_cmds # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms # Symbols that must always be exported. include_expsyms=$lt_include_expsyms # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds # Specify filename containing input files. file_list_spec=$lt_file_list_spec # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs=$lt_compiler_lib_search_dirs # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects=$lt_predep_objects postdep_objects=$lt_postdep_objects predeps=$lt_predeps postdeps=$lt_postdeps # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path=$lt_compiler_lib_search_path # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac ltmain="$ac_aux_dir/ltmain.sh" # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) if test x"$xsi_shell" = xyes; then sed -e '/^func_dirname ()$/,/^} # func_dirname /c\ func_dirname ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ } # Extended-shell func_dirname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_basename ()$/,/^} # func_basename /c\ func_basename ()\ {\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_dirname_and_basename ()$/,/^} # func_dirname_and_basename /c\ func_dirname_and_basename ()\ {\ \ case ${1} in\ \ */*) func_dirname_result="${1%/*}${2}" ;;\ \ * ) func_dirname_result="${3}" ;;\ \ esac\ \ func_basename_result="${1##*/}"\ } # Extended-shell func_dirname_and_basename implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_stripname ()$/,/^} # func_stripname /c\ func_stripname ()\ {\ \ # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\ \ # positional parameters, so assign one to ordinary parameter first.\ \ func_stripname_result=${3}\ \ func_stripname_result=${func_stripname_result#"${1}"}\ \ func_stripname_result=${func_stripname_result%"${2}"}\ } # Extended-shell func_stripname implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_long_opt ()$/,/^} # func_split_long_opt /c\ func_split_long_opt ()\ {\ \ func_split_long_opt_name=${1%%=*}\ \ func_split_long_opt_arg=${1#*=}\ } # Extended-shell func_split_long_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_split_short_opt ()$/,/^} # func_split_short_opt /c\ func_split_short_opt ()\ {\ \ func_split_short_opt_arg=${1#??}\ \ func_split_short_opt_name=${1%"$func_split_short_opt_arg"}\ } # Extended-shell func_split_short_opt implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_lo2o ()$/,/^} # func_lo2o /c\ func_lo2o ()\ {\ \ case ${1} in\ \ *.lo) func_lo2o_result=${1%.lo}.${objext} ;;\ \ *) func_lo2o_result=${1} ;;\ \ esac\ } # Extended-shell func_lo2o implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_xform ()$/,/^} # func_xform /c\ func_xform ()\ {\ func_xform_result=${1%.*}.lo\ } # Extended-shell func_xform implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_arith ()$/,/^} # func_arith /c\ func_arith ()\ {\ func_arith_result=$(( $* ))\ } # Extended-shell func_arith implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_len ()$/,/^} # func_len /c\ func_len ()\ {\ func_len_result=${#1}\ } # Extended-shell func_len implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$lt_shell_append" = xyes; then sed -e '/^func_append ()$/,/^} # func_append /c\ func_append ()\ {\ eval "${1}+=\\${2}"\ } # Extended-shell func_append implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: sed -e '/^func_append_quoted ()$/,/^} # func_append_quoted /c\ func_append_quoted ()\ {\ \ func_quote_for_eval "${2}"\ \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"\ } # Extended-shell func_append_quoted implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([a-zA-Z_]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Unable to substitute extended shell functions in $ofile" >&5 $as_echo "$as_me: WARNING: Unable to substitute extended shell functions in $ofile" >&2;} fi mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" cat <<_LT_EOF >> "$ofile" # ### BEGIN LIBTOOL TAG CONFIG: CXX # The linker used to build libraries. LD=$lt_LD_CXX # How to create reloadable object files. reload_flag=$lt_reload_flag_CXX reload_cmds=$lt_reload_cmds_CXX # Commands used to build an old-style archive. old_archive_cmds=$lt_old_archive_cmds_CXX # A language specific compiler. CC=$lt_compiler_CXX # Is the compiler the GNU compiler? with_gcc=$GCC_CXX # Compiler flag to turn off builtin functions. no_builtin_flag=$lt_lt_prog_compiler_no_builtin_flag_CXX # Additional compiler flags for building library objects. pic_flag=$lt_lt_prog_compiler_pic_CXX # How to pass a linker flag through the compiler. wl=$lt_lt_prog_compiler_wl_CXX # Compiler flag to prevent dynamic linking. link_static_flag=$lt_lt_prog_compiler_static_CXX # Does compiler simultaneously support -c and -o options? compiler_c_o=$lt_lt_cv_prog_compiler_c_o_CXX # Whether or not to add -lc for building shared libraries. build_libtool_need_lc=$archive_cmds_need_lc_CXX # Whether or not to disallow shared libs when runtime libs are static. allow_libtool_libs_with_static_runtimes=$enable_shared_with_static_runtimes_CXX # Compiler flag to allow reflexive dlopens. export_dynamic_flag_spec=$lt_export_dynamic_flag_spec_CXX # Compiler flag to generate shared objects directly from archives. whole_archive_flag_spec=$lt_whole_archive_flag_spec_CXX # Whether the compiler copes with passing no objects directly. compiler_needs_object=$lt_compiler_needs_object_CXX # Create an old-style archive from a shared archive. old_archive_from_new_cmds=$lt_old_archive_from_new_cmds_CXX # Create a temporary old-style archive to link instead of a shared archive. old_archive_from_expsyms_cmds=$lt_old_archive_from_expsyms_cmds_CXX # Commands used to build a shared archive. archive_cmds=$lt_archive_cmds_CXX archive_expsym_cmds=$lt_archive_expsym_cmds_CXX # Commands used to build a loadable module if different from building # a shared archive. module_cmds=$lt_module_cmds_CXX module_expsym_cmds=$lt_module_expsym_cmds_CXX # Whether we are building with GNU ld or not. with_gnu_ld=$lt_with_gnu_ld_CXX # Flag that allows shared libraries with undefined symbols to be built. allow_undefined_flag=$lt_allow_undefined_flag_CXX # Flag that enforces no undefined symbols. no_undefined_flag=$lt_no_undefined_flag_CXX # Flag to hardcode \$libdir into a binary during linking. # This must work even if \$libdir does not exist hardcode_libdir_flag_spec=$lt_hardcode_libdir_flag_spec_CXX # Whether we need a single "-rpath" flag with a separated argument. hardcode_libdir_separator=$lt_hardcode_libdir_separator_CXX # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary. hardcode_direct=$hardcode_direct_CXX # Set to "yes" if using DIR/libNAME\${shared_ext} during linking hardcodes # DIR into the resulting binary and the resulting library dependency is # "absolute",i.e impossible to change by setting \${shlibpath_var} if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute_CXX # Set to "yes" if using the -LDIR flag during linking hardcodes DIR # into the resulting binary. hardcode_minus_L=$hardcode_minus_L_CXX # Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR # into the resulting binary. hardcode_shlibpath_var=$hardcode_shlibpath_var_CXX # Set to "yes" if building a shared library automatically hardcodes DIR # into the library and all subsequent libraries and executables linked # against it. hardcode_automatic=$hardcode_automatic_CXX # Set to yes if linker adds runtime paths of dependent libraries # to runtime path list. inherit_rpath=$inherit_rpath_CXX # Whether libtool must link a program against all its dependency libraries. link_all_deplibs=$link_all_deplibs_CXX # Set to "yes" if exported symbols are required. always_export_symbols=$always_export_symbols_CXX # The commands to list exported symbols. export_symbols_cmds=$lt_export_symbols_cmds_CXX # Symbols that should not be listed in the preloaded symbols. exclude_expsyms=$lt_exclude_expsyms_CXX # Symbols that must always be exported. include_expsyms=$lt_include_expsyms_CXX # Commands necessary for linking programs (against libraries) with templates. prelink_cmds=$lt_prelink_cmds_CXX # Commands necessary for finishing linking programs. postlink_cmds=$lt_postlink_cmds_CXX # Specify filename containing input files. file_list_spec=$lt_file_list_spec_CXX # How to hardcode a shared library path into an executable. hardcode_action=$hardcode_action_CXX # The directories searched by this compiler when creating a shared library. compiler_lib_search_dirs=$lt_compiler_lib_search_dirs_CXX # Dependencies to place before and after the objects being linked to # create a shared library. predep_objects=$lt_predep_objects_CXX postdep_objects=$lt_postdep_objects_CXX predeps=$lt_predeps_CXX postdeps=$lt_postdeps_CXX # The library search path used internally by the compiler when linking # a shared library. compiler_lib_search_path=$lt_compiler_lib_search_path_CXX # ### END LIBTOOL TAG CONFIG: CXX _LT_EOF ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi softhsm-2.0.0/depcomp0000755000175000017500000005601612552216620011503 00000000000000#! /bin/sh # depcomp - compile a program generating dependencies as side-effects scriptversion=2013-05-30.07; # UTC # Copyright (C) 1999-2013 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # Originally written by Alexandre Oliva . case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: depcomp [--help] [--version] PROGRAM [ARGS] Run PROGRAMS ARGS to compile a file, generating dependencies as side-effects. Environment variables: depmode Dependency tracking mode. source Source file read by 'PROGRAMS ARGS'. object Object file output by 'PROGRAMS ARGS'. DEPDIR directory where to store dependencies. depfile Dependency file to output. tmpdepfile Temporary file to use when outputting dependencies. libtool Whether libtool is used (yes/no). Report bugs to . EOF exit $? ;; -v | --v*) echo "depcomp $scriptversion" exit $? ;; esac # Get the directory component of the given path, and save it in the # global variables '$dir'. Note that this directory component will # be either empty or ending with a '/' character. This is deliberate. set_dir_from () { case $1 in */*) dir=`echo "$1" | sed -e 's|/[^/]*$|/|'`;; *) dir=;; esac } # Get the suffix-stripped basename of the given path, and save it the # global variable '$base'. set_base_from () { base=`echo "$1" | sed -e 's|^.*/||' -e 's/\.[^.]*$//'` } # If no dependency file was actually created by the compiler invocation, # we still have to create a dummy depfile, to avoid errors with the # Makefile "include basename.Plo" scheme. make_dummy_depfile () { echo "#dummy" > "$depfile" } # Factor out some common post-processing of the generated depfile. # Requires the auxiliary global variable '$tmpdepfile' to be set. aix_post_process_depfile () { # If the compiler actually managed to produce a dependency file, # post-process it. if test -f "$tmpdepfile"; then # Each line is of the form 'foo.o: dependency.h'. # Do two passes, one to just change these to # $object: dependency.h # and one to simply output # dependency.h: # which is needed to avoid the deleted-header problem. { sed -e "s,^.*\.[$lower]*:,$object:," < "$tmpdepfile" sed -e "s,^.*\.[$lower]*:[$tab ]*,," -e 's,$,:,' < "$tmpdepfile" } > "$depfile" rm -f "$tmpdepfile" else make_dummy_depfile fi } # A tabulation character. tab=' ' # A newline character. nl=' ' # Character ranges might be problematic outside the C locale. # These definitions help. upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz digits=0123456789 alpha=${upper}${lower} if test -z "$depmode" || test -z "$source" || test -z "$object"; then echo "depcomp: Variables source, object and depmode must be set" 1>&2 exit 1 fi # Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. depfile=${depfile-`echo "$object" | sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" # Avoid interferences from the environment. gccflag= dashmflag= # Some modes work just like other modes, but use different flags. We # parameterize here, but still list the modes in the big case below, # to make depend.m4 easier to write. Note that we *cannot* use a case # here, because this file can only contain one case statement. if test "$depmode" = hp; then # HP compiler uses -M and no extra arg. gccflag=-M depmode=gcc fi if test "$depmode" = dashXmstdout; then # This is just like dashmstdout with a different argument. dashmflag=-xM depmode=dashmstdout fi cygpath_u="cygpath -u -f -" if test "$depmode" = msvcmsys; then # This is just like msvisualcpp but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvisualcpp fi if test "$depmode" = msvc7msys; then # This is just like msvc7 but w/o cygpath translation. # Just convert the backslash-escaped backslashes to single forward # slashes to satisfy depend.m4 cygpath_u='sed s,\\\\,/,g' depmode=msvc7 fi if test "$depmode" = xlc; then # IBM C/C++ Compilers xlc/xlC can output gcc-like dependency information. gccflag=-qmakedep=gcc,-MF depmode=gcc fi case "$depmode" in gcc3) ## gcc 3 implements dependency tracking that does exactly what ## we want. Yay! Note: for some reason libtool 1.4 doesn't like ## it if -MD -MP comes after the -MF stuff. Hmm. ## Unfortunately, FreeBSD c89 acceptance of flags depends upon ## the command line argument order; so add the flags where they ## appear in depend2.am. Note that the slowdown incurred here ## affects only configure: in makefiles, %FASTDEP% shortcuts this. for arg do case $arg in -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; *) set fnord "$@" "$arg" ;; esac shift # fnord shift # $arg done "$@" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi mv "$tmpdepfile" "$depfile" ;; gcc) ## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. ## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. ## (see the conditional assignment to $gccflag above). ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: ## - Don't want to use -MD because we'd like the dependencies to end ## up in a subdir. Having to rename by hand is ugly. ## (We might end up doing this anyway to support other compilers.) ## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like ## -MM, not -M (despite what the docs say). Also, it might not be ## supported by the other compilers which use the 'gcc' depmode. ## - Using -M directly means running the compiler twice (even worse ## than renaming). if test -z "$gccflag"; then gccflag=-MD, fi "$@" -Wp,"$gccflag$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The second -e expression handles DOS-style file names with drive # letters. sed -e 's/^[^:]*: / /' \ -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" ## This next piece of magic avoids the "deleted header file" problem. ## The problem is that when a header file which appears in a .P file ## is deleted, the dependency causes make to die (because there is ## typically no way to rebuild the header). We avoid this by adding ## dummy dependencies for each header file. Too bad gcc doesn't do ## this for us directly. ## Some versions of gcc put a space before the ':'. On the theory ## that the space means something, we add a space to the output as ## well. hp depmode also adds that space, but also prefixes the VPATH ## to the object. Take care to not repeat it in the output. ## Some versions of the HPUX 10.20 sed can't process this invocation ## correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e "s|.*$object$||" -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; sgi) if test "$libtool" = yes; then "$@" "-Wp,-MDupdate,$tmpdepfile" else "$@" -MDupdate "$tmpdepfile" fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files echo "$object : \\" > "$depfile" # Clip off the initial element (the dependent). Don't try to be # clever and replace this with sed code, as IRIX sed won't handle # lines with more than a fixed number of characters (4096 in # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; # the IRIX cc adds comments like '#:fec' to the end of the # dependency line. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' \ | tr "$nl" ' ' >> "$depfile" echo >> "$depfile" # The second pass generates a dummy entry for each header file. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" ;; xlc) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; aix) # The C for AIX Compiler uses -M and outputs the dependencies # in a .u file. In older versions, this file always lives in the # current directory. Also, the AIX compiler puts '$object:' at the # start of each line; $object doesn't have directory information. # Version 6 uses the directory in both cases. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.u tmpdepfile2=$base.u tmpdepfile3=$dir.libs/$base.u "$@" -Wc,-M else tmpdepfile1=$dir$base.u tmpdepfile2=$dir$base.u tmpdepfile3=$dir$base.u "$@" -M fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done aix_post_process_depfile ;; tcc) # tcc (Tiny C Compiler) understand '-MD -MF file' since version 0.9.26 # FIXME: That version still under development at the moment of writing. # Make that this statement remains true also for stable, released # versions. # It will wrap lines (doesn't matter whether long or short) with a # trailing '\', as in: # # foo.o : \ # foo.c \ # foo.h \ # # It will put a trailing '\' even on the last line, and will use leading # spaces rather than leading tabs (at least since its commit 0394caf7 # "Emit spaces for -MD"). "$@" -MD -MF "$tmpdepfile" stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each non-empty line is of the form 'foo.o : \' or ' dep.h \'. # We have to change lines of the first kind to '$object: \'. sed -e "s|.*:|$object :|" < "$tmpdepfile" > "$depfile" # And for each line of the second kind, we have to emit a 'dep.h:' # dummy dependency, to avoid the deleted-header problem. sed -n -e 's|^ *\(.*\) *\\$|\1:|p' < "$tmpdepfile" >> "$depfile" rm -f "$tmpdepfile" ;; ## The order of this option in the case statement is important, since the ## shell code in configure will try each of these formats in the order ## listed in this file. A plain '-MD' option would be understood by many ## compilers, so we must ensure this comes after the gcc and icc options. pgcc) # Portland's C compiler understands '-MD'. # Will always output deps to 'file.d' where file is the root name of the # source file under compilation, even if file resides in a subdirectory. # The object file name does not affect the name of the '.d' file. # pgcc 10.2 will output # foo.o: sub/foo.c sub/foo.h # and will wrap long lines using '\' : # foo.o: sub/foo.c ... \ # sub/foo.h ... \ # ... set_dir_from "$object" # Use the source, not the object, to determine the base name, since # that's sadly what pgcc will do too. set_base_from "$source" tmpdepfile=$base.d # For projects that build the same source file twice into different object # files, the pgcc approach of using the *source* file root name can cause # problems in parallel builds. Use a locking strategy to avoid stomping on # the same $tmpdepfile. lockdir=$base.d-lock trap " echo '$0: caught signal, cleaning up...' >&2 rmdir '$lockdir' exit 1 " 1 2 13 15 numtries=100 i=$numtries while test $i -gt 0; do # mkdir is a portable test-and-set. if mkdir "$lockdir" 2>/dev/null; then # This process acquired the lock. "$@" -MD stat=$? # Release the lock. rmdir "$lockdir" break else # If the lock is being held by a different process, wait # until the winning process is done or we timeout. while test -d "$lockdir" && test $i -gt 0; do sleep 1 i=`expr $i - 1` done fi i=`expr $i - 1` done trap - 1 2 13 15 if test $i -le 0; then echo "$0: failed to acquire lock after $numtries attempts" >&2 echo "$0: check lockdir '$lockdir'" >&2 exit 1 fi if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" # Each line is of the form `foo.o: dependent.h', # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. # Do two passes, one to just change these to # `$object: dependent.h' and one to simply `dependent.h:'. sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this invocation # correctly. Breaking it into two sed invocations is a workaround. sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; hp2) # The "hp" stanza above does not work with aCC (C++) and HP's ia64 # compilers, which have integrated preprocessors. The correct option # to use with these is +Maked; it writes dependencies to a file named # 'foo.d', which lands next to the object file, wherever that # happens to be. # Much of this is similar to the tru64 case; see comments there. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then tmpdepfile1=$dir$base.d tmpdepfile2=$dir.libs/$base.d "$@" -Wc,+Maked else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d "$@" +Maked fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" do test -f "$tmpdepfile" && break done if test -f "$tmpdepfile"; then sed -e "s,^.*\.[$lower]*:,$object:," "$tmpdepfile" > "$depfile" # Add 'dependent.h:' lines. sed -ne '2,${ s/^ *// s/ \\*$// s/$/:/ p }' "$tmpdepfile" >> "$depfile" else make_dummy_depfile fi rm -f "$tmpdepfile" "$tmpdepfile2" ;; tru64) # The Tru64 compiler uses -MD to generate dependencies as a side # effect. 'cc -MD -o foo.o ...' puts the dependencies into 'foo.o.d'. # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put # dependencies in 'foo.d' instead, so we check for that too. # Subdirectories are respected. set_dir_from "$object" set_base_from "$object" if test "$libtool" = yes; then # Libtool generates 2 separate objects for the 2 libraries. These # two compilations output dependencies in $dir.libs/$base.o.d and # in $dir$base.o.d. We have to check for both files, because # one of the two compilations can be disabled. We should prefer # $dir$base.o.d over $dir.libs/$base.o.d because the latter is # automatically cleaned when .libs/ is deleted, while ignoring # the former would cause a distcleancheck panic. tmpdepfile1=$dir$base.o.d # libtool 1.5 tmpdepfile2=$dir.libs/$base.o.d # Likewise. tmpdepfile3=$dir.libs/$base.d # Compaq CCC V6.2-504 "$@" -Wc,-MD else tmpdepfile1=$dir$base.d tmpdepfile2=$dir$base.d tmpdepfile3=$dir$base.d "$@" -MD fi stat=$? if test $stat -ne 0; then rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" exit $stat fi for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" do test -f "$tmpdepfile" && break done # Same post-processing that is required for AIX mode. aix_post_process_depfile ;; msvc7) if test "$libtool" = yes; then showIncludes=-Wc,-showIncludes else showIncludes=-showIncludes fi "$@" $showIncludes > "$tmpdepfile" stat=$? grep -v '^Note: including file: ' "$tmpdepfile" if test $stat -ne 0; then rm -f "$tmpdepfile" exit $stat fi rm -f "$depfile" echo "$object : \\" > "$depfile" # The first sed program below extracts the file names and escapes # backslashes for cygpath. The second sed program outputs the file # name when reading, but also accumulates all include files in the # hold buffer in order to output them again at the end. This only # works with sed implementations that can handle large buffers. sed < "$tmpdepfile" -n ' /^Note: including file: *\(.*\)/ { s//\1/ s/\\/\\\\/g p }' | $cygpath_u | sort -u | sed -n ' s/ /\\ /g s/\(.*\)/'"$tab"'\1 \\/p s/.\(.*\) \\/\1:/ H $ { s/.*/'"$tab"'/ G p }' >> "$depfile" echo >> "$depfile" # make sure the fragment doesn't end with a backslash rm -f "$tmpdepfile" ;; msvc7msys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; #nosideeffect) # This comment above is used by automake to tell side-effect # dependency tracking mechanisms from slower ones. dashmstdout) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout, regardless of -o. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done test -z "$dashmflag" && dashmflag=-M # Require at least two characters before searching for ':' # in the target name. This is to cope with DOS-style filenames: # a dependency such as 'c:/foo/bar' could be seen as target 'c' otherwise. "$@" $dashmflag | sed "s|^[$tab ]*[^:$tab ][^:][^:]*:[$tab ]*|$object: |" > "$tmpdepfile" rm -f "$depfile" cat < "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process this sed invocation # correctly. Breaking it into two sed invocations is a workaround. tr ' ' "$nl" < "$tmpdepfile" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; dashXmstdout) # This case only exists to satisfy depend.m4. It is never actually # run, as this mode is specially recognized in the preamble. exit 1 ;; makedepend) "$@" || exit $? # Remove any Libtool call if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # X makedepend shift cleared=no eat=no for arg do case $cleared in no) set ""; shift cleared=yes ;; esac if test $eat = yes; then eat=no continue fi case "$arg" in -D*|-I*) set fnord "$@" "$arg"; shift ;; # Strip any option that makedepend may not understand. Remove # the object too, otherwise makedepend will parse it as a source file. -arch) eat=yes ;; -*|$object) ;; *) set fnord "$@" "$arg"; shift ;; esac done obj_suffix=`echo "$object" | sed 's/^.*\././'` touch "$tmpdepfile" ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" rm -f "$depfile" # makedepend may prepend the VPATH from the source file name to the object. # No need to regex-escape $object, excess matching of '.' is harmless. sed "s|^.*\($object *:\)|\1|" "$tmpdepfile" > "$depfile" # Some versions of the HPUX 10.20 sed can't process the last invocation # correctly. Breaking it into two sed invocations is a workaround. sed '1,2d' "$tmpdepfile" \ | tr ' ' "$nl" \ | sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' \ | sed -e 's/$/ :/' >> "$depfile" rm -f "$tmpdepfile" "$tmpdepfile".bak ;; cpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi # Remove '-o $object'. IFS=" " for arg do case $arg in -o) shift ;; $object) shift ;; *) set fnord "$@" "$arg" shift # fnord shift # $arg ;; esac done "$@" -E \ | sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ | sed '$ s: \\$::' > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" cat < "$tmpdepfile" >> "$depfile" sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" rm -f "$tmpdepfile" ;; msvisualcpp) # Important note: in order to support this mode, a compiler *must* # always write the preprocessed file to stdout. "$@" || exit $? # Remove the call to Libtool. if test "$libtool" = yes; then while test "X$1" != 'X--mode=compile'; do shift done shift fi IFS=" " for arg do case "$arg" in -o) shift ;; $object) shift ;; "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") set fnord "$@" shift shift ;; *) set fnord "$@" "$arg" shift shift ;; esac done "$@" -E 2>/dev/null | sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::\1:p' | $cygpath_u | sort -u > "$tmpdepfile" rm -f "$depfile" echo "$object : \\" > "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::'"$tab"'\1 \\:p' >> "$depfile" echo "$tab" >> "$depfile" sed < "$tmpdepfile" -n -e 's% %\\ %g' -e '/^\(.*\)$/ s::\1\::p' >> "$depfile" rm -f "$tmpdepfile" ;; msvcmsys) # This case exists only to let depend.m4 do its work. It works by # looking at the text of this script. This case will never be run, # since it is checked for above. exit 1 ;; none) exec "$@" ;; *) echo "Unknown depmode $depmode" 1>&2 exit 1 ;; esac exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: softhsm-2.0.0/NEWS0000664000175000017500000001032512552214651010622 00000000000000NEWS for SoftHSM -- History of user visible changes SoftHSM 2.0.0 - 2015-07-17 * SOFTHSM-121: Test cases for C_DecryptUpdate/C_DecryptFinal. * Support C_DecryptUpdate/C_DecryptFinal for symmetric algorithms. (Patch from Thomas Calderon) Bugfixes: * SOFTHSM-120: Segfault after renaming variables. SoftHSM 2.0.0b3 - 2015-04-17 * SOFTHSM-113: Support for Botan 1.11.15 * SOFTHSM-119: softhsm2-util: Support ECDSA key import (Patch from Magnus Ahltorp) * SUPPORT-139: Support deriving generic secrets, DES, DES2, DES3, and AES. Using DH, ECDH or symmetric encryption. Bugfixes: * SOFTHSM-108: A marked as trusted certificate cannot be imported. * SOFTHSM-109: Unused parameter and variable warnings. * SOFTHSM-110: subdir-objects warnings from autoreconf. * SOFTHSM-111: Include FIPS-NOTES.md in dist. * SOFTHSM-112: CKM_AES_KEY_WRAP* conflict in pkcs11.h. * SOFTHSM-114: Fix memory leak in a test script. * SOFTHSM-115: Fix static analysis warnings. * SUPPORT-154: A marked as non-modifiable object cannot be generated. * SUPPORT-155: auto_ptr is deprecated in C++11, use unique_ptr. * SUPPORT-157: Derived secrets were truncated after encryption and could thus not be decrypted. * Mutex should call MutexFactory wrapper functions. (Patch from Jerry Lundström) * Return detailed error message to loadLibrary(). (Patch from Petr Spacek) SoftHSM 2.0.0b2 - 2014-12-28 * SOFTHSM-50: OpenSSL FIPS support. * SOFTHSM-64: Updated build script for Windows. * SOFTHSM-100: Use --free with softhsm2-util to initialize the first free token. * SOFTHSM-103: Allow runtime configuration of log level. * SOFTHSM-107: Support for CKM__CBC_PAD. * Add support for CKM_RSA_PKCS_OAEP key un/wrapping. (Patch from Petr Spacek) * Use OpenSSL EVP interface for AES key wrapping. (Patch from Petr Spacek) * Allow reading configuration file from user's home directory. (Patch from Nikos Mavrogiannopoulos) Bugfixes: * SOFTHSM-102: C_DeriveKey() uses OBJECT_OP_GENERATE. * Coverity found a number of issues. SoftHSM 2.0.0b1 - 2014-09-10 * SOFTHSM-84: Check that all mandatory attributes are given during the creation process. * SOFTHSM-92: Enable -fvisibility=hidden on per default * SUPPORT-137: Implement C_EncryptUpdate and C_EncryptFinal (Patch from Martin Paljak) * Add support for CKM_RSA_PKCS key un/wrapping (Patch from Petr Spacek) Bugfixes: * SOFTHSM-66: Attribute handling when using multiple threads * SOFTHSM-93: Invalid C++ object recycling. * SOFTHSM-95: umask affecting the calling application. * SOFTHSM-97: Check if Botan has already been initialized. * SOFTHSM-98: Handle mandatory attributes for DSA, DH, and ECDSA correctly. * SOFTHSM-99: Binary encoding of GOST values. * SUPPORT-136: softhsm2-keyconv creates files with sensitive material in insecure way. SoftHSM 2.0.0a2 - 2014-03-25 * SOFTHSM-68: Display a better configure message when there is a version of Botan with a broken ECC/GOST/OID implementation. * SOFTHSM-70: Improved handling of the database backend. * SOFTHSM-71: Supporting Botan 1.11. * SOFTHSM-76: Do not generate RSA keys smaller than 1024 bit when using the Botan crypto backend. * SOFTHSM-83: Support CKA_VALUE_BITS for CKK_DH private key object. * SOFTHSM-85: Rename libsofthsm.so to libsofthsm2.so and prefix the command line utilties with softhsm2-. * SOFTHSM-89: Use constants and not strings for signaling algorithms. * SUPPORT-129: Possible to use an empty template in C_GenerateKey. The class and key type are inherited from the generation mechanism. Some mechanisms do however require a length attribute. [SOFTHSM-88] * SUPPORT-131: Support RSA-PSS using SHA1, SHA224, SHA256, SHA384, or SHA512. [SOFTHSM-87] Bugfixes: * SOFTHSM-39: Fix 64 bit build on sparc sun4v. * SOFTHSM-69: GOST did not work when you disabled ECC. * SOFTHSM-78: Correct the attribute checks for a number of objects. * SOFTHSM-80: Prevent segfault in OpenSSL GOST HMAC code. * SOFTHSM-91: Fix a warning from static code analysis. * Fixed a number of memory leaks. SoftHSM 2.0.0a1 - 2014-02-10 This is the first alpha release of SoftHSMv2. It focuses on a higher level of security by encrypting sensitive information and using unswappable memory. There is also a more generalized crypto backend, where you can use Botan or OpenSSL. softhsm-2.0.0/install-sh0000755000175000017500000003325512552216620012132 00000000000000#!/bin/sh # install - install a program, script, or datafile scriptversion=2011-11-20.07; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the # following copyright and license. # # Copyright (C) 1994 X Consortium # # 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 # X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN # AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- # TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # Except as contained in this notice, the name of the X Consortium shall not # be used in advertising or otherwise to promote the sale, use or other deal- # ings in this Software without prior written authorization from the X Consor- # tium. # # # FSF changes to this file are in the public domain. # # Calling this script install-sh is preferred over install.sh, to prevent # 'make' implicit rules from creating a file called install from it # when there is no Makefile. # # This script is compatible with the BSD install script, but was written # from scratch. nl=' ' IFS=" "" $nl" # set DOITPROG to echo to test this script # Don't use :- since 4.3BSD and earlier shells don't like it. doit=${DOITPROG-} if test -z "$doit"; then doit_exec=exec else doit_exec=$doit fi # Put in absolute file names if you don't have them in your path; # or use environment vars. chgrpprog=${CHGRPPROG-chgrp} chmodprog=${CHMODPROG-chmod} chownprog=${CHOWNPROG-chown} cmpprog=${CMPPROG-cmp} cpprog=${CPPROG-cp} mkdirprog=${MKDIRPROG-mkdir} mvprog=${MVPROG-mv} rmprog=${RMPROG-rm} stripprog=${STRIPPROG-strip} posix_glob='?' initialize_posix_glob=' test "$posix_glob" != "?" || { if (set -f) 2>/dev/null; then posix_glob= else posix_glob=: fi } ' posix_mkdir= # Desired mode of installed file. mode=0755 chgrpcmd= chmodcmd=$chmodprog chowncmd= mvcmd=$mvprog rmcmd="$rmprog -f" stripcmd= src= dst= dir_arg= dst_arg= copy_on_change=false no_target_directory= usage="\ Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE or: $0 [OPTION]... SRCFILES... DIRECTORY or: $0 [OPTION]... -t DIRECTORY SRCFILES... or: $0 [OPTION]... -d DIRECTORIES... In the 1st form, copy SRCFILE to DSTFILE. In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. In the 4th, create DIRECTORIES. Options: --help display this help and exit. --version display version info and exit. -c (ignored) -C install only if different (preserve the last data modification time) -d create directories instead of installing files. -g GROUP $chgrpprog installed files to GROUP. -m MODE $chmodprog installed files to MODE. -o USER $chownprog installed files to USER. -s $stripprog installed files. -t DIRECTORY install into DIRECTORY. -T report an error if DSTFILE is a directory. Environment variables override the default commands: CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG " while test $# -ne 0; do case $1 in -c) ;; -C) copy_on_change=true;; -d) dir_arg=true;; -g) chgrpcmd="$chgrpprog $2" shift;; --help) echo "$usage"; exit $?;; -m) mode=$2 case $mode in *' '* | *' '* | *' '* | *'*'* | *'?'* | *'['*) echo "$0: invalid mode: $mode" >&2 exit 1;; esac shift;; -o) chowncmd="$chownprog $2" shift;; -s) stripcmd=$stripprog;; -t) dst_arg=$2 # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac shift;; -T) no_target_directory=true;; --version) echo "$0 $scriptversion"; exit $?;; --) shift break;; -*) echo "$0: invalid option: $1" >&2 exit 1;; *) break;; esac shift done if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then # When -d is used, all remaining arguments are directories to create. # When -t is used, the destination is already specified. # Otherwise, the last argument is the destination. Remove it from $@. for arg do if test -n "$dst_arg"; then # $@ is not empty: it contains at least $arg. set fnord "$@" "$dst_arg" shift # fnord fi shift # arg dst_arg=$arg # Protect names problematic for 'test' and other utilities. case $dst_arg in -* | [=\(\)!]) dst_arg=./$dst_arg;; esac done fi if test $# -eq 0; then if test -z "$dir_arg"; then echo "$0: no input file specified." >&2 exit 1 fi # It's OK to call 'install-sh -d' without argument. # This can happen when creating conditional directories. exit 0 fi if test -z "$dir_arg"; then do_exit='(exit $ret); exit $ret' trap "ret=129; $do_exit" 1 trap "ret=130; $do_exit" 2 trap "ret=141; $do_exit" 13 trap "ret=143; $do_exit" 15 # Set umask so as not to create temps with too-generous modes. # However, 'strip' requires both read and write access to temps. case $mode in # Optimize common cases. *644) cp_umask=133;; *755) cp_umask=22;; *[0-7]) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw='% 200' fi cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; *) if test -z "$stripcmd"; then u_plus_rw= else u_plus_rw=,u+rw fi cp_umask=$mode$u_plus_rw;; esac fi for src do # Protect names problematic for 'test' and other utilities. case $src in -* | [=\(\)!]) src=./$src;; esac if test -n "$dir_arg"; then dst=$src dstdir=$dst test -d "$dstdir" dstdir_status=$? else # Waiting for this to be detected by the "$cpprog $src $dsttmp" command # might cause directories to be created, which would be especially bad # if $src (and thus $dsttmp) contains '*'. if test ! -f "$src" && test ! -d "$src"; then echo "$0: $src does not exist." >&2 exit 1 fi if test -z "$dst_arg"; then echo "$0: no destination specified." >&2 exit 1 fi dst=$dst_arg # If destination is a directory, append the input filename; won't work # if double slashes aren't ignored. if test -d "$dst"; then if test -n "$no_target_directory"; then echo "$0: $dst_arg: Is a directory" >&2 exit 1 fi dstdir=$dst dst=$dstdir/`basename "$src"` dstdir_status=0 else # Prefer dirname, but fall back on a substitute if dirname fails. dstdir=` (dirname "$dst") 2>/dev/null || expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$dst" : 'X\(//\)[^/]' \| \ X"$dst" : 'X\(//\)$' \| \ X"$dst" : 'X\(/\)' \| . 2>/dev/null || echo X"$dst" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q' ` test -d "$dstdir" dstdir_status=$? fi fi obsolete_mkdir_used=false if test $dstdir_status != 0; then case $posix_mkdir in '') # Create intermediate dirs using mode 755 as modified by the umask. # This is like FreeBSD 'install' as of 1997-10-28. umask=`umask` case $stripcmd.$umask in # Optimize common cases. *[2367][2367]) mkdir_umask=$umask;; .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; *[0-7]) mkdir_umask=`expr $umask + 22 \ - $umask % 100 % 40 + $umask % 20 \ - $umask % 10 % 4 + $umask % 2 `;; *) mkdir_umask=$umask,go-w;; esac # With -d, create the new directory with the user-specified mode. # Otherwise, rely on $mkdir_umask. if test -n "$dir_arg"; then mkdir_mode=-m$mode else mkdir_mode= fi posix_mkdir=false case $umask in *[123567][0-7][0-7]) # POSIX mkdir -p sets u+wx bits regardless of umask, which # is incompatible with FreeBSD 'install' when (umask & 300) != 0. ;; *) tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 if (umask $mkdir_umask && exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 then if test -z "$dir_arg" || { # Check for POSIX incompatibilities with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. ls_ld_tmpdir=`ls -ld "$tmpdir"` case $ls_ld_tmpdir in d????-?r-*) different_mode=700;; d????-?--*) different_mode=755;; *) false;; esac && $mkdirprog -m$different_mode -p -- "$tmpdir" && { ls_ld_tmpdir_1=`ls -ld "$tmpdir"` test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" } } then posix_mkdir=: fi rmdir "$tmpdir/d" "$tmpdir" else # Remove any dirs left behind by ancient mkdir implementations. rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null fi trap '' 0;; esac;; esac if $posix_mkdir && ( umask $mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" ) then : else # The umask is ridiculous, or mkdir does not conform to POSIX, # or it failed possibly due to a race condition. Create the # directory the slow way, step by step, checking for races as we go. case $dstdir in /*) prefix='/';; [-=\(\)!]*) prefix='./';; *) prefix='';; esac eval "$initialize_posix_glob" oIFS=$IFS IFS=/ $posix_glob set -f set fnord $dstdir shift $posix_glob set +f IFS=$oIFS prefixes= for d do test X"$d" = X && continue prefix=$prefix$d if test -d "$prefix"; then prefixes= else if $posix_mkdir; then (umask=$mkdir_umask && $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break # Don't fail if two instances are running concurrently. test -d "$prefix" || exit 1 else case $prefix in *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; *) qprefix=$prefix;; esac prefixes="$prefixes '$qprefix'" fi fi prefix=$prefix/ done if test -n "$prefixes"; then # Don't fail if two instances are running concurrently. (umask $mkdir_umask && eval "\$doit_exec \$mkdirprog $prefixes") || test -d "$dstdir" || exit 1 obsolete_mkdir_used=true fi fi fi if test -n "$dir_arg"; then { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 else # Make a couple of temp file names in the proper directory. dsttmp=$dstdir/_inst.$$_ rmtmp=$dstdir/_rm.$$_ # Trap to clean up those temp files at exit. trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 # Copy the file name to the temp name. (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && # and set any options; do chmod last to preserve setuid bits. # # If any of these fail, we abort the whole thing. If we want to # ignore errors from any of these, just make sure not to ignore # errors from the above "$doit $cpprog $src $dsttmp" command. # { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && # If -C, don't bother to copy if it wouldn't change the file. if $copy_on_change && old=`LC_ALL=C ls -dlL "$dst" 2>/dev/null` && new=`LC_ALL=C ls -dlL "$dsttmp" 2>/dev/null` && eval "$initialize_posix_glob" && $posix_glob set -f && set X $old && old=:$2:$4:$5:$6 && set X $new && new=:$2:$4:$5:$6 && $posix_glob set +f && test "$old" = "$new" && $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1 then rm -f "$dsttmp" else # Rename the file to the real destination. $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null || # The rename failed, perhaps because mv can't rename something else # to itself, or perhaps because mv is so ancient that it does not # support -f. { # Now remove or move aside any old file at destination location. # We try this two ways since rm can't unlink itself on some # systems and the destination file might be busy for other # reasons. In this case, the final cleanup might fail but the new # file should still install successfully. { test ! -f "$dst" || $doit $rmcmd -f "$dst" 2>/dev/null || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; } } || { echo "$0: cannot unlink or rename $dst" >&2 (exit 1); exit 1 } } && # Now rename the file to the real destination. $doit $mvcmd "$dsttmp" "$dst" } fi || exit 1 trap '' 0 fi done # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: softhsm-2.0.0/LICENSE0000664000175000017500000000255512533040716011134 00000000000000Copyright (c) 2010 .SE, The Internet Infrastructure Foundation http://www.iis.se Copyright (c) 2010 SURFnet bv http://www.surfnet.nl/en 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. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. softhsm-2.0.0/Makefile.am0000664000175000017500000000524612533040716012163 00000000000000ACLOCAL_AMFLAGS = -I m4 MAINTAINERCLEANFILES = \ config.log config.status \ $(srcdir)/Makefile.in \ $(srcdir)/config.h.in $(srcdir)/config.h.in~ \ $(srcdir)/configure \ $(srcdir)/install-sh $(srcdir)/ltmain.sh $(srcdir)/missing \ $(srcdir)/depcomp $(srcdir)/aclocal.m4 $(srcdir)/compile \ $(srcdir)/config.guess $(srcdir)/config.sub SUBDIRS = src EXTRA_DIST = $(srcdir)/aes_wrap_key_with_pad/botan-diff \ $(srcdir)/aes_wrap_key_with_pad/README \ $(srcdir)/FIPS-NOTES.md \ $(srcdir)/LICENSE \ $(srcdir)/m4/*.m4 \ $(srcdir)/OSX-NOTES.md \ $(srcdir)/README.md \ $(srcdir)/win32/config.h.in \ $(srcdir)/win32/Configure.pl \ $(srcdir)/win32/Configure.py \ $(srcdir)/win32/convarch/convarch.vcxproj.in \ $(srcdir)/win32/convarch/convarch.vcxproj.filters.in \ $(srcdir)/win32/convarch/convarch.vcxproj.user \ $(srcdir)/win32/cryptotest/cryptotest.vcxproj.in \ $(srcdir)/win32/cryptotest/cryptotest.vcxproj.filters \ $(srcdir)/win32/cryptotest/cryptotest.vcxproj.user \ $(srcdir)/win32/datamgrtest/datamgrtest.vcxproj.in \ $(srcdir)/win32/datamgrtest/datamgrtest.vcxproj.filters \ $(srcdir)/win32/datamgrtest/datamgrtest.vcxproj.user \ $(srcdir)/win32/dump/dump.vcxproj.in \ $(srcdir)/win32/dump/dump.vcxproj.filters \ $(srcdir)/win32/dump/dump.vcxproj.user \ $(srcdir)/win32/handlemgrtest/handlemgrtest.vcxproj.in \ $(srcdir)/win32/handlemgrtest/handlemgrtest.vcxproj.filters \ $(srcdir)/win32/handlemgrtest/handlemgrtest.vcxproj.user \ $(srcdir)/win32/keyconv/keyconv.vcxproj.in \ $(srcdir)/win32/keyconv/keyconv.vcxproj.filters.in \ $(srcdir)/win32/keyconv/keyconv.vcxproj.user \ $(srcdir)/win32/objstoretest/objstoretest.vcxproj.in \ $(srcdir)/win32/objstoretest/objstoretest.vcxproj.filters \ $(srcdir)/win32/objstoretest/objstoretest.vcxproj.user \ $(srcdir)/win32/p11test/p11test.vcxproj.in \ $(srcdir)/win32/p11test/p11test.vcxproj.filters \ $(srcdir)/win32/p11test/p11test.vcxproj.user \ $(srcdir)/win32/sessionmgrtest/sessionmgrtest.vcxproj.in \ $(srcdir)/win32/sessionmgrtest/sessionmgrtest.vcxproj.filters \ $(srcdir)/win32/sessionmgrtest/sessionmgrtest.vcxproj.user \ $(srcdir)/win32/slotmgrtest/slotmgrtest.vcxproj.in \ $(srcdir)/win32/slotmgrtest/slotmgrtest.vcxproj.filters \ $(srcdir)/win32/slotmgrtest/slotmgrtest.vcxproj.user \ $(srcdir)/win32/softhsm2/softhsm2.vcxproj.in \ $(srcdir)/win32/softhsm2/softhsm2.vcxproj.filters \ $(srcdir)/win32/softhsm2/softhsm2.vcxproj.user \ $(srcdir)/win32/softhsm2.sln.in \ $(srcdir)/win32/util/util.vcxproj.in \ $(srcdir)/win32/util/util.vcxproj.filters.in \ $(srcdir)/win32/util/util.vcxproj.user \ $(srcdir)/WIN32-NOTES.md softhsm-2.0.0/config.sub0000755000175000017500000010535412552216620012111 00000000000000#! /bin/sh # Configuration validation subroutine script. # Copyright 1992-2013 Free Software Foundation, Inc. timestamp='2013-08-10' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # Please send patches with a ChangeLog entry to config-patches@gnu.org. # # Configuration subroutine to validate and canonicalize a configuration type. # Supply the specified configuration type as an argument. # If it is invalid, we print an error message on stderr and exit with code 1. # Otherwise, we print the canonical config type on stdout and succeed. # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD # This file is supposed to be the same for all GNU packages # and recognize all the CPU types, system types and aliases # that are meaningful with *any* GNU software. # Each package is responsible for reporting which valid configurations # it does not support. The user should be able to distinguish # a failure to support a valid configuration from a meaningless # configuration. # The goal of this file is to map all the various variations of a given # machine specification into a single specification in the form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM # or in some cases, the newer four-part form: # CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM # It is wrong to echo any other type of specification. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] CPU-MFR-OPSYS $0 [OPTION] ALIAS Canonicalize a configuration name. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.sub ($timestamp) Copyright 1992-2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" exit 1 ;; *local*) # First pass through any local machine types. echo $1 exit ;; * ) break ;; esac done case $# in 0) echo "$me: missing argument$help" >&2 exit 1;; 1) ;; *) echo "$me: too many arguments$help" >&2 exit 1;; esac # Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). # Here we must recognize all the valid KERNEL-OS combinations. maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` case $maybe_os in nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \ linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \ knetbsd*-gnu* | netbsd*-gnu* | \ kopensolaris*-gnu* | \ storm-chaos* | os2-emx* | rtmk-nova*) os=-$maybe_os basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` ;; android-linux) os=-linux-android basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown ;; *) basic_machine=`echo $1 | sed 's/-[^-]*$//'` if [ $basic_machine != $1 ] then os=`echo $1 | sed 's/.*-/-/'` else os=; fi ;; esac ### Let's recognize common machines as not being operating systems so ### that things like config.sub decstation-3100 work. We also ### recognize some manufacturers as not being operating systems, so we ### can provide default operating systems below. case $os in -sun*os*) # Prevent following clause from handling this invalid input. ;; -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ -apple | -axis | -knuth | -cray | -microblaze*) os= basic_machine=$1 ;; -bluegene*) os=-cnk ;; -sim | -cisco | -oki | -wec | -winbond) os= basic_machine=$1 ;; -scout) ;; -wrs) os=-vxworks basic_machine=$1 ;; -chorusos*) os=-chorusos basic_machine=$1 ;; -chorusrdb) os=-chorusrdb basic_machine=$1 ;; -hiux*) os=-hiuxwe2 ;; -sco6) os=-sco5v6 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5) os=-sco3.2v5 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco4) os=-sco3.2v4 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2.[4-9]*) os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco3.2v[4-9]*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco5v6*) # Don't forget version if it is 3.2v4 or newer. basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -sco*) os=-sco3.2v2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -udk*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -isc) os=-isc2.2 basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -clix*) basic_machine=clipper-intergraph ;; -isc*) basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` ;; -lynx*178) os=-lynxos178 ;; -lynx*5) os=-lynxos5 ;; -lynx*) os=-lynxos ;; -ptx*) basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` ;; -windowsnt*) os=`echo $os | sed -e 's/windowsnt/winnt/'` ;; -psos*) os=-psos ;; -mint | -mint[0-9]*) basic_machine=m68k-atari os=-mint ;; esac # Decode aliases for certain CPU-COMPANY combinations. case $basic_machine in # Recognize the basic CPU types without company name. # Some are omitted here because they have special meanings below. 1750a | 580 \ | a29k \ | aarch64 | aarch64_be \ | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ | am33_2.0 \ | arc | arceb \ | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \ | avr | avr32 \ | be32 | be64 \ | bfin \ | c4x | c8051 | clipper \ | d10v | d30v | dlx | dsp16xx \ | epiphany \ | fido | fr30 | frv \ | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ | hexagon \ | i370 | i860 | i960 | ia64 \ | ip2k | iq2000 \ | le32 | le64 \ | lm32 \ | m32c | m32r | m32rle | m68000 | m68k | m88k \ | maxq | mb | microblaze | microblazeel | mcore | mep | metag \ | mips | mipsbe | mipseb | mipsel | mipsle \ | mips16 \ | mips64 | mips64el \ | mips64octeon | mips64octeonel \ | mips64orion | mips64orionel \ | mips64r5900 | mips64r5900el \ | mips64vr | mips64vrel \ | mips64vr4100 | mips64vr4100el \ | mips64vr4300 | mips64vr4300el \ | mips64vr5000 | mips64vr5000el \ | mips64vr5900 | mips64vr5900el \ | mipsisa32 | mipsisa32el \ | mipsisa32r2 | mipsisa32r2el \ | mipsisa64 | mipsisa64el \ | mipsisa64r2 | mipsisa64r2el \ | mipsisa64sb1 | mipsisa64sb1el \ | mipsisa64sr71k | mipsisa64sr71kel \ | mipsr5900 | mipsr5900el \ | mipstx39 | mipstx39el \ | mn10200 | mn10300 \ | moxie \ | mt \ | msp430 \ | nds32 | nds32le | nds32be \ | nios | nios2 | nios2eb | nios2el \ | ns16k | ns32k \ | open8 \ | or1k | or32 \ | pdp10 | pdp11 | pj | pjl \ | powerpc | powerpc64 | powerpc64le | powerpcle \ | pyramid \ | rl78 | rx \ | score \ | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ | sh64 | sh64le \ | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ | spu \ | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \ | ubicom32 \ | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \ | we32k \ | x86 | xc16x | xstormy16 | xtensa \ | z8k | z80) basic_machine=$basic_machine-unknown ;; c54x) basic_machine=tic54x-unknown ;; c55x) basic_machine=tic55x-unknown ;; c6x) basic_machine=tic6x-unknown ;; m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | picochip) basic_machine=$basic_machine-unknown os=-none ;; m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) ;; ms1) basic_machine=mt-unknown ;; strongarm | thumb | xscale) basic_machine=arm-unknown ;; xgate) basic_machine=$basic_machine-unknown os=-none ;; xscaleeb) basic_machine=armeb-unknown ;; xscaleel) basic_machine=armel-unknown ;; # We use `pc' rather than `unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) basic_machine=$basic_machine-pc ;; # Object if more than one company name word. *-*-*) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; # Recognize the basic CPU types with company name. 580-* \ | a29k-* \ | aarch64-* | aarch64_be-* \ | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \ | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ | avr-* | avr32-* \ | be32-* | be64-* \ | bfin-* | bs2000-* \ | c[123]* | c30-* | [cjt]90-* | c4x-* \ | c8051-* | clipper-* | craynv-* | cydra-* \ | d10v-* | d30v-* | dlx-* \ | elxsi-* \ | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ | h8300-* | h8500-* \ | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ | hexagon-* \ | i*86-* | i860-* | i960-* | ia64-* \ | ip2k-* | iq2000-* \ | le32-* | le64-* \ | lm32-* \ | m32c-* | m32r-* | m32rle-* \ | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ | m88110-* | m88k-* | maxq-* | mcore-* | metag-* \ | microblaze-* | microblazeel-* \ | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ | mips16-* \ | mips64-* | mips64el-* \ | mips64octeon-* | mips64octeonel-* \ | mips64orion-* | mips64orionel-* \ | mips64r5900-* | mips64r5900el-* \ | mips64vr-* | mips64vrel-* \ | mips64vr4100-* | mips64vr4100el-* \ | mips64vr4300-* | mips64vr4300el-* \ | mips64vr5000-* | mips64vr5000el-* \ | mips64vr5900-* | mips64vr5900el-* \ | mipsisa32-* | mipsisa32el-* \ | mipsisa32r2-* | mipsisa32r2el-* \ | mipsisa64-* | mipsisa64el-* \ | mipsisa64r2-* | mipsisa64r2el-* \ | mipsisa64sb1-* | mipsisa64sb1el-* \ | mipsisa64sr71k-* | mipsisa64sr71kel-* \ | mipsr5900-* | mipsr5900el-* \ | mipstx39-* | mipstx39el-* \ | mmix-* \ | mt-* \ | msp430-* \ | nds32-* | nds32le-* | nds32be-* \ | nios-* | nios2-* | nios2eb-* | nios2el-* \ | none-* | np1-* | ns16k-* | ns32k-* \ | open8-* \ | orion-* \ | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \ | pyramid-* \ | rl78-* | romp-* | rs6000-* | rx-* \ | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ | sparclite-* \ | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \ | tahoe-* \ | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ | tile*-* \ | tron-* \ | ubicom32-* \ | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \ | vax-* \ | we32k-* \ | x86-* | x86_64-* | xc16x-* | xps100-* \ | xstormy16-* | xtensa*-* \ | ymp-* \ | z8k-* | z80-*) ;; # Recognize the basic CPU types without company name, with glob match. xtensa*) basic_machine=$basic_machine-unknown ;; # Recognize the various machine names and aliases which stand # for a CPU type and a company and sometimes even an OS. 386bsd) basic_machine=i386-unknown os=-bsd ;; 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) basic_machine=m68000-att ;; 3b*) basic_machine=we32k-att ;; a29khif) basic_machine=a29k-amd os=-udi ;; abacus) basic_machine=abacus-unknown ;; adobe68k) basic_machine=m68010-adobe os=-scout ;; alliant | fx80) basic_machine=fx80-alliant ;; altos | altos3068) basic_machine=m68k-altos ;; am29k) basic_machine=a29k-none os=-bsd ;; amd64) basic_machine=x86_64-pc ;; amd64-*) basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; amdahl) basic_machine=580-amdahl os=-sysv ;; amiga | amiga-*) basic_machine=m68k-unknown ;; amigaos | amigados) basic_machine=m68k-unknown os=-amigaos ;; amigaunix | amix) basic_machine=m68k-unknown os=-sysv4 ;; apollo68) basic_machine=m68k-apollo os=-sysv ;; apollo68bsd) basic_machine=m68k-apollo os=-bsd ;; aros) basic_machine=i386-pc os=-aros ;; aux) basic_machine=m68k-apple os=-aux ;; balance) basic_machine=ns32k-sequent os=-dynix ;; blackfin) basic_machine=bfin-unknown os=-linux ;; blackfin-*) basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; bluegene*) basic_machine=powerpc-ibm os=-cnk ;; c54x-*) basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c55x-*) basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c6x-*) basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'` ;; c90) basic_machine=c90-cray os=-unicos ;; cegcc) basic_machine=arm-unknown os=-cegcc ;; convex-c1) basic_machine=c1-convex os=-bsd ;; convex-c2) basic_machine=c2-convex os=-bsd ;; convex-c32) basic_machine=c32-convex os=-bsd ;; convex-c34) basic_machine=c34-convex os=-bsd ;; convex-c38) basic_machine=c38-convex os=-bsd ;; cray | j90) basic_machine=j90-cray os=-unicos ;; craynv) basic_machine=craynv-cray os=-unicosmp ;; cr16 | cr16-*) basic_machine=cr16-unknown os=-elf ;; crds | unos) basic_machine=m68k-crds ;; crisv32 | crisv32-* | etraxfs*) basic_machine=crisv32-axis ;; cris | cris-* | etrax*) basic_machine=cris-axis ;; crx) basic_machine=crx-unknown os=-elf ;; da30 | da30-*) basic_machine=m68k-da30 ;; decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) basic_machine=mips-dec ;; decsystem10* | dec10*) basic_machine=pdp10-dec os=-tops10 ;; decsystem20* | dec20*) basic_machine=pdp10-dec os=-tops20 ;; delta | 3300 | motorola-3300 | motorola-delta \ | 3300-motorola | delta-motorola) basic_machine=m68k-motorola ;; delta88) basic_machine=m88k-motorola os=-sysv3 ;; dicos) basic_machine=i686-pc os=-dicos ;; djgpp) basic_machine=i586-pc os=-msdosdjgpp ;; dpx20 | dpx20-*) basic_machine=rs6000-bull os=-bosx ;; dpx2* | dpx2*-bull) basic_machine=m68k-bull os=-sysv3 ;; ebmon29k) basic_machine=a29k-amd os=-ebmon ;; elxsi) basic_machine=elxsi-elxsi os=-bsd ;; encore | umax | mmax) basic_machine=ns32k-encore ;; es1800 | OSE68k | ose68k | ose | OSE) basic_machine=m68k-ericsson os=-ose ;; fx2800) basic_machine=i860-alliant ;; genix) basic_machine=ns32k-ns ;; gmicro) basic_machine=tron-gmicro os=-sysv ;; go32) basic_machine=i386-pc os=-go32 ;; h3050r* | hiux*) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; h8300hms) basic_machine=h8300-hitachi os=-hms ;; h8300xray) basic_machine=h8300-hitachi os=-xray ;; h8500hms) basic_machine=h8500-hitachi os=-hms ;; harris) basic_machine=m88k-harris os=-sysv3 ;; hp300-*) basic_machine=m68k-hp ;; hp300bsd) basic_machine=m68k-hp os=-bsd ;; hp300hpux) basic_machine=m68k-hp os=-hpux ;; hp3k9[0-9][0-9] | hp9[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k2[0-9][0-9] | hp9k31[0-9]) basic_machine=m68000-hp ;; hp9k3[2-9][0-9]) basic_machine=m68k-hp ;; hp9k6[0-9][0-9] | hp6[0-9][0-9]) basic_machine=hppa1.0-hp ;; hp9k7[0-79][0-9] | hp7[0-79][0-9]) basic_machine=hppa1.1-hp ;; hp9k78[0-9] | hp78[0-9]) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) # FIXME: really hppa2.0-hp basic_machine=hppa1.1-hp ;; hp9k8[0-9][13679] | hp8[0-9][13679]) basic_machine=hppa1.1-hp ;; hp9k8[0-9][0-9] | hp8[0-9][0-9]) basic_machine=hppa1.0-hp ;; hppa-next) os=-nextstep3 ;; hppaosf) basic_machine=hppa1.1-hp os=-osf ;; hppro) basic_machine=hppa1.1-hp os=-proelf ;; i370-ibm* | ibm*) basic_machine=i370-ibm ;; i*86v32) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv32 ;; i*86v4*) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv4 ;; i*86v) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-sysv ;; i*86sol2) basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` os=-solaris2 ;; i386mach) basic_machine=i386-mach os=-mach ;; i386-vsta | vsta) basic_machine=i386-unknown os=-vsta ;; iris | iris4d) basic_machine=mips-sgi case $os in -irix*) ;; *) os=-irix4 ;; esac ;; isi68 | isi) basic_machine=m68k-isi os=-sysv ;; m68knommu) basic_machine=m68k-unknown os=-linux ;; m68knommu-*) basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; m88k-omron*) basic_machine=m88k-omron ;; magnum | m3230) basic_machine=mips-mips os=-sysv ;; merlin) basic_machine=ns32k-utek os=-sysv ;; microblaze*) basic_machine=microblaze-xilinx ;; mingw64) basic_machine=x86_64-pc os=-mingw64 ;; mingw32) basic_machine=i686-pc os=-mingw32 ;; mingw32ce) basic_machine=arm-unknown os=-mingw32ce ;; miniframe) basic_machine=m68000-convergent ;; *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) basic_machine=m68k-atari os=-mint ;; mips3*-*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` ;; mips3*) basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown ;; monitor) basic_machine=m68k-rom68k os=-coff ;; morphos) basic_machine=powerpc-unknown os=-morphos ;; msdos) basic_machine=i386-pc os=-msdos ;; ms1-*) basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` ;; msys) basic_machine=i686-pc os=-msys ;; mvs) basic_machine=i370-ibm os=-mvs ;; nacl) basic_machine=le32-unknown os=-nacl ;; ncr3000) basic_machine=i486-ncr os=-sysv4 ;; netbsd386) basic_machine=i386-unknown os=-netbsd ;; netwinder) basic_machine=armv4l-rebel os=-linux ;; news | news700 | news800 | news900) basic_machine=m68k-sony os=-newsos ;; news1000) basic_machine=m68030-sony os=-newsos ;; news-3600 | risc-news) basic_machine=mips-sony os=-newsos ;; necv70) basic_machine=v70-nec os=-sysv ;; next | m*-next ) basic_machine=m68k-next case $os in -nextstep* ) ;; -ns2*) os=-nextstep2 ;; *) os=-nextstep3 ;; esac ;; nh3000) basic_machine=m68k-harris os=-cxux ;; nh[45]000) basic_machine=m88k-harris os=-cxux ;; nindy960) basic_machine=i960-intel os=-nindy ;; mon960) basic_machine=i960-intel os=-mon960 ;; nonstopux) basic_machine=mips-compaq os=-nonstopux ;; np1) basic_machine=np1-gould ;; neo-tandem) basic_machine=neo-tandem ;; nse-tandem) basic_machine=nse-tandem ;; nsr-tandem) basic_machine=nsr-tandem ;; op50n-* | op60c-*) basic_machine=hppa1.1-oki os=-proelf ;; openrisc | openrisc-*) basic_machine=or32-unknown ;; os400) basic_machine=powerpc-ibm os=-os400 ;; OSE68000 | ose68000) basic_machine=m68000-ericsson os=-ose ;; os68k) basic_machine=m68k-none os=-os68k ;; pa-hitachi) basic_machine=hppa1.1-hitachi os=-hiuxwe2 ;; paragon) basic_machine=i860-intel os=-osf ;; parisc) basic_machine=hppa-unknown os=-linux ;; parisc-*) basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` os=-linux ;; pbd) basic_machine=sparc-tti ;; pbb) basic_machine=m68k-tti ;; pc532 | pc532-*) basic_machine=ns32k-pc532 ;; pc98) basic_machine=i386-pc ;; pc98-*) basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium | p5 | k5 | k6 | nexgen | viac3) basic_machine=i586-pc ;; pentiumpro | p6 | 6x86 | athlon | athlon_*) basic_machine=i686-pc ;; pentiumii | pentium2 | pentiumiii | pentium3) basic_machine=i686-pc ;; pentium4) basic_machine=i786-pc ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumpro-* | p6-* | 6x86-* | athlon-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pentium4-*) basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` ;; pn) basic_machine=pn-gould ;; power) basic_machine=power-ibm ;; ppc | ppcbe) basic_machine=powerpc-unknown ;; ppc-* | ppcbe-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppcle | powerpclittle | ppc-le | powerpc-little) basic_machine=powerpcle-unknown ;; ppcle-* | powerpclittle-*) basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64) basic_machine=powerpc64-unknown ;; ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ppc64le | powerpc64little | ppc64-le | powerpc64-little) basic_machine=powerpc64le-unknown ;; ppc64le-* | powerpc64little-*) basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` ;; ps2) basic_machine=i386-ibm ;; pw32) basic_machine=i586-unknown os=-pw32 ;; rdos | rdos64) basic_machine=x86_64-pc os=-rdos ;; rdos32) basic_machine=i386-pc os=-rdos ;; rom68k) basic_machine=m68k-rom68k os=-coff ;; rm[46]00) basic_machine=mips-siemens ;; rtpc | rtpc-*) basic_machine=romp-ibm ;; s390 | s390-*) basic_machine=s390-ibm ;; s390x | s390x-*) basic_machine=s390x-ibm ;; sa29200) basic_machine=a29k-amd os=-udi ;; sb1) basic_machine=mipsisa64sb1-unknown ;; sb1el) basic_machine=mipsisa64sb1el-unknown ;; sde) basic_machine=mipsisa32-sde os=-elf ;; sei) basic_machine=mips-sei os=-seiux ;; sequent) basic_machine=i386-sequent ;; sh) basic_machine=sh-hitachi os=-hms ;; sh5el) basic_machine=sh5le-unknown ;; sh64) basic_machine=sh64-unknown ;; sparclite-wrs | simso-wrs) basic_machine=sparclite-wrs os=-vxworks ;; sps7) basic_machine=m68k-bull os=-sysv2 ;; spur) basic_machine=spur-unknown ;; st2000) basic_machine=m68k-tandem ;; stratus) basic_machine=i860-stratus os=-sysv4 ;; strongarm-* | thumb-*) basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'` ;; sun2) basic_machine=m68000-sun ;; sun2os3) basic_machine=m68000-sun os=-sunos3 ;; sun2os4) basic_machine=m68000-sun os=-sunos4 ;; sun3os3) basic_machine=m68k-sun os=-sunos3 ;; sun3os4) basic_machine=m68k-sun os=-sunos4 ;; sun4os3) basic_machine=sparc-sun os=-sunos3 ;; sun4os4) basic_machine=sparc-sun os=-sunos4 ;; sun4sol2) basic_machine=sparc-sun os=-solaris2 ;; sun3 | sun3-*) basic_machine=m68k-sun ;; sun4) basic_machine=sparc-sun ;; sun386 | sun386i | roadrunner) basic_machine=i386-sun ;; sv1) basic_machine=sv1-cray os=-unicos ;; symmetry) basic_machine=i386-sequent os=-dynix ;; t3e) basic_machine=alphaev5-cray os=-unicos ;; t90) basic_machine=t90-cray os=-unicos ;; tile*) basic_machine=$basic_machine-unknown os=-linux-gnu ;; tx39) basic_machine=mipstx39-unknown ;; tx39el) basic_machine=mipstx39el-unknown ;; toad1) basic_machine=pdp10-xkl os=-tops20 ;; tower | tower-32) basic_machine=m68k-ncr ;; tpf) basic_machine=s390x-ibm os=-tpf ;; udi29k) basic_machine=a29k-amd os=-udi ;; ultra3) basic_machine=a29k-nyu os=-sym1 ;; v810 | necv810) basic_machine=v810-nec os=-none ;; vaxv) basic_machine=vax-dec os=-sysv ;; vms) basic_machine=vax-dec os=-vms ;; vpp*|vx|vx-*) basic_machine=f301-fujitsu ;; vxworks960) basic_machine=i960-wrs os=-vxworks ;; vxworks68) basic_machine=m68k-wrs os=-vxworks ;; vxworks29k) basic_machine=a29k-wrs os=-vxworks ;; w65*) basic_machine=w65-wdc os=-none ;; w89k-*) basic_machine=hppa1.1-winbond os=-proelf ;; xbox) basic_machine=i686-pc os=-mingw32 ;; xps | xps100) basic_machine=xps100-honeywell ;; xscale-* | xscalee[bl]-*) basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'` ;; ymp) basic_machine=ymp-cray os=-unicos ;; z8k-*-coff) basic_machine=z8k-unknown os=-sim ;; z80-*-coff) basic_machine=z80-unknown os=-sim ;; none) basic_machine=none-none os=-none ;; # Here we handle the default manufacturer of certain CPU types. It is in # some cases the only manufacturer, in others, it is the most popular. w89k) basic_machine=hppa1.1-winbond ;; op50n) basic_machine=hppa1.1-oki ;; op60c) basic_machine=hppa1.1-oki ;; romp) basic_machine=romp-ibm ;; mmix) basic_machine=mmix-knuth ;; rs6000) basic_machine=rs6000-ibm ;; vax) basic_machine=vax-dec ;; pdp10) # there are many clones, so DEC is not a safe bet basic_machine=pdp10-unknown ;; pdp11) basic_machine=pdp11-dec ;; we32k) basic_machine=we32k-att ;; sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) basic_machine=sh-unknown ;; sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) basic_machine=sparc-sun ;; cydra) basic_machine=cydra-cydrome ;; orion) basic_machine=orion-highlevel ;; orion105) basic_machine=clipper-highlevel ;; mac | mpw | mac-mpw) basic_machine=m68k-apple ;; pmac | pmac-mpw) basic_machine=powerpc-apple ;; *-unknown) # Make sure to match an already-canonicalized machine name. ;; *) echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 exit 1 ;; esac # Here we canonicalize certain aliases for manufacturers. case $basic_machine in *-digital*) basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` ;; *-commodore*) basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` ;; *) ;; esac # Decode manufacturer-specific aliases for certain operating systems. if [ x"$os" != x"" ] then case $os in # First match some system type aliases # that might get confused with valid system types. # -solaris* is a basic system type, with this one exception. -auroraux) os=-auroraux ;; -solaris1 | -solaris1.*) os=`echo $os | sed -e 's|solaris1|sunos4|'` ;; -solaris) os=-solaris2 ;; -svr4*) os=-sysv4 ;; -unixware*) os=-sysv4.2uw ;; -gnu/linux*) os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` ;; # First accept the basic system types. # The portable systems comes first. # Each alternative MUST END IN A *, to match a version number. # -sysv* is not here because it comes later, after sysvr4. -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ | -sym* | -kopensolaris* | -plan9* \ | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ | -aos* | -aros* \ | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ | -bitrig* | -openbsd* | -solidbsd* \ | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ | -chorusos* | -chorusrdb* | -cegcc* \ | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \ | -linux-newlib* | -linux-musl* | -linux-uclibc* \ | -uxpv* | -beos* | -mpeix* | -udk* \ | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) # Remember, each alternative MUST END IN *, to match a version number. ;; -qnx*) case $basic_machine in x86-* | i*86-*) ;; *) os=-nto$os ;; esac ;; -nto-qnx*) ;; -nto*) os=`echo $os | sed -e 's|nto|nto-qnx|'` ;; -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) ;; -mac*) os=`echo $os | sed -e 's|mac|macos|'` ;; -linux-dietlibc) os=-linux-dietlibc ;; -linux*) os=`echo $os | sed -e 's|linux|linux-gnu|'` ;; -sunos5*) os=`echo $os | sed -e 's|sunos5|solaris2|'` ;; -sunos6*) os=`echo $os | sed -e 's|sunos6|solaris3|'` ;; -opened*) os=-openedition ;; -os400*) os=-os400 ;; -wince*) os=-wince ;; -osfrose*) os=-osfrose ;; -osf*) os=-osf ;; -utek*) os=-bsd ;; -dynix*) os=-bsd ;; -acis*) os=-aos ;; -atheos*) os=-atheos ;; -syllable*) os=-syllable ;; -386bsd) os=-bsd ;; -ctix* | -uts*) os=-sysv ;; -nova*) os=-rtmk-nova ;; -ns2 ) os=-nextstep2 ;; -nsk*) os=-nsk ;; # Preserve the version number of sinix5. -sinix5.*) os=`echo $os | sed -e 's|sinix|sysv|'` ;; -sinix*) os=-sysv4 ;; -tpf*) os=-tpf ;; -triton*) os=-sysv3 ;; -oss*) os=-sysv3 ;; -svr4) os=-sysv4 ;; -svr3) os=-sysv3 ;; -sysvr4) os=-sysv4 ;; # This must come after -sysvr4. -sysv*) ;; -ose*) os=-ose ;; -es1800*) os=-ose ;; -xenix) os=-xenix ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) os=-mint ;; -aros*) os=-aros ;; -zvmoe) os=-zvmoe ;; -dicos*) os=-dicos ;; -nacl*) ;; -none) ;; *) # Get rid of the `-' at the beginning of $os. os=`echo $os | sed 's/[^-]*-//'` echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 exit 1 ;; esac else # Here we handle the default operating systems that come with various machines. # The value should be what the vendor currently ships out the door with their # machine or put another way, the most popular os provided with the machine. # Note that if you're going to try to match "-MANUFACTURER" here (say, # "-sun"), then you have to tell the case statement up towards the top # that MANUFACTURER isn't an operating system. Otherwise, code above # will signal an error saying that MANUFACTURER isn't an operating # system, and we'll never get to this point. case $basic_machine in score-*) os=-elf ;; spu-*) os=-elf ;; *-acorn) os=-riscix1.2 ;; arm*-rebel) os=-linux ;; arm*-semi) os=-aout ;; c4x-* | tic4x-*) os=-coff ;; c8051-*) os=-elf ;; hexagon-*) os=-elf ;; tic54x-*) os=-coff ;; tic55x-*) os=-coff ;; tic6x-*) os=-coff ;; # This must come before the *-dec entry. pdp10-*) os=-tops20 ;; pdp11-*) os=-none ;; *-dec | vax-*) os=-ultrix4.2 ;; m68*-apollo) os=-domain ;; i386-sun) os=-sunos4.0.2 ;; m68000-sun) os=-sunos3 ;; m68*-cisco) os=-aout ;; mep-*) os=-elf ;; mips*-cisco) os=-elf ;; mips*-*) os=-elf ;; or1k-*) os=-elf ;; or32-*) os=-coff ;; *-tti) # must be before sparc entry or we get the wrong os. os=-sysv3 ;; sparc-* | *-sun) os=-sunos4.1.1 ;; *-be) os=-beos ;; *-haiku) os=-haiku ;; *-ibm) os=-aix ;; *-knuth) os=-mmixware ;; *-wec) os=-proelf ;; *-winbond) os=-proelf ;; *-oki) os=-proelf ;; *-hp) os=-hpux ;; *-hitachi) os=-hiux ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=-sysv ;; *-cbm) os=-amigaos ;; *-dg) os=-dgux ;; *-dolphin) os=-sysv3 ;; m68k-ccur) os=-rtu ;; m88k-omron*) os=-luna ;; *-next ) os=-nextstep ;; *-sequent) os=-ptx ;; *-crds) os=-unos ;; *-ns) os=-genix ;; i370-*) os=-mvs ;; *-next) os=-nextstep3 ;; *-gould) os=-sysv ;; *-highlevel) os=-bsd ;; *-encore) os=-bsd ;; *-sgi) os=-irix ;; *-siemens) os=-sysv4 ;; *-masscomp) os=-rtu ;; f30[01]-fujitsu | f700-fujitsu) os=-uxpv ;; *-rom68k) os=-coff ;; *-*bug) os=-coff ;; *-apple) os=-macos ;; *-atari*) os=-mint ;; *) os=-none ;; esac fi # Here we handle the case where we know the os, and the CPU type, but not the # manufacturer. We pick the logical manufacturer. vendor=unknown case $basic_machine in *-unknown) case $os in -riscix*) vendor=acorn ;; -sunos*) vendor=sun ;; -cnk*|-aix*) vendor=ibm ;; -beos*) vendor=be ;; -hpux*) vendor=hp ;; -mpeix*) vendor=hp ;; -hiux*) vendor=hitachi ;; -unos*) vendor=crds ;; -dgux*) vendor=dg ;; -luna*) vendor=omron ;; -genix*) vendor=ns ;; -mvs* | -opened*) vendor=ibm ;; -os400*) vendor=ibm ;; -ptx*) vendor=sequent ;; -tpf*) vendor=ibm ;; -vxsim* | -vxworks* | -windiss*) vendor=wrs ;; -aux*) vendor=apple ;; -hms*) vendor=hitachi ;; -mpw* | -macos*) vendor=apple ;; -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) vendor=atari ;; -vos*) vendor=stratus ;; esac basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` ;; esac echo $basic_machine$os exit # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: softhsm-2.0.0/WIN32-NOTES.md0000664000175000017500000000646612533040716012146 00000000000000# WIN32 Specific Notes Works and checked on Visual Studio 2010 C++ Express, should work with any Visual Studio 2010, 2012 or 2013 Desktop. Default locations and names are: OpenSSL in ssl directory at the same level, Botan in btn, CppUnit in cu, if you want Debug versions you need ssl_d, btn_d and cu/lib/cppunitd.lib or cu/cppunitd.lib. You can use the DLL or the static library for Botan and OpenSSL, if it exists the DLL is copied in the Configuration (i.e., Release or Debug) directory so is at the same place than other binaries. Configure scripts in win32, same syntax than autotools but without --, e.g., 'perl Configure.pl with-crypto-backend=botan' (or if you prefer Python 2 'python Configure.py with-crypto-backend=botan') in a Visual Studio Command Prompt windows (which is a command.exe windows where the script \VC\vcvarsall.bat was invoked). After you can open the softhsm2.sln file with the Visual Studio GUI or invoke MSBuild for instance with: msbuild /t:Build /p:Configuration=Release softhsm2.sln ## Botan build python configure.py --cpu=x86_32 --cc=msvc --link-mode=copy --prefix=... options: --cpu=x86_64 --enable-debug --disable-shared GNU MP: --with-gnump could be fine but GNU MP is not available on WIN32 nmake /f Makefile nmake /f Makefile check .\check --validate name /f Makefile install ## OpenSSL build perl Configure --prefix=... enable-static-engine VC-WIN32 options: VC-WIN64A debug-VS-WIN* ms\do_ms (or ms\do_win64a) nmake /f ms\ntdll.mak (or ms\nt.make) nmake /f ms\ntdll.mak test nmake /f ms\ntdll.mak install ## CppUnit build Get a recent CppUnit distrib, for instance the 1.13.2 version. Open with the Visual Studio GUI the src\CppUnitLibraries2010.sln solution file. The interesting project is the cppunit one which builds the needed cppunit.lib and cppunitd.lib static libraries. Note there is no installation tool so you have to copy include and library files at the right place yourselves. ## Project List - convarch: internal "convenience" static library - softhsm2 (main project): softhsm2.dll - keyconv, util, dump: softhsm2-keyconv.exe, softhsm2-util.exe, and softhsm2-dump-file.exe tools - p11test, cryptotest, datamgrtest, handlemgrtest, objstoretest, sessionmgrtest, slotmgrtest: checking tools ## C4996 "unsafe" functions - fopen - getenv - gmtime _ _open - _snprintf (or snprintf on Visual Studio 14) - sprintf - sscanf - strncpy - strtok - _vsnprintf - vsnprintf - vsprintf ## Port Summary (_WIN32 stuff) - windows.h included from config.h with some tuning (so config.h should be included first) - softhsm2.conf.win32 (installed by VS p11test project including in the topdir) - No unistd.h, sys/mman.h, sys/socket.h, etc - sys/time.h -> time.h - / in file path -> \ (\\\\ in chars/strings) - \_\_func\_\_ -> \_\_FUNCTION\_\_ (should be _MSC_VER in place of _WIN32?) - wb/rb in fopen for binary files - dlopen & co -> LoadLibrary & co - valloc, mlock, etc -> VirtualAlloc, VirtualLock, etc - threadID -> GetCurrentThreadId - pthread_mutex -> Mutex (note CreateMutex is now defined by config.h) - dirent & co -> _findfirst & co - remove -> _rmdir or _unlink (WIN32 remove() doesn't handle directories) - fcntl F_SETL & co* -> LockFileEx & co - shell "rm -rf foo" -> cmd.exe "rmdir /s /q foo 2> nul" - syslog -> provided using Event - getopt, getpassphrase -> provided - setenv -> provided using _putenv softhsm-2.0.0/config.h.in0000664000175000017500000000711112552216617012151 00000000000000/* config.h.in. Generated from configure.ac by autoheader. */ /* Define to default visibility of PKCS#11 entry points */ #undef CRYPTOKI_VISIBILITY /* The default log level */ #undef DEFAULT_LOG_LEVEL /* Default storage backend for token objects */ #undef DEFAULT_OBJECTSTORE_BACKEND /* The default PKCS#11 library */ #undef DEFAULT_PKCS11_LIB /* The default location of softhsm2.conf */ #undef DEFAULT_SOFTHSM2_CONF /* The default location of the token directory */ #undef DEFAULT_TOKENDIR /* Define if advanced AES key wrap without pad is supported */ #undef HAVE_AES_KEY_WRAP /* Define if advanced AES key wrap with pad is supported */ #undef HAVE_AES_KEY_WRAP_PAD /* define if the compiler supports basic C++11 syntax */ #undef HAVE_CXX11 /* Define to 1 if you have the header file. */ #undef HAVE_DLFCN_H /* Define if you have dlopen */ #undef HAVE_DLOPEN /* Define to 1 if you have the `getpwuid_r' function. */ #undef HAVE_GETPWUID_R /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `crypto' library (-lcrypto). */ #undef HAVE_LIBCRYPTO /* Define to 1 if you have the `sqlite3' library (-lsqlite3). */ #undef HAVE_LIBSQLITE3 /* Whether LoadLibrary is available */ #undef HAVE_LOADLIBRARY /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Build with object store database backend. */ #undef HAVE_OBJECTSTORE_BACKEND_DB /* Define to 1 if you have the header file. */ #undef HAVE_OPENSSL_SSL_H /* Define to 1 if you have the header file. */ #undef HAVE_PTHREAD_H /* Define to 1 if you have the header file. */ #undef HAVE_SQLITE3_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_MMAN_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to the sub-directory in which libtool stores uninstalled libraries. */ #undef LT_OBJDIR /* Maximum PIN length */ #undef MAX_PIN_LEN /* Minimum PIN length */ #undef MIN_PIN_LEN /* Name of package */ #undef PACKAGE /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* Non-paged memory for secure storage */ #undef SENSITIVE_NON_PAGE /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Version number of package */ #undef VERSION /* SoftHSM major version number via PKCS#11 */ #undef VERSION_MAJOR /* SoftHSM minor version number via PKCS#11 */ #undef VERSION_MINOR /* Compile with Botan support */ #undef WITH_BOTAN /* Compile with ECC support */ #undef WITH_ECC /* Compile with FIPS 140-2 mode */ #undef WITH_FIPS /* Compile with GOST support */ #undef WITH_GOST /* Compile with OpenSSL support */ #undef WITH_OPENSSL softhsm-2.0.0/configure.ac0000664000175000017500000001264712552215361012421 00000000000000################## # # # Version # # # ################ # Program version define([SOFTHSM_VERSION_MAJOR], [2]) define([SOFTHSM_VERSION_MINOR], [0]) define([SOFTHSM_VERSION_FIX], [0]) define([PACKAGE_SUFFIX], []) # Library version # Code changed: SOFTHSM_VERSION_REVISION++ # Interface added/removed/changed: SOFTHSM_VERSION_CURRENT++, SOFTHSM_VERSION_REVISION=0 # Interface added: SOFTHSM_VERSION_AGE++ # Interface removed: SOFTHSM_VERSION_AGE=0 define([SOFTHSM_VERSION_CURRENT], [2]) define([SOFTHSM_VERSION_AGE], [1]) define([SOFTHSM_VERSION_REVISION], [0]) ################## # # # Configure code # # # ################## # Init AC_PREREQ(2.61) AC_INIT([SoftHSM],[SOFTHSM_VERSION_MAJOR.SOFTHSM_VERSION_MINOR.SOFTHSM_VERSION_FIX[]PACKAGE_SUFFIX]) AC_CONFIG_HEADER([config.h]) AC_CONFIG_SRCDIR([src/Makefile.am]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE(foreign) ACX_PREFIXHACK # Version info for the library VERSION_INFO="SOFTHSM_VERSION_CURRENT:SOFTHSM_VERSION_REVISION:SOFTHSM_VERSION_AGE" AC_SUBST(VERSION_INFO) # Checks for compilers AC_PROG_CC AC_PROG_CXX # Compiler flags ACX_PEDANTIC ACX_STRICT ACX_64BIT # Check for libraries (-ldl can be required by OpenSSL too) ACX_DLOPEN # Check for headers AC_CHECK_HEADERS([pthread.h]) # What crypto backend to use and if we want to have support GOST ACX_CRYPTO_BACKEND # Non-paged memory for secure storage ACX_NON_PAGED_MEMORY # If the user want to have the migration tool # Requires SQLite3 AC_ARG_WITH(migrate, AC_HELP_STRING([--with-migrate], [Build the migration tool. Requires SQLite3.] ), [build_migrate="${withval}"], [build_migrate="no"] ) AC_MSG_CHECKING(if building with softhsm2-migrate) if test "x${build_migrate}" = "xyes"; then AC_MSG_RESULT(yes) ACX_YIELD else AC_MSG_RESULT(no) fi AM_CONDITIONAL([BUILD_MIGRATE], [test "x${build_migrate}" = "xyes"]) # If the user wants to have the database storage backend AC_ARG_WITH([objectstore-backend-db], AC_HELP_STRING([--with-objectstore-backend-db], [Build with object store backend database (SQLite3).] ), [build_objectstore_backend_db="${withval}"], [build_objectstore_backend_db="no"] ) AC_MSG_CHECKING(if building database object store backend) if test "x${build_objectstore_backend_db}" = "xyes"; then AC_MSG_RESULT(yes) AC_DEFINE_UNQUOTED( [HAVE_OBJECTSTORE_BACKEND_DB], [1], [Build with object store database backend.] ) else AC_MSG_RESULT(no) fi AM_CONDITIONAL([BUILD_OBJECTSTORE_BACKEND_DB], [test "x${build_objectstore_backend_db}" = "xyes"]) # Require SQLite3 if either building --with-migrate or --with-objectstore-backend-db AC_MSG_CHECKING(if SQLite3 required) if test "x${build_migrate}" = "xyes" -o "x${build_objectstore_backend_db}" = "xyes"; then AC_MSG_RESULT(yes) ACX_SQLITE3 else AC_MSG_RESULT(no) fi # Set visibility flags so only PKCS#11 entry points are exported ACX_VISIBILITY # Set full directory paths full_sysconfdir=`eval eval eval eval eval echo "${sysconfdir}" | sed "s#NONE#${prefix}#" | sed "s#NONE#${ac_default_prefix}#"` full_localstatedir=`eval eval eval eval eval echo "${localstatedir}" | sed "s#NONE#${prefix}#" | sed "s#NONE#${ac_default_prefix}#"` full_libdir=`eval eval eval eval eval echo "${libdir}" | sed "s#NONE#${prefix}#" | sed "s#NONE#${ac_default_prefix}#"` default_softhsm2_conf="`eval echo ${full_sysconfdir} | sed s,NONE,$ac_default_prefix,g`/softhsm2.conf" softhsmtokendir=${full_localstatedir}/lib/softhsm/tokens/ # Install the library in a sub-directory full_libdir="$full_libdir/softhsm" libdir=$full_libdir # For getConfigPath() AC_CHECK_FUNCS([getpwuid_r]) # Define some variables for the code AC_DEFINE_UNQUOTED( [VERSION_MAJOR], [SOFTHSM_VERSION_MAJOR], [SoftHSM major version number via PKCS#11] ) AC_DEFINE_UNQUOTED( [VERSION_MINOR], [SOFTHSM_VERSION_MINOR], [SoftHSM minor version number via PKCS#11] ) AC_DEFINE_UNQUOTED( [MAX_PIN_LEN], [255], [Maximum PIN length] ) AC_DEFINE_UNQUOTED( [MIN_PIN_LEN], [4], [Minimum PIN length] ) AC_DEFINE_UNQUOTED( [DEFAULT_SOFTHSM2_CONF], ["$default_softhsm2_conf"], [The default location of softhsm2.conf] ) AC_DEFINE_UNQUOTED( [DEFAULT_TOKENDIR], ["$softhsmtokendir"], [The default location of the token directory] ) AC_DEFINE_UNQUOTED( [DEFAULT_OBJECTSTORE_BACKEND], ["file"], [Default storage backend for token objects] ) AC_DEFINE_UNQUOTED( [DEFAULT_LOG_LEVEL], ["INFO"], [The default log level] ) AC_DEFINE_UNQUOTED( [DEFAULT_PKCS11_LIB], ["$full_libdir/libsofthsm2.so"], [The default PKCS#11 library] ) AC_SUBST([softhsmtokendir]) AC_SUBST([default_softhsm2_conf]) # Generate the libtool script and install script AC_PROG_INSTALL AC_PROG_LIBTOOL # Generate the makefiles AC_CONFIG_FILES([ Makefile src/Makefile src/lib/Makefile src/lib/common/Makefile src/lib/common/softhsm2.conf src/lib/common/softhsm2.conf.5 src/lib/crypto/Makefile src/lib/crypto/test/Makefile src/lib/data_mgr/Makefile src/lib/data_mgr/test/Makefile src/lib/object_store/Makefile src/lib/object_store/test/Makefile src/lib/session_mgr/Makefile src/lib/session_mgr/test/Makefile src/lib/slot_mgr/Makefile src/lib/slot_mgr/test/Makefile src/lib/handle_mgr/Makefile src/lib/handle_mgr/test/Makefile src/lib/test/Makefile src/lib/test/softhsm2.conf src/lib/test/tokens/dummy src/bin/Makefile src/bin/common/Makefile src/bin/dump/Makefile src/bin/keyconv/Makefile src/bin/migrate/Makefile src/bin/util/Makefile ]) AC_OUTPUT softhsm-2.0.0/compile0000755000175000017500000001624512552216620011504 00000000000000#! /bin/sh # Wrapper for compilers which do not understand '-c -o'. scriptversion=2012-10-14.11; # UTC # Copyright (C) 1999-2013 Free Software Foundation, Inc. # Written by Tom Tromey . # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . nl=' ' # We need space, tab and new line, in precisely that order. Quoting is # there to prevent tools from complaining about whitespace usage. IFS=" "" $nl" file_conv= # func_file_conv build_file lazy # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. If the determined conversion # type is listed in (the comma separated) LAZY, no conversion will # take place. func_file_conv () { file=$1 case $file in / | /[!/]*) # absolute file, and not a UNC file if test -z "$file_conv"; then # lazily determine how to convert abs files case `uname -s` in MINGW*) file_conv=mingw ;; CYGWIN*) file_conv=cygwin ;; *) file_conv=wine ;; esac fi case $file_conv/,$2, in *,$file_conv,*) ;; mingw/*) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; cygwin/*) file=`cygpath -m "$file" || echo "$file"` ;; wine/*) file=`winepath -w "$file" || echo "$file"` ;; esac ;; esac } # func_cl_dashL linkdir # Make cl look for libraries in LINKDIR func_cl_dashL () { func_file_conv "$1" if test -z "$lib_path"; then lib_path=$file else lib_path="$lib_path;$file" fi linker_opts="$linker_opts -LIBPATH:$file" } # func_cl_dashl library # Do a library search-path lookup for cl func_cl_dashl () { lib=$1 found=no save_IFS=$IFS IFS=';' for dir in $lib_path $LIB do IFS=$save_IFS if $shared && test -f "$dir/$lib.dll.lib"; then found=yes lib=$dir/$lib.dll.lib break fi if test -f "$dir/$lib.lib"; then found=yes lib=$dir/$lib.lib break fi if test -f "$dir/lib$lib.a"; then found=yes lib=$dir/lib$lib.a break fi done IFS=$save_IFS if test "$found" != yes; then lib=$lib.lib fi } # func_cl_wrapper cl arg... # Adjust compile command to suit cl func_cl_wrapper () { # Assume a capable shell lib_path= shared=: linker_opts= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. eat=1 case $2 in *.o | *.[oO][bB][jJ]) func_file_conv "$2" set x "$@" -Fo"$file" shift ;; *) func_file_conv "$2" set x "$@" -Fe"$file" shift ;; esac ;; -I) eat=1 func_file_conv "$2" mingw set x "$@" -I"$file" shift ;; -I*) func_file_conv "${1#-I}" mingw set x "$@" -I"$file" shift ;; -l) eat=1 func_cl_dashl "$2" set x "$@" "$lib" shift ;; -l*) func_cl_dashl "${1#-l}" set x "$@" "$lib" shift ;; -L) eat=1 func_cl_dashL "$2" ;; -L*) func_cl_dashL "${1#-L}" ;; -static) shared=false ;; -Wl,*) arg=${1#-Wl,} save_ifs="$IFS"; IFS=',' for flag in $arg; do IFS="$save_ifs" linker_opts="$linker_opts $flag" done IFS="$save_ifs" ;; -Xlinker) eat=1 linker_opts="$linker_opts $2" ;; -*) set x "$@" "$1" shift ;; *.cc | *.CC | *.cxx | *.CXX | *.[cC]++) func_file_conv "$1" set x "$@" -Tp"$file" shift ;; *.c | *.cpp | *.CPP | *.lib | *.LIB | *.Lib | *.OBJ | *.obj | *.[oO]) func_file_conv "$1" mingw set x "$@" "$file" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -n "$linker_opts"; then linker_opts="-link$linker_opts" fi exec "$@" $linker_opts exit 1 } eat= case $1 in '') echo "$0: No command. Try '$0 --help' for more information." 1>&2 exit 1; ;; -h | --h*) cat <<\EOF Usage: compile [--help] [--version] PROGRAM [ARGS] Wrapper for compilers which do not understand '-c -o'. Remove '-o dest.o' from ARGS, run PROGRAM with the remaining arguments, and rename the output as expected. If you are trying to build a whole package this is not the right script to run: please start by reading the file 'INSTALL'. Report bugs to . EOF exit $? ;; -v | --v*) echo "compile $scriptversion" exit $? ;; cl | *[/\\]cl | cl.exe | *[/\\]cl.exe ) func_cl_wrapper "$@" # Doesn't return... ;; esac ofile= cfile= for arg do if test -n "$eat"; then eat= else case $1 in -o) # configure might choose to run compile as 'compile cc -o foo foo.c'. # So we strip '-o arg' only if arg is an object. eat=1 case $2 in *.o | *.obj) ofile=$2 ;; *) set x "$@" -o "$2" shift ;; esac ;; *.c) cfile=$1 set x "$@" "$1" shift ;; *) set x "$@" "$1" shift ;; esac fi shift done if test -z "$ofile" || test -z "$cfile"; then # If no '-o' option was seen then we might have been invoked from a # pattern rule where we don't need one. That is ok -- this is a # normal compilation that the losing compiler can handle. If no # '.c' file was seen then we are probably linking. That is also # ok. exec "$@" fi # Name of file we expect compiler to create. cofile=`echo "$cfile" | sed 's|^.*[\\/]||; s|^[a-zA-Z]:||; s/\.c$/.o/'` # Create the lock directory. # Note: use '[/\\:.-]' here to ensure that we don't use the same name # that we are using for the .o file. Also, base the name on the expected # object file name, since that is what matters with a parallel build. lockdir=`echo "$cofile" | sed -e 's|[/\\:.-]|_|g'`.d while true; do if mkdir "$lockdir" >/dev/null 2>&1; then break fi sleep 1 done # FIXME: race condition here if user kills between mkdir and trap. trap "rmdir '$lockdir'; exit 1" 1 2 15 # Run the compile. "$@" ret=$? if test -f "$cofile"; then test "$cofile" = "$ofile" || mv "$cofile" "$ofile" elif test -f "${cofile}bj"; then test "${cofile}bj" = "$ofile" || mv "${cofile}bj" "$ofile" fi rmdir "$lockdir" exit $ret # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: softhsm-2.0.0/test-driver0000755000175000017500000001027712552216621012324 00000000000000#! /bin/sh # test-driver - basic testsuite driver script. scriptversion=2013-07-13.22; # UTC # Copyright (C) 2011-2013 Free Software Foundation, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. # This file is maintained in Automake, please report # bugs to or send patches to # . # Make unconditional expansion of undefined variables an error. This # helps a lot in preventing typo-related bugs. set -u usage_error () { echo "$0: $*" >&2 print_usage >&2 exit 2 } print_usage () { cat <$log_file 2>&1 estatus=$? if test $enable_hard_errors = no && test $estatus -eq 99; then estatus=1 fi case $estatus:$expect_failure in 0:yes) col=$red res=XPASS recheck=yes gcopy=yes;; 0:*) col=$grn res=PASS recheck=no gcopy=no;; 77:*) col=$blu res=SKIP recheck=no gcopy=yes;; 99:*) col=$mgn res=ERROR recheck=yes gcopy=yes;; *:yes) col=$lgn res=XFAIL recheck=no gcopy=yes;; *:*) col=$red res=FAIL recheck=yes gcopy=yes;; esac # Report outcome to console. echo "${col}${res}${std}: $test_name" # Register the test result, and other relevant metadata. echo ":test-result: $res" > $trs_file echo ":global-test-result: $res" >> $trs_file echo ":recheck: $recheck" >> $trs_file echo ":copy-in-global-log: $gcopy" >> $trs_file # Local Variables: # mode: shell-script # sh-indentation: 2 # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: softhsm-2.0.0/aes_wrap_key_with_pad/0000775000175000017500000000000012552220146014526 500000000000000softhsm-2.0.0/aes_wrap_key_with_pad/botan-diff0000664000175000017500000002445012533040716016411 00000000000000--- src/constructs/rfc3394/rfc3394.h-dist 2013-11-10 17:06:11.000000000 +0100 +++ src/constructs/rfc3394/rfc3394.h 2013-12-22 02:14:50.000000000 +0100 @@ -27,6 +27,13 @@ const SymmetricKey& kek, Algorithm_Factory& af); +/* overload with an extra initial value */ + +SecureVector BOTAN_DLL rfc3394_keywrap(const MemoryRegion& key, + const byte iv[8], + const SymmetricKey& kek, + Algorithm_Factory& af); + /** * Decrypt a key under a key encryption key using the algorithm * described in RFC 3394 @@ -40,6 +47,47 @@ const SymmetricKey& kek, Algorithm_Factory& af); +/* overload with an extra initial value */ + +SecureVector BOTAN_DLL rfc3394_keyunwrap(const MemoryRegion& key, + const byte iv[8], + const SymmetricKey& kek, + Algorithm_Factory& af); + +/* overload with an extra initial value and integrity check value */ + +SecureVector BOTAN_DLL rfc3394_keyunwrap(const MemoryRegion& key, + const byte iv[8], + byte icv[8], + const SymmetricKey& kek, + Algorithm_Factory& af); + +/** +* Pad and encrypt a key under a key encryption key using the algorithm +* described in RFC 5649 +* +* @param key the plaintext key to encrypt +* @param kek the key encryption key +* @param af an algorithm factory +* @return key encrypted under kek +*/ +SecureVector BOTAN_DLL rfc5649_keywrap(const MemoryRegion& key, + const SymmetricKey& kek, + Algorithm_Factory& af); + +/** +* Decrypt and unpad a key under a key encryption key using the algorithm +* described in RFC 5649 +* +* @param key the encrypted key to decrypt +* @param kek the key encryption key +* @param af an algorithm factory +* @return key decrypted under kek +*/ +SecureVector BOTAN_DLL rfc5649_keyunwrap(const MemoryRegion& key, + const SymmetricKey& kek, + Algorithm_Factory& af); + } #endif --- src/constructs/rfc3394/rfc3394.cpp-dist 2013-11-10 17:06:11.000000000 +0100 +++ src/constructs/rfc3394/rfc3394.cpp 2013-12-22 03:46:13.000000000 +0100 @@ -30,12 +30,35 @@ throw std::invalid_argument("Bad KEK length for NIST keywrap"); } +BlockCipher* make_aesp(size_t keylength, + Algorithm_Factory& af) + { + if(keylength == 16) + return af.make_block_cipher("AES-128"); + else if(keylength == 24) + return af.make_block_cipher("AES-192"); + else if(keylength == 32) + return af.make_block_cipher("AES-256"); + else + throw std::invalid_argument("Bad KEK length for NIST keywrap with pad"); + } } SecureVector rfc3394_keywrap(const MemoryRegion& key, const SymmetricKey& kek, Algorithm_Factory& af) { + byte iv[8]; + for(size_t i = 0; i != 8; ++i) + iv[i] = 0xA6; + return rfc3394_keywrap(key, iv, kek, af); + } + +SecureVector rfc3394_keywrap(const MemoryRegion& key, + const byte iv[8], + const SymmetricKey& kek, + Algorithm_Factory& af) + { if(key.size() % 8 != 0) throw std::invalid_argument("Bad input key size for NIST key wrap"); @@ -48,7 +71,7 @@ SecureVector A(16); for(size_t i = 0; i != 8; ++i) - A[i] = 0xA6; + A[i] = iv[i]; copy_mem(&R[8], key.begin(), key.size()); @@ -78,6 +101,29 @@ const SymmetricKey& kek, Algorithm_Factory& af) { + byte iv[8]; + for(size_t i = 0; i != 8; ++i) + iv[i] = 0xA6; + return rfc3394_keyunwrap(key, iv, kek, af); + } + +SecureVector rfc3394_keyunwrap(const MemoryRegion& key, + const byte iv[8], + const SymmetricKey& kek, + Algorithm_Factory& af) + { + byte icv[8]; + for(size_t i = 0; i != 8; ++i) + icv[i] = iv[i]; + return rfc3394_keyunwrap(key, iv, icv, kek, af); + } + +SecureVector rfc3394_keyunwrap(const MemoryRegion& key, + const byte iv[8], + byte icv[8], + const SymmetricKey& kek, + Algorithm_Factory& af) + { if(key.size() < 16 || key.size() % 8 != 0) throw std::invalid_argument("Bad input key size for NIST key unwrap"); @@ -113,10 +159,107 @@ } } - if(load_be(&A[0], 0) != 0xA6A6A6A6A6A6A6A6) - throw Integrity_Failure("NIST key unwrap failed"); + if(load_be(iv, 0) == load_be(icv, 0)) + { + if(load_be(&A[0], 0) != load_be(iv, 0)) + throw Integrity_Failure("NIST key unwrap failed"); + } + else + store_be(load_be(&A[0], 0), icv); return R; } +SecureVector rfc5649_keywrap(const MemoryRegion& key, + const SymmetricKey& kek, + Algorithm_Factory& af) + { + const size_t len = key.size() + + (key.size() % 8 == 0 ? 0 : (8 - key.size() % 8)); + + u32bit aivh = 0xA65959A6; + byte ivh[4] = { 0 }; + store_be(aivh, ivh); + u32bit mli = key.size(); + byte ivl[4] = { 0 }; + store_be(mli, ivl); + + if(len == 8) + { + std::auto_ptr aes(make_aesp(kek.length(), af)); + aes->set_key(kek); + + SecureVector buf(16); + copy_mem(&buf[0], ivh, 4); + copy_mem(&buf[4], ivl, 4); + copy_mem(&buf[8], key.begin(), key.size()); + + aes->encrypt(&buf[0]); + + return buf; + } + else + { + MemoryVector buf(len); + copy_mem(&buf[0], key.begin(), key.size()); + byte iv[8] = { 0 }; + copy_mem(iv, ivh, 4); + copy_mem(&iv[4], ivl, 4); + return rfc3394_keywrap(buf, iv, kek, af); + } + } + +SecureVector rfc5649_keyunwrap(const MemoryRegion& key, + const SymmetricKey& kek, + Algorithm_Factory& af) + { + if(key.size() < 16 || key.size() % 8 != 0) + throw std::invalid_argument("Bad input key size for NIST key unwrap with pad"); + + byte iv[8] = { 0 }; + SecureVector out; + + if(key.size() == 16) + { + std::auto_ptr aes(make_aesp(kek.length(), af)); + aes->set_key(kek); + + SecureVector buf(key); + + aes->decrypt(&buf[0]); + + copy_mem(iv, buf.begin(), 8); + out.resize(8); + copy_mem(&out[0], &buf[8], 8); + } + else + { + byte dummy[8] = { 1 }; + try + { + out = rfc3394_keyunwrap(key, dummy, iv, kek, af); + } + catch(...) + { + throw Integrity_Failure("NIST key unwrap with pad failed"); + } + } + + if(load_be(&iv[0], 0) != 0xA65959A6) + throw Integrity_Failure("NIST key unwrap with pad failed"); + + u32bit mli = load_be(iv, 1); + if(mli > out.size() || mli <= out.size() - 8) + throw Integrity_Failure("NIST key unwrap with pad failed"); + + size_t padlen = out.size() - mli; + byte zero[8] = { 0 }; + clear_mem(zero, 8); + if(padlen && !same_mem(zero, &out[mli], padlen)) + throw Integrity_Failure("NIST key unwrap with pad failed"); + + out.resize(mli); + return out; + } + } --- src/constructs/rfc3394/info.txt-dist 2013-11-10 17:06:11.000000000 +0100 +++ src/constructs/rfc3394/info.txt 2013-12-22 00:42:08.000000000 +0100 @@ -1 +1,2 @@ define RFC3394_KEYWRAP +define RFC5649_KEYWRAP --- checks/validate.cpp-dist 2013-11-10 17:06:11.000000000 +0100 +++ checks/validate.cpp 2013-12-22 02:15:12.000000000 +0100 @@ -180,6 +180,68 @@ return ok; } +bool keywrap_withpad_test(const char* key_str, + const char* expected_str, + const char* kek_str) + { + std::cout << '.' << std::flush; + + bool ok = true; + +#if defined(BOTAN_HAS_RFC5649_KEYWRAP) + try + { + SymmetricKey key(key_str); + SymmetricKey expected(expected_str); + SymmetricKey kek(kek_str); + + Algorithm_Factory& af = global_state().algorithm_factory(); + + SecureVector enc = rfc5649_keywrap(key.bits_of(), kek, af); + + if(enc != expected.bits_of()) + { + std::cout << "NIST key wrap encryption failure: " + << hex_encode(enc) << " != " << hex_encode(expected.bits_of()) << "\n"; + ok = false; + } + + SecureVector dec = rfc5649_keyunwrap(expected.bits_of(), kek, af); + + if(dec != key.bits_of()) + { + std::cout << "NIST key wrap decryption failure: " + << hex_encode(dec) << " != " << hex_encode(key.bits_of()) << "\n"; + ok = false; + } + } + catch(std::exception& e) + { + std::cout << e.what() << "\n"; + } +#endif + + return ok; + } + +bool test_keywrap_withpad() + { + std::cout << "Testing NIST keywrap with pad: " << std::flush; + + bool ok = true; + + ok &= keywrap_withpad_test("C37B7E6492584340BED12207808941155068F738", + "138BDEAA9B8FA7FC61F97742E72248EE5AE6AE5360D1AE6A5F54F373FA543B6A", + "5840DF6E29B02AF1AB493B705BF16EA1AE8338F4DCC176A8"); + + ok &= keywrap_withpad_test("466f7250617369", + "AFBEB0F07DFBF5419200F2CCB50BB24F", + "5840DF6E29B02AF1AB493B705BF16EA1AE8338F4DCC176A8"); + + std::cout << "\n"; + return ok; + } + bool test_bcrypt(RandomNumberGenerator& rng) { #if defined(BOTAN_HAS_BCRYPT) @@ -410,6 +472,12 @@ errors++; } + if(should_pass && !test_keywrap_withpad()) + { + std::cout << "NIST keywrap with pad tests failed" << std::endl; + errors++; + } + if(should_pass && !test_cryptobox(rng)) { std::cout << "Cryptobox tests failed" << std::endl; softhsm-2.0.0/aes_wrap_key_with_pad/README0000664000175000017500000000060612533040716015332 00000000000000Here are the patches to add advanced AES key wrap *with pad*, aka RFC 5649, to Botan (1.10, not 1.11 even it should be easy). PS: standardized (and approved) under the KWP name in NIST SP 800-38F. OpenSSL added support for RFC 5649 in commit d31fed73e25391cd71a0de488d88724db78f6f8a and it is waiting for nearest release. Some distributions backported the interface, e.g. Fedora and RHEL. softhsm-2.0.0/missing0000755000175000017500000001533012552216620011517 00000000000000#! /bin/sh # Common wrapper for a few potentially missing GNU programs. scriptversion=2013-10-28.13; # UTC # Copyright (C) 1996-2013 Free Software Foundation, Inc. # Originally written by Fran,cois Pinard , 1996. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that program. if test $# -eq 0; then echo 1>&2 "Try '$0 --help' for more information" exit 1 fi case $1 in --is-lightweight) # Used by our autoconf macros to check whether the available missing # script is modern enough. exit 0 ;; --run) # Back-compat with the calling convention used by older automake. shift ;; -h|--h|--he|--hel|--help) echo "\ $0 [OPTION]... PROGRAM [ARGUMENT]... Run 'PROGRAM [ARGUMENT]...', returning a proper advice when this fails due to PROGRAM being missing or too old. Options: -h, --help display this help and exit -v, --version output version information and exit Supported PROGRAM values: aclocal autoconf autoheader autom4te automake makeinfo bison yacc flex lex help2man Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and 'g' are ignored when checking the name. Send bug reports to ." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) echo "missing $scriptversion (GNU Automake)" exit $? ;; -*) echo 1>&2 "$0: unknown '$1' option" echo 1>&2 "Try '$0 --help' for more information" exit 1 ;; esac # Run the given program, remember its exit status. "$@"; st=$? # If it succeeded, we are done. test $st -eq 0 && exit 0 # Also exit now if we it failed (or wasn't found), and '--version' was # passed; such an option is passed most likely to detect whether the # program is present and works. case $2 in --version|--help) exit $st;; esac # Exit code 63 means version mismatch. This often happens when the user # tries to use an ancient version of a tool on a file that requires a # minimum version. if test $st -eq 63; then msg="probably too old" elif test $st -eq 127; then # Program was missing. msg="missing on your system" else # Program was found and executed, but failed. Give up. exit $st fi perl_URL=http://www.perl.org/ flex_URL=http://flex.sourceforge.net/ gnu_software_URL=http://www.gnu.org/software program_details () { case $1 in aclocal|automake) echo "The '$1' program is part of the GNU Automake package:" echo "<$gnu_software_URL/automake>" echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/autoconf>" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; autoconf|autom4te|autoheader) echo "The '$1' program is part of the GNU Autoconf package:" echo "<$gnu_software_URL/autoconf/>" echo "It also requires GNU m4 and Perl in order to run:" echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; esac } give_advice () { # Normalize program name to check for. normalized_program=`echo "$1" | sed ' s/^gnu-//; t s/^gnu//; t s/^g//; t'` printf '%s\n' "'$1' is $msg." configure_deps="'configure.ac' or m4 files included by 'configure.ac'" case $normalized_program in autoconf*) echo "You should only need it if you modified 'configure.ac'," echo "or m4 files included by it." program_details 'autoconf' ;; autoheader*) echo "You should only need it if you modified 'acconfig.h' or" echo "$configure_deps." program_details 'autoheader' ;; automake*) echo "You should only need it if you modified 'Makefile.am' or" echo "$configure_deps." program_details 'automake' ;; aclocal*) echo "You should only need it if you modified 'acinclude.m4' or" echo "$configure_deps." program_details 'aclocal' ;; autom4te*) echo "You might have modified some maintainer files that require" echo "the 'autom4te' program to be rebuilt." program_details 'autom4te' ;; bison*|yacc*) echo "You should only need it if you modified a '.y' file." echo "You may want to install the GNU Bison package:" echo "<$gnu_software_URL/bison/>" ;; lex*|flex*) echo "You should only need it if you modified a '.l' file." echo "You may want to install the Fast Lexical Analyzer package:" echo "<$flex_URL>" ;; help2man*) echo "You should only need it if you modified a dependency" \ "of a man page." echo "You may want to install the GNU Help2man package:" echo "<$gnu_software_URL/help2man/>" ;; makeinfo*) echo "You should only need it if you modified a '.texi' file, or" echo "any other file indirectly affecting the aspect of the manual." echo "You might want to install the Texinfo package:" echo "<$gnu_software_URL/texinfo/>" echo "The spurious makeinfo call might also be the consequence of" echo "using a buggy 'make' (AIX, DU, IRIX), in which case you might" echo "want to install GNU make:" echo "<$gnu_software_URL/make/>" ;; *) echo "You might have modified some files without having the proper" echo "tools for further handling them. Check the 'README' file, it" echo "often tells you about the needed prerequisites for installing" echo "this package. You may also peek at any GNU archive site, in" echo "case some other package contains this missing '$1' program." ;; esac } give_advice "$1" | sed -e '1s/^/WARNING: /' \ -e '2,$s/^/ /' >&2 # Propagate the correct exit status (expected to be 127 for a program # not found, 63 for a program that failed due to version mismatch). exit $st # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "scriptversion=" # time-stamp-format: "%:y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC" # time-stamp-end: "; # UTC" # End: softhsm-2.0.0/FIPS-NOTES.md0000664000175000017500000000320012533040716012064 00000000000000# FIPS 140-2 The OpenSSL crypto backend can be a FIPS 140-2 capable library, cf. the OpenSSL FIPS 140 documents SecurityPolicy and UserGuide. ## Introduction Please read the OpenSSL FIPS 140 documents about to get a FIPS Capable OpenSSL library. ## Hard points Reread the OpenSSL FIPS 140 documents as they are hard to apply. Note the following is for Unix/Linux. Now I suppose you have a >= 1.0.1e capable static library (a dynamic library is far easier but always possible and often dubious from a security point of view... BTW if you have built a FIPS Capable OpenSSL library you should not be afraid of extra complexity :-). Do not forget to compile OpenSSL with position indepent code (aka PIC) as the libsofthsm.so requires it. The FIPS module canister is already compiled this way. A usual issue is the C++ compiler not compiling .c files as C code. A simple test can show this, put in foo.c file this code: foo() { char *x = "ab"; } and compile with the C and C++ compilers with all warnings: the C++ compiler should raise an extra warning or error about the no type for foo() and/or for the char* string constant. When this raises some errors in the fispld script, you have to insert '-x c' and '-x none' before and after each .c file in the C++ commands, for instance using this wrapper: -------------------------------- cut here -------------------------------- #!/bin/sh commands="g++" for elem in $@ do case $elem in *.c) commands+=" -x c $elem -x none";; *) commands+=" $elem";; esac done exec $commands -------------------------------- end -------------------------------- In any cases you have to set CC and CXX to fipsld. softhsm-2.0.0/Makefile.in0000664000175000017500000007123712552216620012177 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = . DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/configure $(am__configure_deps) \ $(srcdir)/config.h.in \ $(top_srcdir)/src/lib/test/tokens/dummy.in NEWS compile \ config.guess config.sub depcomp install-sh missing ltmain.sh ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \ configure.lineno config.status.lineno mkinstalldirs = $(install_sh) -d CONFIG_HEADER = config.h CONFIG_CLEAN_FILES = src/lib/test/tokens/dummy CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ cscope distdir dist dist-all distcheck am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) \ $(LISP)config.h.in # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags CSCOPE = cscope DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ && rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz GZIP_ENV = --best DIST_TARGETS = dist-gzip distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' distcleancheck_listfiles = find . -type f -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ ACLOCAL_AMFLAGS = -I m4 MAINTAINERCLEANFILES = \ config.log config.status \ $(srcdir)/Makefile.in \ $(srcdir)/config.h.in $(srcdir)/config.h.in~ \ $(srcdir)/configure \ $(srcdir)/install-sh $(srcdir)/ltmain.sh $(srcdir)/missing \ $(srcdir)/depcomp $(srcdir)/aclocal.m4 $(srcdir)/compile \ $(srcdir)/config.guess $(srcdir)/config.sub SUBDIRS = src EXTRA_DIST = $(srcdir)/aes_wrap_key_with_pad/botan-diff \ $(srcdir)/aes_wrap_key_with_pad/README \ $(srcdir)/FIPS-NOTES.md \ $(srcdir)/LICENSE \ $(srcdir)/m4/*.m4 \ $(srcdir)/OSX-NOTES.md \ $(srcdir)/README.md \ $(srcdir)/win32/config.h.in \ $(srcdir)/win32/Configure.pl \ $(srcdir)/win32/Configure.py \ $(srcdir)/win32/convarch/convarch.vcxproj.in \ $(srcdir)/win32/convarch/convarch.vcxproj.filters.in \ $(srcdir)/win32/convarch/convarch.vcxproj.user \ $(srcdir)/win32/cryptotest/cryptotest.vcxproj.in \ $(srcdir)/win32/cryptotest/cryptotest.vcxproj.filters \ $(srcdir)/win32/cryptotest/cryptotest.vcxproj.user \ $(srcdir)/win32/datamgrtest/datamgrtest.vcxproj.in \ $(srcdir)/win32/datamgrtest/datamgrtest.vcxproj.filters \ $(srcdir)/win32/datamgrtest/datamgrtest.vcxproj.user \ $(srcdir)/win32/dump/dump.vcxproj.in \ $(srcdir)/win32/dump/dump.vcxproj.filters \ $(srcdir)/win32/dump/dump.vcxproj.user \ $(srcdir)/win32/handlemgrtest/handlemgrtest.vcxproj.in \ $(srcdir)/win32/handlemgrtest/handlemgrtest.vcxproj.filters \ $(srcdir)/win32/handlemgrtest/handlemgrtest.vcxproj.user \ $(srcdir)/win32/keyconv/keyconv.vcxproj.in \ $(srcdir)/win32/keyconv/keyconv.vcxproj.filters.in \ $(srcdir)/win32/keyconv/keyconv.vcxproj.user \ $(srcdir)/win32/objstoretest/objstoretest.vcxproj.in \ $(srcdir)/win32/objstoretest/objstoretest.vcxproj.filters \ $(srcdir)/win32/objstoretest/objstoretest.vcxproj.user \ $(srcdir)/win32/p11test/p11test.vcxproj.in \ $(srcdir)/win32/p11test/p11test.vcxproj.filters \ $(srcdir)/win32/p11test/p11test.vcxproj.user \ $(srcdir)/win32/sessionmgrtest/sessionmgrtest.vcxproj.in \ $(srcdir)/win32/sessionmgrtest/sessionmgrtest.vcxproj.filters \ $(srcdir)/win32/sessionmgrtest/sessionmgrtest.vcxproj.user \ $(srcdir)/win32/slotmgrtest/slotmgrtest.vcxproj.in \ $(srcdir)/win32/slotmgrtest/slotmgrtest.vcxproj.filters \ $(srcdir)/win32/slotmgrtest/slotmgrtest.vcxproj.user \ $(srcdir)/win32/softhsm2/softhsm2.vcxproj.in \ $(srcdir)/win32/softhsm2/softhsm2.vcxproj.filters \ $(srcdir)/win32/softhsm2/softhsm2.vcxproj.user \ $(srcdir)/win32/softhsm2.sln.in \ $(srcdir)/win32/util/util.vcxproj.in \ $(srcdir)/win32/util/util.vcxproj.filters.in \ $(srcdir)/win32/util/util.vcxproj.user \ $(srcdir)/WIN32-NOTES.md all: config.h $(MAKE) $(AM_MAKEFLAGS) all-recursive .SUFFIXES: am--refresh: Makefile @: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ echo ' cd $(srcdir) && $(AUTOMAKE) --foreign'; \ $(am__cd) $(srcdir) && $(AUTOMAKE) --foreign \ && exit 0; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ echo ' $(SHELL) ./config.status'; \ $(SHELL) ./config.status;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) $(SHELL) ./config.status --recheck $(top_srcdir)/configure: $(am__configure_deps) $(am__cd) $(srcdir) && $(AUTOCONF) $(ACLOCAL_M4): $(am__aclocal_m4_deps) $(am__cd) $(srcdir) && $(ACLOCAL) $(ACLOCAL_AMFLAGS) $(am__aclocal_m4_deps): config.h: stamp-h1 @test -f $@ || rm -f stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status @rm -f stamp-h1 cd $(top_builddir) && $(SHELL) ./config.status config.h $(srcdir)/config.h.in: $(am__configure_deps) ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) rm -f stamp-h1 touch $@ distclean-hdr: -rm -f config.h stamp-h1 src/lib/test/tokens/dummy: $(top_builddir)/config.status $(top_srcdir)/src/lib/test/tokens/dummy.in cd $(top_builddir) && $(SHELL) ./config.status $@ mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs distclean-libtool: -rm -f libtool config.lt # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscope: cscope.files test ! -s cscope.files \ || $(CSCOPE) -b -q $(AM_CSCOPEFLAGS) $(CSCOPEFLAGS) -i cscope.files $(CSCOPE_ARGS) clean-cscope: -rm -f cscope.files cscope.files: clean-cscope cscopelist cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files distdir: $(DISTFILES) $(am__remove_distdir) test -d "$(distdir)" || mkdir "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done -test -n "$(am__skip_mode_fix)" \ || find "$(distdir)" -type d ! -perm -755 \ -exec chmod u+rwx,go+rx {} \; -o \ ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \ ! -type d ! -perm -400 -exec chmod a+r {} \; -o \ ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \ || chmod -R a+r "$(distdir)" dist-gzip: distdir tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz $(am__post_remove_distdir) dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) dist-xz: distdir tardir=$(distdir) && $(am__tar) | XZ_OPT=$${XZ_OPT--e} xz -c >$(distdir).tar.xz $(am__post_remove_distdir) dist-tarZ: distdir @echo WARNING: "Support for shar distribution archives is" \ "deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z $(am__post_remove_distdir) dist-shar: distdir @echo WARNING: "Support for distribution archives compressed with" \ "legacy program 'compress' is deprecated." >&2 @echo WARNING: "It will be removed altogether in Automake 2.0" >&2 shar $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).shar.gz $(am__post_remove_distdir) dist-zip: distdir -rm -f $(distdir).zip zip -rq $(distdir).zip $(distdir) $(am__post_remove_distdir) dist dist-all: $(MAKE) $(AM_MAKEFLAGS) $(DIST_TARGETS) am__post_remove_distdir='@:' $(am__post_remove_distdir) # This target untars the dist file and tries a VPATH configuration. Then # it guarantees that the distribution is self-contained by making another # tarfile. distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ xz -dc $(distdir).tar.xz | $(am__untar) ;;\ *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ GZIP=$(GZIP_ENV) gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ esac chmod -R a-w $(distdir) chmod u+w $(distdir) mkdir $(distdir)/_build $(distdir)/_inst chmod a-w $(distdir) test -d $(distdir)/_build || exit 0; \ dc_install_base=`$(am__cd) $(distdir)/_inst && pwd | sed -e 's,^[^:\\/]:[\\/],/,'` \ && dc_destdir="$${TMPDIR-/tmp}/am-dc-$$$$/" \ && am__cwd=`pwd` \ && $(am__cd) $(distdir)/_build \ && ../configure \ $(AM_DISTCHECK_CONFIGURE_FLAGS) \ $(DISTCHECK_CONFIGURE_FLAGS) \ --srcdir=.. --prefix="$$dc_install_base" \ && $(MAKE) $(AM_MAKEFLAGS) \ && $(MAKE) $(AM_MAKEFLAGS) dvi \ && $(MAKE) $(AM_MAKEFLAGS) check \ && $(MAKE) $(AM_MAKEFLAGS) install \ && $(MAKE) $(AM_MAKEFLAGS) installcheck \ && $(MAKE) $(AM_MAKEFLAGS) uninstall \ && $(MAKE) $(AM_MAKEFLAGS) distuninstallcheck_dir="$$dc_install_base" \ distuninstallcheck \ && chmod -R a-w "$$dc_install_base" \ && ({ \ (cd ../.. && umask 077 && mkdir "$$dc_destdir") \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" install \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" uninstall \ && $(MAKE) $(AM_MAKEFLAGS) DESTDIR="$$dc_destdir" \ distuninstallcheck_dir="$$dc_destdir" distuninstallcheck; \ } || { rm -rf "$$dc_destdir"; exit 1; }) \ && rm -rf "$$dc_destdir" \ && $(MAKE) $(AM_MAKEFLAGS) dist \ && rm -rf $(DIST_ARCHIVES) \ && $(MAKE) $(AM_MAKEFLAGS) distcleancheck \ && cd "$$am__cwd" \ || exit 1 $(am__post_remove_distdir) @(echo "$(distdir) archives ready for distribution: "; \ list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \ sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x' distuninstallcheck: @test -n '$(distuninstallcheck_dir)' || { \ echo 'ERROR: trying to run $@ with an empty' \ '$$(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ $(am__cd) '$(distuninstallcheck_dir)' || { \ echo 'ERROR: cannot chdir into $(distuninstallcheck_dir)' >&2; \ exit 1; \ }; \ test `$(am__distuninstallcheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left after uninstall:" ; \ if test -n "$(DESTDIR)"; then \ echo " (check DESTDIR support)"; \ fi ; \ $(distuninstallcheck_listfiles) ; \ exit 1; } >&2 distcleancheck: distclean @if test '$(srcdir)' = . ; then \ echo "ERROR: distcleancheck can only run from a VPATH build" ; \ exit 1 ; \ fi @test `$(distcleancheck_listfiles) | wc -l` -eq 0 \ || { echo "ERROR: files left in build directory after distclean:" ; \ $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am check: check-recursive all-am: Makefile config.h installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -f Makefile distclean-am: clean-am distclean-generic distclean-hdr \ distclean-libtool distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) all install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ am--refresh check check-am clean clean-cscope clean-generic \ clean-libtool cscope cscopelist-am ctags ctags-am dist \ dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \ dist-xz dist-zip distcheck distclean distclean-generic \ distclean-hdr distclean-libtool distclean-tags distcleancheck \ distdir distuninstallcheck dvi dvi-am html html-am info \ info-am install install-am install-data install-data-am \ install-dvi install-dvi-am install-exec install-exec-am \ install-html install-html-am install-info install-info-am \ install-man install-pdf install-pdf-am install-ps \ install-ps-am install-strip installcheck installcheck-am \ installdirs installdirs-am maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/ltmain.sh0000644000175000017500000105204412552216615011750 00000000000000 # libtool (GNU libtool) 2.4.2 # Written by Gordon Matzigkeit , 1996 # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, # 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, # or obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # Usage: $progname [OPTION]... [MODE-ARG]... # # Provide generalized library-building support services. # # --config show all configuration variables # --debug enable verbose shell tracing # -n, --dry-run display commands without modifying any files # --features display basic configuration information and exit # --mode=MODE use operation mode MODE # --preserve-dup-deps don't remove duplicate dependency libraries # --quiet, --silent don't print informational messages # --no-quiet, --no-silent # print informational messages (default) # --no-warn don't display warning messages # --tag=TAG use configuration variables from tag TAG # -v, --verbose print more informational messages than default # --no-verbose don't print the extra informational messages # --version print version information # -h, --help, --help-all print short, long, or detailed help message # # MODE must be one of the following: # # clean remove files from the build directory # compile compile a source file into a libtool object # execute automatically set library path, then run a program # finish complete the installation of libtool libraries # install install libraries or executables # link create a library or an executable # uninstall remove libraries from an installed directory # # MODE-ARGS vary depending on the MODE. When passed as first option, # `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. # Try `$progname --help --mode=MODE' for a more detailed description of MODE. # # When reporting a bug, please describe a test case to reproduce it and # include the following information: # # host-triplet: $host # shell: $SHELL # compiler: $LTCC # compiler flags: $LTCFLAGS # linker: $LD (gnu? $with_gnu_ld) # $progname: (GNU libtool) 2.4.2 Debian-2.4.2-1.7ubuntu1 # automake: $automake_version # autoconf: $autoconf_version # # Report bugs to . # GNU libtool home page: . # General help using GNU software: . PROGRAM=libtool PACKAGE=libtool VERSION="2.4.2 Debian-2.4.2-1.7ubuntu1" TIMESTAMP="" package_revision=1.3337 # Be Bourne compatible if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $1 _LTECHO_EOF' } # NLS nuisances: We save the old values to restore during execute mode. lt_user_locale= lt_safe_locale= for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${$lt_var+set}\" = set; then save_$lt_var=\$$lt_var $lt_var=C export $lt_var lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" fi" done LC_ALL=C LANGUAGE=C export LANGUAGE LC_ALL $lt_unset CDPATH # Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh # is ksh but when the shell is invoked as "sh" and the current value of # the _XPG environment variable is not equal to 1 (one), the special # positional parameter $0, within a function call, is the name of the # function. progpath="$0" : ${CP="cp -f"} test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} : ${MAKE="make"} : ${MKDIR="mkdir"} : ${MV="mv -f"} : ${RM="rm -f"} : ${SHELL="${CONFIG_SHELL-/bin/sh}"} : ${Xsed="$SED -e 1s/^X//"} # Global variables: EXIT_SUCCESS=0 EXIT_FAILURE=1 EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. exit_status=$EXIT_SUCCESS # Make sure IFS has a sensible default lt_nl=' ' IFS=" $lt_nl" dirname="s,/[^/]*$,," basename="s,^.*/,," # func_dirname file append nondir_replacement # Compute the dirname of FILE. If nonempty, add APPEND to the result, # otherwise set result to NONDIR_REPLACEMENT. func_dirname () { func_dirname_result=`$ECHO "${1}" | $SED "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi } # func_dirname may be replaced by extended shell implementation # func_basename file func_basename () { func_basename_result=`$ECHO "${1}" | $SED "$basename"` } # func_basename may be replaced by extended shell implementation # func_dirname_and_basename file append nondir_replacement # perform func_basename and func_dirname in a single function # call: # dirname: Compute the dirname of FILE. If nonempty, # add APPEND to the result, otherwise set result # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. # value retuned in "$func_basename_result" # Implementation must be kept synchronized with func_dirname # and func_basename. For efficiency, we do not delegate to # those functions but instead duplicate the functionality here. func_dirname_and_basename () { # Extract subdirectory from the argument. func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"` if test "X$func_dirname_result" = "X${1}"; then func_dirname_result="${3}" else func_dirname_result="$func_dirname_result${2}" fi func_basename_result=`$ECHO "${1}" | $SED -e "$basename"` } # func_dirname_and_basename may be replaced by extended shell implementation # func_stripname prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # func_strip_suffix prefix name func_stripname () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname may be replaced by extended shell implementation # These SED scripts presuppose an absolute path with a trailing slash. pathcar='s,^/\([^/]*\).*$,\1,' pathcdr='s,^/[^/]*,,' removedotparts=':dotsl s@/\./@/@g t dotsl s,/\.$,/,' collapseslashes='s@/\{1,\}@/@g' finalslash='s,/*$,/,' # func_normal_abspath PATH # Remove doubled-up and trailing slashes, "." path components, # and cancel out any ".." path components in PATH after making # it an absolute path. # value returned in "$func_normal_abspath_result" func_normal_abspath () { # Start from root dir and reassemble the path. func_normal_abspath_result= func_normal_abspath_tpath=$1 func_normal_abspath_altnamespace= case $func_normal_abspath_tpath in "") # Empty path, that just means $cwd. func_stripname '' '/' "`pwd`" func_normal_abspath_result=$func_stripname_result return ;; # The next three entries are used to spot a run of precisely # two leading slashes without using negated character classes; # we take advantage of case's first-match behaviour. ///*) # Unusual form of absolute path, do nothing. ;; //*) # Not necessarily an ordinary path; POSIX reserves leading '//' # and for example Cygwin uses it to access remote file shares # over CIFS/SMB, so we conserve a leading double slash if found. func_normal_abspath_altnamespace=/ ;; /*) # Absolute path, do nothing. ;; *) # Relative path, prepend $cwd. func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath ;; esac # Cancel out all the simple stuff to save iterations. We also want # the path to end with a slash for ease of parsing, so make sure # there is one (and only one) here. func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` while :; do # Processed it all yet? if test "$func_normal_abspath_tpath" = / ; then # If we ascended to the root using ".." the result may be empty now. if test -z "$func_normal_abspath_result" ; then func_normal_abspath_result=/ fi break fi func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcar"` func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ -e "$pathcdr"` # Figure out what to do with it case $func_normal_abspath_tcomponent in "") # Trailing empty path component, ignore it. ;; ..) # Parent dir; strip last assembled component from result. func_dirname "$func_normal_abspath_result" func_normal_abspath_result=$func_dirname_result ;; *) # Actual path component, append it. func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent ;; esac done # Restore leading double-slash if one was found on entry. func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result } # func_relative_path SRCDIR DSTDIR # generates a relative path from SRCDIR to DSTDIR, with a trailing # slash if non-empty, suitable for immediately appending a filename # without needing to append a separator. # value returned in "$func_relative_path_result" func_relative_path () { func_relative_path_result= func_normal_abspath "$1" func_relative_path_tlibdir=$func_normal_abspath_result func_normal_abspath "$2" func_relative_path_tbindir=$func_normal_abspath_result # Ascend the tree starting from libdir while :; do # check if we have found a prefix of bindir case $func_relative_path_tbindir in $func_relative_path_tlibdir) # found an exact match func_relative_path_tcancelled= break ;; $func_relative_path_tlibdir*) # found a matching prefix func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" func_relative_path_tcancelled=$func_stripname_result if test -z "$func_relative_path_result"; then func_relative_path_result=. fi break ;; *) func_dirname $func_relative_path_tlibdir func_relative_path_tlibdir=${func_dirname_result} if test "x$func_relative_path_tlibdir" = x ; then # Have to descend all the way to the root! func_relative_path_result=../$func_relative_path_result func_relative_path_tcancelled=$func_relative_path_tbindir break fi func_relative_path_result=../$func_relative_path_result ;; esac done # Now calculate path; take care to avoid doubling-up slashes. func_stripname '' '/' "$func_relative_path_result" func_relative_path_result=$func_stripname_result func_stripname '/' '/' "$func_relative_path_tcancelled" if test "x$func_stripname_result" != x ; then func_relative_path_result=${func_relative_path_result}/${func_stripname_result} fi # Normalisation. If bindir is libdir, return empty string, # else relative path ending with a slash; either way, target # file name can be directly appended. if test ! -z "$func_relative_path_result"; then func_stripname './' '' "$func_relative_path_result/" func_relative_path_result=$func_stripname_result fi } # The name of this program: func_dirname_and_basename "$progpath" progname=$func_basename_result # Make sure we have an absolute path for reexecution: case $progpath in [\\/]*|[A-Za-z]:\\*) ;; *[\\/]*) progdir=$func_dirname_result progdir=`cd "$progdir" && pwd` progpath="$progdir/$progname" ;; *) save_IFS="$IFS" IFS=${PATH_SEPARATOR-:} for progdir in $PATH; do IFS="$save_IFS" test -x "$progdir/$progname" && break done IFS="$save_IFS" test -n "$progdir" || progdir=`pwd` progpath="$progdir/$progname" ;; esac # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. Xsed="${SED}"' -e 1s/^X//' sed_quote_subst='s/\([`"$\\]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\(["`\\]\)/\\\1/g' # Sed substitution that turns a string into a regex matching for the # string literally. sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' # Sed substitution that converts a w32 file name or path # which contains forward slashes, into one that contains # (escaped) backslashes. A very naive implementation. lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' # Re-`\' parameter expansions in output of double_quote_subst that were # `\'-ed in input to the same. If an odd number of `\' preceded a '$' # in input to double_quote_subst, that '$' was protected from expansion. # Since each input `\' is now two `\'s, look for any number of runs of # four `\'s followed by two `\'s and then a '$'. `\' that '$'. bs='\\' bs2='\\\\' bs4='\\\\\\\\' dollar='\$' sed_double_backslash="\ s/$bs4/&\\ /g s/^$bs2$dollar/$bs&/ s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g s/\n//g" # Standard options: opt_dry_run=false opt_help=false opt_quiet=false opt_verbose=false opt_warning=: # func_echo arg... # Echo program name prefixed message, along with the current mode # name if it has been set yet. func_echo () { $ECHO "$progname: ${opt_mode+$opt_mode: }$*" } # func_verbose arg... # Echo program name prefixed message in verbose mode only. func_verbose () { $opt_verbose && func_echo ${1+"$@"} # A bug in bash halts the script if the last line of a function # fails when set -e is in force, so we need another command to # work around that: : } # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } # func_error arg... # Echo program name prefixed message to standard error. func_error () { $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 } # func_warning arg... # Echo program name prefixed warning message to standard error. func_warning () { $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 # bash bug again: : } # func_fatal_error arg... # Echo program name prefixed message to standard error, and exit. func_fatal_error () { func_error ${1+"$@"} exit $EXIT_FAILURE } # func_fatal_help arg... # Echo program name prefixed message to standard error, followed by # a help hint, and exit. func_fatal_help () { func_error ${1+"$@"} func_fatal_error "$help" } help="Try \`$progname --help' for more information." ## default # func_grep expression filename # Check whether EXPRESSION matches any line of FILENAME, without output. func_grep () { $GREP "$1" "$2" >/dev/null 2>&1 } # func_mkdir_p directory-path # Make sure the entire path to DIRECTORY-PATH is available. func_mkdir_p () { my_directory_path="$1" my_dir_list= if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then # Protect directory names starting with `-' case $my_directory_path in -*) my_directory_path="./$my_directory_path" ;; esac # While some portion of DIR does not yet exist... while test ! -d "$my_directory_path"; do # ...make a list in topmost first order. Use a colon delimited # list incase some portion of path contains whitespace. my_dir_list="$my_directory_path:$my_dir_list" # If the last portion added has no slash in it, the list is done case $my_directory_path in */*) ;; *) break ;; esac # ...otherwise throw away the child directory and loop my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` done my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` save_mkdir_p_IFS="$IFS"; IFS=':' for my_dir in $my_dir_list; do IFS="$save_mkdir_p_IFS" # mkdir can fail with a `File exist' error if two processes # try to create one of the directories concurrently. Don't # stop in that case! $MKDIR "$my_dir" 2>/dev/null || : done IFS="$save_mkdir_p_IFS" # Bail out if we (or some other process) failed to create a directory. test -d "$my_directory_path" || \ func_fatal_error "Failed to create \`$1'" fi } # func_mktempdir [string] # Make a temporary directory that won't clash with other running # libtool processes, and avoids race conditions if possible. If # given, STRING is the basename for that directory. func_mktempdir () { my_template="${TMPDIR-/tmp}/${1-$progname}" if test "$opt_dry_run" = ":"; then # Return a directory name, but don't create it in dry-run mode my_tmpdir="${my_template}-$$" else # If mktemp works, use that first and foremost my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` if test ! -d "$my_tmpdir"; then # Failing that, at least try and use $RANDOM to avoid a race my_tmpdir="${my_template}-${RANDOM-0}$$" save_mktempdir_umask=`umask` umask 0077 $MKDIR "$my_tmpdir" umask $save_mktempdir_umask fi # If we're not in dry-run mode, bomb out on failure test -d "$my_tmpdir" || \ func_fatal_error "cannot create temporary directory \`$my_tmpdir'" fi $ECHO "$my_tmpdir" } # func_quote_for_eval arg # Aesthetically quote ARG to be evaled later. # This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT # is double-quoted, suitable for a subsequent eval, whereas # FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters # which are still active within double quotes backslashified. func_quote_for_eval () { case $1 in *[\\\`\"\$]*) func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; *) func_quote_for_eval_unquoted_result="$1" ;; esac case $func_quote_for_eval_unquoted_result in # Double-quote args containing shell metacharacters to delay # word splitting, command substitution and and variable # expansion for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" ;; *) func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" esac } # func_quote_for_expand arg # Aesthetically quote ARG to be evaled later; same as above, # but do not quote variable references. func_quote_for_expand () { case $1 in *[\\\`\"]*) my_arg=`$ECHO "$1" | $SED \ -e "$double_quote_subst" -e "$sed_double_backslash"` ;; *) my_arg="$1" ;; esac case $my_arg in # Double-quote args containing shell metacharacters to delay # word splitting and command substitution for a subsequent eval. # Many Bourne shells cannot handle close brackets correctly # in scan sets, so we specify it separately. *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") my_arg="\"$my_arg\"" ;; esac func_quote_for_expand_result="$my_arg" } # func_show_eval cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. func_show_eval () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$my_cmd" my_status=$? if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_show_eval_locale cmd [fail_exp] # Unless opt_silent is true, then output CMD. Then, if opt_dryrun is # not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP # is given, then evaluate it. Use the saved locale for evaluation. func_show_eval_locale () { my_cmd="$1" my_fail_exp="${2-:}" ${opt_silent-false} || { func_quote_for_expand "$my_cmd" eval "func_echo $func_quote_for_expand_result" } if ${opt_dry_run-false}; then :; else eval "$lt_user_locale $my_cmd" my_status=$? eval "$lt_safe_locale" if test "$my_status" -eq 0; then :; else eval "(exit $my_status); $my_fail_exp" fi fi } # func_tr_sh # Turn $1 into a string suitable for a shell variable name. # Result is stored in $func_tr_sh_result. All characters # not in the set a-zA-Z0-9_ are replaced with '_'. Further, # if $1 begins with a digit, a '_' is prepended as well. func_tr_sh () { case $1 in [0-9]* | *[!a-zA-Z0-9_]*) func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` ;; * ) func_tr_sh_result=$1 ;; esac } # func_version # Echo version message to standard output and exit. func_version () { $opt_debug $SED -n '/(C)/!b go :more /\./!{ N s/\n# / / b more } :go /^# '$PROGRAM' (GNU /,/# warranty; / { s/^# // s/^# *$// s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ p }' < "$progpath" exit $? } # func_usage # Echo short help message to standard output and exit. func_usage () { $opt_debug $SED -n '/^# Usage:/,/^# *.*--help/ { s/^# // s/^# *$// s/\$progname/'$progname'/ p }' < "$progpath" echo $ECHO "run \`$progname --help | more' for full usage" exit $? } # func_help [NOEXIT] # Echo long help message to standard output and exit, # unless 'noexit' is passed as argument. func_help () { $opt_debug $SED -n '/^# Usage:/,/# Report bugs to/ { :print s/^# // s/^# *$// s*\$progname*'$progname'* s*\$host*'"$host"'* s*\$SHELL*'"$SHELL"'* s*\$LTCC*'"$LTCC"'* s*\$LTCFLAGS*'"$LTCFLAGS"'* s*\$LD*'"$LD"'* s/\$with_gnu_ld/'"$with_gnu_ld"'/ s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ p d } /^# .* home page:/b print /^# General help using/b print ' < "$progpath" ret=$? if test -z "$1"; then exit $ret fi } # func_missing_arg argname # Echo program name prefixed message to standard error and set global # exit_cmd. func_missing_arg () { $opt_debug func_error "missing argument for $1." exit_cmd=exit } # func_split_short_opt shortopt # Set func_split_short_opt_name and func_split_short_opt_arg shell # variables after splitting SHORTOPT after the 2nd character. func_split_short_opt () { my_sed_short_opt='1s/^\(..\).*$/\1/;q' my_sed_short_rest='1s/^..\(.*\)$/\1/;q' func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"` func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"` } # func_split_short_opt may be replaced by extended shell implementation # func_split_long_opt longopt # Set func_split_long_opt_name and func_split_long_opt_arg shell # variables after splitting LONGOPT at the `=' sign. func_split_long_opt () { my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q' my_sed_long_arg='1s/^--[^=]*=//' func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"` func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"` } # func_split_long_opt may be replaced by extended shell implementation exit_cmd=: magic="%%%MAGIC variable%%%" magic_exe="%%%MAGIC EXE variable%%%" # Global variables. nonopt= preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" extracted_archives= extracted_serial=0 # If this variable is set in any of the actions, the command in it # will be execed at the end. This prevents here-documents from being # left over by shells. exec_cmd= # func_append var value # Append VALUE to the end of shell variable VAR. func_append () { eval "${1}=\$${1}\${2}" } # func_append may be replaced by extended shell implementation # func_append_quoted var value # Quote VALUE and append to the end of shell variable VAR, separated # by a space. func_append_quoted () { func_quote_for_eval "${2}" eval "${1}=\$${1}\\ \$func_quote_for_eval_result" } # func_append_quoted may be replaced by extended shell implementation # func_arith arithmetic-term... func_arith () { func_arith_result=`expr "${@}"` } # func_arith may be replaced by extended shell implementation # func_len string # STRING may not start with a hyphen. func_len () { func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len` } # func_len may be replaced by extended shell implementation # func_lo2o object func_lo2o () { func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"` } # func_lo2o may be replaced by extended shell implementation # func_xform libobj-or-source func_xform () { func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'` } # func_xform may be replaced by extended shell implementation # func_fatal_configuration arg... # Echo program name prefixed message to standard error, followed by # a configuration failure hint, and exit. func_fatal_configuration () { func_error ${1+"$@"} func_error "See the $PACKAGE documentation for more information." func_fatal_error "Fatal configuration error." } # func_config # Display the configuration for all the tags in this script. func_config () { re_begincf='^# ### BEGIN LIBTOOL' re_endcf='^# ### END LIBTOOL' # Default configuration. $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" # Now print the configurations for the tags. for tagname in $taglist; do $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" done exit $? } # func_features # Display the features supported by this script. func_features () { echo "host: $host" if test "$build_libtool_libs" = yes; then echo "enable shared libraries" else echo "disable shared libraries" fi if test "$build_old_libs" = yes; then echo "enable static libraries" else echo "disable static libraries" fi exit $? } # func_enable_tag tagname # Verify that TAGNAME is valid, and either flag an error and exit, or # enable the TAGNAME tag. We also add TAGNAME to the global $taglist # variable here. func_enable_tag () { # Global variable: tagname="$1" re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" sed_extractcf="/$re_begincf/,/$re_endcf/p" # Validate tagname. case $tagname in *[!-_A-Za-z0-9,/]*) func_fatal_error "invalid tag name: $tagname" ;; esac # Don't test for the "default" C tag, as we know it's # there but not specially marked. case $tagname in CC) ;; *) if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then taglist="$taglist $tagname" # Evaluate the configuration. Be careful to quote the path # and the sed script, to avoid splitting on whitespace, but # also don't use non-portable quotes within backquotes within # quotes we have to do it in 2 steps: extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` eval "$extractedcf" else func_error "ignoring unknown tag $tagname" fi ;; esac } # func_check_version_match # Ensure that we are using m4 macros, and libtool script from the same # release of libtool. func_check_version_match () { if test "$package_revision" != "$macro_revision"; then if test "$VERSION" != "$macro_version"; then if test -z "$macro_version"; then cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from an older release. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, but the $progname: definition of this LT_INIT comes from $PACKAGE $macro_version. $progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION $progname: and run autoconf again. _LT_EOF fi else cat >&2 <<_LT_EOF $progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, $progname: but the definition of this LT_INIT comes from revision $macro_revision. $progname: You should recreate aclocal.m4 with macros from revision $package_revision $progname: of $PACKAGE $VERSION and run autoconf again. _LT_EOF fi exit $EXIT_MISMATCH fi } # Shorthand for --mode=foo, only valid as the first argument case $1 in clean|clea|cle|cl) shift; set dummy --mode clean ${1+"$@"}; shift ;; compile|compil|compi|comp|com|co|c) shift; set dummy --mode compile ${1+"$@"}; shift ;; execute|execut|execu|exec|exe|ex|e) shift; set dummy --mode execute ${1+"$@"}; shift ;; finish|finis|fini|fin|fi|f) shift; set dummy --mode finish ${1+"$@"}; shift ;; install|instal|insta|inst|ins|in|i) shift; set dummy --mode install ${1+"$@"}; shift ;; link|lin|li|l) shift; set dummy --mode link ${1+"$@"}; shift ;; uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) shift; set dummy --mode uninstall ${1+"$@"}; shift ;; esac # Option defaults: opt_debug=: opt_dry_run=false opt_config=false opt_preserve_dup_deps=false opt_features=false opt_finish=false opt_help=false opt_help_all=false opt_silent=: opt_warning=: opt_verbose=: opt_silent=false opt_verbose=false # Parse options once, thoroughly. This comes as soon as possible in the # script to make things like `--version' happen as quickly as we can. { # this just eases exit handling while test $# -gt 0; do opt="$1" shift case $opt in --debug|-x) opt_debug='set -x' func_echo "enabling shell trace mode" $opt_debug ;; --dry-run|--dryrun|-n) opt_dry_run=: ;; --config) opt_config=: func_config ;; --dlopen|-dlopen) optarg="$1" opt_dlopen="${opt_dlopen+$opt_dlopen }$optarg" shift ;; --preserve-dup-deps) opt_preserve_dup_deps=: ;; --features) opt_features=: func_features ;; --finish) opt_finish=: set dummy --mode finish ${1+"$@"}; shift ;; --help) opt_help=: ;; --help-all) opt_help_all=: opt_help=': help-all' ;; --mode) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_mode="$optarg" case $optarg in # Valid mode arguments: clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error *) func_error "invalid argument for $opt" exit_cmd=exit break ;; esac shift ;; --no-silent|--no-quiet) opt_silent=false func_append preserve_args " $opt" ;; --no-warning|--no-warn) opt_warning=false func_append preserve_args " $opt" ;; --no-verbose) opt_verbose=false func_append preserve_args " $opt" ;; --silent|--quiet) opt_silent=: func_append preserve_args " $opt" opt_verbose=false ;; --verbose|-v) opt_verbose=: func_append preserve_args " $opt" opt_silent=false ;; --tag) test $# = 0 && func_missing_arg $opt && break optarg="$1" opt_tag="$optarg" func_append preserve_args " $opt $optarg" func_enable_tag "$optarg" shift ;; -\?|-h) func_usage ;; --help) func_help ;; --version) func_version ;; # Separate optargs to long options: --*=*) func_split_long_opt "$opt" set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} shift ;; # Separate non-argument short options: -\?*|-h*|-n*|-v*) func_split_short_opt "$opt" set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} shift ;; --) break ;; -*) func_fatal_help "unrecognized option \`$opt'" ;; *) set dummy "$opt" ${1+"$@"}; shift; break ;; esac done # Validate options: # save first non-option argument if test "$#" -gt 0; then nonopt="$opt" shift fi # preserve --debug test "$opt_debug" = : || func_append preserve_args " --debug" case $host in *cygwin* | *mingw* | *pw32* | *cegcc*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; *) opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps ;; esac $opt_help || { # Sanity checks first: func_check_version_match if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then func_fatal_configuration "not configured to build any kind of library" fi # Darwin sucks eval std_shrext=\"$shrext_cmds\" # Only execute mode is allowed to have -dlopen flags. if test -n "$opt_dlopen" && test "$opt_mode" != execute; then func_error "unrecognized option \`-dlopen'" $ECHO "$help" 1>&2 exit $EXIT_FAILURE fi # Change the help message to a mode-specific one. generic_help="$help" help="Try \`$progname --help --mode=$opt_mode' for more information." } # Bail if the options were screwed $exit_cmd $EXIT_FAILURE } ## ----------- ## ## Main. ## ## ----------- ## # func_lalib_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_lalib_p () { test -f "$1" && $SED -e 4q "$1" 2>/dev/null \ | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 } # func_lalib_unsafe_p file # True iff FILE is a libtool `.la' library or `.lo' object file. # This function implements the same check as func_lalib_p without # resorting to external programs. To this end, it redirects stdin and # closes it afterwards, without saving the original file descriptor. # As a safety measure, use it only where a negative result would be # fatal anyway. Works if `file' does not exist. func_lalib_unsafe_p () { lalib_p=no if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then for lalib_p_l in 1 2 3 4 do read lalib_p_line case "$lalib_p_line" in \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; esac done exec 0<&5 5<&- fi test "$lalib_p" = yes } # func_ltwrapper_script_p file # True iff FILE is a libtool wrapper script # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_script_p () { func_lalib_p "$1" } # func_ltwrapper_executable_p file # True iff FILE is a libtool wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_executable_p () { func_ltwrapper_exec_suffix= case $1 in *.exe) ;; *) func_ltwrapper_exec_suffix=.exe ;; esac $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 } # func_ltwrapper_scriptname file # Assumes file is an ltwrapper_executable # uses $file to determine the appropriate filename for a # temporary ltwrapper_script. func_ltwrapper_scriptname () { func_dirname_and_basename "$1" "" "." func_stripname '' '.exe' "$func_basename_result" func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" } # func_ltwrapper_p file # True iff FILE is a libtool wrapper script or wrapper executable # This function is only a basic sanity check; it will hardly flush out # determined imposters. func_ltwrapper_p () { func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" } # func_execute_cmds commands fail_cmd # Execute tilde-delimited COMMANDS. # If FAIL_CMD is given, eval that upon failure. # FAIL_CMD may read-access the current command in variable CMD! func_execute_cmds () { $opt_debug save_ifs=$IFS; IFS='~' for cmd in $1; do IFS=$save_ifs eval cmd=\"$cmd\" func_show_eval "$cmd" "${2-:}" done IFS=$save_ifs } # func_source file # Source FILE, adding directory component if necessary. # Note that it is not necessary on cygwin/mingw to append a dot to # FILE even if both FILE and FILE.exe exist: automatic-append-.exe # behavior happens only for exec(3), not for open(2)! Also, sourcing # `FILE.' does not work on cygwin managed mounts. func_source () { $opt_debug case $1 in */* | *\\*) . "$1" ;; *) . "./$1" ;; esac } # func_resolve_sysroot PATH # Replace a leading = in PATH with a sysroot. Store the result into # func_resolve_sysroot_result func_resolve_sysroot () { func_resolve_sysroot_result=$1 case $func_resolve_sysroot_result in =*) func_stripname '=' '' "$func_resolve_sysroot_result" func_resolve_sysroot_result=$lt_sysroot$func_stripname_result ;; esac } # func_replace_sysroot PATH # If PATH begins with the sysroot, replace it with = and # store the result into func_replace_sysroot_result. func_replace_sysroot () { case "$lt_sysroot:$1" in ?*:"$lt_sysroot"*) func_stripname "$lt_sysroot" '' "$1" func_replace_sysroot_result="=$func_stripname_result" ;; *) # Including no sysroot. func_replace_sysroot_result=$1 ;; esac } # func_infer_tag arg # Infer tagged configuration to use if any are available and # if one wasn't chosen via the "--tag" command line option. # Only attempt this if the compiler in the base compile # command doesn't match the default compiler. # arg is usually of the form 'gcc ...' func_infer_tag () { $opt_debug if test -n "$available_tags" && test -z "$tagname"; then CC_quoted= for arg in $CC; do func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case $@ in # Blanks in the command may have been stripped by the calling shell, # but not from the CC environment variable when configure was run. " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; # Blanks at the start of $base_compile will cause this to fail # if we don't check for them as well. *) for z in $available_tags; do if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then # Evaluate the configuration. eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" CC_quoted= for arg in $CC; do # Double-quote args containing other shell metacharacters. func_append_quoted CC_quoted "$arg" done CC_expanded=`func_echo_all $CC` CC_quoted_expanded=`func_echo_all $CC_quoted` case "$@ " in " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) # The compiler in the base compile command matches # the one in the tagged configuration. # Assume this is the tagged configuration we want. tagname=$z break ;; esac fi done # If $tagname still isn't set, then no tagged configuration # was found and let the user know that the "--tag" command # line option must be used. if test -z "$tagname"; then func_echo "unable to infer tagged configuration" func_fatal_error "specify a tag with \`--tag'" # else # func_verbose "using $tagname tagged configuration" fi ;; esac fi } # func_write_libtool_object output_name pic_name nonpic_name # Create a libtool object file (analogous to a ".la" file), # but don't create it if we're doing a dry run. func_write_libtool_object () { write_libobj=${1} if test "$build_libtool_libs" = yes; then write_lobj=\'${2}\' else write_lobj=none fi if test "$build_old_libs" = yes; then write_oldobj=\'${3}\' else write_oldobj=none fi $opt_dry_run || { cat >${write_libobj}T </dev/null` if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | $SED -e "$lt_sed_naive_backslashify"` else func_convert_core_file_wine_to_w32_result= fi fi } # end: func_convert_core_file_wine_to_w32 # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and # $host is mingw, cygwin, or some other w32 environment. Relies on a correctly # configured wine environment available, with the winepath program in $build's # $PATH. Assumes ARG has no leading or trailing path separator characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. # Unconvertible file (directory) names in ARG are skipped; if no directory names # are convertible, then the result may be empty. func_convert_core_path_wine_to_w32 () { $opt_debug # unfortunately, winepath doesn't convert paths, only file names func_convert_core_path_wine_to_w32_result="" if test -n "$1"; then oldIFS=$IFS IFS=: for func_convert_core_path_wine_to_w32_f in $1; do IFS=$oldIFS func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" if test -n "$func_convert_core_file_wine_to_w32_result" ; then if test -z "$func_convert_core_path_wine_to_w32_result"; then func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" else func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" fi fi done IFS=$oldIFS fi } # end: func_convert_core_path_wine_to_w32 # func_cygpath ARGS... # Wrapper around calling the cygpath program via LT_CYGPATH. This is used when # when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) # $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or # (2), returns the Cygwin file name or path in func_cygpath_result (input # file name or path is assumed to be in w32 format, as previously converted # from $build's *nix or MSYS format). In case (3), returns the w32 file name # or path in func_cygpath_result (input file name or path is assumed to be in # Cygwin format). Returns an empty string on error. # # ARGS are passed to cygpath, with the last one being the file name or path to # be converted. # # Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH # environment variable; do not put it in $PATH. func_cygpath () { $opt_debug if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` if test "$?" -ne 0; then # on failure, ensure result is empty func_cygpath_result= fi else func_cygpath_result= func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" fi } #end: func_cygpath # func_convert_core_msys_to_w32 ARG # Convert file name or path ARG from MSYS format to w32 format. Return # result in func_convert_core_msys_to_w32_result. func_convert_core_msys_to_w32 () { $opt_debug # awkward: cmd appends spaces to result func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` } #end: func_convert_core_msys_to_w32 # func_convert_file_check ARG1 ARG2 # Verify that ARG1 (a file name in $build format) was converted to $host # format in ARG2. Otherwise, emit an error message, but continue (resetting # func_to_host_file_result to ARG1). func_convert_file_check () { $opt_debug if test -z "$2" && test -n "$1" ; then func_error "Could not determine host file name corresponding to" func_error " \`$1'" func_error "Continuing, but uninstalled executables may not work." # Fallback: func_to_host_file_result="$1" fi } # end func_convert_file_check # func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH # Verify that FROM_PATH (a path in $build format) was converted to $host # format in TO_PATH. Otherwise, emit an error message, but continue, resetting # func_to_host_file_result to a simplistic fallback value (see below). func_convert_path_check () { $opt_debug if test -z "$4" && test -n "$3"; then func_error "Could not determine the host path corresponding to" func_error " \`$3'" func_error "Continuing, but uninstalled executables may not work." # Fallback. This is a deliberately simplistic "conversion" and # should not be "improved". See libtool.info. if test "x$1" != "x$2"; then lt_replace_pathsep_chars="s|$1|$2|g" func_to_host_path_result=`echo "$3" | $SED -e "$lt_replace_pathsep_chars"` else func_to_host_path_result="$3" fi fi } # end func_convert_path_check # func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG # Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT # and appending REPL if ORIG matches BACKPAT. func_convert_path_front_back_pathsep () { $opt_debug case $4 in $1 ) func_to_host_path_result="$3$func_to_host_path_result" ;; esac case $4 in $2 ) func_append func_to_host_path_result "$3" ;; esac } # end func_convert_path_front_back_pathsep ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## # invoked via `$to_host_file_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # Result will be available in $func_to_host_file_result. # func_to_host_file ARG # Converts the file name ARG from $build format to $host format. Return result # in func_to_host_file_result. func_to_host_file () { $opt_debug $to_host_file_cmd "$1" } # end func_to_host_file # func_to_tool_file ARG LAZY # converts the file name ARG from $build format to toolchain format. Return # result in func_to_tool_file_result. If the conversion in use is listed # in (the comma separated) LAZY, no conversion takes place. func_to_tool_file () { $opt_debug case ,$2, in *,"$to_tool_file_cmd",*) func_to_tool_file_result=$1 ;; *) $to_tool_file_cmd "$1" func_to_tool_file_result=$func_to_host_file_result ;; esac } # end func_to_tool_file # func_convert_file_noop ARG # Copy ARG to func_to_host_file_result. func_convert_file_noop () { func_to_host_file_result="$1" } # end func_convert_file_noop # func_convert_file_msys_to_w32 ARG # Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_file_result. func_convert_file_msys_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_to_host_file_result="$func_convert_core_msys_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_w32 # func_convert_file_cygwin_to_w32 ARG # Convert file name ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_file_cygwin_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # because $build is cygwin, we call "the" cygpath in $PATH; no need to use # LT_CYGPATH in this case. func_to_host_file_result=`cygpath -m "$1"` fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_cygwin_to_w32 # func_convert_file_nix_to_w32 ARG # Convert file name ARG from *nix to w32 format. Requires a wine environment # and a working winepath. Returns result in func_to_host_file_result. func_convert_file_nix_to_w32 () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_file_wine_to_w32 "$1" func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_w32 # func_convert_file_msys_to_cygwin ARG # Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_file_msys_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then func_convert_core_msys_to_w32 "$1" func_cygpath -u "$func_convert_core_msys_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_msys_to_cygwin # func_convert_file_nix_to_cygwin ARG # Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed # in a wine environment, working winepath, and LT_CYGPATH set. Returns result # in func_to_host_file_result. func_convert_file_nix_to_cygwin () { $opt_debug func_to_host_file_result="$1" if test -n "$1"; then # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. func_convert_core_file_wine_to_w32 "$1" func_cygpath -u "$func_convert_core_file_wine_to_w32_result" func_to_host_file_result="$func_cygpath_result" fi func_convert_file_check "$1" "$func_to_host_file_result" } # end func_convert_file_nix_to_cygwin ############################################# # $build to $host PATH CONVERSION FUNCTIONS # ############################################# # invoked via `$to_host_path_cmd ARG' # # In each case, ARG is the path to be converted from $build to $host format. # The result will be available in $func_to_host_path_result. # # Path separators are also converted from $build format to $host format. If # ARG begins or ends with a path separator character, it is preserved (but # converted to $host format) on output. # # All path conversion functions are named using the following convention: # file name conversion function : func_convert_file_X_to_Y () # path conversion function : func_convert_path_X_to_Y () # where, for any given $build/$host combination the 'X_to_Y' value is the # same. If conversion functions are added for new $build/$host combinations, # the two new functions must follow this pattern, or func_init_to_host_path_cmd # will break. # func_init_to_host_path_cmd # Ensures that function "pointer" variable $to_host_path_cmd is set to the # appropriate value, based on the value of $to_host_file_cmd. to_host_path_cmd= func_init_to_host_path_cmd () { $opt_debug if test -z "$to_host_path_cmd"; then func_stripname 'func_convert_file_' '' "$to_host_file_cmd" to_host_path_cmd="func_convert_path_${func_stripname_result}" fi } # func_to_host_path ARG # Converts the path ARG from $build format to $host format. Return result # in func_to_host_path_result. func_to_host_path () { $opt_debug func_init_to_host_path_cmd $to_host_path_cmd "$1" } # end func_to_host_path # func_convert_path_noop ARG # Copy ARG to func_to_host_path_result. func_convert_path_noop () { func_to_host_path_result="$1" } # end func_convert_path_noop # func_convert_path_msys_to_w32 ARG # Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic # conversion to w32 is not available inside the cwrapper. Returns result in # func_to_host_path_result. func_convert_path_msys_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from ARG. MSYS # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; # and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_msys_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_msys_to_w32 # func_convert_path_cygwin_to_w32 ARG # Convert path ARG from Cygwin to w32 format. Returns result in # func_to_host_file_result. func_convert_path_cygwin_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_cygwin_to_w32 # func_convert_path_nix_to_w32 ARG # Convert path ARG from *nix to w32 format. Requires a wine environment and # a working winepath. Returns result in func_to_host_file_result. func_convert_path_nix_to_w32 () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" func_convert_path_check : ";" \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" fi } # end func_convert_path_nix_to_w32 # func_convert_path_msys_to_cygwin ARG # Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. # Returns result in func_to_host_file_result. func_convert_path_msys_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # See func_convert_path_msys_to_w32: func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_msys_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_msys_to_cygwin # func_convert_path_nix_to_cygwin ARG # Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a # a wine environment, working winepath, and LT_CYGPATH set. Returns result in # func_to_host_file_result. func_convert_path_nix_to_cygwin () { $opt_debug func_to_host_path_result="$1" if test -n "$1"; then # Remove leading and trailing path separator characters from # ARG. msys behavior is inconsistent here, cygpath turns them # into '.;' and ';.', and winepath ignores them completely. func_stripname : : "$1" func_to_host_path_tmp1=$func_stripname_result func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" func_to_host_path_result="$func_cygpath_result" func_convert_path_check : : \ "$func_to_host_path_tmp1" "$func_to_host_path_result" func_convert_path_front_back_pathsep ":*" "*:" : "$1" fi } # end func_convert_path_nix_to_cygwin # func_mode_compile arg... func_mode_compile () { $opt_debug # Get the compilation command and the source file. base_compile= srcfile="$nonopt" # always keep a non-empty value in "srcfile" suppress_opt=yes suppress_output= arg_mode=normal libobj= later= pie_flag= for arg do case $arg_mode in arg ) # do not "continue". Instead, add this to base_compile lastarg="$arg" arg_mode=normal ;; target ) libobj="$arg" arg_mode=normal continue ;; normal ) # Accept any command-line options. case $arg in -o) test -n "$libobj" && \ func_fatal_error "you cannot specify \`-o' more than once" arg_mode=target continue ;; -pie | -fpie | -fPIE) func_append pie_flag " $arg" continue ;; -shared | -static | -prefer-pic | -prefer-non-pic) func_append later " $arg" continue ;; -no-suppress) suppress_opt=no continue ;; -Xcompiler) arg_mode=arg # the next one goes into the "base_compile" arg list continue # The current "srcfile" will either be retained or ;; # replaced later. I would guess that would be a bug. -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result lastarg= save_ifs="$IFS"; IFS=',' for arg in $args; do IFS="$save_ifs" func_append_quoted lastarg "$arg" done IFS="$save_ifs" func_stripname ' ' '' "$lastarg" lastarg=$func_stripname_result # Add the arguments to base_compile. func_append base_compile " $lastarg" continue ;; *) # Accept the current argument as the source file. # The previous "srcfile" becomes the current argument. # lastarg="$srcfile" srcfile="$arg" ;; esac # case $arg ;; esac # case $arg_mode # Aesthetically quote the previous argument. func_append_quoted base_compile "$lastarg" done # for arg case $arg_mode in arg) func_fatal_error "you must specify an argument for -Xcompile" ;; target) func_fatal_error "you must specify a target with \`-o'" ;; *) # Get the name of the library object. test -z "$libobj" && { func_basename "$srcfile" libobj="$func_basename_result" } ;; esac # Recognize several different file suffixes. # If the user specifies -o file.o, it is replaced with file.lo case $libobj in *.[cCFSifmso] | \ *.ada | *.adb | *.ads | *.asm | \ *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) func_xform "$libobj" libobj=$func_xform_result ;; esac case $libobj in *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; *) func_fatal_error "cannot determine name of library object from \`$libobj'" ;; esac func_infer_tag $base_compile for arg in $later; do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no continue ;; -static) build_libtool_libs=no build_old_libs=yes continue ;; -prefer-pic) pic_mode=yes continue ;; -prefer-non-pic) pic_mode=no continue ;; esac done func_quote_for_eval "$libobj" test "X$libobj" != "X$func_quote_for_eval_result" \ && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ && func_warning "libobj name \`$libobj' may not contain shell special characters." func_dirname_and_basename "$obj" "/" "" objname="$func_basename_result" xdir="$func_dirname_result" lobj=${xdir}$objdir/$objname test -z "$base_compile" && \ func_fatal_help "you must specify a compilation command" # Delete any leftover library objects. if test "$build_old_libs" = yes; then removelist="$obj $lobj $libobj ${libobj}T" else removelist="$lobj $libobj ${libobj}T" fi # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in cygwin* | mingw* | pw32* | os2* | cegcc*) pic_mode=default ;; esac if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then # non-PIC code in shared libraries is not supported pic_mode=default fi # Calculate the filename of the output object if compiler does # not support -o with -c if test "$compiler_c_o" = no; then output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} lockfile="$output_obj.lock" else output_obj= need_locks=no lockfile= fi # Lock this critical section if it is needed # We use this script file to make the link, it avoids creating a new file if test "$need_locks" = yes; then until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done elif test "$need_locks" = warn; then if test -f "$lockfile"; then $ECHO "\ *** ERROR, $lockfile exists and contains: `cat $lockfile 2>/dev/null` This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi func_append removelist " $output_obj" $ECHO "$srcfile" > "$lockfile" fi $opt_dry_run || $RM $removelist func_append removelist " $lockfile" trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 srcfile=$func_to_tool_file_result func_quote_for_eval "$srcfile" qsrcfile=$func_quote_for_eval_result # Only build a PIC object if we are building libtool libraries. if test "$build_libtool_libs" = yes; then # Without this assignment, base_compile gets emptied. fbsd_hideous_sh_bug=$base_compile if test "$pic_mode" != no; then command="$base_compile $qsrcfile $pic_flag" else # Don't build PIC code command="$base_compile $qsrcfile" fi func_mkdir_p "$xdir$objdir" if test -z "$output_obj"; then # Place PIC objects in $objdir func_append command " -o $lobj" fi func_show_eval_locale "$command" \ 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed, then go on to compile the next one if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then func_show_eval '$MV "$output_obj" "$lobj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi # Allow error messages only from the first compilation. if test "$suppress_opt" = yes; then suppress_output=' >/dev/null 2>&1' fi fi # Only build a position-dependent object if we build old libraries. if test "$build_old_libs" = yes; then if test "$pic_mode" != yes; then # Don't build PIC code command="$base_compile $qsrcfile$pie_flag" else command="$base_compile $qsrcfile $pic_flag" fi if test "$compiler_c_o" = yes; then func_append command " -o $obj" fi # Suppress compiler output if we already did a PIC compilation. func_append command "$suppress_output" func_show_eval_locale "$command" \ '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' if test "$need_locks" = warn && test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then $ECHO "\ *** ERROR, $lockfile contains: `cat $lockfile 2>/dev/null` but it should contain: $srcfile This indicates that another process is trying to use the same temporary object file, and libtool could not work around it because your compiler does not support \`-c' and \`-o' together. If you repeat this compilation, it may succeed, by chance, but you had better avoid parallel builds (make -j) in this platform, or get a better compiler." $opt_dry_run || $RM $removelist exit $EXIT_FAILURE fi # Just move the object if needed if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then func_show_eval '$MV "$output_obj" "$obj"' \ 'error=$?; $opt_dry_run || $RM $removelist; exit $error' fi fi $opt_dry_run || { func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" # Unlock the critical section if it was locked if test "$need_locks" != no; then removelist=$lockfile $RM "$lockfile" fi } exit $EXIT_SUCCESS } $opt_help || { test "$opt_mode" = compile && func_mode_compile ${1+"$@"} } func_mode_help () { # We need to display help for each of the modes. case $opt_mode in "") # Generic help is extracted from the usage comments # at the start of this file. func_help ;; clean) $ECHO \ "Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... Remove files from the build directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, object or program, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; compile) $ECHO \ "Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE Compile a source file into a libtool library object. This mode accepts the following additional options: -o OUTPUT-FILE set the output file name to OUTPUT-FILE -no-suppress do not suppress compiler output for multiple passes -prefer-pic try to build PIC objects only -prefer-non-pic try to build non-PIC objects only -shared do not build a \`.o' file suitable for static linking -static only build a \`.o' file suitable for static linking -Wc,FLAG pass FLAG directly to the compiler COMPILE-COMMAND is a command to be used in creating a \`standard' object file from the given SOURCEFILE. The output file name is determined by removing the directory component from SOURCEFILE, then substituting the C source code suffix \`.c' with the library object suffix, \`.lo'." ;; execute) $ECHO \ "Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... Automatically set library path, then run a program. This mode accepts the following additional options: -dlopen FILE add the directory containing FILE to the library path This mode sets the library path environment variable according to \`-dlopen' flags. If any of the ARGS are libtool executable wrappers, then they are translated into their corresponding uninstalled binary, and any of their required library directories are added to the library path. Then, COMMAND is executed, with ARGS as arguments." ;; finish) $ECHO \ "Usage: $progname [OPTION]... --mode=finish [LIBDIR]... Complete the installation of libtool libraries. Each LIBDIR is a directory that contains libtool libraries. The commands that this mode executes may require superuser privileges. Use the \`--dry-run' option if you just want to see what would be executed." ;; install) $ECHO \ "Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... Install executables or libraries. INSTALL-COMMAND is the installation command. The first component should be either the \`install' or \`cp' program. The following components of INSTALL-COMMAND are treated specially: -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation The rest of the components are interpreted as arguments to that command (only BSD-compatible install options are recognized)." ;; link) $ECHO \ "Usage: $progname [OPTION]... --mode=link LINK-COMMAND... Link object files or libraries together to form another library, or to create an executable program. LINK-COMMAND is a command using the C compiler that you would use to create a program from several object files. The following components of LINK-COMMAND are treated specially: -all-static do not do any dynamic linking at all -avoid-version do not add a version suffix if possible -bindir BINDIR specify path to binaries directory (for systems where libraries must be found in the PATH setting at runtime) -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened -no-fast-install disable the fast-install mode -no-install link a not-installable executable -no-undefined declare that a library does not refer to external symbols -o OUTPUT-FILE create OUTPUT-FILE from the specified objects -objectlist FILE Use a list of object files found in FILE to specify objects -precious-files-regex REGEX don't remove output files matching REGEX -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries -shared only do dynamic linking of libtool libraries -shrext SUFFIX override the standard shared library file extension -static do not do any dynamic linking of uninstalled libtool libraries -static-libtool-libs do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] specify library version info [each variable defaults to 0] -weak LIBNAME declare that the target provides the LIBNAME interface -Wc,FLAG -Xcompiler FLAG pass linker-specific FLAG directly to the compiler -Wl,FLAG -Xlinker FLAG pass linker-specific FLAG directly to the linker -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) All other options (arguments beginning with \`-') are ignored. Every other argument is treated as a filename. Files ending in \`.la' are treated as uninstalled libtool libraries, other files are standard or library object files. If the OUTPUT-FILE ends in \`.la', then a libtool library is created, only library objects (\`.lo' files) may be specified, and \`-rpath' is required, except when creating a convenience library. If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created using \`ar' and \`ranlib', or on Windows using \`lib'. If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file is created, otherwise an executable program is created." ;; uninstall) $ECHO \ "Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... Remove libraries from an installation directory. RM is the name of the program to use to delete files associated with each FILE (typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed to RM. If FILE is a libtool library, all the files associated with it are deleted. Otherwise, only FILE itself is deleted using RM." ;; *) func_fatal_help "invalid operation mode \`$opt_mode'" ;; esac echo $ECHO "Try \`$progname --help' for more information about other modes." } # Now that we've collected a possible --mode arg, show help if necessary if $opt_help; then if test "$opt_help" = :; then func_mode_help else { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do func_mode_help done } | sed -n '1p; 2,$s/^Usage:/ or: /p' { func_help noexit for opt_mode in compile link execute install finish uninstall clean; do echo func_mode_help done } | sed '1d /^When reporting/,/^Report/{ H d } $x /information about other modes/d /more detailed .*MODE/d s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' fi exit $? fi # func_mode_execute arg... func_mode_execute () { $opt_debug # The first argument is the command name. cmd="$nonopt" test -z "$cmd" && \ func_fatal_help "you must specify a COMMAND" # Handle -dlopen flags immediately. for file in $opt_dlopen; do test -f "$file" \ || func_fatal_help "\`$file' is not a file" dir= case $file in *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$lib' is not a valid libtool archive" # Read the libtool library. dlname= library_names= func_source "$file" # Skip this library if it cannot be dlopened. if test -z "$dlname"; then # Warn if it was a shared library. test -n "$library_names" && \ func_warning "\`$file' was not linked with \`-export-dynamic'" continue fi func_dirname "$file" "" "." dir="$func_dirname_result" if test -f "$dir/$objdir/$dlname"; then func_append dir "/$objdir" else if test ! -f "$dir/$dlname"; then func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" fi fi ;; *.lo) # Just add the directory containing the .lo file. func_dirname "$file" "" "." dir="$func_dirname_result" ;; *) func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" continue ;; esac # Get the absolute pathname. absdir=`cd "$dir" && pwd` test -n "$absdir" && dir="$absdir" # Now add the directory to shlibpath_var. if eval "test -z \"\$$shlibpath_var\""; then eval "$shlibpath_var=\"\$dir\"" else eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" fi done # This variable tells wrapper scripts just to set shlibpath_var # rather than running their programs. libtool_execute_magic="$magic" # Check if any of the arguments is a wrapper script. args= for file do case $file in -* | *.la | *.lo ) ;; *) # Do a test to see if this is really a libtool program. if func_ltwrapper_script_p "$file"; then func_source "$file" # Transform arg to wrapped name. file="$progdir/$program" elif func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" func_source "$func_ltwrapper_scriptname_result" # Transform arg to wrapped name. file="$progdir/$program" fi ;; esac # Quote arguments (to preserve shell metacharacters). func_append_quoted args "$file" done if test "X$opt_dry_run" = Xfalse; then if test -n "$shlibpath_var"; then # Export the shlibpath_var. eval "export $shlibpath_var" fi # Restore saved environment variables for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES do eval "if test \"\${save_$lt_var+set}\" = set; then $lt_var=\$save_$lt_var; export $lt_var else $lt_unset $lt_var fi" done # Now prepare to actually exec the command. exec_cmd="\$cmd$args" else # Display what would be done. if test -n "$shlibpath_var"; then eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" echo "export $shlibpath_var" fi $ECHO "$cmd$args" exit $EXIT_SUCCESS fi } test "$opt_mode" = execute && func_mode_execute ${1+"$@"} # func_mode_finish arg... func_mode_finish () { $opt_debug libs= libdirs= admincmds= for opt in "$nonopt" ${1+"$@"} do if test -d "$opt"; then func_append libdirs " $opt" elif test -f "$opt"; then if func_lalib_unsafe_p "$opt"; then func_append libs " $opt" else func_warning "\`$opt' is not a valid libtool archive" fi else func_fatal_error "invalid argument \`$opt'" fi done if test -n "$libs"; then if test -n "$lt_sysroot"; then sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" else sysroot_cmd= fi # Remove sysroot references if $opt_dry_run; then for lib in $libs; do echo "removing references to $lt_sysroot and \`=' prefixes from $lib" done else tmpdir=`func_mktempdir` for lib in $libs; do sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ > $tmpdir/tmp-la mv -f $tmpdir/tmp-la $lib done ${RM}r "$tmpdir" fi fi if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. func_execute_cmds "$finish_cmds" 'admincmds="$admincmds '"$cmd"'"' fi if test -n "$finish_eval"; then # Do the single finish_eval. eval cmds=\"$finish_eval\" $opt_dry_run || eval "$cmds" || func_append admincmds " $cmds" fi done fi # Exit here if they wanted silent mode. $opt_silent && exit $EXIT_SUCCESS if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then echo "----------------------------------------------------------------------" echo "Libraries have been installed in:" for libdir in $libdirs; do $ECHO " $libdir" done echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" echo "specify the full pathname of the library, or use the \`-LLIBDIR'" echo "flag during linking and do at least one of the following:" if test -n "$shlibpath_var"; then echo " - add LIBDIR to the \`$shlibpath_var' environment variable" echo " during execution" fi if test -n "$runpath_var"; then echo " - add LIBDIR to the \`$runpath_var' environment variable" echo " during linking" fi if test -n "$hardcode_libdir_flag_spec"; then libdir=LIBDIR eval flag=\"$hardcode_libdir_flag_spec\" $ECHO " - use the \`$flag' linker flag" fi if test -n "$admincmds"; then $ECHO " - have your system administrator run these commands:$admincmds" fi if test -f /etc/ld.so.conf; then echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" fi echo echo "See any operating system documentation about shared libraries for" case $host in solaris2.[6789]|solaris2.1[0-9]) echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" echo "pages." ;; *) echo "more information, such as the ld(1) and ld.so(8) manual pages." ;; esac echo "----------------------------------------------------------------------" fi exit $EXIT_SUCCESS } test "$opt_mode" = finish && func_mode_finish ${1+"$@"} # func_mode_install arg... func_mode_install () { $opt_debug # There may be an optional sh(1) argument at the beginning of # install_prog (especially on Windows NT). if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || # Allow the use of GNU shtool's install command. case $nonopt in *shtool*) :;; *) false;; esac; then # Aesthetically quote it. func_quote_for_eval "$nonopt" install_prog="$func_quote_for_eval_result " arg=$1 shift else install_prog= arg=$nonopt fi # The real first argument should be the name of the installation program. # Aesthetically quote it. func_quote_for_eval "$arg" func_append install_prog "$func_quote_for_eval_result" install_shared_prog=$install_prog case " $install_prog " in *[\\\ /]cp\ *) install_cp=: ;; *) install_cp=false ;; esac # We need to accept at least all the BSD install flags. dest= files= opts= prev= install_type= isdir=no stripme= no_mode=: for arg do arg2= if test -n "$dest"; then func_append files " $dest" dest=$arg continue fi case $arg in -d) isdir=yes ;; -f) if $install_cp; then :; else prev=$arg fi ;; -g | -m | -o) prev=$arg ;; -s) stripme=" -s" continue ;; -*) ;; *) # If the previous option needed an argument, then skip it. if test -n "$prev"; then if test "x$prev" = x-m && test -n "$install_override_mode"; then arg2=$install_override_mode no_mode=false fi prev= else dest=$arg continue fi ;; esac # Aesthetically quote the argument. func_quote_for_eval "$arg" func_append install_prog " $func_quote_for_eval_result" if test -n "$arg2"; then func_quote_for_eval "$arg2" fi func_append install_shared_prog " $func_quote_for_eval_result" done test -z "$install_prog" && \ func_fatal_help "you must specify an install program" test -n "$prev" && \ func_fatal_help "the \`$prev' option requires an argument" if test -n "$install_override_mode" && $no_mode; then if $install_cp; then :; else func_quote_for_eval "$install_override_mode" func_append install_shared_prog " -m $func_quote_for_eval_result" fi fi if test -z "$files"; then if test -z "$dest"; then func_fatal_help "no file or destination specified" else func_fatal_help "you must specify a destination" fi fi # Strip any trailing slash from the destination. func_stripname '' '/' "$dest" dest=$func_stripname_result # Check to see that the destination is a directory. test -d "$dest" && isdir=yes if test "$isdir" = yes; then destdir="$dest" destname= else func_dirname_and_basename "$dest" "" "." destdir="$func_dirname_result" destname="$func_basename_result" # Not a directory, so check to see that there is only one file specified. set dummy $files; shift test "$#" -gt 1 && \ func_fatal_help "\`$dest' is not a directory" fi case $destdir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) for file in $files; do case $file in *.lo) ;; *) func_fatal_help "\`$destdir' must be an absolute directory name" ;; esac done ;; esac # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" staticlibs= future_libdirs= current_libdirs= for file in $files; do # Do each installation. case $file in *.$libext) # Do the static libraries later. func_append staticlibs " $file" ;; *.la) func_resolve_sysroot "$file" file=$func_resolve_sysroot_result # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$file" \ || func_fatal_help "\`$file' is not a valid libtool archive" library_names= old_library= relink_command= func_source "$file" # Add the libdir to current_libdirs if it is the destination. if test "X$destdir" = "X$libdir"; then case "$current_libdirs " in *" $libdir "*) ;; *) func_append current_libdirs " $libdir" ;; esac else # Note the libdir as a future libdir. case "$future_libdirs " in *" $libdir "*) ;; *) func_append future_libdirs " $libdir" ;; esac fi func_dirname "$file" "/" "" dir="$func_dirname_result" func_append dir "$objdir" if test -n "$relink_command"; then # Determine the prefix the user has applied to our future dir. inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that # are installed to the same prefix. # At present, this check doesn't affect windows .dll's that # are installed into $libdir/../bin (currently, that works fine) # but it's something to keep an eye on. test "$inst_prefix_dir" = "$destdir" && \ func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi func_warning "relinking \`$file'" func_show_eval "$relink_command" \ 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' fi # See the names of the shared library. set dummy $library_names; shift if test -n "$1"; then realname="$1" shift srcname="$realname" test -n "$relink_command" && srcname="$realname"T # Install the shared library and build the symlinks. func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ 'exit $?' tstripme="$stripme" case $host_os in cygwin* | mingw* | pw32* | cegcc*) case $realname in *.dll.a) tstripme="" ;; esac ;; esac if test -n "$tstripme" && test -n "$striplib"; then func_show_eval "$striplib $destdir/$realname" 'exit $?' fi if test "$#" -gt 0; then # Delete the old symlinks, and create new ones. # Try `ln -sf' first, because the `ln' binary might depend on # the symlink we replace! Solaris /bin/ln does not understand -f, # so we also need to try rm && ln -s. for linkname do test "$linkname" != "$realname" \ && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" done fi # Do each command in the postinstall commands. lib="$destdir/$realname" func_execute_cmds "$postinstall_cmds" 'exit $?' fi # Install the pseudo-library for information purposes. func_basename "$file" name="$func_basename_result" instname="$dir/$name"i func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' # Maybe install the static library, too. test -n "$old_library" && func_append staticlibs " $dir/$old_library" ;; *.lo) # Install (i.e. copy) a libtool object. # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # Deduce the name of the destination old-style object file. case $destfile in *.lo) func_lo2o "$destfile" staticdest=$func_lo2o_result ;; *.$objext) staticdest="$destfile" destfile= ;; *) func_fatal_help "cannot copy a libtool object to \`$destfile'" ;; esac # Install the libtool object if requested. test -n "$destfile" && \ func_show_eval "$install_prog $file $destfile" 'exit $?' # Install the old object if enabled. if test "$build_old_libs" = yes; then # Deduce the name of the old-style object file. func_lo2o "$file" staticobj=$func_lo2o_result func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' fi exit $EXIT_SUCCESS ;; *) # Figure out destination file name, if it wasn't already specified. if test -n "$destname"; then destfile="$destdir/$destname" else func_basename "$file" destfile="$func_basename_result" destfile="$destdir/$destfile" fi # If the file is missing, and there is a .exe on the end, strip it # because it is most likely a libtool script we actually want to # install stripped_ext="" case $file in *.exe) if test ! -f "$file"; then func_stripname '' '.exe' "$file" file=$func_stripname_result stripped_ext=".exe" fi ;; esac # Do a test to see if this is really a libtool program. case $host in *cygwin* | *mingw*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result else func_stripname '' '.exe' "$file" wrapper=$func_stripname_result fi ;; *) wrapper=$file ;; esac if func_ltwrapper_script_p "$wrapper"; then notinst_deplibs= relink_command= func_source "$wrapper" # Check the variables that should have been set. test -z "$generated_by_libtool_version" && \ func_fatal_error "invalid libtool wrapper script \`$wrapper'" finalize=yes for lib in $notinst_deplibs; do # Check to see that each library is installed. libdir= if test -f "$lib"; then func_source "$lib" fi libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test if test -n "$libdir" && test ! -f "$libfile"; then func_warning "\`$lib' has not been installed in \`$libdir'" finalize=no fi done relink_command= func_source "$wrapper" outputname= if test "$fast_install" = no && test -n "$relink_command"; then $opt_dry_run || { if test "$finalize" = yes; then tmpdir=`func_mktempdir` func_basename "$file$stripped_ext" file="$func_basename_result" outputname="$tmpdir/$file" # Replace the output file specification. relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` $opt_silent || { func_quote_for_expand "$relink_command" eval "func_echo $func_quote_for_expand_result" } if eval "$relink_command"; then : else func_error "error: relink \`$file' with the above command before installing it" $opt_dry_run || ${RM}r "$tmpdir" continue fi file="$outputname" else func_warning "cannot relink \`$file'" fi } else # Install the binary that we compiled earlier. file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` fi fi # remove .exe since cygwin /usr/bin/install will append another # one anyway case $install_prog,$host in */usr/bin/install*,*cygwin*) case $file:$destfile in *.exe:*.exe) # this is ok ;; *.exe:*) destfile=$destfile.exe ;; *:*.exe) func_stripname '' '.exe' "$destfile" destfile=$func_stripname_result ;; esac ;; esac func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' $opt_dry_run || if test -n "$outputname"; then ${RM}r "$tmpdir" fi ;; esac done for file in $staticlibs; do func_basename "$file" name="$func_basename_result" # Set up the ranlib parameters. oldlib="$destdir/$name" func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result func_show_eval "$install_prog \$file \$oldlib" 'exit $?' if test -n "$stripme" && test -n "$old_striplib"; then func_show_eval "$old_striplib $tool_oldlib" 'exit $?' fi # Do each command in the postinstall commands. func_execute_cmds "$old_postinstall_cmds" 'exit $?' done test -n "$future_libdirs" && \ func_warning "remember to run \`$progname --finish$future_libdirs'" if test -n "$current_libdirs"; then # Maybe just do a dry run. $opt_dry_run && current_libdirs=" -n$current_libdirs" exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' else exit $EXIT_SUCCESS fi } test "$opt_mode" = install && func_mode_install ${1+"$@"} # func_generate_dlsyms outputname originator pic_p # Extract symbols from dlprefiles and create ${outputname}S.o with # a dlpreopen symbol table. func_generate_dlsyms () { $opt_debug my_outputname="$1" my_originator="$2" my_pic_p="${3-no}" my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` my_dlsyms= if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then if test -n "$NM" && test -n "$global_symbol_pipe"; then my_dlsyms="${my_outputname}S.c" else func_error "not configured to extract global symbols from dlpreopened files" fi fi if test -n "$my_dlsyms"; then case $my_dlsyms in "") ;; *.c) # Discover the nlist of each of the dlfiles. nlist="$output_objdir/${my_outputname}.nm" func_show_eval "$RM $nlist ${nlist}S ${nlist}T" # Parse the name list into a source file. func_verbose "creating $output_objdir/$my_dlsyms" $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ /* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ /* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ #ifdef __cplusplus extern \"C\" { #endif #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) #pragma GCC diagnostic ignored \"-Wstrict-prototypes\" #endif /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT_DLSYM_CONST #else # define LT_DLSYM_CONST const #endif /* External symbol declarations for the compiler. */\ " if test "$dlself" = yes; then func_verbose "generating symbol list for \`$output'" $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" # Add our own program objects to the symbol list. progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` for progfile in $progfiles; do func_to_tool_file "$progfile" func_convert_file_msys_to_w32 func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" done if test -n "$exclude_expsyms"; then $opt_dry_run || { eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi if test -n "$export_symbols_regex"; then $opt_dry_run || { eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' } fi # Prepare the list of exported symbols if test -z "$export_symbols"; then export_symbols="$output_objdir/$outputname.exp" $opt_dry_run || { $RM $export_symbols eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; esac } else $opt_dry_run || { eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in *cygwin* | *mingw* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; esac } fi fi for dlprefile in $dlprefiles; do func_verbose "extracting global C symbols from \`$dlprefile'" func_basename "$dlprefile" name="$func_basename_result" case $host in *cygwin* | *mingw* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" eval "curr_lafile=\$libfile_$func_tr_sh_result" dlprefile_dlbasename="" if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then # Use subshell, to avoid clobbering current variable values dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` if test -n "$dlprefile_dlname" ; then func_basename "$dlprefile_dlname" dlprefile_dlbasename="$func_basename_result" else # no lafile. user explicitly requested -dlpreopen . $sharedlib_from_linklib_cmd "$dlprefile" dlprefile_dlbasename=$sharedlib_from_linklib_result fi fi $opt_dry_run || { if test -n "$dlprefile_dlbasename" ; then eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' else func_warning "Could not compute DLL name from $name" eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" } else # not an import lib $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } fi ;; *) $opt_dry_run || { eval '$ECHO ": $name " >> "$nlist"' func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" } ;; esac done $opt_dry_run || { # Make sure we have at least an empty file. test -f "$nlist" || : > "$nlist" if test -n "$exclude_expsyms"; then $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T $MV "$nlist"T "$nlist" fi # Try sorting and uniquifying the output. if $GREP -v "^: " < "$nlist" | if sort -k 3 /dev/null 2>&1; then sort -k 3 else sort +2 fi | uniq > "$nlist"S; then : else $GREP -v "^: " < "$nlist" > "$nlist"S fi if test -f "$nlist"S; then eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' else echo '/* NONE */' >> "$output_objdir/$my_dlsyms" fi echo >> "$output_objdir/$my_dlsyms" "\ /* The mapping between symbol names and symbols. */ typedef struct { const char *name; void *address; } lt_dlsymlist; extern LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[]; LT_DLSYM_CONST lt_dlsymlist lt_${my_prefix}_LTX_preloaded_symbols[] = {\ { \"$my_originator\", (void *) 0 }," case $need_lib_prefix in no) eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; *) eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" ;; esac echo >> "$output_objdir/$my_dlsyms" "\ {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt_${my_prefix}_LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif\ " } # !$opt_dry_run pic_flag_for_symtable= case "$compile_command " in *" -static "*) ;; *) case $host in # compiling the symbol table file with pic_flag works around # a FreeBSD bug that causes programs to crash when -lm is # linked before any other PIC object. But we must not use # pic_flag when linking with -static. The problem exists in # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; *-*-hpux*) pic_flag_for_symtable=" $pic_flag" ;; *) if test "X$my_pic_p" != Xno; then pic_flag_for_symtable=" $pic_flag" fi ;; esac ;; esac symtab_cflags= for arg in $LTCFLAGS; do case $arg in -pie | -fpie | -fPIE) ;; *) func_append symtab_cflags " $arg" ;; esac done # Now compile the dynamic symbol file. func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' # Clean up the generated files. func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' # Transform the symbol file into the correct name. symfileobj="$output_objdir/${my_outputname}S.$objext" case $host in *cygwin* | *mingw* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` else compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` fi ;; *) compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` ;; esac ;; *) func_fatal_error "unknown suffix for \`$my_dlsyms'" ;; esac else # We keep going just in case the user didn't refer to # lt_preloaded_symbols. The linker will fail if global_symbol_pipe # really was required. # Nullify the symbol file. compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` fi } # func_win32_libid arg # return the library type of file 'arg' # # Need a lot of goo to handle *both* DLLs and import libs # Has to be a shell function in order to 'eat' the argument # that is supplied when $file_magic_command is called. # Despite the name, also deal with 64 bit binaries. func_win32_libid () { $opt_debug win32_libid_type="unknown" win32_fileres=`file -L $1 2>/dev/null` case $win32_fileres in *ar\ archive\ import\ library*) # definitely import win32_libid_type="x86 archive import" ;; *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then func_to_tool_file "$1" func_convert_file_msys_to_w32 win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | $SED -n -e ' 1,100{ / I /{ s,.*,import, p q } }'` case $win32_nmres in import*) win32_libid_type="x86 archive import";; *) win32_libid_type="x86 archive static";; esac fi ;; *DLL*) win32_libid_type="x86 DLL" ;; *executable*) # but shell scripts are "executable" too... case $win32_fileres in *MS\ Windows\ PE\ Intel*) win32_libid_type="x86 DLL" ;; esac ;; esac $ECHO "$win32_libid_type" } # func_cygming_dll_for_implib ARG # # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib () { $opt_debug sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` } # func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs # # The is the core of a fallback implementation of a # platform-specific function to extract the name of the # DLL associated with the specified import library LIBNAME. # # SECTION_NAME is either .idata$6 or .idata$7, depending # on the platform and compiler that created the implib. # # Echos the name of the DLL associated with the # specified import library. func_cygming_dll_for_implib_fallback_core () { $opt_debug match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` $OBJDUMP -s --section "$1" "$2" 2>/dev/null | $SED '/^Contents of section '"$match_literal"':/{ # Place marker at beginning of archive member dllname section s/.*/====MARK====/ p d } # These lines can sometimes be longer than 43 characters, but # are always uninteresting /:[ ]*file format pe[i]\{,1\}-/d /^In archive [^:]*:/d # Ensure marker is printed /^====MARK====/p # Remove all lines with less than 43 characters /^.\{43\}/!d # From remaining lines, remove first 43 characters s/^.\{43\}//' | $SED -n ' # Join marker and all lines until next marker into a single line /^====MARK====/ b para H $ b para b :para x s/\n//g # Remove the marker s/^====MARK====// # Remove trailing dots and whitespace s/[\. \t]*$// # Print /./p' | # we now have a list, one entry per line, of the stringified # contents of the appropriate section of all members of the # archive which possess that section. Heuristic: eliminate # all those which have a first or second character that is # a '.' (that is, objdump's representation of an unprintable # character.) This should work for all archives with less than # 0x302f exports -- but will fail for DLLs whose name actually # begins with a literal '.' or a single character followed by # a '.'. # # Of those that remain, print the first one. $SED -e '/^\./d;/^.\./d;q' } # func_cygming_gnu_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is a GNU/binutils-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_gnu_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` test -n "$func_cygming_gnu_implib_tmp" } # func_cygming_ms_implib_p ARG # This predicate returns with zero status (TRUE) if # ARG is an MS-style import library. Returns # with nonzero status (FALSE) otherwise. func_cygming_ms_implib_p () { $opt_debug func_to_tool_file "$1" func_convert_file_msys_to_w32 func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` test -n "$func_cygming_ms_implib_tmp" } # func_cygming_dll_for_implib_fallback ARG # Platform-specific function to extract the # name of the DLL associated with the specified # import library ARG. # # This fallback implementation is for use when $DLLTOOL # does not support the --identify-strict option. # Invoked by eval'ing the libtool variable # $sharedlib_from_linklib_cmd # Result is available in the variable # $sharedlib_from_linklib_result func_cygming_dll_for_implib_fallback () { $opt_debug if func_cygming_gnu_implib_p "$1" ; then # binutils import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` elif func_cygming_ms_implib_p "$1" ; then # ms-generated import library sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` else # unknown sharedlib_from_linklib_result="" fi } # func_extract_an_archive dir oldlib func_extract_an_archive () { $opt_debug f_ex_an_ar_dir="$1"; shift f_ex_an_ar_oldlib="$1" if test "$lock_old_archive_extraction" = yes; then lockfile=$f_ex_an_ar_oldlib.lock until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do func_echo "Waiting for $lockfile to be removed" sleep 2 done fi func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ 'stat=$?; rm -f "$lockfile"; exit $stat' if test "$lock_old_archive_extraction" = yes; then $opt_dry_run || rm -f "$lockfile" fi if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then : else func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" fi } # func_extract_archives gentop oldlib ... func_extract_archives () { $opt_debug my_gentop="$1"; shift my_oldlibs=${1+"$@"} my_oldobjs="" my_xlib="" my_xabs="" my_xdir="" for my_xlib in $my_oldlibs; do # Extract the objects. case $my_xlib in [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; *) my_xabs=`pwd`"/$my_xlib" ;; esac func_basename "$my_xlib" my_xlib="$func_basename_result" my_xlib_u=$my_xlib while :; do case " $extracted_archives " in *" $my_xlib_u "*) func_arith $extracted_serial + 1 extracted_serial=$func_arith_result my_xlib_u=lt$extracted_serial-$my_xlib ;; *) break ;; esac done extracted_archives="$extracted_archives $my_xlib_u" my_xdir="$my_gentop/$my_xlib_u" func_mkdir_p "$my_xdir" case $host in *-darwin*) func_verbose "Extracting $my_xabs" # Do not bother doing anything if just a dry run $opt_dry_run || { darwin_orig_dir=`pwd` cd $my_xdir || exit $? darwin_archive=$my_xabs darwin_curdir=`pwd` darwin_base_archive=`basename "$darwin_archive"` darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` if test -n "$darwin_arches"; then darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` darwin_arch= func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" for darwin_arch in $darwin_arches ; do func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" func_extract_an_archive "`pwd`" "${darwin_base_archive}" cd "$darwin_curdir" $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" done # $darwin_arches ## Okay now we've a bunch of thin objects, gotta fatten them up :) darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` darwin_file= darwin_files= for darwin_file in $darwin_filelist; do darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` $LIPO -create -output "$darwin_file" $darwin_files done # $darwin_filelist $RM -rf unfat-$$ cd "$darwin_orig_dir" else cd $darwin_orig_dir func_extract_an_archive "$my_xdir" "$my_xabs" fi # $darwin_arches } # !$opt_dry_run ;; *) func_extract_an_archive "$my_xdir" "$my_xabs" ;; esac my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` done func_extract_archives_result="$my_oldobjs" } # func_emit_wrapper [arg=no] # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to # incorporate the script contents within a cygwin/mingw # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. # # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory in which it is stored is # the $objdir directory. This is a cygwin/mingw-specific # behavior. func_emit_wrapper () { func_emit_wrapper_arg1=${1-no} $ECHO "\ #! $SHELL # $output - temporary wrapper script for $objdir/$outputname # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # The $output program cannot be directly executed until all the libtool # libraries that it depends on are installed. # # This wrapper script should never be moved out of the build directory. # If it is, it will not operate correctly. # Sed substitution that helps us do robust quoting. It backslashifies # metacharacters that are still active within double-quoted strings. sed_quote_subst='$sed_quote_subst' # Be Bourne compatible if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then emulate sh NULLCMD=: # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac fi BIN_SH=xpg4; export BIN_SH # for Tru64 DUALCASE=1; export DUALCASE # for MKS sh # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH relink_command=\"$relink_command\" # This environment variable determines our operation mode. if test \"\$libtool_install_magic\" = \"$magic\"; then # install mode needs the following variables: generated_by_libtool_version='$macro_version' notinst_deplibs='$notinst_deplibs' else # When we are sourced in execute mode, \$file and \$ECHO are already set. if test \"\$libtool_execute_magic\" != \"$magic\"; then file=\"\$0\"" qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` $ECHO "\ # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$1 _LTECHO_EOF' } ECHO=\"$qECHO\" fi # Very basic option parsing. These options are (a) specific to # the libtool wrapper, (b) are identical between the wrapper # /script/ and the wrapper /executable/ which is used only on # windows platforms, and (c) all begin with the string "--lt-" # (application programs are unlikely to have options which match # this pattern). # # There are only two supported options: --lt-debug and # --lt-dump-script. There is, deliberately, no --lt-help. # # The first argument to this parsing function should be the # script's $0 value, followed by "$@". lt_option_debug= func_parse_lt_options () { lt_script_arg0=\$0 shift for lt_opt do case \"\$lt_opt\" in --lt-debug) lt_option_debug=1 ;; --lt-dump-script) lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` cat \"\$lt_dump_D/\$lt_dump_F\" exit 0 ;; --lt-*) \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 exit 1 ;; esac done # Print the debug banner immediately: if test -n \"\$lt_option_debug\"; then echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 fi } # Used when --lt-debug. Prints its arguments to stdout # (redirection is the responsibility of the caller) func_lt_dump_args () { lt_dump_args_N=1; for lt_arg do \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` done } # Core function for launching the target application func_exec_program_core () { " case $host in # Backslashes separate directories on plain windows *-*-mingw | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} " ;; *) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 func_lt_dump_args \${1+\"\$@\"} 1>&2 fi exec \"\$progdir/\$program\" \${1+\"\$@\"} " ;; esac $ECHO "\ \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 exit 1 } # A function to encapsulate launching the target application # Strips options in the --lt-* namespace from \$@ and # launches target application with the remaining arguments. func_exec_program () { case \" \$* \" in *\\ --lt-*) for lt_wr_arg do case \$lt_wr_arg in --lt-*) ;; *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; esac shift done ;; esac func_exec_program_core \${1+\"\$@\"} } # Parse options func_parse_lt_options \"\$0\" \${1+\"\$@\"} # Find the directory that this script lives in. thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` test \"x\$thisdir\" = \"x\$file\" && thisdir=. # Follow symbolic links until we get to the real thisdir. file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` while test -n \"\$file\"; do destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` # If there was a directory component, then change thisdir. if test \"x\$destdir\" != \"x\$file\"; then case \"\$destdir\" in [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; *) thisdir=\"\$thisdir/\$destdir\" ;; esac fi file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done # Usually 'no', except on cygwin/mingw when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then # special case for '.' if test \"\$thisdir\" = \".\"; then thisdir=\`pwd\` fi # remove .libs from thisdir case \"\$thisdir\" in *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; $objdir ) thisdir=. ;; esac fi # Try to get the absolute directory name. absdir=\`cd \"\$thisdir\" && pwd\` test -n \"\$absdir\" && thisdir=\"\$absdir\" " if test "$fast_install" = yes; then $ECHO "\ program=lt-'$outputname'$exeext progdir=\"\$thisdir/$objdir\" if test ! -f \"\$progdir/\$program\" || { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ test \"X\$file\" != \"X\$progdir/\$program\"; }; then file=\"\$\$-\$program\" if test ! -d \"\$progdir\"; then $MKDIR \"\$progdir\" else $RM \"\$progdir/\$file\" fi" $ECHO "\ # relink executable if necessary if test -n \"\$relink_command\"; then if relink_command_output=\`eval \$relink_command 2>&1\`; then : else $ECHO \"\$relink_command_output\" >&2 $RM \"\$progdir/\$file\" exit 1 fi fi $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || { $RM \"\$progdir/\$program\"; $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } $RM \"\$progdir/\$file\" fi" else $ECHO "\ program='$outputname' progdir=\"\$thisdir/$objdir\" " fi $ECHO "\ if test -f \"\$progdir/\$program\"; then" # fixup the dll searchpath if we need to. # # Fix the DLL searchpath if we need to. Do this before prepending # to shlibpath, because on Windows, both are PATH and uninstalled # libraries must come first. if test -n "$dllsearchpath"; then $ECHO "\ # Add the dll search path components to the executable PATH PATH=$dllsearchpath:\$PATH " fi # Export our shlibpath_var if we have one. if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then $ECHO "\ # Add our own library path to $shlibpath_var $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" # Some systems cannot cope with colon-terminated $shlibpath_var # The second colon is a workaround for a bug in BeOS R4 sed $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` export $shlibpath_var " fi $ECHO "\ if test \"\$libtool_execute_magic\" != \"$magic\"; then # Run the actual program with our arguments. func_exec_program \${1+\"\$@\"} fi else # The program doesn't exist. \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 exit 1 fi fi\ " } # func_emit_cwrapperexe_src # emit the source code for a wrapper executable on stdout # Must ONLY be called from within func_mode_link because # it depends on a number of variable set therein. func_emit_cwrapperexe_src () { cat < #include #ifdef _MSC_VER # include # include # include #else # include # include # ifdef __CYGWIN__ # include # endif #endif #include #include #include #include #include #include #include #include /* declarations of non-ANSI functions */ #if defined(__MINGW32__) # ifdef __STRICT_ANSI__ int _putenv (const char *); # endif #elif defined(__CYGWIN__) # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif /* #elif defined (other platforms) ... */ #endif /* portability defines, excluding path handling macros */ #if defined(_MSC_VER) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv # define S_IXUSR _S_IEXEC # ifndef _INTPTR_T_DEFINED # define _INTPTR_T_DEFINED # define intptr_t int # endif #elif defined(__MINGW32__) # define setmode _setmode # define stat _stat # define chmod _chmod # define getcwd _getcwd # define putenv _putenv #elif defined(__CYGWIN__) # define HAVE_SETENV # define FOPEN_WB "wb" /* #elif defined (other platforms) ... */ #endif #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif /* path handling portability macros */ #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #if defined(LT_DEBUGWRAPPER) static int lt_debug = 1; #else static int lt_debug = 0; #endif const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_debugprintf (const char *file, int line, const char *fmt, ...); void lt_fatal (const char *file, int line, const char *message, ...); static const char *nonnull (const char *s); static const char *nonempty (const char *s); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); char **prepare_spawn (char **argv); void lt_dump_script (FILE *f); EOF cat <= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", nonempty (path)); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", nonempty (wrapper)); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", nonnull (strerror (errno))); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { lt_debugprintf (__FILE__, __LINE__, "checking path component for symlinks: %s\n", tmp_pathspec); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { lt_fatal (__FILE__, __LINE__, "error accessing file \"%s\": %s", tmp_pathspec, nonnull (strerror (errno))); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal (__FILE__, __LINE__, "could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } void lt_debugprintf (const char *file, int line, const char *fmt, ...) { va_list args; if (lt_debug) { (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } } static void lt_error_core (int exit_status, const char *file, int line, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *file, int line, const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); va_end (ap); } static const char * nonnull (const char *s) { return s ? s : "(null)"; } static const char * nonempty (const char *s) { return (s && !*s) ? "(empty)" : nonnull (s); } void lt_setenv (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_setenv) setting '%s' to '%s'\n", nonnull (name), nonnull (value)); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } void lt_update_exe_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { lt_debugprintf (__FILE__, __LINE__, "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", nonnull (name), nonnull (value)); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } } EOF case $host_os in mingw*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). Note that spawn() does not by itself call the command interpreter (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&v); v.dwPlatformId == VER_PLATFORM_WIN32_NT; }) ? "cmd.exe" : "command.com"). Instead it simply concatenates the arguments, separated by ' ', and calls CreateProcess(). We must quote the arguments since Win32 CreateProcess() interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a special way: - Space and tab are interpreted as delimiters. They are not treated as delimiters if they are surrounded by double quotes: "...". - Unescaped double quotes are removed from the input. Their only effect is that within double quotes, space and tab are treated like normal characters. - Backslashes not followed by double quotes are not special. - But 2*n+1 backslashes followed by a double quote become n backslashes followed by a double quote (n >= 0): \" -> " \\\" -> \" \\\\\" -> \\" */ #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" char ** prepare_spawn (char **argv) { size_t argc; char **new_argv; size_t i; /* Count number of arguments. */ for (argc = 0; argv[argc] != NULL; argc++) ; /* Allocate new argument vector. */ new_argv = XMALLOC (char *, argc + 1); /* Put quoted arguments into the new argument vector. */ for (i = 0; i < argc; i++) { const char *string = argv[i]; if (string[0] == '\0') new_argv[i] = xstrdup ("\"\""); else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) { int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); size_t length; unsigned int backslashes; const char *s; char *quoted_string; char *p; length = 0; backslashes = 0; if (quote_around) length++; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') length += backslashes + 1; length++; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) length += backslashes + 1; quoted_string = XMALLOC (char, length + 1); p = quoted_string; backslashes = 0; if (quote_around) *p++ = '"'; for (s = string; *s != '\0'; s++) { char c = *s; if (c == '"') { unsigned int j; for (j = backslashes + 1; j > 0; j--) *p++ = '\\'; } *p++ = c; if (c == '\\') backslashes++; else backslashes = 0; } if (quote_around) { unsigned int j; for (j = backslashes; j > 0; j--) *p++ = '\\'; *p++ = '"'; } *p = '\0'; new_argv[i] = quoted_string; } else new_argv[i] = (char *) string; } new_argv[argc] = NULL; return new_argv; } EOF ;; esac cat <<"EOF" void lt_dump_script (FILE* f) { EOF func_emit_wrapper yes | $SED -n -e ' s/^\(.\{79\}\)\(..*\)/\1\ \2/ h s/\([\\"]\)/\\\1/g s/$/\\n/ s/\([^\n]*\).*/ fputs ("\1", f);/p g D' cat <<"EOF" } EOF } # end: func_emit_cwrapperexe_src # func_win32_import_lib_p ARG # True if ARG is an import lib, as indicated by $file_magic_cmd func_win32_import_lib_p () { $opt_debug case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in *import*) : ;; *) false ;; esac } # func_mode_link arg... func_mode_link () { $opt_debug case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # which system we are compiling for in order to pass an extra # flag for every libtool invocation. # allow_undefined=no # FIXME: Unfortunately, there are problems with the above when trying # to make a dll which has undefined symbols, in which case not # even a static library is built. For now, we need to specify # -no-undefined on the libtool link line when we can be certain # that all symbols are satisfied, otherwise we get a static library. allow_undefined=yes ;; *) allow_undefined=yes ;; esac libtool_args=$nonopt base_compile="$nonopt $@" compile_command=$nonopt finalize_command=$nonopt compile_rpath= finalize_rpath= compile_shlibpath= finalize_shlibpath= convenience= old_convenience= deplibs= old_deplibs= compiler_flags= linker_flags= dllsearchpath= lib_search_path=`pwd` inst_prefix_dir= new_inherited_linker_flags= avoid_version=no bindir= dlfiles= dlprefiles= dlself=no export_dynamic=no export_symbols= export_symbols_regex= generated= libobjs= ltlibs= module=no no_install=no objs= non_pic_objects= precious_files_regex= prefer_static_libs=no preload=no prev= prevarg= release= rpath= xrpath= perm_rpath= temp_rpath= thread_safe=no vinfo= vinfo_number=no weak_libs= single_module="${wl}-single_module" func_infer_tag $base_compile # We need to know -static, to get the right output filenames. for arg do case $arg in -shared) test "$build_libtool_libs" != yes && \ func_fatal_configuration "can not build a shared library" build_old_libs=no break ;; -all-static | -static | -static-libtool-libs) case $arg in -all-static) if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then func_warning "complete static linking is impossible in this configuration" fi if test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; -static) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built ;; -static-libtool-libs) if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=yes ;; esac build_libtool_libs=no build_old_libs=yes break ;; esac done # See if our shared archives depend on static archives. test -n "$old_archive_from_new_cmds" && build_old_libs=yes # Go through the arguments, transforming them on the way. while test "$#" -gt 0; do arg="$1" shift func_quote_for_eval "$arg" qarg=$func_quote_for_eval_unquoted_result func_append libtool_args " $func_quote_for_eval_result" # If the previous option needs an argument, assign it. if test -n "$prev"; then case $prev in output) func_append compile_command " @OUTPUT@" func_append finalize_command " @OUTPUT@" ;; esac case $prev in bindir) bindir="$arg" prev= continue ;; dlfiles|dlprefiles) if test "$preload" = no; then # Add the symbol object into the linking commands. func_append compile_command " @SYMFILE@" func_append finalize_command " @SYMFILE@" preload=yes fi case $arg in *.la | *.lo) ;; # We handle these cases below. force) if test "$dlself" = no; then dlself=needless export_dynamic=yes fi prev= continue ;; self) if test "$prev" = dlprefiles; then dlself=yes elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then dlself=yes else dlself=needless export_dynamic=yes fi prev= continue ;; *) if test "$prev" = dlfiles; then func_append dlfiles " $arg" else func_append dlprefiles " $arg" fi prev= continue ;; esac ;; expsyms) export_symbols="$arg" test -f "$arg" \ || func_fatal_error "symbol file \`$arg' does not exist" prev= continue ;; expsyms_regex) export_symbols_regex="$arg" prev= continue ;; framework) case $host in *-*-darwin*) case "$deplibs " in *" $qarg.ltframework "*) ;; *) func_append deplibs " $qarg.ltframework" # this is fixed later ;; esac ;; esac prev= continue ;; inst_prefix) inst_prefix_dir="$arg" prev= continue ;; objectlist) if test -f "$arg"; then save_arg=$arg moreargs= for fil in `cat "$save_arg"` do # func_append moreargs " $fil" arg=$fil # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi done else func_fatal_error "link input file \`$arg' does not exist" fi arg=$save_arg prev= continue ;; precious_regex) precious_files_regex="$arg" prev= continue ;; release) release="-$arg" prev= continue ;; rpath | xrpath) # We need an absolute path. case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac if test "$prev" = rpath; then case "$rpath " in *" $arg "*) ;; *) func_append rpath " $arg" ;; esac else case "$xrpath " in *" $arg "*) ;; *) func_append xrpath " $arg" ;; esac fi prev= continue ;; shrext) shrext_cmds="$arg" prev= continue ;; weak) func_append weak_libs " $arg" prev= continue ;; xcclinker) func_append linker_flags " $qarg" func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xcompiler) func_append compiler_flags " $qarg" prev= func_append compile_command " $qarg" func_append finalize_command " $qarg" continue ;; xlinker) func_append linker_flags " $qarg" func_append compiler_flags " $wl$qarg" prev= func_append compile_command " $wl$qarg" func_append finalize_command " $wl$qarg" continue ;; *) eval "$prev=\"\$arg\"" prev= continue ;; esac fi # test -n "$prev" prevarg="$arg" case $arg in -all-static) if test -n "$link_static_flag"; then # See comment for -static flag below, for more details. func_append compile_command " $link_static_flag" func_append finalize_command " $link_static_flag" fi continue ;; -allow-undefined) # FIXME: remove this flag sometime in the future. func_fatal_error "\`-allow-undefined' must not be used because it is the default" ;; -avoid-version) avoid_version=yes continue ;; -bindir) prev=bindir continue ;; -dlopen) prev=dlfiles continue ;; -dlpreopen) prev=dlprefiles continue ;; -export-dynamic) export_dynamic=yes continue ;; -export-symbols | -export-symbols-regex) if test -n "$export_symbols" || test -n "$export_symbols_regex"; then func_fatal_error "more than one -exported-symbols argument is not allowed" fi if test "X$arg" = "X-export-symbols"; then prev=expsyms else prev=expsyms_regex fi continue ;; -framework) prev=framework continue ;; -inst-prefix-dir) prev=inst_prefix continue ;; # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* # so, if we see these flags be careful not to treat them like -L -L[A-Z][A-Z]*:*) case $with_gcc/$host in no/*-*-irix* | /*-*-irix*) func_append compile_command " $arg" func_append finalize_command " $arg" ;; esac continue ;; -L*) func_stripname "-L" '' "$arg" if test -z "$func_stripname_result"; then if test "$#" -gt 0; then func_fatal_error "require no space between \`-L' and \`$1'" else func_fatal_error "need path for \`-L' option" fi fi func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; *) absdir=`cd "$dir" && pwd` test -z "$absdir" && \ func_fatal_error "cannot determine absolute directory name of \`$dir'" dir="$absdir" ;; esac case "$deplibs " in *" -L$dir "* | *" $arg "*) # Will only happen for absolute or sysroot arguments ;; *) # Preserve sysroot, but never include relative directories case $dir in [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; *) func_append deplibs " -L$dir" ;; esac func_append lib_search_path " $dir" ;; esac case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; ::) dllsearchpath=$dir;; *) func_append dllsearchpath ":$dir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac continue ;; -l*) if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; *-*-os2*) # These systems don't actually have a C library (as such) test "X$arg" = "X-lc" && continue ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. test "X$arg" = "X-lc" && continue ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C and math libraries are in the System framework func_append deplibs " System.ltframework" continue ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype test "X$arg" = "X-lc" && continue ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work test "X$arg" = "X-lc" && continue ;; esac elif test "X$arg" = "X-lc_r"; then case $host in *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc_r directly, use -pthread flag. continue ;; esac fi func_append deplibs " $arg" continue ;; -module) module=yes continue ;; # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. -model|-arch|-isysroot|--sysroot) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" prev=xcompiler continue ;; -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" case "$new_inherited_linker_flags " in *" $arg "*) ;; * ) func_append new_inherited_linker_flags " $arg" ;; esac continue ;; -multi_module) single_module="${wl}-multi_module" continue ;; -no-fast-install) fast_install=no continue ;; -no-install) case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "\`-no-install' is ignored for $host" func_warning "assuming \`-no-fast-install' instead" fast_install=no ;; *) no_install=yes ;; esac continue ;; -no-undefined) allow_undefined=no continue ;; -objectlist) prev=objectlist continue ;; -o) prev=output ;; -precious-files-regex) prev=precious_regex continue ;; -release) prev=release continue ;; -rpath) prev=rpath continue ;; -R) prev=xrpath continue ;; -R*) func_stripname '-R' '' "$arg" dir=$func_stripname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) ;; =*) func_stripname '=' '' "$dir" dir=$lt_sysroot$func_stripname_result ;; *) func_fatal_error "only absolute run-paths are allowed" ;; esac case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac continue ;; -shared) # The effects of -shared are defined in a previous loop. continue ;; -shrext) prev=shrext continue ;; -static | -static-libtool-libs) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects # would be equivalent was wrong. It would break on at least # Digital Unix and AIX. continue ;; -thread-safe) thread_safe=yes continue ;; -version-info) prev=vinfo continue ;; -version-number) prev=vinfo vinfo_number=yes continue ;; -weak) prev=weak continue ;; -Wc,*) func_stripname '-Wc,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $func_quote_for_eval_result" func_append compiler_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Wl,*) func_stripname '-Wl,' '' "$arg" args=$func_stripname_result arg= save_ifs="$IFS"; IFS=',' for flag in $args; do IFS="$save_ifs" func_quote_for_eval "$flag" func_append arg " $wl$func_quote_for_eval_result" func_append compiler_flags " $wl$func_quote_for_eval_result" func_append linker_flags " $func_quote_for_eval_result" done IFS="$save_ifs" func_stripname ' ' '' "$arg" arg=$func_stripname_result ;; -Xcompiler) prev=xcompiler continue ;; -Xlinker) prev=xlinker continue ;; -XCClinker) prev=xcclinker continue ;; # -msg_* for osf cc -msg_*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; # Flags to be passed through unchanged, with rationale: # -64, -mips[0-9] enable 64-bit mode for the SGI compiler # -r[0-9][0-9]* specify processor for the SGI compiler # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler # +DA*, +DD* enable 64-bit mode for the HP compiler # -q* compiler args for the IBM compiler # -m*, -t[45]*, -txscale* architecture-specific flags for GCC # -F/path path to uninstalled frameworks, gcc on darwin # -p, -pg, --coverage, -fprofile-* profiling flags for GCC # @file GCC response files # -tp=* Portland pgcc target processor selection # --sysroot=* for sysroot support # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ -O*|-flto*|-fwhopr*|-fuse-linker-plugin) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" func_append compile_command " $arg" func_append finalize_command " $arg" func_append compiler_flags " $arg" continue ;; # Some other compiler flag. -* | +*) func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; *.$objext) # A standard object. func_append objs " $arg" ;; *.lo) # A libtool-controlled object. # Check to see that this really is a libtool object. if func_lalib_unsafe_p "$arg"; then pic_object= non_pic_object= # Read the .lo file func_source "$arg" if test -z "$pic_object" || test -z "$non_pic_object" || test "$pic_object" = none && test "$non_pic_object" = none; then func_fatal_error "cannot find name of object for \`$arg'" fi # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" if test "$pic_object" != none; then # Prepend the subdirectory the object is found in. pic_object="$xdir$pic_object" if test "$prev" = dlfiles; then if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then func_append dlfiles " $pic_object" prev= continue else # If libtool objects are unsupported, then we need to preload. prev=dlprefiles fi fi # CHECK ME: I think I busted this. -Ossama if test "$prev" = dlprefiles; then # Preload the old-style object. func_append dlprefiles " $pic_object" prev= fi # A PIC object. func_append libobjs " $pic_object" arg="$pic_object" fi # Non-PIC object. if test "$non_pic_object" != none; then # Prepend the subdirectory the object is found in. non_pic_object="$xdir$non_pic_object" # A standard non-PIC object func_append non_pic_objects " $non_pic_object" if test -z "$pic_object" || test "$pic_object" = none ; then arg="$non_pic_object" fi else # If the PIC object exists, use it instead. # $xdir was prepended to $pic_object above. non_pic_object="$pic_object" func_append non_pic_objects " $non_pic_object" fi else # Only an error if not doing a dry-run. if $opt_dry_run; then # Extract subdirectory from the argument. func_dirname "$arg" "/" "" xdir="$func_dirname_result" func_lo2o "$arg" pic_object=$xdir$objdir/$func_lo2o_result non_pic_object=$xdir$func_lo2o_result func_append libobjs " $pic_object" func_append non_pic_objects " $non_pic_object" else func_fatal_error "\`$arg' is not a valid libtool object" fi fi ;; *.$libext) # An archive. func_append deplibs " $arg" func_append old_deplibs " $arg" continue ;; *.la) # A libtool-controlled library. func_resolve_sysroot "$arg" if test "$prev" = dlfiles; then # This library was specified with -dlopen. func_append dlfiles " $func_resolve_sysroot_result" prev= elif test "$prev" = dlprefiles; then # The library was specified with -dlpreopen. func_append dlprefiles " $func_resolve_sysroot_result" prev= else func_append deplibs " $func_resolve_sysroot_result" fi continue ;; # Some other compiler argument. *) # Unknown arguments in both finalize_command and compile_command need # to be aesthetically quoted because they are evaled later. func_quote_for_eval "$arg" arg="$func_quote_for_eval_result" ;; esac # arg # Now actually substitute the argument into the commands. if test -n "$arg"; then func_append compile_command " $arg" func_append finalize_command " $arg" fi done # argument parsing loop test -n "$prev" && \ func_fatal_help "the \`$prevarg' option requires an argument" if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then eval arg=\"$export_dynamic_flag_spec\" func_append compile_command " $arg" func_append finalize_command " $arg" fi oldlibs= # calculate the name of the file, without its directory func_basename "$output" outputname="$func_basename_result" libobjs_save="$libobjs" if test -n "$shlibpath_var"; then # get the directories listed in $shlibpath_var eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` else shlib_search_path= fi eval sys_lib_search_path=\"$sys_lib_search_path_spec\" eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" func_dirname "$output" "/" "" output_objdir="$func_dirname_result$objdir" func_to_tool_file "$output_objdir/" tool_output_objdir=$func_to_tool_file_result # Create the object directory. func_mkdir_p "$output_objdir" # Determine the type of output case $output in "") func_fatal_help "you must specify an output file" ;; *.$libext) linkmode=oldlib ;; *.lo | *.$objext) linkmode=obj ;; *.la) linkmode=lib ;; *) linkmode=prog ;; # Anything else should be a program. esac specialdeplibs= libs= # Find all interdependent deplibs by searching for libraries # that are linked more than once (e.g. -la -lb -la) for deplib in $deplibs; do if $opt_preserve_dup_deps ; then case "$libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append libs " $deplib" done if test "$linkmode" = lib; then libs="$predeps $libs $compiler_lib_search_path $postdeps" # Compute libraries that are listed more than once in $predeps # $postdeps and mark them as special (i.e., whose duplicates are # not to be eliminated). pre_post_deps= if $opt_duplicate_compiler_generated_deps; then for pre_post_dep in $predeps $postdeps; do case "$pre_post_deps " in *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; esac func_append pre_post_deps " $pre_post_dep" done fi pre_post_deps= fi deplibs= newdependency_libs= newlib_search_path= need_relink=no # whether we're linking any uninstalled libtool libraries notinst_deplibs= # not-installed libtool libraries notinst_path= # paths that contain not-installed libtool libraries case $linkmode in lib) passes="conv dlpreopen link" for file in $dlfiles $dlprefiles; do case $file in *.la) ;; *) func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" ;; esac done ;; prog) compile_deplibs= finalize_deplibs= alldeplibs=no newdlfiles= newdlprefiles= passes="conv scan dlopen dlpreopen link" ;; *) passes="conv" ;; esac for pass in $passes; do # The preopen pass in lib mode reverses $deplibs; put it back here # so that -L comes before libs that need it for instance... if test "$linkmode,$pass" = "lib,link"; then ## FIXME: Find the place where the list is rebuilt in the wrong ## order, and fix it there properly tmp_deplibs= for deplib in $deplibs; do tmp_deplibs="$deplib $tmp_deplibs" done deplibs="$tmp_deplibs" fi if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan"; then libs="$deplibs" deplibs= fi if test "$linkmode" = prog; then case $pass in dlopen) libs="$dlfiles" ;; dlpreopen) libs="$dlprefiles" ;; link) libs="$deplibs %DEPLIBS%" test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" ;; esac fi if test "$linkmode,$pass" = "lib,dlpreopen"; then # Collect and forward deplibs of preopened libtool libs for lib in $dlprefiles; do # Ignore non-libtool-libs dependency_libs= func_resolve_sysroot "$lib" case $lib in *.la) func_source "$func_resolve_sysroot_result" ;; esac # Collect preopened libtool deplibs, except any this library # has declared as weak libs for deplib in $dependency_libs; do func_basename "$deplib" deplib_base=$func_basename_result case " $weak_libs " in *" $deplib_base "*) ;; *) func_append deplibs " $deplib" ;; esac done done libs="$dlprefiles" fi if test "$pass" = dlopen; then # Collect dlpreopened libraries save_deplibs="$deplibs" deplibs= fi for deplib in $libs; do lib= found=no case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append compiler_flags " $deplib" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -l*) if test "$linkmode" != lib && test "$linkmode" != prog; then func_warning "\`-l' is ignored for archives/objects" continue fi func_stripname '-l' '' "$deplib" name=$func_stripname_result if test "$linkmode" = lib; then searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" else searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" fi for searchdir in $searchdirs; do for search_ext in .la $std_shrext .so .a; do # Search the libtool library lib="$searchdir/lib${name}${search_ext}" if test -f "$lib"; then if test "$search_ext" = ".la"; then found=yes else found=no fi break 2 fi done done if test "$found" != yes; then # deplib doesn't seem to be a libtool library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue else # deplib is a libtool library # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, # We need to do some special things here, and not later. if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $deplib "*) if func_lalib_p "$lib"; then library_names= old_library= func_source "$lib" for l in $old_library $library_names; do ll="$l" done if test "X$ll" = "X$old_library" ; then # only static version available found=no func_dirname "$lib" "" "." ladir="$func_dirname_result" lib=$ladir/$old_library if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" fi continue fi fi ;; *) ;; esac fi fi ;; # -l *.ltframework) if test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else deplibs="$deplib $deplibs" if test "$linkmode" = lib ; then case "$new_inherited_linker_flags " in *" $deplib "*) ;; * ) func_append new_inherited_linker_flags " $deplib" ;; esac fi fi continue ;; -L*) case $linkmode in lib) deplibs="$deplib $deplibs" test "$pass" = conv && continue newdependency_libs="$deplib $newdependency_libs" func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; prog) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi if test "$pass" = scan; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; *) func_warning "\`-L' is ignored for archives/objects" ;; esac # linkmode continue ;; # -L -R*) if test "$pass" = link; then func_stripname '-R' '' "$deplib" func_resolve_sysroot "$func_stripname_result" dir=$func_resolve_sysroot_result # Make sure the xrpath contains only unique directories. case "$xrpath " in *" $dir "*) ;; *) func_append xrpath " $dir" ;; esac fi deplibs="$deplib $deplibs" continue ;; *.la) func_resolve_sysroot "$deplib" lib=$func_resolve_sysroot_result ;; *.$libext) if test "$pass" = conv; then deplibs="$deplib $deplibs" continue fi case $linkmode in lib) # Linking convenience modules into shared libraries is allowed, # but linking other static libraries is non-portable. case " $dlpreconveniencelibs " in *" $deplib "*) ;; *) valid_a_lib=no case $deplibs_check_method in match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ | $EGREP "$match_pattern_regex" > /dev/null; then valid_a_lib=yes fi ;; pass_all) valid_a_lib=yes ;; esac if test "$valid_a_lib" != yes; then echo $ECHO "*** Warning: Trying to link with static lib archive $deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because the file extensions .$libext of this argument makes me believe" echo "*** that it is just a static archive that I should not use here." else echo $ECHO "*** Warning: Linking the shared library $output against the" $ECHO "*** static library $deplib is not portable!" deplibs="$deplib $deplibs" fi ;; esac continue ;; prog) if test "$pass" != link; then deplibs="$deplib $deplibs" else compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" fi continue ;; esac # linkmode ;; # *.$libext *.lo | *.$objext) if test "$pass" = conv; then deplibs="$deplib $deplibs" elif test "$linkmode" = prog; then if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlopen support or we're linking statically, # we need to preload. func_append newdlprefiles " $deplib" compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" else func_append newdlfiles " $deplib" fi fi continue ;; %DEPLIBS%) alldeplibs=yes continue ;; esac # case $deplib if test "$found" = yes || test -f "$lib"; then : else func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" fi # Check to see that this really is a libtool archive. func_lalib_unsafe_p "$lib" \ || func_fatal_error "\`$lib' is not a valid libtool archive" func_dirname "$lib" "" "." ladir="$func_dirname_result" dlname= dlopen= dlpreopen= libdir= library_names= old_library= inherited_linker_flags= # If the library was installed with an old release of libtool, # it will not redefine variables installed, or shouldnotlink installed=yes shouldnotlink=no avoidtemprpath= # Read the .la file func_source "$lib" # Convert "-framework foo" to "foo.ltframework" if test -n "$inherited_linker_flags"; then tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do case " $new_inherited_linker_flags " in *" $tmp_inherited_linker_flag "*) ;; *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; esac done fi dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` if test "$linkmode,$pass" = "lib,link" || test "$linkmode,$pass" = "prog,scan" || { test "$linkmode" != prog && test "$linkmode" != lib; }; then test -n "$dlopen" && func_append dlfiles " $dlopen" test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" fi if test "$pass" = conv; then # Only check for convenience libraries deplibs="$lib $deplibs" if test -z "$libdir"; then if test -z "$old_library"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # It is a libtool convenience library, so add in its objects. func_append convenience " $ladir/$objdir/$old_library" func_append old_convenience " $ladir/$objdir/$old_library" tmp_libs= for deplib in $dependency_libs; do deplibs="$deplib $deplibs" if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done elif test "$linkmode" != prog && test "$linkmode" != lib; then func_fatal_error "\`$lib' is not a convenience library" fi continue fi # $pass = conv # Get the name of the library we link against. linklib= if test -n "$old_library" && { test "$prefer_static_libs" = yes || test "$prefer_static_libs,$installed" = "built,no"; }; then linklib=$old_library else for l in $old_library $library_names; do linklib="$l" done fi if test -z "$linklib"; then func_fatal_error "cannot find name of link library for \`$lib'" fi # This library was specified with -dlopen. if test "$pass" = dlopen; then if test -z "$libdir"; then func_fatal_error "cannot -dlopen a convenience library: \`$lib'" fi if test -z "$dlname" || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then # If there is no dlname, no dlopen support or we're linking # statically, we need to preload. We also need to preload any # dependent libraries so libltdl's deplib preloader doesn't # bomb out in the load deplibs phase. func_append dlprefiles " $lib $dependency_libs" else func_append newdlfiles " $lib" fi continue fi # $pass = dlopen # We need an absolute path. case $ladir in [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; *) abs_ladir=`cd "$ladir" && pwd` if test -z "$abs_ladir"; then func_warning "cannot determine absolute directory name of \`$ladir'" func_warning "passing it literally to the linker, although it might fail" abs_ladir="$ladir" fi ;; esac func_basename "$lib" laname="$func_basename_result" # Find the relevant object directory and library name. if test "X$installed" = Xyes; then if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then func_warning "library \`$lib' was moved." dir="$ladir" absdir="$abs_ladir" libdir="$abs_ladir" else dir="$lt_sysroot$libdir" absdir="$lt_sysroot$libdir" fi test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes else if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then dir="$ladir" absdir="$abs_ladir" # Remove this search path later func_append notinst_path " $abs_ladir" else dir="$ladir/$objdir" absdir="$abs_ladir/$objdir" # Remove this search path later func_append notinst_path " $abs_ladir" fi fi # $installed = yes func_stripname 'lib' '.la' "$laname" name=$func_stripname_result # This library was specified with -dlpreopen. if test "$pass" = dlpreopen; then if test -z "$libdir" && test "$linkmode" = prog; then func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" fi case "$host" in # special handling for platforms with PE-DLLs. *cygwin* | *mingw* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present # (otherwise, the dlopen module name will be incorrect). We do # this by putting the import library name into $newdlprefiles. # We recover the dlopen module name by 'saving' the la file # name in a special purpose variable, and (later) extracting the # dlname from the la file. if test -n "$dlname"; then func_tr_sh "$dir/$linklib" eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" func_append newdlprefiles " $dir/$linklib" else func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" fi ;; * ) # Prefer using a static library (so that no silly _DYNAMIC symbols # are required to link). if test -n "$old_library"; then func_append newdlprefiles " $dir/$old_library" # Keep a list of preopened convenience libraries to check # that they are being used correctly in the link pass. test -z "$libdir" && \ func_append dlpreconveniencelibs " $dir/$old_library" # Otherwise, use the dlname, so that lt_dlopen finds it. elif test -n "$dlname"; then func_append newdlprefiles " $dir/$dlname" else func_append newdlprefiles " $dir/$linklib" fi ;; esac fi # $pass = dlpreopen if test -z "$libdir"; then # Link the convenience library if test "$linkmode" = lib; then deplibs="$dir/$old_library $deplibs" elif test "$linkmode,$pass" = "prog,link"; then compile_deplibs="$dir/$old_library $compile_deplibs" finalize_deplibs="$dir/$old_library $finalize_deplibs" else deplibs="$lib $deplibs" # used for prog,scan pass fi continue fi if test "$linkmode" = prog && test "$pass" != link; then func_append newlib_search_path " $ladir" deplibs="$lib $deplibs" linkalldeplibs=no if test "$link_all_deplibs" != no || test -z "$library_names" || test "$build_libtool_libs" = no; then linkalldeplibs=yes fi tmp_libs= for deplib in $dependency_libs; do case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result" func_append newlib_search_path " $func_resolve_sysroot_result" ;; esac # Need to link against all dependency_libs? if test "$linkalldeplibs" = yes; then deplibs="$deplib $deplibs" else # Need to hardcode shared library paths # or/and link against static libraries newdependency_libs="$deplib $newdependency_libs" fi if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $deplib "*) func_append specialdeplibs " $deplib" ;; esac fi func_append tmp_libs " $deplib" done # for deplib continue fi # $linkmode = prog... if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && { { test "$prefer_static_libs" = no || test "$prefer_static_libs,$installed" = "built,yes"; } || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. case "$temp_rpath:" in *"$absdir:"*) ;; *) func_append temp_rpath "$absdir:" ;; esac fi # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi # $linkmode,$pass = prog,link... if test "$alldeplibs" = yes && { test "$deplibs_check_method" = pass_all || { test "$build_libtool_libs" = yes && test -n "$library_names"; }; }; then # We only need to search for static libraries continue fi fi link_static=no # Whether the deplib will be linked statically use_static_libs=$prefer_static_libs if test "$use_static_libs" = built && test "$installed" = yes; then use_static_libs=no fi if test -n "$library_names" && { test "$use_static_libs" = no || test -z "$old_library"; }; then case $host in *cygwin* | *mingw* | *cegcc*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no ;; *) if test "$installed" = no; then func_append notinst_deplibs " $lib" need_relink=yes fi ;; esac # This is a shared library # Warn about portability, can't link against -module's on some # systems (darwin). Don't bleat about dlopened modules though! dlopenmodule="" for dlpremoduletest in $dlprefiles; do if test "X$dlpremoduletest" = "X$lib"; then dlopenmodule="$dlpremoduletest" break fi done if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then echo if test "$linkmode" = prog; then $ECHO "*** Warning: Linking the executable $output against the loadable module" else $ECHO "*** Warning: Linking the shared library $output against the loadable module" fi $ECHO "*** $linklib is not portable!" fi if test "$linkmode" = lib && test "$hardcode_into_libs" = yes; then # Hardcode the library path. # Skip directories that are in the system default run-time # search path. case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) case "$compile_rpath " in *" $absdir "*) ;; *) func_append compile_rpath " $absdir" ;; esac ;; esac case " $sys_lib_dlsearch_path " in *" $libdir "*) ;; *) case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac ;; esac fi if test -n "$old_archive_from_expsyms_cmds"; then # figure out the soname set dummy $library_names shift realname="$1" shift libname=`eval "\\$ECHO \"$libname_spec\""` # use dlname if we got it. it's perfectly good, no? if test -n "$dlname"; then soname="$dlname" elif test -n "$soname_spec"; then # bleh windows case $host in *cygwin* | mingw* | *cegcc*) func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; esac eval soname=\"$soname_spec\" else soname="$realname" fi # Make a new name for the extract_expsyms_cmds to use soroot="$soname" func_basename "$soroot" soname="$func_basename_result" func_stripname 'lib' '.dll' "$soname" newlib=libimp-$func_stripname_result.a # If the library has no export list, then create one now if test -f "$output_objdir/$soname-def"; then : else func_verbose "extracting exported symbol list from \`$soname'" func_execute_cmds "$extract_expsyms_cmds" 'exit $?' fi # Create $newlib if test -f "$output_objdir/$newlib"; then :; else func_verbose "generating import library for \`$soname'" func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' fi # make sure the library variables are pointing to the new library dir=$output_objdir linklib=$newlib fi # test -n "$old_archive_from_expsyms_cmds" if test "$linkmode" = prog || test "$opt_mode" != relink; then add_shlibpath= add_dir= add= lib_linked=yes case $hardcode_action in immediate | unsupported) if test "$hardcode_direct" = no; then add="$dir/$linklib" case $host in *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; *-*-sysv4*uw2*) add_dir="-L$dir" ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir="-L$dir" ;; *-*-darwin* ) # if the lib is a (non-dlopened) module then we can not # link against it, someone is ignoring the earlier warnings if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null ; then if test "X$dlopenmodule" != "X$lib"; then $ECHO "*** Warning: lib $linklib is a module, not a shared library" if test -z "$old_library" ; then echo echo "*** And there doesn't seem to be a static archive available" echo "*** The link will probably fail, sorry" else add="$dir/$old_library" fi elif test -n "$old_library"; then add="$dir/$old_library" fi fi esac elif test "$hardcode_minus_L" = no; then case $host in *-*-sunos*) add_shlibpath="$dir" ;; esac add_dir="-L$dir" add="-l$name" elif test "$hardcode_shlibpath_var" = no; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; relink) if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$dir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$absdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then add_shlibpath="$dir" add="-l$name" else lib_linked=no fi ;; *) lib_linked=no ;; esac if test "$lib_linked" != yes; then func_fatal_configuration "unsupported hardcode properties" fi if test -n "$add_shlibpath"; then case :$compile_shlibpath: in *":$add_shlibpath:"*) ;; *) func_append compile_shlibpath "$add_shlibpath:" ;; esac fi if test "$linkmode" = prog; then test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" test -n "$add" && compile_deplibs="$add $compile_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" if test "$hardcode_direct" != yes && test "$hardcode_minus_L" != yes && test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac fi fi fi if test "$linkmode" = prog || test "$opt_mode" = relink; then add_shlibpath= add_dir= add= # Finalize command for both is simple: just hardcode it. if test "$hardcode_direct" = yes && test "$hardcode_direct_absolute" = no; then add="$libdir/$linklib" elif test "$hardcode_minus_L" = yes; then add_dir="-L$libdir" add="-l$name" elif test "$hardcode_shlibpath_var" = yes; then case :$finalize_shlibpath: in *":$libdir:"*) ;; *) func_append finalize_shlibpath "$libdir:" ;; esac add="-l$name" elif test "$hardcode_automatic" = yes; then if test -n "$inst_prefix_dir" && test -f "$inst_prefix_dir$libdir/$linklib" ; then add="$inst_prefix_dir$libdir/$linklib" else add="$libdir/$linklib" fi else # We cannot seem to hardcode it, guess we'll fake it. add_dir="-L$libdir" # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in [\\/]*) func_append add_dir " -L$inst_prefix_dir$libdir" ;; esac fi add="-l$name" fi if test "$linkmode" = prog; then test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" test -n "$add" && finalize_deplibs="$add $finalize_deplibs" else test -n "$add_dir" && deplibs="$add_dir $deplibs" test -n "$add" && deplibs="$add $deplibs" fi fi elif test "$linkmode" = prog; then # Here we assume that one of hardcode_direct or hardcode_minus_L # is not unsupported. This is valid on all known static and # shared platforms. if test "$hardcode_direct" != unsupported; then test -n "$old_library" && linklib="$old_library" compile_deplibs="$dir/$linklib $compile_deplibs" finalize_deplibs="$dir/$linklib $finalize_deplibs" else compile_deplibs="-l$name -L$dir $compile_deplibs" finalize_deplibs="-l$name -L$dir $finalize_deplibs" fi elif test "$build_libtool_libs" = yes; then # Not a shared library if test "$deplibs_check_method" != pass_all; then # We're trying link a shared library against a static one # but the system doesn't support it. # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. echo $ECHO "*** Warning: This system can not link to static lib archive $lib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have." if test "$module" = yes; then echo "*** But as you try to build a module library, libtool will still create " echo "*** a static module, that should work as long as the dlopening application" echo "*** is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi else deplibs="$dir/$old_library $deplibs" link_static=yes fi fi # link shared/static library? if test "$linkmode" = lib; then if test -n "$dependency_libs" && { test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes || test "$link_static" = yes; }; then # Extract -R from dependency_libs temp_deplibs= for libdir in $dependency_libs; do case $libdir in -R*) func_stripname '-R' '' "$libdir" temp_xrpath=$func_stripname_result case " $xrpath " in *" $temp_xrpath "*) ;; *) func_append xrpath " $temp_xrpath";; esac;; *) func_append temp_deplibs " $libdir";; esac done dependency_libs="$temp_deplibs" fi func_append newlib_search_path " $absdir" # Link against this library test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" # ... and its dependency_libs tmp_libs= for deplib in $dependency_libs; do newdependency_libs="$deplib $newdependency_libs" case $deplib in -L*) func_stripname '-L' '' "$deplib" func_resolve_sysroot "$func_stripname_result";; *) func_resolve_sysroot "$deplib" ;; esac if $opt_preserve_dup_deps ; then case "$tmp_libs " in *" $func_resolve_sysroot_result "*) func_append specialdeplibs " $func_resolve_sysroot_result" ;; esac fi func_append tmp_libs " $func_resolve_sysroot_result" done if test "$link_all_deplibs" != no; then # Add the search paths of all dependency libraries for deplib in $dependency_libs; do path= case $deplib in -L*) path="$deplib" ;; *.la) func_resolve_sysroot "$deplib" deplib=$func_resolve_sysroot_result func_dirname "$deplib" "" "." dir=$func_dirname_result # We need an absolute path. case $dir in [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; *) absdir=`cd "$dir" && pwd` if test -z "$absdir"; then func_warning "cannot determine absolute directory name of \`$dir'" absdir="$dir" fi ;; esac if $GREP "^installed=no" $deplib > /dev/null; then case $host in *-*-darwin*) depdepl= eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` if test -n "$deplibrary_names" ; then for tmp in $deplibrary_names ; do depdepl=$tmp done if test -f "$absdir/$objdir/$depdepl" ; then depdepl="$absdir/$objdir/$depdepl" darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` if test -z "$darwin_install_name"; then darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` fi func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}" path= fi fi ;; *) path="-L$absdir/$objdir" ;; esac else eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" test "$absdir" != "$libdir" && \ func_warning "\`$deplib' seems to be moved" path="-L$absdir" fi ;; esac case " $deplibs " in *" $path "*) ;; *) deplibs="$path $deplibs" ;; esac done fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs if test "$pass" = link; then if test "$linkmode" = "prog"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" else compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` fi fi dependency_libs="$newdependency_libs" if test "$pass" = dlpreopen; then # Link the dlpreopened libraries before other libraries for deplib in $save_deplibs; do deplibs="$deplib $deplibs" done fi if test "$pass" != dlopen; then if test "$pass" != conv; then # Make sure lib_search_path contains only unique directories. lib_search_path= for dir in $newlib_search_path; do case "$lib_search_path " in *" $dir "*) ;; *) func_append lib_search_path " $dir" ;; esac done newlib_search_path= fi if test "$linkmode,$pass" != "prog,link"; then vars="deplibs" else vars="compile_deplibs finalize_deplibs" fi for var in $vars dependency_libs; do # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= for deplib in $tmp_libs; do # FIXME: Pedantically, this is the right thing to do, so # that some nasty dependency loop isn't accidentally # broken: #new_libs="$deplib $new_libs" # Pragmatically, this seems to cause very few problems in # practice: case $deplib in -L*) new_libs="$deplib $new_libs" ;; -R*) ;; *) # And here is the reason: when a library appears more # than once as an explicit dependence of a library, or # is implicitly linked in more than once by the # compiler, it is considered special, and multiple # occurrences thereof are not removed. Compare this # with having the same library being listed as a # dependency of multiple other libraries: in this case, # we know (pedantically, we assume) the library does not # need to be listed more than once, so we keep only the # last copy. This is not always right, but it is rare # enough that we require users that really mean to play # such unportable linking tricks to link the library # using -Wl,-lname, so that libtool does not consider it # for duplicate removal. case " $specialdeplibs " in *" $deplib "*) new_libs="$deplib $new_libs" ;; *) case " $new_libs " in *" $deplib "*) ;; *) new_libs="$deplib $new_libs" ;; esac ;; esac ;; esac done tmp_libs= for deplib in $new_libs; do case $deplib in -L*) case " $tmp_libs " in *" $deplib "*) ;; *) func_append tmp_libs " $deplib" ;; esac ;; *) func_append tmp_libs " $deplib" ;; esac done eval $var=\"$tmp_libs\" done # for var fi # Last step: remove runtime libs from dependency_libs # (they stay in deplibs) tmp_libs= for i in $dependency_libs ; do case " $predeps $postdeps $compiler_lib_search_path " in *" $i "*) i="" ;; esac if test -n "$i" ; then func_append tmp_libs " $i" fi done dependency_libs=$tmp_libs done # for pass if test "$linkmode" = prog; then dlfiles="$newdlfiles" fi if test "$linkmode" = prog || test "$linkmode" = lib; then dlprefiles="$newdlprefiles" fi case $linkmode in oldlib) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for archives" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for archives" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for archives" test -n "$xrpath" && \ func_warning "\`-R' is ignored for archives" test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for archives" test -n "$release" && \ func_warning "\`-release' is ignored for archives" test -n "$export_symbols$export_symbols_regex" && \ func_warning "\`-export-symbols' is ignored for archives" # Now set the variables for building old libraries. build_libtool_libs=no oldlibs="$output" func_append objs "$old_deplibs" ;; lib) # Make sure we only generate libraries of the form `libNAME.la'. case $outputname in lib*) func_stripname 'lib' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" ;; *) test "$module" = no && \ func_fatal_help "libtool library \`$output' must begin with \`lib'" if test "$need_lib_prefix" != no; then # Add the "lib" prefix for modules if required func_stripname '' '.la' "$outputname" name=$func_stripname_result eval shared_ext=\"$shrext_cmds\" eval libname=\"$libname_spec\" else func_stripname '' '.la' "$outputname" libname=$func_stripname_result fi ;; esac if test -n "$objs"; then if test "$deplibs_check_method" != pass_all; then func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" else echo $ECHO "*** Warning: Linking the shared library $output against the non-libtool" $ECHO "*** objects $objs is not portable!" func_append libobjs " $objs" fi fi test "$dlself" != no && \ func_warning "\`-dlopen self' is ignored for libtool libraries" set dummy $rpath shift test "$#" -gt 1 && \ func_warning "ignoring multiple \`-rpath's for a libtool library" install_libdir="$1" oldlibs= if test -z "$rpath"; then if test "$build_libtool_libs" = yes; then # Building a libtool convenience library. # Some compilers have problems with a `.al' extension so # convenience libraries should have the same extension an # archive normally would. oldlibs="$output_objdir/$libname.$libext $oldlibs" build_libtool_libs=convenience build_old_libs=yes fi test -n "$vinfo" && \ func_warning "\`-version-info/-version-number' is ignored for convenience libraries" test -n "$release" && \ func_warning "\`-release' is ignored for convenience libraries" else # Parse the version information argument. save_ifs="$IFS"; IFS=':' set dummy $vinfo 0 0 0 shift IFS="$save_ifs" test -n "$7" && \ func_fatal_help "too many parameters to \`-version-info'" # convert absolute version numbers to libtool ages # this retains compatibility with .la files and attempts # to make the code below a bit more comprehensible case $vinfo_number in yes) number_major="$1" number_minor="$2" number_revision="$3" # # There are really only two kinds -- those that # use the current revision as the major version # and those that subtract age and use age as # a minor version. But, then there is irix # which has an extra 1 added just for fun # case $version_type in # correct linux to gnu/linux during the next big refactor darwin|linux|osf|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_revision" ;; freebsd-aout|freebsd-elf|qnx|sunos) current="$number_major" revision="$number_minor" age="0" ;; irix|nonstopux) func_arith $number_major + $number_minor current=$func_arith_result age="$number_minor" revision="$number_minor" lt_irix_increment=no ;; *) func_fatal_configuration "$modename: unknown library version type \`$version_type'" ;; esac ;; no) current="$1" revision="$2" age="$3" ;; esac # Check that each of the things are valid numbers. case $current in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "CURRENT \`$current' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $revision in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "REVISION \`$revision' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac case $age in 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; *) func_error "AGE \`$age' must be a nonnegative integer" func_fatal_error "\`$vinfo' is not valid version information" ;; esac if test "$age" -gt "$current"; then func_error "AGE \`$age' is greater than the current interface number \`$current'" func_fatal_error "\`$vinfo' is not valid version information" fi # Calculate the version variables. major= versuffix= verstring= case $version_type in none) ;; darwin) # Like Linux, but with the current version available in # verstring for coding it into the library header func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" # Darwin ld doesn't like 0 for these options... func_arith $current + 1 minor_current=$func_arith_result xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" ;; freebsd-aout) major=".$current" versuffix=".$current.$revision"; ;; freebsd-elf) major=".$current" versuffix=".$current" ;; irix | nonstopux) if test "X$lt_irix_increment" = "Xno"; then func_arith $current - $age else func_arith $current - $age + 1 fi major=$func_arith_result case $version_type in nonstopux) verstring_prefix=nonstopux ;; *) verstring_prefix=sgi ;; esac verstring="$verstring_prefix$major.$revision" # Add in all the interfaces that we are compatible with. loop=$revision while test "$loop" -ne 0; do func_arith $revision - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring_prefix$major.$iface:$verstring" done # Before this point, $major must not contain `.'. major=.$major versuffix="$major.$revision" ;; linux) # correct to gnu/linux during the next big refactor func_arith $current - $age major=.$func_arith_result versuffix="$major.$age.$revision" ;; osf) func_arith $current - $age major=.$func_arith_result versuffix=".$current.$age.$revision" verstring="$current.$age.$revision" # Add in all the interfaces that we are compatible with. loop=$age while test "$loop" -ne 0; do func_arith $current - $loop iface=$func_arith_result func_arith $loop - 1 loop=$func_arith_result verstring="$verstring:${iface}.0" done # Make executables depend on our current version. func_append verstring ":${current}.0" ;; qnx) major=".$current" versuffix=".$current" ;; sunos) major=".$current" versuffix=".$current.$revision" ;; windows) # Use '-' rather than '.', since we only want one # extension on DOS 8.3 filesystems. func_arith $current - $age major=$func_arith_result versuffix="-$major" ;; *) func_fatal_configuration "unknown library version type \`$version_type'" ;; esac # Clear the version info if we defaulted, and they specified a release. if test -z "$vinfo" && test -n "$release"; then major= case $version_type in darwin) # we can't check for "0.0" in archive_cmds due to quoting # problems, so we reset it completely verstring= ;; *) verstring="0.0" ;; esac if test "$need_version" = no; then versuffix= else versuffix=".0.0" fi fi # Remove version info from name if versioning should be avoided if test "$avoid_version" = yes && test "$need_version" = no; then major= versuffix= verstring="" fi # Check to see if the archive will have undefined symbols. if test "$allow_undefined" = yes; then if test "$allow_undefined_flag" = unsupported; then func_warning "undefined symbols not allowed in $host shared libraries" build_libtool_libs=no build_old_libs=yes fi else # Don't allow undefined symbols. allow_undefined_flag="$no_undefined_flag" fi fi func_generate_dlsyms "$libname" "$libname" "yes" func_append libobjs " $symfileobj" test "X$libobjs" = "X " && libobjs= if test "$opt_mode" != relink; then # Remove our outputs, but don't remove object files since they # may have been created when compiling PIC objects. removelist= tempremovelist=`$ECHO "$output_objdir/*"` for p in $tempremovelist; do case $p in *.$objext | *.gcno) ;; $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) if test "X$precious_files_regex" != "X"; then if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 then continue fi fi func_append removelist " $p" ;; *) ;; esac done test -n "$removelist" && \ func_show_eval "${RM}r \$removelist" fi # Now set the variables for building old libraries. if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then func_append oldlibs " $output_objdir/$libname.$libext" # Transform .lo files to .o files. oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` fi # Eliminate all temporary directories. #for path in $notinst_path; do # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` #done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. temp_xrpath= for libdir in $xrpath; do func_replace_sysroot "$libdir" func_append temp_xrpath " -R$func_replace_sysroot_result" case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then dependency_libs="$temp_xrpath $dependency_libs" fi fi # Make sure dlfiles contains only unique files that won't be dlpreopened old_dlfiles="$dlfiles" dlfiles= for lib in $old_dlfiles; do case " $dlprefiles $dlfiles " in *" $lib "*) ;; *) func_append dlfiles " $lib" ;; esac done # Make sure dlprefiles contains only unique files old_dlprefiles="$dlprefiles" dlprefiles= for lib in $old_dlprefiles; do case "$dlprefiles " in *" $lib "*) ;; *) func_append dlprefiles " $lib" ;; esac done if test "$build_libtool_libs" = yes; then if test -n "$rpath"; then case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) # Rhapsody C library is in the System framework func_append deplibs " System.ltframework" ;; *-*-netbsd*) # Don't link with libc until the a.out ld.so is fixed. ;; *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) # Do not include libc due to us having libc/libc_r. ;; *-*-sco3.2v5* | *-*-sco5v6*) # Causes problems with __ctype ;; *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) # Compiler inserts libc in the correct place for threads to work ;; *) # Add libc to deplibs on all other systems if necessary. if test "$build_libtool_need_lc" = "yes"; then func_append deplibs " -lc" fi ;; esac fi # Transform deplibs into only deplibs that can be linked in shared. name_save=$name libname_save=$libname release_save=$release versuffix_save=$versuffix major_save=$major # I'm not sure if I'm treating the release correctly. I think # release should show up in the -l (ie -lgmp5) so we don't want to # add it in twice. Is that correct? release="" versuffix="" major="" newdeplibs= droppeddeps=no case $deplibs_check_method in pass_all) # Don't check for shared/static. Everything works. # This might be a little naive. We might want to check # whether the library exists or not. But this is on # osf3 & osf4 and I'm not really sure... Just # implementing what was already the behavior. newdeplibs=$deplibs ;; test_compile) # This code stresses the "libraries are programs" paradigm to its # limits. Maybe even breaks it. We compile a program, linking it # against the deplibs as a proxy for the library. Then we can check # whether they linked in statically or dynamically with ldd. $opt_dry_run || $RM conftest.c cat > conftest.c </dev/null` $nocaseglob else potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` fi for potent_lib in $potential_libs; do # Follow soft links. if ls -lLd "$potent_lib" 2>/dev/null | $GREP " -> " >/dev/null; then continue fi # The statement above tries to avoid entering an # endless loop below, in case of cyclic links. # We might still enter an endless loop, since a link # loop can be closed while we follow links, # but so what? potlib="$potent_lib" while test -h "$potlib" 2>/dev/null; do potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` case $potliblink in [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; esac done if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | $SED -e 10q | $EGREP "$file_magic_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for file magic test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a file magic. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; match_pattern*) set dummy $deplibs_check_method; shift match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` for a_deplib in $deplibs; do case $a_deplib in -l*) func_stripname -l '' "$a_deplib" name=$func_stripname_result if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $a_deplib "*) func_append newdeplibs " $a_deplib" a_deplib="" ;; esac fi if test -n "$a_deplib" ; then libname=`eval "\\$ECHO \"$libname_spec\""` for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do potential_libs=`ls $i/$libname[.-]* 2>/dev/null` for potent_lib in $potential_libs; do potlib="$potent_lib" # see symlink-check above in file_magic test if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ $EGREP "$match_pattern_regex" > /dev/null; then func_append newdeplibs " $a_deplib" a_deplib="" break 2 fi done done fi if test -n "$a_deplib" ; then droppeddeps=yes echo $ECHO "*** Warning: linker path does not have real file for library $a_deplib." echo "*** I have the capability to make that library automatically link in when" echo "*** you link to this library. But I can only do this if you have a" echo "*** shared version of the library, which you do not appear to have" echo "*** because I did check the linker path looking for a file starting" if test -z "$potlib" ; then $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" else $ECHO "*** with $libname and none of the candidates passed a file format test" $ECHO "*** using a regex pattern. Last file checked: $potlib" fi fi ;; *) # Add a -L argument. func_append newdeplibs " $a_deplib" ;; esac done # Gone through all deplibs. ;; none | unknown | *) newdeplibs="" tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then for i in $predeps $postdeps ; do # can't use Xsed below, because $i might contain '/' tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` done fi case $tmp_deplibs in *[!\ \ ]*) echo if test "X$deplibs_check_method" = "Xnone"; then echo "*** Warning: inter-library dependencies are not supported in this platform." else echo "*** Warning: inter-library dependencies are not known to be supported." fi echo "*** All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac ;; esac versuffix=$versuffix_save major=$major_save release=$release_save libname=$libname_save name=$name_save case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library with the System framework newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac if test "$droppeddeps" = yes; then if test "$module" = yes; then echo echo "*** Warning: libtool could not satisfy all declared inter-library" $ECHO "*** dependencies of module $libname. Therefore, libtool will create" echo "*** a static module, that should work as long as the dlopening" echo "*** application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then echo echo "*** However, this would only work if libtool was able to extract symbol" echo "*** lists from a program, using \`nm' or equivalent, but libtool could" echo "*** not find such a program. So, this module is probably useless." echo "*** \`nm' from GNU binutils and a full rebuild may help." fi if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi else echo "*** The inter-library dependencies that have been dropped here will be" echo "*** automatically added whenever a program is linked with this library" echo "*** or is declared to -dlopen it." if test "$allow_undefined" = no; then echo echo "*** Since this library must not contain undefined symbols," echo "*** because either the platform does not support them or" echo "*** it was explicitly requested with -no-undefined," echo "*** libtool will only create a static version of it." if test "$build_old_libs" = no; then oldlibs="$output_objdir/$libname.$libext" build_libtool_libs=module build_old_libs=yes else build_libtool_libs=no fi fi fi fi # Done checking deplibs! deplibs=$newdeplibs fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" case $host in *-*-darwin*) newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done deplibs="$new_libs" # All the library-specific variables (install_libdir is set above). library_names= old_library= dlname= # Test again, we may have decided not to build it any more if test "$build_libtool_libs" = yes; then # Remove ${wl} instances when linking with ld. # FIXME: should test the right _cmds variable. case $archive_cmds in *\$LD\ *) wl= ;; esac if test "$hardcode_into_libs" = yes; then # Hardcode the library paths hardcode_libdirs= dep_rpath= rpath="$finalize_rpath" test "$opt_mode" != relink && rpath="$compile_rpath$rpath" for libdir in $rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then func_replace_sysroot "$libdir" libdir=$func_replace_sysroot_result if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append dep_rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" fi if test -n "$runpath_var" && test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" fi test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" fi shlibpath="$finalize_shlibpath" test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" if test -n "$shlibpath"; then eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" fi # Get the real and link names of the library. eval shared_ext=\"$shrext_cmds\" eval library_names=\"$library_names_spec\" set dummy $library_names shift realname="$1" shift if test -n "$soname_spec"; then eval soname=\"$soname_spec\" else soname="$realname" fi if test -z "$dlname"; then dlname=$soname fi lib="$output_objdir/$realname" linknames= for link do func_append linknames " $link" done # Use standard objects if they are pic test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` test "X$libobjs" = "X " && libobjs= delfiles= if test -n "$export_symbols" && test -n "$include_expsyms"; then $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" export_symbols="$output_objdir/$libname.uexp" func_append delfiles " $export_symbols" fi orig_export_symbols= case $host_os in cygwin* | mingw* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile if test "x`$SED 1q $export_symbols`" != xEXPORTS; then # and it's NOT already a .def file. Must figure out # which of the given symbols are data symbols and tag # them as such. So, trigger use of export_symbols_cmds. # export_symbols gets reassigned inside the "prepare # the list of exported symbols" if statement, so the # include_expsyms logic still works. orig_export_symbols="$export_symbols" export_symbols= always_export_symbols=yes fi fi ;; esac # Prepare the list of exported symbols if test -z "$export_symbols"; then if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols cmds=$export_symbols_cmds save_ifs="$IFS"; IFS='~' for cmd1 in $cmds; do IFS="$save_ifs" # Take the normal branch if the nm_file_list_spec branch # doesn't work or if tool conversion is not needed. case $nm_file_list_spec~$to_tool_file_cmd in *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) try_normal_branch=yes eval cmd=\"$cmd1\" func_len " $cmd" len=$func_len_result ;; *) try_normal_branch=no ;; esac if test "$try_normal_branch" = yes \ && { test "$len" -lt "$max_cmd_len" \ || test "$max_cmd_len" -le -1; } then func_show_eval "$cmd" 'exit $?' skipped_export=false elif test -n "$nm_file_list_spec"; then func_basename "$output" output_la=$func_basename_result save_libobjs=$libobjs save_output=$output output=${output_objdir}/${output_la}.nm func_to_tool_file "$output" libobjs=$nm_file_list_spec$func_to_tool_file_result func_append delfiles " $output" func_verbose "creating $NM input file list: $output" for obj in $save_libobjs; do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > "$output" eval cmd=\"$cmd1\" func_show_eval "$cmd" 'exit $?' output=$save_output libobjs=$save_libobjs skipped_export=false else # The command line is too long to execute in one step. func_verbose "using reloadable object file for export list..." skipped_export=: # Break out early, otherwise skipped_export may be # set to false by a later but shorter cmd. break fi done IFS="$save_ifs" if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi fi if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi tmp_deplibs= for test_deplib in $deplibs; do case " $convenience " in *" $test_deplib "*) ;; *) func_append tmp_deplibs " $test_deplib" ;; esac done deplibs="$tmp_deplibs" if test -n "$convenience"; then if test -n "$whole_archive_flag_spec" && test "$compiler_needs_object" = yes && test -z "$libobjs"; then # extract the archives, so we have objects to list. # TODO: could optimize this to just extract one archive. whole_archive_flag_spec= fi if test -n "$whole_archive_flag_spec"; then save_libobjs=$libobjs eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= else gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $convenience func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi fi if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then eval flag=\"$thread_safe_flag_spec\" func_append linker_flags " $flag" fi # Make a backup of the uninstalled library when relinking if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? fi # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then eval test_cmds=\"$module_expsym_cmds\" cmds=$module_expsym_cmds else eval test_cmds=\"$module_cmds\" cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then eval test_cmds=\"$archive_expsym_cmds\" cmds=$archive_expsym_cmds else eval test_cmds=\"$archive_cmds\" cmds=$archive_cmds fi fi if test "X$skipped_export" != "X:" && func_len " $test_cmds" && len=$func_len_result && test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then : else # The command line is too long to link in one step, link piecewise # or, if using GNU ld and skipped_export is not :, use a linker # script. # Save the value of $output and $libobjs because we want to # use them later. If we have whole_archive_flag_spec, we # want to use save_libobjs as it was before # whole_archive_flag_spec was expanded, because we can't # assume the linker understands whole_archive_flag_spec. # This may have to be revisited, in case too many # convenience libraries get linked in and end up exceeding # the spec. if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then save_libobjs=$libobjs fi save_output=$output func_basename "$output" output_la=$func_basename_result # Clear the reloadable object creation command queue and # initialize k to one. test_cmds= concat_cmds= objlist= last_robj= k=1 if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then output=${output_objdir}/${output_la}.lnkscript func_verbose "creating GNU ld script: $output" echo 'INPUT (' > $output for obj in $save_libobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done echo ')' >> $output func_append delfiles " $output" func_to_tool_file "$output" output=$func_to_tool_file_result elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then output=${output_objdir}/${output_la}.lnk func_verbose "creating linker input file list: $output" : > $output set x $save_libobjs shift firstobj= if test "$compiler_needs_object" = yes; then firstobj="$1 " shift fi for obj do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" >> $output done func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." output=$output_objdir/$output_la-${k}.$objext eval test_cmds=\"$reload_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 # Loop over the list of objects to be linked. for obj in $save_libobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result if test "X$objlist" = X || test "$len" -lt "$max_cmd_len"; then func_append objlist " $obj" else # The command $test_cmds is almost too long, add a # command to the queue. if test "$k" -eq 1 ; then # The first file doesn't have a previous command to add. reload_objs=$objlist eval concat_cmds=\"$reload_cmds\" else # All subsequent reloadable object files will link in # the last one created. reload_objs="$objlist $last_robj" eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" fi last_robj=$output_objdir/$output_la-${k}.$objext func_arith $k + 1 k=$func_arith_result output=$output_objdir/$output_la-${k}.$objext objlist=" $obj" func_len " $last_robj" func_arith $len0 + $func_len_result len=$func_arith_result fi done # Handle the remaining objects by creating one last # reloadable object file. All subsequent reloadable object # files will link in the last one created. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ reload_objs="$objlist $last_robj" eval concat_cmds=\"\${concat_cmds}$reload_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" fi func_append delfiles " $output" else output= fi if ${skipped_export-false}; then func_verbose "generating symbol list for \`$libname.la'" export_symbols="$output_objdir/$libname.exp" $opt_dry_run || $RM $export_symbols libobjs=$output # Append the command to create the export file. test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" if test -n "$last_robj"; then eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" fi fi test -n "$save_libobjs" && func_verbose "creating a temporary reloadable object file: $output" # Loop through the commands generated above and execute them. save_ifs="$IFS"; IFS='~' for cmd in $concat_cmds; do IFS="$save_ifs" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" if test -n "$export_symbols_regex" && ${skipped_export-false}; then func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' func_show_eval '$MV "${export_symbols}T" "$export_symbols"' fi fi if ${skipped_export-false}; then if test -n "$export_symbols" && test -n "$include_expsyms"; then tmp_export_symbols="$export_symbols" test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' fi if test -n "$orig_export_symbols"; then # The given exports_symbols file has to be filtered, so filter it. func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" # FIXME: $output_objdir/$libname.filter potentially contains lots of # 's' commands which not all seds can handle. GNU sed should be fine # though. Also, the filter scales superlinearly with the number of # global variables. join(1) would be nice here, but unfortunately # isn't a blessed tool. $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter func_append delfiles " $export_symbols $output_objdir/$libname.filter" export_symbols=$output_objdir/$libname.def $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols fi fi libobjs=$output # Restore the value of output. output=$save_output if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then eval libobjs=\"\$libobjs $whole_archive_flag_spec\" test "X$libobjs" = "X " && libobjs= fi # Expand the library linking commands again to reset the # value of $libobjs for piecewise linking. # Do each of the archive commands. if test "$module" = yes && test -n "$module_cmds" ; then if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then cmds=$module_expsym_cmds else cmds=$module_cmds fi else if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then cmds=$archive_expsym_cmds else cmds=$archive_cmds fi fi fi if test -n "$delfiles"; then # Append the command to remove temporary files to $cmds. eval cmds=\"\$cmds~\$RM $delfiles\" fi # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append libobjs " $func_extract_archives_result" test "X$libobjs" = "X " && libobjs= fi save_ifs="$IFS"; IFS='~' for cmd in $cmds; do IFS="$save_ifs" eval cmd=\"$cmd\" $opt_silent || { func_quote_for_expand "$cmd" eval "func_echo $func_quote_for_expand_result" } $opt_dry_run || eval "$cmd" || { lt_exit=$? # Restore the uninstalled library and exit if test "$opt_mode" = relink; then ( cd "$output_objdir" && \ $RM "${realname}T" && \ $MV "${realname}U" "$realname" ) fi exit $lt_exit } done IFS="$save_ifs" # Restore the uninstalled library and exit if test "$opt_mode" = relink; then $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? if test -n "$convenience"; then if test -z "$whole_archive_flag_spec"; then func_show_eval '${RM}r "$gentop"' fi fi exit $EXIT_SUCCESS fi # Create links to the real library. for linkname in $linknames; do if test "$realname" != "$linkname"; then func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' fi done # If -module or -export-dynamic was specified, set the dlname. if test "$module" = yes || test "$export_dynamic" = yes; then # On all known operating systems, these are identical. dlname="$soname" fi fi ;; obj) if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then func_warning "\`-dlopen' is ignored for objects" fi case " $deplibs" in *\ -l* | *\ -L*) func_warning "\`-l' and \`-L' are ignored for objects" ;; esac test -n "$rpath" && \ func_warning "\`-rpath' is ignored for objects" test -n "$xrpath" && \ func_warning "\`-R' is ignored for objects" test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for objects" test -n "$release" && \ func_warning "\`-release' is ignored for objects" case $output in *.lo) test -n "$objs$old_deplibs" && \ func_fatal_error "cannot build library object \`$output' from non-libtool objects" libobj=$output func_lo2o "$libobj" obj=$func_lo2o_result ;; *) libobj= obj="$output" ;; esac # Delete the old objects. $opt_dry_run || $RM $obj $libobj # Objects from convenience libraries. This assumes # single-version convenience libraries. Whenever we create # different ones for PIC/non-PIC, this we'll have to duplicate # the extraction. reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of # -Wl from whole_archive_flag_spec and hope we can get by with # turning comma into space.. wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` else gentop="$output_objdir/${obj}x" func_append generated " $gentop" func_extract_archives $gentop $convenience reload_conv_objs="$reload_objs $func_extract_archives_result" fi fi # If we're not building shared, we need to use non_pic_objs test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" # Create the old-style object. reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test output="$obj" func_execute_cmds "$reload_cmds" 'exit $?' # Exit if we aren't doing a library object file. if test -z "$libobj"; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS fi if test "$build_libtool_libs" != yes; then if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi # Create an invalid libtool object if no PIC, so that we don't # accidentally link it into a program. # $show "echo timestamp > $libobj" # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? exit $EXIT_SUCCESS fi if test -n "$pic_flag" || test "$pic_mode" != default; then # Only do commands if we really have different PIC objects. reload_objs="$libobjs $reload_conv_objs" output="$libobj" func_execute_cmds "$reload_cmds" 'exit $?' fi if test -n "$gentop"; then func_show_eval '${RM}r "$gentop"' fi exit $EXIT_SUCCESS ;; prog) case $host in *cygwin*) func_stripname '' '.exe' "$output" output=$func_stripname_result.exe;; esac test -n "$vinfo" && \ func_warning "\`-version-info' is ignored for programs" test -n "$release" && \ func_warning "\`-release' is ignored for programs" test "$preload" = yes \ && test "$dlopen_support" = unknown \ && test "$dlopen_self" = unknown \ && test "$dlopen_self_static" = unknown && \ func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." case $host in *-*-rhapsody* | *-*-darwin1.[012]) # On Rhapsody replace the C library is the System framework compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` ;; esac case $host in *-*-darwin*) # Don't allow lazy linking, it breaks C++ global constructors # But is supposedly fixed on 10.4 or later (yay!). if test "$tagname" = CXX ; then case ${MACOSX_DEPLOYMENT_TARGET-10.0} in 10.[0123]) func_append compile_command " ${wl}-bind_at_load" func_append finalize_command " ${wl}-bind_at_load" ;; esac fi # Time to change all our "foo.ltframework" stuff back to "-framework foo" compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` ;; esac # move library search paths that coincide with paths to not yet # installed libraries to the beginning of the library search list new_libs= for path in $notinst_path; do case " $new_libs " in *" -L$path/$objdir "*) ;; *) case " $compile_deplibs " in *" -L$path/$objdir "*) func_append new_libs " -L$path/$objdir" ;; esac ;; esac done for deplib in $compile_deplibs; do case $deplib in -L*) case " $new_libs " in *" $deplib "*) ;; *) func_append new_libs " $deplib" ;; esac ;; *) func_append new_libs " $deplib" ;; esac done compile_deplibs="$new_libs" func_append compile_command " $compile_deplibs" func_append finalize_command " $finalize_deplibs" if test -n "$rpath$xrpath"; then # If the user specified any rpath flags, then add them. for libdir in $rpath $xrpath; do # This is the magic to use -rpath. case "$finalize_rpath " in *" $libdir "*) ;; *) func_append finalize_rpath " $libdir" ;; esac done fi # Now hardcode the library paths rpath= hardcode_libdirs= for libdir in $compile_rpath $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$perm_rpath " in *" $libdir "*) ;; *) func_append perm_rpath " $libdir" ;; esac fi case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; ::) dllsearchpath=$libdir;; *) func_append dllsearchpath ":$libdir";; esac case :$dllsearchpath: in *":$testbindir:"*) ;; ::) dllsearchpath=$testbindir;; *) func_append dllsearchpath ":$testbindir";; esac ;; esac done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi compile_rpath="$rpath" rpath= hardcode_libdirs= for libdir in $finalize_rpath; do if test -n "$hardcode_libdir_flag_spec"; then if test -n "$hardcode_libdir_separator"; then if test -z "$hardcode_libdirs"; then hardcode_libdirs="$libdir" else # Just accumulate the unique libdirs. case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) ;; *) func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" ;; esac fi else eval flag=\"$hardcode_libdir_flag_spec\" func_append rpath " $flag" fi elif test -n "$runpath_var"; then case "$finalize_perm_rpath " in *" $libdir "*) ;; *) func_append finalize_perm_rpath " $libdir" ;; esac fi done # Substitute the hardcoded libdirs into the rpath. if test -n "$hardcode_libdir_separator" && test -n "$hardcode_libdirs"; then libdir="$hardcode_libdirs" eval rpath=\" $hardcode_libdir_flag_spec\" fi finalize_rpath="$rpath" if test -n "$libobjs" && test "$build_old_libs" = yes; then # Transform all the library objects into standard objects. compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` fi func_generate_dlsyms "$outputname" "@PROGRAM@" "no" # template prelinking step if test -n "$prelink_cmds"; then func_execute_cmds "$prelink_cmds" 'exit $?' fi wrappers_required=yes case $host in *cegcc* | *mingw32ce*) # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=no ;; *cygwin* | *mingw* ) if test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; *) if test "$need_relink" = no || test "$build_libtool_libs" != yes; then wrappers_required=no fi ;; esac if test "$wrappers_required" = no; then # Replace the output file specification. compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. exit_status=0 func_show_eval "$link_command" 'exit_status=$?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Delete the generated files. if test -f "$output_objdir/${outputname}S.${objext}"; then func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' fi exit $exit_status fi if test -n "$compile_shlibpath$finalize_shlibpath"; then compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" fi if test -n "$finalize_shlibpath"; then finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" fi compile_var= finalize_var= if test -n "$runpath_var"; then if test -n "$perm_rpath"; then # We should set the runpath_var. rpath= for dir in $perm_rpath; do func_append rpath "$dir:" done compile_var="$runpath_var=\"$rpath\$$runpath_var\" " fi if test -n "$finalize_perm_rpath"; then # We should set the runpath_var. rpath= for dir in $finalize_perm_rpath; do func_append rpath "$dir:" done finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " fi fi if test "$no_install" = yes; then # We don't need to create a wrapper script. link_command="$compile_var$compile_command$compile_rpath" # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` # Delete the old output file. $opt_dry_run || $RM $output # Link the executable and exit func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi exit $EXIT_SUCCESS fi if test "$hardcode_action" = relink; then # Fast installation is not supported link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" func_warning "this platform does not like uninstalled shared libraries" func_warning "\`$output' will be relinked during installation" else if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= fi else link_command="$compile_var$compile_command$compile_rpath" relink_command="$finalize_var$finalize_command$finalize_rpath" fi fi # Replace the output file specification. link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` # Delete the old output files. $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname func_show_eval "$link_command" 'exit $?' if test -n "$postlink_cmds"; then func_to_tool_file "$output_objdir/$outputname" postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` func_execute_cmds "$postlink_cmds" 'exit $?' fi # Now create the wrapper script. func_verbose "creating $output" # Quote the relink command for shipping. if test -n "$relink_command"; then # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done relink_command="(cd `pwd`; $relink_command)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` fi # Only actually do things if not in dry run mode. $opt_dry_run || { # win32 will think the script is a binary if it has # a .exe suffix, so we strip it off here. case $output in *.exe) func_stripname '' '.exe' "$output" output=$func_stripname_result ;; esac # test for cygwin because mv fails w/o .exe extensions case $host in *cygwin*) exeext=.exe func_stripname '' '.exe' "$outputname" outputname=$func_stripname_result ;; *) exeext= ;; esac case $host in *cygwin* | *mingw* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result cwrappersource="$output_path/$objdir/lt-$output_name.c" cwrapper="$output_path/$output_name.exe" $RM $cwrappersource $cwrapper trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 func_emit_cwrapperexe_src > $cwrappersource # The wrapper executable is built using the $host compiler, # because it contains $host paths and files. If cross- # compiling, it, like the target executable, must be # executed on the $host or under an emulation environment. $opt_dry_run || { $LTCC $LTCFLAGS -o $cwrapper $cwrappersource $STRIP $cwrapper } # Now, create the wrapper script for func_source use: func_ltwrapper_scriptname $cwrapper $RM $func_ltwrapper_scriptname_result trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 $opt_dry_run || { # note: this script will not be executed, so do not chmod. if test "x$build" = "x$host" ; then $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result else func_emit_wrapper no > $func_ltwrapper_scriptname_result fi } ;; * ) $RM $output trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 func_emit_wrapper no > $output chmod +x $output ;; esac } exit $EXIT_SUCCESS ;; esac # See if we need to build an old-fashioned archive. for oldlib in $oldlibs; do if test "$build_libtool_libs" = convenience; then oldobjs="$libobjs_save $symfileobj" addlibs="$convenience" build_libtool_libs=no else if test "$build_libtool_libs" = module; then oldobjs="$libobjs_save" build_libtool_libs=no else oldobjs="$old_deplibs $non_pic_objects" if test "$preload" = yes && test -f "$symfileobj"; then func_append oldobjs " $symfileobj" fi fi addlibs="$old_convenience" fi if test -n "$addlibs"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $addlibs func_append oldobjs " $func_extract_archives_result" fi # Do each command in the archive commands. if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then cmds=$old_archive_from_new_cmds else # Add any objects from preloaded convenience libraries if test -n "$dlprefiles"; then gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_extract_archives $gentop $dlprefiles func_append oldobjs " $func_extract_archives_result" fi # POSIX demands no paths to be encoded in archives. We have # to avoid creating archives with duplicate basenames if we # might have to extract them afterwards, e.g., when creating a # static archive out of a convenience library, or when linking # the entirety of a libtool archive into another (currently # not supported by libtool). if (for obj in $oldobjs do func_basename "$obj" $ECHO "$func_basename_result" done | sort | sort -uc >/dev/null 2>&1); then : else echo "copying selected object files to avoid basename conflicts..." gentop="$output_objdir/${outputname}x" func_append generated " $gentop" func_mkdir_p "$gentop" save_oldobjs=$oldobjs oldobjs= counter=1 for obj in $save_oldobjs do func_basename "$obj" objbase="$func_basename_result" case " $oldobjs " in " ") oldobjs=$obj ;; *[\ /]"$objbase "*) while :; do # Make sure we don't pick an alternate name that also # overlaps. newobj=lt$counter-$objbase func_arith $counter + 1 counter=$func_arith_result case " $oldobjs " in *[\ /]"$newobj "*) ;; *) if test ! -f "$gentop/$newobj"; then break; fi ;; esac done func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" func_append oldobjs " $gentop/$newobj" ;; *) func_append oldobjs " $obj" ;; esac done fi func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 tool_oldlib=$func_to_tool_file_result eval cmds=\"$old_archive_cmds\" func_len " $cmds" len=$func_len_result if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then cmds=$old_archive_cmds elif test -n "$archiver_list_spec"; then func_verbose "using command file archive linking..." for obj in $oldobjs do func_to_tool_file "$obj" $ECHO "$func_to_tool_file_result" done > $output_objdir/$libname.libcmd func_to_tool_file "$output_objdir/$libname.libcmd" oldobjs=" $archiver_list_spec$func_to_tool_file_result" cmds=$old_archive_cmds else # the command line is too long to link in one step, link in parts func_verbose "using piecewise archive linking..." save_RANLIB=$RANLIB RANLIB=: objlist= concat_cmds= save_oldobjs=$oldobjs oldobjs= # Is there a better way of finding the last object in the list? for obj in $save_oldobjs do last_oldobj=$obj done eval test_cmds=\"$old_archive_cmds\" func_len " $test_cmds" len0=$func_len_result len=$len0 for obj in $save_oldobjs do func_len " $obj" func_arith $len + $func_len_result len=$func_arith_result func_append objlist " $obj" if test "$len" -lt "$max_cmd_len"; then : else # the above command should be used before it gets too long oldobjs=$objlist if test "$obj" = "$last_oldobj" ; then RANLIB=$save_RANLIB fi test -z "$concat_cmds" || concat_cmds=$concat_cmds~ eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" objlist= len=$len0 fi done RANLIB=$save_RANLIB oldobjs=$objlist if test "X$oldobjs" = "X" ; then eval cmds=\"\$concat_cmds\" else eval cmds=\"\$concat_cmds~\$old_archive_cmds\" fi fi fi func_execute_cmds "$cmds" 'exit $?' done test -n "$generated" && \ func_show_eval "${RM}r$generated" # Now create the libtool archive. case $output in *.la) old_library= test "$build_old_libs" = yes && old_library="$libname.$libext" func_verbose "creating $output" # Preserve any variables that may affect compiler behavior for var in $variables_saved_for_relink; do if eval test -z \"\${$var+set}\"; then relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" elif eval var_value=\$$var; test -z "$var_value"; then relink_command="$var=; export $var; $relink_command" else func_quote_for_eval "$var_value" relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" fi done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi # Only create the output if not a dry run. $opt_dry_run || { for installed in no yes; do if test "$installed" = yes; then if test -z "$install_libdir"; then break fi output="$output_objdir/$outputname"i # Replace all uninstalled libtool libraries with the installed ones newdependency_libs= for deplib in $dependency_libs; do case $deplib in *.la) func_basename "$deplib" name="$func_basename_result" func_resolve_sysroot "$deplib" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` test -z "$libdir" && \ func_fatal_error "\`$deplib' is not a valid libtool archive" func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" ;; -L*) func_stripname -L '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -L$func_replace_sysroot_result" ;; -R*) func_stripname -R '' "$deplib" func_replace_sysroot "$func_stripname_result" func_append newdependency_libs " -R$func_replace_sysroot_result" ;; *) func_append newdependency_libs " $deplib" ;; esac done dependency_libs="$newdependency_libs" newdlfiles= for lib in $dlfiles; do case $lib in *.la) func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" ;; *) func_append newdlfiles " $lib" ;; esac done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in *.la) # Only pass preopened files to the pseudo-archive (for # eventual linking with the app. that links it) if we # didn't already link the preopened objects directly into # the library: func_basename "$lib" name="$func_basename_result" eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` test -z "$libdir" && \ func_fatal_error "\`$lib' is not a valid libtool archive" func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" ;; esac done dlprefiles="$newdlprefiles" else newdlfiles= for lib in $dlfiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlfiles " $abs" done dlfiles="$newdlfiles" newdlprefiles= for lib in $dlprefiles; do case $lib in [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; *) abs=`pwd`"/$lib" ;; esac func_append newdlprefiles " $abs" done dlprefiles="$newdlprefiles" fi $RM $output # place dlname in correct position for cygwin # In fact, it would be nice if we could use this code for all target # systems that can't hard-code library paths into their executables # and that have no shared library path variable independent of PATH, # but it turns out we can't easily determine that from inspecting # libtool variables, so we have to hard-code the OSs to which it # applies here; at the moment, that means platforms that use the PE # object format with DLL files. See the long comment at the top of # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test "x$bindir" != x ; then func_relative_path "$install_libdir" "$bindir" tdlname=$func_relative_path_result$dlname else # Otherwise fall back on heuristic. tdlname=../bin/$dlname fi ;; esac $ECHO > $output "\ # $outputname - a libtool library file # Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION # # Please DO NOT delete this file! # It is necessary for linking the library. # The name that we can dlopen(3). dlname='$tdlname' # Names of this library. library_names='$library_names' # The name of the static archive. old_library='$old_library' # Linker flags that can not go in dependency_libs. inherited_linker_flags='$new_inherited_linker_flags' # Libraries that this one depends upon. dependency_libs='$dependency_libs' # Names of additional weak libraries provided by this library weak_library_names='$weak_libs' # Version information for $libname. current=$current age=$age revision=$revision # Is this an already installed library? installed=$installed # Should we warn about portability when linking against -modules? shouldnotlink=$module # Files to dlopen/dlpreopen dlopen='$dlfiles' dlpreopen='$dlprefiles' # Directory that this library needs to be installed in: libdir='$install_libdir'" if test "$installed" = no && test "$need_relink" = yes; then $ECHO >> $output "\ relink_command=\"$relink_command\"" fi done } # Do a symbolic link so that the libtool archive can be found in # LD_LIBRARY_PATH before the program is installed. func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' ;; esac exit $EXIT_SUCCESS } { test "$opt_mode" = link || test "$opt_mode" = relink; } && func_mode_link ${1+"$@"} # func_mode_uninstall arg... func_mode_uninstall () { $opt_debug RM="$nonopt" files= rmforce= exit_status=0 # This variable tells wrapper scripts just to set variables rather # than running their programs. libtool_install_magic="$magic" for arg do case $arg in -f) func_append RM " $arg"; rmforce=yes ;; -*) func_append RM " $arg" ;; *) func_append files " $arg" ;; esac done test -z "$RM" && \ func_fatal_help "you must specify an RM program" rmdirs= for file in $files; do func_dirname "$file" "" "." dir="$func_dirname_result" if test "X$dir" = X.; then odir="$objdir" else odir="$dir/$objdir" fi func_basename "$file" name="$func_basename_result" test "$opt_mode" = uninstall && odir="$dir" # Remember odir for removal later, being careful to avoid duplicates if test "$opt_mode" = clean; then case " $rmdirs " in *" $odir "*) ;; *) func_append rmdirs " $odir" ;; esac fi # Don't error if the file doesn't exist and rm -f was used. if { test -L "$file"; } >/dev/null 2>&1 || { test -h "$file"; } >/dev/null 2>&1 || test -f "$file"; then : elif test -d "$file"; then exit_status=1 continue elif test "$rmforce" = yes; then continue fi rmfiles="$file" case $name in *.la) # Possibly a libtool archive, so verify it. if func_lalib_p "$file"; then func_source $dir/$name # Delete the libtool libraries and symlinks. for n in $library_names; do func_append rmfiles " $odir/$n" done test -n "$old_library" && func_append rmfiles " $odir/$old_library" case "$opt_mode" in clean) case " $library_names " in *" $dlname "*) ;; *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; esac test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" ;; uninstall) if test -n "$library_names"; then # Do each command in the postuninstall commands. func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi if test -n "$old_library"; then # Do each command in the old_postuninstall commands. func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' fi # FIXME: should reinstall the best remaining shared library. ;; esac fi ;; *.lo) # Possibly a libtool object, so verify it. if func_lalib_p "$file"; then # Read the .lo file func_source $dir/$name # Add PIC object to the list of files to remove. if test -n "$pic_object" && test "$pic_object" != none; then func_append rmfiles " $dir/$pic_object" fi # Add non-PIC object to the list of files to remove. if test -n "$non_pic_object" && test "$non_pic_object" != none; then func_append rmfiles " $dir/$non_pic_object" fi fi ;; *) if test "$opt_mode" = clean ; then noexename=$name case $file in *.exe) func_stripname '' '.exe' "$file" file=$func_stripname_result func_stripname '' '.exe' "$name" noexename=$func_stripname_result # $file with .exe has already been added to rmfiles, # add $file without .exe func_append rmfiles " $file" ;; esac # Do a test to see if this is a libtool program. if func_ltwrapper_p "$file"; then if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" relink_command= func_source $func_ltwrapper_scriptname_result func_append rmfiles " $func_ltwrapper_scriptname_result" else relink_command= func_source $dir/$noexename fi # note $name still contains .exe if it was in $file originally # as does the version of $file that was added into $rmfiles func_append rmfiles " $odir/$name $odir/${name}S.${objext}" if test "$fast_install" = yes && test -n "$relink_command"; then func_append rmfiles " $odir/lt-$name" fi if test "X$noexename" != "X$name" ; then func_append rmfiles " $odir/lt-${noexename}.c" fi fi fi ;; esac func_show_eval "$RM $rmfiles" 'exit_status=1' done # Try to remove the ${objdir}s in the directories where we deleted files for dir in $rmdirs; do if test -d "$dir"; then func_show_eval "rmdir $dir >/dev/null 2>&1" fi done exit $exit_status } { test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && func_mode_uninstall ${1+"$@"} test -z "$opt_mode" && { help="$generic_help" func_fatal_help "you must specify a MODE" } test -z "$exec_cmd" && \ func_fatal_help "invalid operation mode \`$opt_mode'" if test -n "$exec_cmd"; then eval exec "$exec_cmd" exit $EXIT_FAILURE fi exit $exit_status # The TAGs below are defined such that we never get into a situation # in which we disable both kinds of libraries. Given conflicting # choices, we go for a static library, that is the most portable, # since we can't tell whether shared libraries were disabled because # the user asked for that or because the platform doesn't support # them. This is particularly important on AIX, because we don't # support having both static and shared libraries enabled at the same # time on that platform, so we default to a shared-only configuration. # If a disable-shared tag is given, we'll fallback to a static-only # configuration. But we'll never go from static-only to shared-only. # ### BEGIN LIBTOOL TAG CONFIG: disable-shared build_libtool_libs=no build_old_libs=yes # ### END LIBTOOL TAG CONFIG: disable-shared # ### BEGIN LIBTOOL TAG CONFIG: disable-static build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` # ### END LIBTOOL TAG CONFIG: disable-static # Local Variables: # mode:shell-script # sh-indentation:2 # End: # vi:sw=2 softhsm-2.0.0/src/0000775000175000017500000000000012552220146010765 500000000000000softhsm-2.0.0/src/Makefile.am0000664000175000017500000000010012533040716012732 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in SUBDIRS = bin lib softhsm-2.0.0/src/bin/0000775000175000017500000000000012552220146011535 500000000000000softhsm-2.0.0/src/bin/util/0000775000175000017500000000000012552220146012512 500000000000000softhsm-2.0.0/src/bin/util/softhsm2-util.10000664000175000017500000001125412533040716015241 00000000000000.TH SOFTHSM2-UTIL 1 "29 October 2014" "SoftHSM" .SH NAME softhsm2-util \- support tool for libsofthsm2 .SH SYNOPSIS .B softhsm2-util \-\-show-slots .PP .B softhsm2-util \-\-init-token .B \-\-slot .I number .B \-\-label .I text \\ .ti +0.7i .RB [ \-\-so-pin .I PIN .B \-\-pin .IR PIN ] .PP .B softhsm2-util \-\-import .I path .RB [ \-\-file-pin .IR PIN ] .B \-\-slot .I number \\ .ti +0.7i .RB [ \-\-pin .I PIN .B \-\-no\-public\-key] .B \-\-label .I text .B \-\-id .I hex .SH DESCRIPTION .B softhsm2-util is a support tool mainly for libsofthsm2. It can also be used with other PKCS#11 libraries by using the option .B \-\-module .PP Read the sections below to get more information on the libsofthsm2 and PKCS#11. Most applications assumes that the token they want to use is already initialized. It is then up to the user to initialize the PKCS#11 token. This is done by using the PKCS#11 interface, but instead of writing your own tool you can use the .B softhsm2-util tool. .PP Keys are usually created directly in the token, but the user may want to use an existing key pair. Keys can be imported to a token by using the PKCS#11 interface, but this tool can also be used if the user has the key pair in a PKCS#8 file. If you need to convert keys from BIND .private-key format over to PKCS#8, one can use .BR softhsm2-keyconv . .LP The libary .BR libsofthsm2 , known as SoftHSM, provides cryptographic functionality by using the PKCS#11 API. It was developed as a part of the OpenDNSSEC project, thus designed to meet the requirements of OpenDNSSEC, but can also work together with other software that want to use the functionality of the PKCS#11 API. .PP SoftHSM is a software implementation of a generic cryptographic device with a PKCS#11 interface. These devices are often called tokens. Read in the manual softhsm2.conf(5) on how to create these tokens and how they are added to a slot in SoftHSM. .LP The .B PKCS#11 API can be used to handle and store cryptographic keys. This interface specifies how to communicate with cryptographic devices such as HSMs (Hardware Security Modules) and smart cards. The purpose of these devices is, among others, to generate cryptographic keys and sign information without revealing private-key material to the outside world. They are often designed to perform well on these specific tasks compared to ordinary processes in a normal computer. .LP .SH ACTIONS .TP .B \-\-help\fR, \fB\-h\fR Show the help information. .TP .B \-\-import \fIpath\fR Import a key pair from the given .IR path . The file must be in PKCS#8-format. .br Use with .BR \-\-file-pin , .BR \-\-slot , .BR \-\-pin , .BR \-\-no\-public\-key , .BR \-\-label , and .BR \-\-id . .TP .B \-\-init-token Initialize the token at a given slot. If the token is already initialized then this command will reinitialize it, thus erasing all the objects in the token. The matching Security Officer (SO) PIN must also be provided when doing reinitialization. .br Use with .BR \-\-slot or .BR \-\-free , .BR \-\-label , .BR \-\-so-pin , and .BR \-\-pin . .LP .TP .B \-\-show-slots Display all the available slots and their current status. .TP .B \-\-version\fR, \fB\-v\fR Show the version info. .SH OPTIONS .TP .B \-\-file-pin \fIPIN\fR The .I PIN will be used to decrypt the PKCS#8 file. If not given then the PKCS#8 file is assumed to be unencrypted. .TP .B \-\-force Use this option to override the warnings and force the given action. .TP .B \-\-free Initialize the first free token. .TP .B \-\-id \fIhex\fR Choose an ID of the key pair. The ID is in hexadecimal with a variable length. Use with .B \-\-force when importing a key pair if the ID already exists. .TP .B \-\-label \fItext\fR Defines the .I label of the object or the token. .TP .B \-\-module \fIpath\fR Use another PKCS#11 library than SoftHSM. .TP .B \-\-no\-public\-key Do not import the public key. .TP .B \-\-pin \fIPIN\fR The .I PIN for the normal user. .TP .B \-\-slot \fInumber\fR The slot where the token is located. .TP .B \-\-so-pin \fIPIN\fR The .I PIN for the Security Officer (SO). .SH EXAMPLES .LP The token can be initialized using this command: .LP .RS .nf softhsm2-util \-\-init-token \-\-slot 1 \-\-label "A token" .fi .RE .LP A key pair can be imported using the softhsm tool where you specify the path to the key file, slot number, label and ID of the new objects, and the user PIN. The file must be in PKCS#8 format. .LP .RS .nf softhsm2-util \-\-import key1.pem \-\-slot 1 \-\-label "My key" \\ .ti +0.7i \-\-id A1B2 \-\-pin 123456 .fi (Add, \-\-file-pin .IR PIN , if the key file is encrypted.) .RE .LP .SH AUTHORS Written by Rickard Bellgrim, Francis Dupont, René Post, and Roland van Rijswijk. .LP .SH "SEE ALSO" .IR softhsm2-keyconv (1), .IR softhsm2-migrate (1), .IR softhsm2.conf (5) softhsm-2.0.0/src/bin/util/Makefile.am0000664000175000017500000000117612533040716014475 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../../lib/cryptoki_compat \ -I$(srcdir)/../common \ @CRYPTO_INCLUDES@ dist_man_MANS = softhsm2-util.1 bin_PROGRAMS = softhsm2-util AUTOMAKE_OPTIONS = subdir-objects softhsm2_util_SOURCES = softhsm2-util.cpp \ ../common/getpw.cpp \ ../common/library.cpp softhsm2_util_LDADD = @CRYPTO_LIBS@ # Compile with support of OpenSSL if WITH_OPENSSL softhsm2_util_SOURCES += softhsm2-util-ossl.cpp endif # Compile with support of Botan if WITH_BOTAN softhsm2_util_SOURCES += softhsm2-util-botan.cpp endif EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/*.cpp softhsm-2.0.0/src/bin/util/softhsm2-util-botan.h0000664000175000017500000001003512533040716016425 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-util-botan.h Header file for Botan implemented *****************************************************************************/ #ifndef _SOFTHSM_V2_SOFTHSM2_UTIL_BOTAN_H #define _SOFTHSM_V2_SOFTHSM2_UTIL_BOTAN_H #include #include #ifdef WITH_ECC #include #endif typedef struct rsa_key_material_t { CK_ULONG sizeE; CK_ULONG sizeN; CK_ULONG sizeD; CK_ULONG sizeP; CK_ULONG sizeQ; CK_ULONG sizeDMP1; CK_ULONG sizeDMQ1; CK_ULONG sizeIQMP; CK_VOID_PTR bigE; CK_VOID_PTR bigN; CK_VOID_PTR bigD; CK_VOID_PTR bigP; CK_VOID_PTR bigQ; CK_VOID_PTR bigDMP1; CK_VOID_PTR bigDMQ1; CK_VOID_PTR bigIQMP; rsa_key_material_t() { sizeE = 0; sizeN = 0; sizeD = 0; sizeP = 0; sizeQ = 0; sizeDMP1 = 0; sizeDMQ1 = 0; sizeIQMP = 0; bigE = NULL_PTR; bigN = NULL_PTR; bigD = NULL_PTR; bigP = NULL_PTR; bigQ = NULL_PTR; bigDMP1 = NULL_PTR; bigDMQ1 = NULL_PTR; bigIQMP = NULL_PTR; } } rsa_key_material_t; typedef struct dsa_key_material_t { CK_ULONG sizeP; CK_ULONG sizeQ; CK_ULONG sizeG; CK_ULONG sizeX; CK_ULONG sizeY; CK_VOID_PTR bigP; CK_VOID_PTR bigQ; CK_VOID_PTR bigG; CK_VOID_PTR bigX; CK_VOID_PTR bigY; dsa_key_material_t() { sizeP = 0; sizeQ = 0; sizeG = 0; sizeX = 0; sizeY = 0; bigP = NULL_PTR; bigQ = NULL_PTR; bigG = NULL_PTR; bigX = NULL_PTR; bigY = NULL_PTR; } } dsa_key_material_t; #ifdef WITH_ECC typedef struct ecdsa_key_material_t { CK_ULONG sizeParams; CK_ULONG sizeD; CK_ULONG sizeQ; CK_VOID_PTR derParams; CK_VOID_PTR bigD; CK_VOID_PTR derQ; ecdsa_key_material_t() { sizeParams = 0; sizeD = 0; sizeQ = 0; derParams = NULL_PTR; bigD = NULL_PTR; derQ = NULL_PTR; } } ecdsa_key_material_t; #endif Botan::Private_Key* crypto_read_file(char* filePath, char* filePIN); // RSA int crypto_save_rsa(CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, Botan::RSA_PrivateKey* rsa); rsa_key_material_t* crypto_malloc_rsa(Botan::RSA_PrivateKey* rsa); void crypto_free_rsa(rsa_key_material_t* keyMat); // DSA int crypto_save_dsa(CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, Botan::DSA_PrivateKey* dsa); dsa_key_material_t* crypto_malloc_dsa(Botan::DSA_PrivateKey* dsa); void crypto_free_dsa(dsa_key_material_t* keyMat); // ECDSA #ifdef WITH_ECC int crypto_save_ecdsa(CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, Botan::ECDSA_PrivateKey* ecdsa); ecdsa_key_material_t* crypto_malloc_ecdsa(Botan::ECDSA_PrivateKey* ecdsa); void crypto_free_ecdsa(ecdsa_key_material_t* keyMat); #endif #endif // !_SOFTHSM_V2_SOFTHSM2_UTIL_OSSL_H softhsm-2.0.0/src/bin/util/softhsm2-util.h0000664000175000017500000000512512533040716015330 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-util.h This program can be used for interacting with HSMs using PKCS#11. The default library is the libsofthsm2.so *****************************************************************************/ #ifndef _SOFTHSM_V2_SOFTHSM2_UTIL_H #define _SOFTHSM_V2_SOFTHSM2_UTIL_H #include "pkcs11.h" // Main functions void usage(); int initToken(char* slot, int freeToken, char* label, char* soPIN, char* userPIN); int showSlots(); int importKeyPair(char* filePath, char* filePIN, char* slot, char* userPIN, char* objectLabel, char* objectID, int forceExec, int noPublicKey); int crypto_import_key_pair(CK_SESSION_HANDLE hSession, char* filePath, char* filePIN, char* label, char* objID, size_t objIDLen, int noPublicKey); // Support functions void crypto_init(); void crypto_final(); int getFirstFreeToken(CK_SLOT_ID &slot); /// Hex char* hexStrToBin(char* objectID, int idLength, size_t* newLen); int hexdigit_to_int(char ch); /// Library #if !defined(UTIL_BOTAN) && !defined(UTIL_OSSL) static void* moduleHandle; #endif extern CK_FUNCTION_LIST_PTR p11; /// PKCS#11 support CK_OBJECT_HANDLE searchObject(CK_SESSION_HANDLE hSession, char* objID, size_t objIDLen); #endif // !_SOFTHSM_V2_SOFTHSM2_UTIL_H softhsm-2.0.0/src/bin/util/softhsm2-util-ossl.cpp0000664000175000017500000004515612533040716016651 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-util-ossl.cpp Code specific for OpenSSL *****************************************************************************/ #include #define UTIL_OSSL #include "softhsm2-util.h" #include "softhsm2-util-ossl.h" #include #include #include #include #include #include #include #include #include // Init OpenSSL void crypto_init() { // We do not need to do this one // OpenSSL_add_all_algorithms(); #ifdef WITH_FIPS // The PKCS#11 library might be using a FIPS capable OpenSSL if (FIPS_mode()) return; if (!FIPS_mode_set(1)) { fprintf(stderr, "ERROR: can't enter into FIPS mode.\n"); exit(0); } #endif } // Final OpenSSL void crypto_final() { // EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); } // Import a key pair from given path int crypto_import_key_pair ( CK_SESSION_HANDLE hSession, char* filePath, char* filePIN, char* label, char* objID, size_t objIDLen, int noPublicKey ) { EVP_PKEY* pkey = crypto_read_file(filePath, filePIN); if (pkey == NULL) { return 1; } RSA* rsa = NULL; DSA* dsa = NULL; #ifdef WITH_ECC EC_KEY* ecdsa = NULL; #endif switch (EVP_PKEY_type(pkey->type)) { case EVP_PKEY_RSA: rsa = EVP_PKEY_get1_RSA(pkey); break; case EVP_PKEY_DSA: dsa = EVP_PKEY_get1_DSA(pkey); break; #ifdef WITH_ECC case EVP_PKEY_EC: ecdsa = EVP_PKEY_get1_EC_KEY(pkey); break; #endif default: fprintf(stderr, "ERROR: Cannot handle this algorithm.\n"); EVP_PKEY_free(pkey); return 1; break; } EVP_PKEY_free(pkey); int result = 0; if (rsa) { result = crypto_save_rsa(hSession, label, objID, objIDLen, noPublicKey, rsa); RSA_free(rsa); } else if (dsa) { result = crypto_save_dsa(hSession, label, objID, objIDLen, noPublicKey, dsa); DSA_free(dsa); } #ifdef WITH_ECC else if (ecdsa) { result = crypto_save_ecdsa(hSession, label, objID, objIDLen, noPublicKey, ecdsa); EC_KEY_free(ecdsa); } #endif else { fprintf(stderr, "ERROR: Could not get the key material.\n"); result = 1; } return result; } // Read the key from file EVP_PKEY* crypto_read_file(char* filePath, char* filePIN) { BIO* in = NULL; PKCS8_PRIV_KEY_INFO* p8inf = NULL; EVP_PKEY* pkey = NULL; X509_SIG* p8 = NULL; if (!(in = BIO_new_file(filePath, "rb"))) { fprintf(stderr, "ERROR: Could open the PKCS#8 file: %s\n", filePath); return NULL; } // The PKCS#8 file is encrypted if (filePIN) { p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL); BIO_free(in); if (!p8) { fprintf(stderr, "ERROR: Could not read the PKCS#8 file. " "Maybe the file is not encrypted.\n"); return NULL; } p8inf = PKCS8_decrypt(p8, filePIN, strlen(filePIN)); X509_SIG_free(p8); if (!p8inf) { fprintf(stderr, "ERROR: Could not decrypt the PKCS#8 file. " "Maybe wrong PIN to file (--file-pin )\n"); return NULL; } } else { p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL); BIO_free(in); if (!p8inf) { fprintf(stderr, "ERROR: Could not read the PKCS#8 file. " "Maybe it is encypted (--file-pin )\n"); return NULL; } } if (p8inf->broken) { fprintf(stderr, "ERROR: Broken key encoding.\n"); PKCS8_PRIV_KEY_INFO_free(p8inf); return NULL; } // Convert the PKCS#8 to OpenSSL pkey = EVP_PKCS82PKEY(p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); if (!pkey) { fprintf(stderr, "ERROR: Could not convert the key.\n"); return NULL; } return pkey; } // Save the key data in PKCS#11 int crypto_save_rsa ( CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, RSA* rsa ) { rsa_key_material_t* keyMat = crypto_malloc_rsa(rsa); if (!keyMat) { fprintf(stderr, "ERROR: Could not convert the key material to binary information.\n"); return 1; } CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY, privClass = CKO_PRIVATE_KEY; CK_KEY_TYPE keyType = CKK_RSA; CK_BBOOL ckTrue = CK_TRUE, ckFalse = CK_FALSE, ckToken = CK_TRUE; if (noPublicKey) { ckToken = CK_FALSE; } CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, &pubClass, sizeof(pubClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_TOKEN, &ckToken, sizeof(ckToken) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_ENCRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_WRAP, &ckFalse, sizeof(ckFalse) }, { CKA_PUBLIC_EXPONENT, keyMat->bigE, keyMat->sizeE }, { CKA_MODULUS, keyMat->bigN, keyMat->sizeN } }; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, &privClass, sizeof(privClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof(ckFalse) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof(ckFalse) }, { CKA_PUBLIC_EXPONENT, keyMat->bigE, keyMat->sizeE }, { CKA_MODULUS, keyMat->bigN, keyMat->sizeN }, { CKA_PRIVATE_EXPONENT, keyMat->bigD, keyMat->sizeD }, { CKA_PRIME_1, keyMat->bigP, keyMat->sizeP }, { CKA_PRIME_2, keyMat->bigQ, keyMat->sizeQ }, { CKA_EXPONENT_1, keyMat->bigDMP1, keyMat->sizeDMP1 }, { CKA_EXPONENT_2, keyMat->bigDMQ1, keyMat->sizeDMQ1 }, { CKA_COEFFICIENT, keyMat->bigIQMP, keyMat->sizeIQMP } }; CK_OBJECT_HANDLE hKey1, hKey2; CK_RV rv = p11->C_CreateObject(hSession, privTemplate, 19, &hKey1); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not save the private key in the token. " "Maybe the algorithm is not supported.\n"); crypto_free_rsa(keyMat); return 1; } rv = p11->C_CreateObject(hSession, pubTemplate, 10, &hKey2); crypto_free_rsa(keyMat); if (rv != CKR_OK) { p11->C_DestroyObject(hSession, hKey1); fprintf(stderr, "ERROR: Could not save the public key in the token.\n"); return 1; } printf("The key pair has been imported.\n"); return 0; } // Convert the OpenSSL key to binary rsa_key_material_t* crypto_malloc_rsa(RSA* rsa) { if (rsa == NULL) { return NULL; } rsa_key_material_t* keyMat = (rsa_key_material_t*)malloc(sizeof(rsa_key_material_t)); if (keyMat == NULL) { return NULL; } keyMat->sizeE = BN_num_bytes(rsa->e); keyMat->sizeN = BN_num_bytes(rsa->n); keyMat->sizeD = BN_num_bytes(rsa->d); keyMat->sizeP = BN_num_bytes(rsa->p); keyMat->sizeQ = BN_num_bytes(rsa->q); keyMat->sizeDMP1 = BN_num_bytes(rsa->dmp1); keyMat->sizeDMQ1 = BN_num_bytes(rsa->dmq1); keyMat->sizeIQMP = BN_num_bytes(rsa->iqmp); keyMat->bigE = (CK_VOID_PTR)malloc(keyMat->sizeE); keyMat->bigN = (CK_VOID_PTR)malloc(keyMat->sizeN); keyMat->bigD = (CK_VOID_PTR)malloc(keyMat->sizeD); keyMat->bigP = (CK_VOID_PTR)malloc(keyMat->sizeP); keyMat->bigQ = (CK_VOID_PTR)malloc(keyMat->sizeQ); keyMat->bigDMP1 = (CK_VOID_PTR)malloc(keyMat->sizeDMP1); keyMat->bigDMQ1 = (CK_VOID_PTR)malloc(keyMat->sizeDMQ1); keyMat->bigIQMP = (CK_VOID_PTR)malloc(keyMat->sizeIQMP); if ( !keyMat->bigE || !keyMat->bigN || !keyMat->bigD || !keyMat->bigP || !keyMat->bigQ || !keyMat->bigDMP1 || !keyMat->bigDMQ1 || !keyMat->bigIQMP ) { crypto_free_rsa(keyMat); return NULL; } BN_bn2bin(rsa->e, (unsigned char*)keyMat->bigE); BN_bn2bin(rsa->n, (unsigned char*)keyMat->bigN); BN_bn2bin(rsa->d, (unsigned char*)keyMat->bigD); BN_bn2bin(rsa->p, (unsigned char*)keyMat->bigP); BN_bn2bin(rsa->q, (unsigned char*)keyMat->bigQ); BN_bn2bin(rsa->dmp1, (unsigned char*)keyMat->bigDMP1); BN_bn2bin(rsa->dmq1, (unsigned char*)keyMat->bigDMQ1); BN_bn2bin(rsa->iqmp, (unsigned char*)keyMat->bigIQMP); return keyMat; } // Free the memory of the key void crypto_free_rsa(rsa_key_material_t* keyMat) { if (keyMat == NULL) return; if (keyMat->bigE) free(keyMat->bigE); if (keyMat->bigN) free(keyMat->bigN); if (keyMat->bigD) free(keyMat->bigD); if (keyMat->bigP) free(keyMat->bigP); if (keyMat->bigQ) free(keyMat->bigQ); if (keyMat->bigDMP1) free(keyMat->bigDMP1); if (keyMat->bigDMQ1) free(keyMat->bigDMQ1); if (keyMat->bigIQMP) free(keyMat->bigIQMP); free(keyMat); } // Save the key data in PKCS#11 int crypto_save_dsa ( CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, DSA* dsa ) { dsa_key_material_t* keyMat = crypto_malloc_dsa(dsa); if (keyMat == NULL) { fprintf(stderr, "ERROR: Could not convert the key material to binary information.\n"); return 1; } CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY, privClass = CKO_PRIVATE_KEY; CK_KEY_TYPE keyType = CKK_DSA; CK_BBOOL ckTrue = CK_TRUE, ckFalse = CK_FALSE, ckToken = CK_TRUE; if (noPublicKey) { ckToken = CK_FALSE; } CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, &pubClass, sizeof(pubClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_TOKEN, &ckToken, sizeof(ckToken) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_ENCRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_WRAP, &ckFalse, sizeof(ckFalse) }, { CKA_PRIME, keyMat->bigP, keyMat->sizeP }, { CKA_SUBPRIME, keyMat->bigQ, keyMat->sizeQ }, { CKA_BASE, keyMat->bigG, keyMat->sizeG }, { CKA_VALUE, keyMat->bigY, keyMat->sizeY } }; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, &privClass, sizeof(privClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof(ckFalse) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof(ckFalse) }, { CKA_PRIME, keyMat->bigP, keyMat->sizeP }, { CKA_SUBPRIME, keyMat->bigQ, keyMat->sizeQ }, { CKA_BASE, keyMat->bigG, keyMat->sizeG }, { CKA_VALUE, keyMat->bigX, keyMat->sizeX } }; CK_OBJECT_HANDLE hKey1, hKey2; CK_RV rv = p11->C_CreateObject(hSession, privTemplate, 15, &hKey1); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not save the private key in the token. " "Maybe the algorithm is not supported.\n"); crypto_free_dsa(keyMat); return 1; } rv = p11->C_CreateObject(hSession, pubTemplate, 12, &hKey2); crypto_free_dsa(keyMat); if (rv != CKR_OK) { p11->C_DestroyObject(hSession, hKey1); fprintf(stderr, "ERROR: Could not save the public key in the token.\n"); return 1; } printf("The key pair has been imported.\n"); return 0; } // Convert the OpenSSL key to binary dsa_key_material_t* crypto_malloc_dsa(DSA* dsa) { if (dsa == NULL) { return NULL; } dsa_key_material_t* keyMat = (dsa_key_material_t*)malloc(sizeof(dsa_key_material_t)); if (keyMat == NULL) { return NULL; } keyMat->sizeP = BN_num_bytes(dsa->p); keyMat->sizeQ = BN_num_bytes(dsa->q); keyMat->sizeG = BN_num_bytes(dsa->g); keyMat->sizeX = BN_num_bytes(dsa->priv_key); keyMat->sizeY = BN_num_bytes(dsa->pub_key); keyMat->bigP = (CK_VOID_PTR)malloc(keyMat->sizeP); keyMat->bigQ = (CK_VOID_PTR)malloc(keyMat->sizeQ); keyMat->bigG = (CK_VOID_PTR)malloc(keyMat->sizeG); keyMat->bigX = (CK_VOID_PTR)malloc(keyMat->sizeX); keyMat->bigY = (CK_VOID_PTR)malloc(keyMat->sizeY); if (!keyMat->bigP || !keyMat->bigQ || !keyMat->bigG || !keyMat->bigX || !keyMat->bigY) { crypto_free_dsa(keyMat); return NULL; } BN_bn2bin(dsa->p, (unsigned char*)keyMat->bigP); BN_bn2bin(dsa->q, (unsigned char*)keyMat->bigQ); BN_bn2bin(dsa->g, (unsigned char*)keyMat->bigG); BN_bn2bin(dsa->priv_key, (unsigned char*)keyMat->bigX); BN_bn2bin(dsa->pub_key, (unsigned char*)keyMat->bigY); return keyMat; } // Free the memory of the key void crypto_free_dsa(dsa_key_material_t* keyMat) { if (keyMat == NULL) return; if (keyMat->bigP) free(keyMat->bigP); if (keyMat->bigQ) free(keyMat->bigQ); if (keyMat->bigG) free(keyMat->bigG); if (keyMat->bigX) free(keyMat->bigX); if (keyMat->bigY) free(keyMat->bigY); free(keyMat); } #ifdef WITH_ECC // Save the key data in PKCS#11 int crypto_save_ecdsa ( CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, EC_KEY* ecdsa ) { ecdsa_key_material_t* keyMat = crypto_malloc_ecdsa(ecdsa); if (keyMat == NULL) { fprintf(stderr, "ERROR: Could not convert the key material to binary information.\n"); return 1; } CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY, privClass = CKO_PRIVATE_KEY; CK_KEY_TYPE keyType = CKK_EC; CK_BBOOL ckTrue = CK_TRUE, ckFalse = CK_FALSE, ckToken = CK_TRUE; if (noPublicKey) { ckToken = CK_FALSE; } CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, &pubClass, sizeof(pubClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_TOKEN, &ckToken, sizeof(ckToken) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_ENCRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_WRAP, &ckFalse, sizeof(ckFalse) }, { CKA_EC_PARAMS, keyMat->derParams, keyMat->sizeParams }, { CKA_EC_POINT, keyMat->derQ, keyMat->sizeQ }, }; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, &privClass, sizeof(privClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof(ckFalse) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof(ckFalse) }, { CKA_EC_PARAMS, keyMat->derParams, keyMat->sizeParams }, { CKA_VALUE, keyMat->bigD, keyMat->sizeD } }; CK_OBJECT_HANDLE hKey1, hKey2; CK_RV rv = p11->C_CreateObject(hSession, privTemplate, 13, &hKey1); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not save the private key in the token. " "Maybe the algorithm is not supported.\n"); crypto_free_ecdsa(keyMat); return 1; } rv = p11->C_CreateObject(hSession, pubTemplate, 10, &hKey2); crypto_free_ecdsa(keyMat); if (rv != CKR_OK) { p11->C_DestroyObject(hSession, hKey1); fprintf(stderr, "ERROR: Could not save the public key in the token.\n"); return 1; } printf("The key pair has been imported.\n"); return 0; } // Convert the OpenSSL key to binary ecdsa_key_material_t* crypto_malloc_ecdsa(EC_KEY* ec_key) { int result; if (ec_key == NULL) { return NULL; } ecdsa_key_material_t* keyMat = (ecdsa_key_material_t*)malloc(sizeof(ecdsa_key_material_t)); if (keyMat == NULL) { return NULL; } const BIGNUM *d = EC_KEY_get0_private_key(ec_key); const EC_GROUP *group = EC_KEY_get0_group(ec_key); const EC_POINT *point = EC_KEY_get0_public_key(ec_key); keyMat->sizeParams = i2d_ECPKParameters(group, NULL); keyMat->sizeD = BN_num_bytes(d); int point_length = EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); keyMat->sizeQ = point_length + 2; keyMat->derParams = (CK_VOID_PTR)malloc(keyMat->sizeParams); keyMat->bigD = (CK_VOID_PTR)malloc(keyMat->sizeD); keyMat->derQ = (CK_VOID_PTR)malloc(keyMat->sizeQ); if (!keyMat->derParams || !keyMat->bigD || !keyMat->derQ) { crypto_free_ecdsa(keyMat); return NULL; } /* * i2d functions increment the pointer, so we have to use a * sacrificial pointer */ unsigned char *derParams = (unsigned char*) keyMat->derParams; result = i2d_ECPKParameters(group, &derParams); if (result == 0) { crypto_free_ecdsa(keyMat); return NULL; } BN_bn2bin(d, (unsigned char*)keyMat->bigD); /* Only sizes up to 0x7f are supported right now */ if (point_length > 0x7f) { crypto_free_ecdsa(keyMat); return NULL; } unsigned char *derQ = (unsigned char *)keyMat->derQ; derQ[0] = V_ASN1_OCTET_STRING; derQ[1] = point_length & 0x7f; result = EC_POINT_point2oct(group, point, POINT_CONVERSION_UNCOMPRESSED, &derQ[2], point_length, NULL); if (result == 0) { crypto_free_ecdsa(keyMat); return NULL; } return keyMat; } // Free the memory of the key void crypto_free_ecdsa(ecdsa_key_material_t* keyMat) { if (keyMat == NULL) return; if (keyMat->derParams) free(keyMat->derParams); if (keyMat->bigD) free(keyMat->bigD); if (keyMat->derQ) free(keyMat->derQ); free(keyMat); } #endif softhsm-2.0.0/src/bin/util/Makefile.in0000664000175000017500000006216012552216620014506 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = softhsm2-util$(EXEEXT) # Compile with support of OpenSSL @WITH_OPENSSL_TRUE@am__append_1 = softhsm2-util-ossl.cpp # Compile with support of Botan @WITH_BOTAN_TRUE@am__append_2 = softhsm2-util-botan.cpp subdir = src/bin/util DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(dist_man_MANS) ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" PROGRAMS = $(bin_PROGRAMS) am__softhsm2_util_SOURCES_DIST = softhsm2-util.cpp ../common/getpw.cpp \ ../common/library.cpp softhsm2-util-ossl.cpp \ softhsm2-util-botan.cpp am__dirstamp = $(am__leading_dot)dirstamp @WITH_OPENSSL_TRUE@am__objects_1 = softhsm2-util-ossl.$(OBJEXT) @WITH_BOTAN_TRUE@am__objects_2 = softhsm2-util-botan.$(OBJEXT) am_softhsm2_util_OBJECTS = softhsm2-util.$(OBJEXT) \ ../common/getpw.$(OBJEXT) ../common/library.$(OBJEXT) \ $(am__objects_1) $(am__objects_2) softhsm2_util_OBJECTS = $(am_softhsm2_util_OBJECTS) softhsm2_util_DEPENDENCIES = AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(softhsm2_util_SOURCES) DIST_SOURCES = $(am__softhsm2_util_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 NROFF = nroff MANS = $(dist_man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../../lib/cryptoki_compat \ -I$(srcdir)/../common \ @CRYPTO_INCLUDES@ dist_man_MANS = softhsm2-util.1 AUTOMAKE_OPTIONS = subdir-objects softhsm2_util_SOURCES = softhsm2-util.cpp ../common/getpw.cpp \ ../common/library.cpp $(am__append_1) $(am__append_2) softhsm2_util_LDADD = @CRYPTO_LIBS@ EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/*.cpp all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/util/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/util/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list ../common/$(am__dirstamp): @$(MKDIR_P) ../common @: > ../common/$(am__dirstamp) ../common/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) ../common/$(DEPDIR) @: > ../common/$(DEPDIR)/$(am__dirstamp) ../common/getpw.$(OBJEXT): ../common/$(am__dirstamp) \ ../common/$(DEPDIR)/$(am__dirstamp) ../common/library.$(OBJEXT): ../common/$(am__dirstamp) \ ../common/$(DEPDIR)/$(am__dirstamp) softhsm2-util$(EXEEXT): $(softhsm2_util_OBJECTS) $(softhsm2_util_DEPENDENCIES) $(EXTRA_softhsm2_util_DEPENDENCIES) @rm -f softhsm2-util$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(softhsm2_util_OBJECTS) $(softhsm2_util_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) -rm -f ../common/*.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@../common/$(DEPDIR)/getpw.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@../common/$(DEPDIR)/library.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-util-botan.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-util-ossl.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-util.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(dist_man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(dist_man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) $(MANS) installdirs: for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f ../common/$(DEPDIR)/$(am__dirstamp) -rm -f ../common/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ../common/$(DEPDIR) ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ../common/$(DEPDIR) ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-man uninstall-man: uninstall-man1 .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-man1 \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-man uninstall-man1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/bin/util/softhsm2-util.cpp0000664000175000017500000004420512533040716015665 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-util.cpp This program can be used for interacting with HSMs using PKCS#11. The default library is the libsofthsm2.so *****************************************************************************/ #include #include "softhsm2-util.h" #include "getpw.h" #include "library.h" #include #include #include #include #ifndef _WIN32 #include #include #include #endif #include #include // Display the usage void usage() { printf("Support tool for PKCS#11\n"); printf("Usage: softhsm2-util [ACTION] [OPTIONS]\n"); printf("Action:\n"); printf(" -h Shows this help screen.\n"); printf(" --help Shows this help screen.\n"); printf(" --import Import a key pair from the given path.\n"); printf(" The file must be in PKCS#8-format.\n"); printf(" Use with --file-pin, --slot, --label, --id,\n"); printf(" --no-public-key, and --pin.\n"); printf(" --init-token Initialize the token at a given slot.\n"); printf(" Use with --slot or --free, --label, --so-pin, and --pin.\n"); printf(" WARNING: Any content in token token will be erased.\n"); printf(" --show-slots Display all the available slots.\n"); printf(" -v Show version info.\n"); printf(" --version Show version info.\n"); printf("Options:\n"); printf(" --file-pin Supply a PIN if the file is encrypted.\n"); printf(" --force Used to override a warning.\n"); printf(" --free Initialize the first free token.\n"); printf(" --id Defines the ID of the object. Hexadecimal characters.\n"); printf(" Use with --force if multiple key pairs may share\n"); printf(" the same ID.\n"); printf(" --label Defines the label of the object or the token.\n"); printf(" --module Use another PKCS#11 library than SoftHSM.\n"); printf(" --no-public-key Do not import the public key.\n"); printf(" --pin The PIN for the normal user.\n"); printf(" --slot The slot where the token is located.\n"); printf(" --so-pin The PIN for the Security Officer (SO).\n"); } // Enumeration of the long options enum { OPT_FILE_PIN = 0x100, OPT_FORCE, OPT_FREE, OPT_HELP, OPT_ID, OPT_IMPORT, OPT_INIT_TOKEN, OPT_LABEL, OPT_MODULE, OPT_NO_PUBLIC_KEY, OPT_PIN, OPT_SHOW_SLOTS, OPT_SLOT, OPT_SO_PIN, OPT_VERSION }; // Text representation of the long options static const struct option long_options[] = { { "file-pin", 1, NULL, OPT_FILE_PIN }, { "force", 0, NULL, OPT_FORCE }, { "free", 0, NULL, OPT_FREE }, { "help", 0, NULL, OPT_HELP }, { "id", 1, NULL, OPT_ID }, { "import", 1, NULL, OPT_IMPORT }, { "init-token", 0, NULL, OPT_INIT_TOKEN }, { "label", 1, NULL, OPT_LABEL }, { "module", 1, NULL, OPT_MODULE }, { "no-public-key", 0, NULL, OPT_NO_PUBLIC_KEY }, { "pin", 1, NULL, OPT_PIN }, { "show-slots", 0, NULL, OPT_SHOW_SLOTS }, { "slot", 1, NULL, OPT_SLOT }, { "so-pin", 1, NULL, OPT_SO_PIN }, { "version", 0, NULL, OPT_VERSION }, { NULL, 0, NULL, 0 } }; CK_FUNCTION_LIST_PTR p11; // The main function int main(int argc, char* argv[]) { int option_index = 0; int opt; char* inPath = NULL; //char* outPath = NULL; char* soPIN = NULL; char* userPIN = NULL; char* filePIN = NULL; char* label = NULL; char* module = NULL; char* objectID = NULL; char* slot = NULL; char* errMsg = NULL; int forceExec = 0; int freeToken = 0; int noPublicKey = 0; int doInitToken = 0; int doShowSlots = 0; int doImport = 0; //int doExport = 0; int action = 0; int rv = 0; moduleHandle = NULL; p11 = NULL; while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1) { switch (opt) { case OPT_SHOW_SLOTS: doShowSlots = 1; action++; break; case OPT_INIT_TOKEN: doInitToken = 1; action++; break; case OPT_IMPORT: doImport = 1; action++; inPath = optarg; break; case OPT_SLOT: slot = optarg; break; case OPT_LABEL: label = optarg; break; case OPT_MODULE: module = optarg; break; case OPT_NO_PUBLIC_KEY: noPublicKey = 1; break; case OPT_ID: objectID = optarg; break; case OPT_SO_PIN: soPIN = optarg; break; case OPT_PIN: userPIN = optarg; break; case OPT_FILE_PIN: filePIN = optarg; break; case OPT_FORCE: forceExec = 1; break; case OPT_FREE: freeToken = 1; break; case OPT_VERSION: case 'v': printf("%s\n", PACKAGE_VERSION); exit(0); break; case OPT_HELP: case 'h': default: usage(); exit(0); break; } } // No action given, display the usage. if (!action) { usage(); } else { // Get a pointer to the function list for PKCS#11 library CK_C_GetFunctionList pGetFunctionList = loadLibrary(module, &moduleHandle, &errMsg); if (!pGetFunctionList) { fprintf(stderr, "ERROR: Could not load the library: %s\n", errMsg); exit(1); } // Load the function list (*pGetFunctionList)(&p11); // Initialize the library CK_RV p11rv = p11->C_Initialize(NULL_PTR); if (p11rv != CKR_OK) { fprintf(stderr, "ERROR: Could not initialize the library.\n"); exit(1); } } // We should create the token. if (doInitToken) { rv = initToken(slot, freeToken, label, soPIN, userPIN); } // Show all available slots if (doShowSlots) { rv = showSlots(); } // Import a key pair from the given path if (doImport) { rv = importKeyPair(inPath, filePIN, slot, userPIN, label, objectID, forceExec, noPublicKey); } // Finalize the library if (action) { p11->C_Finalize(NULL_PTR); unloadLibrary(moduleHandle); } return rv; } // Initialize the token int initToken(char* slot, int freeToken, char* label, char* soPIN, char* userPIN) { char so_pin_copy[MAX_PIN_LEN+1]; char user_pin_copy[MAX_PIN_LEN+1]; if (slot != NULL && freeToken == 1) { fprintf(stderr, "ERROR: Select --slot or --free\n"); return 1; } if (slot == NULL && freeToken != 1) { fprintf(stderr, "ERROR: A slot number must be supplied. " "Use --slot or --free\n"); return 1; } if (label == NULL) { fprintf(stderr, "ERROR: A label for the token must be supplied. " "Use --label \n"); return 1; } if (strlen(label) > 32) { fprintf(stderr, "ERROR: The token label must not have a length " "greater than 32 chars.\n"); return 1; } // Get the passwords getPW(soPIN, so_pin_copy, CKU_SO); getPW(userPIN, user_pin_copy, CKU_USER); // Load the variables CK_SLOT_ID slotID = 0; CK_UTF8CHAR paddedLabel[32]; memset(paddedLabel, ' ', sizeof(paddedLabel)); memcpy(paddedLabel, label, strlen(label)); if (slot != NULL) { int slotNumber = atoi(slot); if (slotNumber < 0) { fprintf(stderr, "ERROR: The slot number is negative.\n"); return 1; } slotID = slotNumber; } else { CK_SLOT_ID slotNumber = 0; if (getFirstFreeToken(slotNumber) != 0) return 1; slotID = slotNumber; } CK_RV rv = p11->C_InitToken(slotID, (CK_UTF8CHAR_PTR)so_pin_copy, strlen(so_pin_copy), paddedLabel); switch (rv) { case CKR_OK: break; case CKR_SLOT_ID_INVALID: fprintf(stderr, "CKR_SLOT_ID_INVALID: Slot %lu does not exist.\n", slotID); return 1; break; case CKR_PIN_INCORRECT: fprintf(stderr, "CKR_PIN_INCORRECT: The given SO PIN does not match the " "one in the token. Needed when reinitializing the token.\n"); return 1; break; case CKR_TOKEN_NOT_PRESENT: fprintf(stderr, "CKR_TOKEN_NOT_PRESENT: The token is not present. " "Please read the HSM manual for further assistance.\n"); return 1; break; default: fprintf(stderr, "ERROR %X: Could not initialize the token.\n", (unsigned int)rv); return 1; break; } CK_SESSION_HANDLE hSession; rv = p11->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not open a session with the library.\n"); return 1; } rv = p11->C_Login(hSession, CKU_SO, (CK_UTF8CHAR_PTR)so_pin_copy, strlen(so_pin_copy)); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not log in on the token.\n"); return 1; } rv = p11->C_InitPIN(hSession, (CK_UTF8CHAR_PTR)user_pin_copy, strlen(user_pin_copy)); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not initialize the user PIN.\n"); return 1; } printf("The token has been initialized.\n"); return 0; } // Search and return the first free token int getFirstFreeToken(CK_SLOT_ID &slot) { CK_ULONG ulSlotCount; CK_RV rv = p11->C_GetSlotList(CK_TRUE, NULL_PTR, &ulSlotCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the number of slots.\n"); return -1; } CK_SLOT_ID_PTR pSlotList = (CK_SLOT_ID_PTR) malloc(ulSlotCount*sizeof(CK_SLOT_ID)); if (!pSlotList) { fprintf(stderr, "ERROR: Could not allocate memory.\n"); return -1; } rv = p11->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the slot list.\n"); free(pSlotList); return -1; } for (CK_ULONG i = 0; i < ulSlotCount; i++) { CK_TOKEN_INFO tokenInfo; rv = p11->C_GetTokenInfo(pSlotList[i], &tokenInfo); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get info about the token in slot %lu.\n", pSlotList[i]); free(pSlotList); return -1; } if ((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == 0) { printf("Token %lu is free.\n", pSlotList[i]); slot = pSlotList[i]; free(pSlotList); return 0; } } free(pSlotList); fprintf(stderr, "ERROR: Could not find the first free token.\n"); return -1; } // Show what slots are available int showSlots() { CK_ULONG ulSlotCount; CK_RV rv = p11->C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the number of slots.\n"); return 1; } CK_SLOT_ID_PTR pSlotList = (CK_SLOT_ID_PTR) malloc(ulSlotCount*sizeof(CK_SLOT_ID)); if (!pSlotList) { fprintf(stderr, "ERROR: Could not allocate memory.\n"); return 1; } rv = p11->C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the slot list.\n"); free(pSlotList); return 1; } printf("Available slots:\n"); for (CK_ULONG i = 0; i < ulSlotCount; i++) { CK_SLOT_INFO slotInfo; CK_TOKEN_INFO tokenInfo; rv = p11->C_GetSlotInfo(pSlotList[i], &slotInfo); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get info about slot %lu.\n", pSlotList[i]); continue; } printf("Slot %lu\n", pSlotList[i]); printf(" Slot info:\n"); printf(" Description: %.*s\n", 64, slotInfo.slotDescription); printf(" Manufacturer ID: %.*s\n", 32, slotInfo.manufacturerID); printf(" Hardware version: %i.%i\n", slotInfo.hardwareVersion.major, slotInfo.hardwareVersion.minor); printf(" Firmware version: %i.%i\n", slotInfo.firmwareVersion.major, slotInfo.firmwareVersion.minor); printf(" Token present: "); if ((slotInfo.flags & CKF_TOKEN_PRESENT) == 0) { printf("no\n"); continue; } printf("yes\n"); printf(" Token info:\n"); rv = p11->C_GetTokenInfo(pSlotList[i], &tokenInfo); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get info about the token in slot %lu.\n", pSlotList[i]); continue; } printf(" Manufacturer ID: %.*s\n", 32, tokenInfo.manufacturerID); printf(" Model: %.*s\n", 16, tokenInfo.model); printf(" Hardware version: %i.%i\n", tokenInfo.hardwareVersion.major, tokenInfo.hardwareVersion.minor); printf(" Firmware version: %i.%i\n", tokenInfo.firmwareVersion.major, tokenInfo.firmwareVersion.minor); printf(" Serial number: %.*s\n", 16, tokenInfo.serialNumber); printf(" Initialized: "); if ((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == 0) { printf("no\n"); } else { printf("yes\n"); } printf(" User PIN init.: "); if ((tokenInfo.flags & CKF_USER_PIN_INITIALIZED) == 0) { printf("no\n"); } else { printf("yes\n"); } printf(" Label: %.*s\n", 32, tokenInfo.label); } free(pSlotList); return 0; } // Import a key pair from given path int importKeyPair ( char* filePath, char* filePIN, char* slot, char* userPIN, char* label, char* objectID, int forceExec, int noPublicKey ) { char user_pin_copy[MAX_PIN_LEN+1]; if (slot == NULL) { fprintf(stderr, "ERROR: A slot number must be supplied. " "Use --slot \n"); return 1; } if (label == NULL) { fprintf(stderr, "ERROR: A label for the object must be supplied. " "Use --label \n"); return 1; } if (objectID == NULL) { fprintf(stderr, "ERROR: An ID for the object must be supplied. " "Use --id \n"); return 1; } size_t objIDLen = 0; char* objID = hexStrToBin(objectID, strlen(objectID), &objIDLen); if (objID == NULL) { fprintf(stderr, "Please edit --id to correct error.\n"); return 1; } CK_SLOT_ID slotID = atoi(slot); CK_SESSION_HANDLE hSession; CK_RV rv = p11->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); if (rv != CKR_OK) { if (rv == CKR_SLOT_ID_INVALID) { fprintf(stderr, "ERROR: The given slot does not exist.\n"); } else { fprintf(stderr, "ERROR: Could not open a session on the given slot.\n"); } free(objID); return 1; } // Get the password getPW(userPIN, user_pin_copy, CKU_USER); rv = p11->C_Login(hSession, CKU_USER, (CK_UTF8CHAR_PTR)user_pin_copy, strlen(user_pin_copy)); if (rv != CKR_OK) { if (rv == CKR_PIN_INCORRECT) { fprintf(stderr, "ERROR: The given user PIN does not match the one in the token.\n"); } else { fprintf(stderr, "ERROR: Could not log in on the token.\n"); } free(objID); return 1; } CK_OBJECT_HANDLE oHandle = searchObject(hSession, objID, objIDLen); if (oHandle != CK_INVALID_HANDLE && forceExec == 0) { free(objID); fprintf(stderr, "ERROR: The ID is already assigned to another object. " "Use --force to override this message.\n"); return 1; } crypto_init(); int result = crypto_import_key_pair(hSession, filePath, filePIN, label, objID, objIDLen, noPublicKey); crypto_final(); free(objID); return result; } // Convert a char array of hexadecimal characters into a binary representation char* hexStrToBin(char* objectID, int idLength, size_t* newLen) { char* bytes = NULL; if (idLength < 2 || idLength % 2 != 0) { fprintf(stderr, "ERROR: Invalid length on hex string.\n"); return NULL; } for (int i = 0; i < idLength; i++) { if (hexdigit_to_int(objectID[i]) == -1) { fprintf(stderr, "ERROR: Invalid character in hex string.\n"); return NULL; } } *newLen = idLength / 2; bytes = (char*) malloc(*newLen); if (bytes == NULL) { fprintf(stderr, "ERROR: Could not allocate memory.\n"); return NULL; } for (size_t i = 0; i < *newLen; i++) { bytes[i] = hexdigit_to_int(objectID[2*i]) * 16 + hexdigit_to_int(objectID[2*i+1]); } return bytes; } // Return the integer value of a hexadecimal character int hexdigit_to_int(char ch) { switch (ch) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return -1; } } // Search for an object CK_OBJECT_HANDLE searchObject(CK_SESSION_HANDLE hSession, char* objID, size_t objIDLen) { if (objID == NULL) { return CK_INVALID_HANDLE; } CK_OBJECT_CLASS oClass = CKO_PRIVATE_KEY; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; CK_ULONG objectCount = 0; CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &oClass, sizeof(oClass) }, { CKA_ID, objID, objIDLen } }; CK_RV rv = p11->C_FindObjectsInit(hSession, objTemplate, 2); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not prepare the object search.\n"); return CK_INVALID_HANDLE; } rv = p11->C_FindObjects(hSession, &hObject, 1, &objectCount); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not get the search results.\n"); return CK_INVALID_HANDLE; } rv = p11->C_FindObjectsFinal(hSession); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not finalize the search.\n"); return CK_INVALID_HANDLE; } if (objectCount == 0) { return CK_INVALID_HANDLE; } return hObject; } softhsm-2.0.0/src/bin/util/softhsm2-util-botan.cpp0000664000175000017500000004512212533040716016765 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-util-botan.cpp Code specific for Botan *****************************************************************************/ #include #define UTIL_BOTAN #include "softhsm2-util.h" #include "softhsm2-util-botan.h" #include #include #include #include #include #include #include #include #include #include #include #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) #include bool wasInitialized = false; #endif // Init Botan void crypto_init() { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) // The PKCS#11 library might be using Botan // Check if it has already initialized Botan if (Botan::Global_State_Management::global_state_exists()) { wasInitialized = true; } if (!wasInitialized) { Botan::LibraryInitializer::initialize("thread_safe=true"); } #else Botan::LibraryInitializer::initialize("thread_safe=true"); #endif } // Final Botan void crypto_final() { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) if (!wasInitialized) { Botan::LibraryInitializer::deinitialize(); } #else Botan::LibraryInitializer::deinitialize(); #endif } // Import a key pair from given path int crypto_import_key_pair ( CK_SESSION_HANDLE hSession, char* filePath, char* filePIN, char* label, char* objID, size_t objIDLen, int noPublicKey ) { Botan::Private_Key* pkey = crypto_read_file(filePath, filePIN); if (pkey == NULL) { return 1; } Botan::RSA_PrivateKey* rsa = NULL; Botan::DSA_PrivateKey* dsa = NULL; #ifdef WITH_ECC Botan::ECDSA_PrivateKey* ecdsa = NULL; #endif if (pkey->algo_name().compare("RSA") == 0) { rsa = dynamic_cast(pkey); } else if (pkey->algo_name().compare("DSA") == 0) { dsa = dynamic_cast(pkey); } #ifdef WITH_ECC else if (pkey->algo_name().compare("ECDSA") == 0) { ecdsa = dynamic_cast(pkey); } #endif else { fprintf(stderr, "ERROR: %s is not a supported algorithm.\n", pkey->algo_name().c_str()); delete pkey; return 1; } int result = 0; if (rsa) { result = crypto_save_rsa(hSession, label, objID, objIDLen, noPublicKey, rsa); } else if (dsa) { result = crypto_save_dsa(hSession, label, objID, objIDLen, noPublicKey, dsa); } #ifdef WITH_ECC else if (ecdsa) { result = crypto_save_ecdsa(hSession, label, objID, objIDLen, noPublicKey, ecdsa); } #endif else { fprintf(stderr, "ERROR: Could not get the key material.\n"); result = 1; } delete pkey; return result; } // Read the key from file Botan::Private_Key* crypto_read_file(char* filePath, char* filePIN) { if (filePath == NULL) { return NULL; } Botan::AutoSeeded_RNG* rng = new Botan::AutoSeeded_RNG(); Botan::Private_Key* pkey = NULL; try { #if BOTAN_VERSION_MINOR == 11 if (filePIN == NULL) { pkey = Botan::PKCS8::load_key(std::string(filePath), *rng); } else { pkey = Botan::PKCS8::load_key(std::string(filePath), *rng, std::string(filePIN)); } #else if (filePIN == NULL) { pkey = Botan::PKCS8::load_key(filePath, *rng); } else { pkey = Botan::PKCS8::load_key(filePath, *rng, filePIN); } #endif } catch (std::exception& e) { fprintf(stderr, "%s\n", e.what()); fprintf(stderr, "ERROR: Perhaps wrong path to file, wrong file format, " "or wrong PIN to file (--file-pin ).\n"); delete rng; return NULL; } delete rng; return pkey; } // Save the key data in PKCS#11 int crypto_save_rsa ( CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, Botan::RSA_PrivateKey* rsa ) { rsa_key_material_t* keyMat = crypto_malloc_rsa(rsa); if (!keyMat) { fprintf(stderr, "ERROR: Could not convert the key material to binary information.\n"); return 1; } CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY, privClass = CKO_PRIVATE_KEY; CK_KEY_TYPE keyType = CKK_RSA; CK_BBOOL ckTrue = CK_TRUE, ckFalse = CK_FALSE, ckToken = CK_TRUE; if (noPublicKey) { ckToken = CK_FALSE; } CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, &pubClass, sizeof(pubClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_TOKEN, &ckToken, sizeof(ckToken) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_ENCRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_WRAP, &ckFalse, sizeof(ckFalse) }, { CKA_PUBLIC_EXPONENT, keyMat->bigE, keyMat->sizeE }, { CKA_MODULUS, keyMat->bigN, keyMat->sizeN } }; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, &privClass, sizeof(privClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof(ckFalse) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof(ckFalse) }, { CKA_PUBLIC_EXPONENT, keyMat->bigE, keyMat->sizeE }, { CKA_MODULUS, keyMat->bigN, keyMat->sizeN }, { CKA_PRIVATE_EXPONENT, keyMat->bigD, keyMat->sizeD }, { CKA_PRIME_1, keyMat->bigP, keyMat->sizeP }, { CKA_PRIME_2, keyMat->bigQ, keyMat->sizeQ }, { CKA_EXPONENT_1, keyMat->bigDMP1, keyMat->sizeDMP1 }, { CKA_EXPONENT_2, keyMat->bigDMQ1, keyMat->sizeDMQ1 }, { CKA_COEFFICIENT, keyMat->bigIQMP, keyMat->sizeIQMP } }; CK_OBJECT_HANDLE hKey1, hKey2; CK_RV rv = p11->C_CreateObject(hSession, privTemplate, 19, &hKey1); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not save the private key in the token. " "Maybe the algorithm is not supported.\n"); crypto_free_rsa(keyMat); return 1; } rv = p11->C_CreateObject(hSession, pubTemplate, 10, &hKey2); crypto_free_rsa(keyMat); if (rv != CKR_OK) { p11->C_DestroyObject(hSession, hKey1); fprintf(stderr, "ERROR: Could not save the public key in the token.\n"); return 1; } printf("The key pair has been imported.\n"); return 0; } // Convert the Botan key to binary rsa_key_material_t* crypto_malloc_rsa(Botan::RSA_PrivateKey* rsa) { if (rsa == NULL) { return NULL; } rsa_key_material_t* keyMat = (rsa_key_material_t*)malloc(sizeof(rsa_key_material_t)); if (keyMat == NULL) { return NULL; } keyMat->sizeE = rsa->get_e().bytes(); keyMat->sizeN = rsa->get_n().bytes(); keyMat->sizeD = rsa->get_d().bytes(); keyMat->sizeP = rsa->get_p().bytes(); keyMat->sizeQ = rsa->get_q().bytes(); keyMat->sizeDMP1 = rsa->get_d1().bytes(); keyMat->sizeDMQ1 = rsa->get_d2().bytes(); keyMat->sizeIQMP = rsa->get_c().bytes(); keyMat->bigE = (CK_VOID_PTR)malloc(keyMat->sizeE); keyMat->bigN = (CK_VOID_PTR)malloc(keyMat->sizeN); keyMat->bigD = (CK_VOID_PTR)malloc(keyMat->sizeD); keyMat->bigP = (CK_VOID_PTR)malloc(keyMat->sizeP); keyMat->bigQ = (CK_VOID_PTR)malloc(keyMat->sizeQ); keyMat->bigDMP1 = (CK_VOID_PTR)malloc(keyMat->sizeDMP1); keyMat->bigDMQ1 = (CK_VOID_PTR)malloc(keyMat->sizeDMQ1); keyMat->bigIQMP = (CK_VOID_PTR)malloc(keyMat->sizeIQMP); if ( !keyMat->bigE || !keyMat->bigN || !keyMat->bigD || !keyMat->bigP || !keyMat->bigQ || !keyMat->bigDMP1 || !keyMat->bigDMQ1 || !keyMat->bigIQMP ) { crypto_free_rsa(keyMat); return NULL; } rsa->get_e().binary_encode((Botan::byte*)keyMat->bigE); rsa->get_n().binary_encode((Botan::byte*)keyMat->bigN); rsa->get_d().binary_encode((Botan::byte*)keyMat->bigD); rsa->get_p().binary_encode((Botan::byte*)keyMat->bigP); rsa->get_q().binary_encode((Botan::byte*)keyMat->bigQ); rsa->get_d1().binary_encode((Botan::byte*)keyMat->bigDMP1); rsa->get_d2().binary_encode((Botan::byte*)keyMat->bigDMQ1); rsa->get_c().binary_encode((Botan::byte*)keyMat->bigIQMP); return keyMat; } // Free the memory of the key void crypto_free_rsa(rsa_key_material_t* keyMat) { if (keyMat == NULL) return; if (keyMat->bigE) free(keyMat->bigE); if (keyMat->bigN) free(keyMat->bigN); if (keyMat->bigD) free(keyMat->bigD); if (keyMat->bigP) free(keyMat->bigP); if (keyMat->bigQ) free(keyMat->bigQ); if (keyMat->bigDMP1) free(keyMat->bigDMP1); if (keyMat->bigDMQ1) free(keyMat->bigDMQ1); if (keyMat->bigIQMP) free(keyMat->bigIQMP); free(keyMat); } // Save the key data in PKCS#11 int crypto_save_dsa ( CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, Botan::DSA_PrivateKey* dsa ) { dsa_key_material_t* keyMat = crypto_malloc_dsa(dsa); if (keyMat == NULL) { fprintf(stderr, "ERROR: Could not convert the key material to binary information.\n"); return 1; } CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY, privClass = CKO_PRIVATE_KEY; CK_KEY_TYPE keyType = CKK_DSA; CK_BBOOL ckTrue = CK_TRUE, ckFalse = CK_FALSE, ckToken = CK_TRUE; if (noPublicKey) { ckToken = CK_FALSE; } CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, &pubClass, sizeof(pubClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_TOKEN, &ckToken, sizeof(ckToken) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_ENCRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_WRAP, &ckFalse, sizeof(ckFalse) }, { CKA_PRIME, keyMat->bigP, keyMat->sizeP }, { CKA_SUBPRIME, keyMat->bigQ, keyMat->sizeQ }, { CKA_BASE, keyMat->bigG, keyMat->sizeG }, { CKA_VALUE, keyMat->bigY, keyMat->sizeY } }; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, &privClass, sizeof(privClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof(ckFalse) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof(ckFalse) }, { CKA_PRIME, keyMat->bigP, keyMat->sizeP }, { CKA_SUBPRIME, keyMat->bigQ, keyMat->sizeQ }, { CKA_BASE, keyMat->bigG, keyMat->sizeG }, { CKA_VALUE, keyMat->bigX, keyMat->sizeX } }; CK_OBJECT_HANDLE hKey1, hKey2; CK_RV rv = p11->C_CreateObject(hSession, privTemplate, 15, &hKey1); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not save the private key in the token. " "Maybe the algorithm is not supported.\n"); crypto_free_dsa(keyMat); return 1; } rv = p11->C_CreateObject(hSession, pubTemplate, 12, &hKey2); crypto_free_dsa(keyMat); if (rv != CKR_OK) { p11->C_DestroyObject(hSession, hKey1); fprintf(stderr, "ERROR: Could not save the public key in the token.\n"); return 1; } printf("The key pair has been imported.\n"); return 0; } // Convert the Botan key to binary dsa_key_material_t* crypto_malloc_dsa(Botan::DSA_PrivateKey* dsa) { if (dsa == NULL) { return NULL; } dsa_key_material_t *keyMat = (dsa_key_material_t *)malloc(sizeof(dsa_key_material_t)); if (keyMat == NULL) { return NULL; } keyMat->sizeP = dsa->group_p().bytes(); keyMat->sizeQ = dsa->group_q().bytes(); keyMat->sizeG = dsa->group_g().bytes(); keyMat->sizeX = dsa->get_x().bytes(); keyMat->sizeY = dsa->get_y().bytes(); keyMat->bigP = (CK_VOID_PTR)malloc(keyMat->sizeP); keyMat->bigQ = (CK_VOID_PTR)malloc(keyMat->sizeQ); keyMat->bigG = (CK_VOID_PTR)malloc(keyMat->sizeG); keyMat->bigX = (CK_VOID_PTR)malloc(keyMat->sizeX); keyMat->bigY = (CK_VOID_PTR)malloc(keyMat->sizeY); if (!keyMat->bigP || !keyMat->bigQ || !keyMat->bigG || !keyMat->bigX || !keyMat->bigY) { crypto_free_dsa(keyMat); return NULL; } dsa->group_p().binary_encode((Botan::byte*)keyMat->bigP); dsa->group_q().binary_encode((Botan::byte*)keyMat->bigQ); dsa->group_g().binary_encode((Botan::byte*)keyMat->bigG); dsa->get_x().binary_encode((Botan::byte*)keyMat->bigX); dsa->get_y().binary_encode((Botan::byte*)keyMat->bigY); return keyMat; } // Free the memory of the key void crypto_free_dsa(dsa_key_material_t* keyMat) { if (keyMat == NULL) return; if (keyMat->bigP) free(keyMat->bigP); if (keyMat->bigQ) free(keyMat->bigQ); if (keyMat->bigG) free(keyMat->bigG); if (keyMat->bigX) free(keyMat->bigX); if (keyMat->bigY) free(keyMat->bigY); free(keyMat); } #ifdef WITH_ECC // Save the key data in PKCS#11 int crypto_save_ecdsa ( CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, Botan::ECDSA_PrivateKey* ecdsa ) { ecdsa_key_material_t* keyMat = crypto_malloc_ecdsa(ecdsa); if (keyMat == NULL) { fprintf(stderr, "ERROR: Could not convert the key material to binary information.\n"); return 1; } CK_OBJECT_CLASS pubClass = CKO_PUBLIC_KEY, privClass = CKO_PRIVATE_KEY; CK_KEY_TYPE keyType = CKK_ECDSA; CK_BBOOL ckTrue = CK_TRUE, ckFalse = CK_FALSE, ckToken = CK_TRUE; if (noPublicKey) { ckToken = CK_FALSE; } CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, &pubClass, sizeof(pubClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_TOKEN, &ckToken, sizeof(ckToken) }, { CKA_VERIFY, &ckTrue, sizeof(ckTrue) }, { CKA_ENCRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_WRAP, &ckFalse, sizeof(ckFalse) }, { CKA_EC_PARAMS, keyMat->derParams, keyMat->sizeParams }, { CKA_EC_POINT, keyMat->derQ, keyMat->sizeQ } }; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, &privClass, sizeof(privClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_LABEL, label, strlen(label) }, { CKA_ID, objID, objIDLen }, { CKA_SIGN, &ckTrue, sizeof(ckTrue) }, { CKA_DECRYPT, &ckFalse, sizeof(ckFalse) }, { CKA_UNWRAP, &ckFalse, sizeof(ckFalse) }, { CKA_SENSITIVE, &ckTrue, sizeof(ckTrue) }, { CKA_TOKEN, &ckTrue, sizeof(ckTrue) }, { CKA_PRIVATE, &ckTrue, sizeof(ckTrue) }, { CKA_EXTRACTABLE, &ckFalse, sizeof(ckFalse) }, { CKA_EC_PARAMS, keyMat->derParams, keyMat->sizeParams }, { CKA_VALUE, keyMat->bigD, keyMat->sizeD } }; CK_OBJECT_HANDLE hKey1, hKey2; CK_RV rv = p11->C_CreateObject(hSession, privTemplate, 13, &hKey1); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not save the private key in the token. " "Maybe the algorithm is not supported.\n"); crypto_free_ecdsa(keyMat); return 1; } rv = p11->C_CreateObject(hSession, pubTemplate, 10, &hKey2); crypto_free_ecdsa(keyMat); if (rv != CKR_OK) { p11->C_DestroyObject(hSession, hKey1); fprintf(stderr, "ERROR: Could not save the public key in the token.\n"); return 1; } printf("The key pair has been imported.\n"); return 0; } // Convert the Botan key to binary ecdsa_key_material_t* crypto_malloc_ecdsa(Botan::ECDSA_PrivateKey* ecdsa) { if (ecdsa == NULL) { return NULL; } ecdsa_key_material_t *keyMat = (ecdsa_key_material_t *)malloc(sizeof(ecdsa_key_material_t)); if (keyMat == NULL) { return NULL; } #if BOTAN_VERSION_MINOR == 11 std::vector derEC = ecdsa->domain().DER_encode(Botan::EC_DOMPAR_ENC_OID); Botan::secure_vector derPoint; #else Botan::SecureVector derEC = ecdsa->domain().DER_encode(Botan::EC_DOMPAR_ENC_OID); Botan::SecureVector derPoint; #endif try { #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector repr = Botan::EC2OSP(ecdsa->public_point(), Botan::PointGFp::UNCOMPRESSED); #else Botan::SecureVector repr = Botan::EC2OSP(ecdsa->public_point(), Botan::PointGFp::UNCOMPRESSED); #endif derPoint = Botan::DER_Encoder() .encode(repr, Botan::OCTET_STRING) .get_contents(); } catch (...) { return NULL; } keyMat->sizeParams = derEC.size(); keyMat->sizeD = ecdsa->private_value().bytes(); keyMat->sizeQ = derPoint.size(); keyMat->derParams = (CK_VOID_PTR)malloc(keyMat->sizeParams); keyMat->bigD = (CK_VOID_PTR)malloc(keyMat->sizeD); keyMat->derQ = (CK_VOID_PTR)malloc(keyMat->sizeQ); if (!keyMat->derParams || !keyMat->bigD || !keyMat->derQ) { crypto_free_ecdsa(keyMat); return NULL; } memcpy(keyMat->derParams, &derEC[0], derEC.size()); ecdsa->private_value().binary_encode((Botan::byte*)keyMat->bigD); memcpy(keyMat->derQ, &derPoint[0], derPoint.size()); return keyMat; } // Free the memory of the key void crypto_free_ecdsa(ecdsa_key_material_t* keyMat) { if (keyMat == NULL) return; if (keyMat->derParams) free(keyMat->derParams); if (keyMat->bigD) free(keyMat->bigD); if (keyMat->derQ) free(keyMat->derQ); free(keyMat); } #endif softhsm-2.0.0/src/bin/util/softhsm2-util-ossl.h0000664000175000017500000000765312533040716016316 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-util-ossl.h Header file for OpenSSL implemented *****************************************************************************/ #ifndef _SOFTHSM_V2_SOFTHSM2_UTIL_OSSL_H #define _SOFTHSM_V2_SOFTHSM2_UTIL_OSSL_H #include #include #ifdef WITH_ECC #include #endif typedef struct rsa_key_material_t { CK_ULONG sizeE; CK_ULONG sizeN; CK_ULONG sizeD; CK_ULONG sizeP; CK_ULONG sizeQ; CK_ULONG sizeDMP1; CK_ULONG sizeDMQ1; CK_ULONG sizeIQMP; CK_VOID_PTR bigE; CK_VOID_PTR bigN; CK_VOID_PTR bigD; CK_VOID_PTR bigP; CK_VOID_PTR bigQ; CK_VOID_PTR bigDMP1; CK_VOID_PTR bigDMQ1; CK_VOID_PTR bigIQMP; rsa_key_material_t() { sizeE = 0; sizeN = 0; sizeD = 0; sizeP = 0; sizeQ = 0; sizeDMP1 = 0; sizeDMQ1 = 0; sizeIQMP = 0; bigE = NULL_PTR; bigN = NULL_PTR; bigD = NULL_PTR; bigP = NULL_PTR; bigQ = NULL_PTR; bigDMP1 = NULL_PTR; bigDMQ1 = NULL_PTR; bigIQMP = NULL_PTR; } } rsa_key_material_t; typedef struct dsa_key_material_t { CK_ULONG sizeP; CK_ULONG sizeQ; CK_ULONG sizeG; CK_ULONG sizeX; CK_ULONG sizeY; CK_VOID_PTR bigP; CK_VOID_PTR bigQ; CK_VOID_PTR bigG; CK_VOID_PTR bigX; CK_VOID_PTR bigY; dsa_key_material_t() { sizeP = 0; sizeQ = 0; sizeG = 0; sizeX = 0; sizeY = 0; bigP = NULL_PTR; bigQ = NULL_PTR; bigG = NULL_PTR; bigX = NULL_PTR; bigY = NULL_PTR; } } dsa_key_material_t; #ifdef WITH_ECC typedef struct ecdsa_key_material_t { CK_ULONG sizeParams; CK_ULONG sizeD; CK_ULONG sizeQ; CK_VOID_PTR derParams; CK_VOID_PTR bigD; CK_VOID_PTR derQ; ecdsa_key_material_t() { sizeParams = 0; sizeD = 0; sizeQ = 0; derParams = NULL_PTR; bigD = NULL_PTR; derQ = NULL_PTR; } } ecdsa_key_material_t; #endif EVP_PKEY* crypto_read_file(char* filePath, char* filePIN); // RSA int crypto_save_rsa(CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, RSA* rsa); rsa_key_material_t* crypto_malloc_rsa(RSA* rsa); void crypto_free_rsa(rsa_key_material_t* keyMat); // DSA int crypto_save_dsa(CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, DSA* dsa); dsa_key_material_t* crypto_malloc_dsa(DSA* dsa); void crypto_free_dsa(dsa_key_material_t* keyMat); #ifdef WITH_ECC // ECDSA int crypto_save_ecdsa(CK_SESSION_HANDLE hSession, char* label, char* objID, size_t objIDLen, int noPublicKey, EC_KEY* ecdsa); ecdsa_key_material_t* crypto_malloc_ecdsa(EC_KEY* ecdsa); void crypto_free_ecdsa(ecdsa_key_material_t* keyMat); #endif #endif // !_SOFTHSM_V2_SOFTHSM2_UTIL_OSSL_H softhsm-2.0.0/src/bin/Makefile.am0000664000175000017500000000027012533040716013512 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in SUBDIRS = common keyconv util dump if BUILD_MIGRATE SUBDIRS += migrate endif EXTRA_DIST = $(srcdir)/win32/*.cpp \ $(srcdir)/win32/*.h softhsm-2.0.0/src/bin/migrate/0000775000175000017500000000000012552220146013165 500000000000000softhsm-2.0.0/src/bin/migrate/Makefile.am0000664000175000017500000000067712533040716015155 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../../lib/cryptoki_compat \ -I$(srcdir)/../common \ @SQLITE3_INCLUDES@ dist_man_MANS = softhsm2-migrate.1 bin_PROGRAMS = softhsm2-migrate AUTOMAKE_OPTIONS = subdir-objects softhsm2_migrate_SOURCES = softhsm2-migrate.cpp \ ../common/getpw.cpp \ ../common/library.cpp softhsm2_migrate_LDADD = @SQLITE3_LIBS@ \ @YIELD_LIB@ EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/bin/migrate/softhsm2-migrate.10000664000175000017500000000245312533040716016370 00000000000000.TH SOFTHSM2-MIGRATE 1 "20 March 2014" "SoftHSM" .SH NAME softhsm2-migrate \- SoftHSM v1 migration tool .SH SYNOPSIS .PP .B softhsm2-migrate \-\-db .I path .B \-\-slot .I number .RB [ \-\-pin .I PIN .B \-\-no\-public\-key] .SH DESCRIPTION .B softhsm2-migrate is a tool that can migrate SoftHSM v1 databases to PKCS#11. The default HSM is SoftHSM v2, but can be used with other PKCS#11 libraries by using the option .B \-\-module .LP .SH OPTIONS .TP .B \-\-db \fIpath\fR The SoftHSM v1 database that is going to be migrated. The location of the token database can be found in the configuration file for SoftHSM v1. .TP .B \-\-help\fR, \fB\-h\fR Show the help information. .TP .B \-\-module \fIpath\fR Use another PKCS#11 library than SoftHSM. .TP .B \-\-no\-public\-key Do not migrate the public key. .TP .B \-\-pin \fIPIN\fR The .I PIN for the normal user. .TP .B \-\-slot \fInumber\fR The database will be migrated to this slot. .TP .B \-\-version\fR, \fB\-v\fR Show the version info. .SH EXAMPLE .LP A token database can be migrated with the following command: .LP .RS .nf softhsm2-migrate \-\-db /home/user/token.db \-\-slot 1 .fi .RE .SH AUTHORS Written by Rickard Bellgrim, Francis Dupont, René Post, and Roland van Rijswijk. .LP .SH "SEE ALSO" .IR softhsm2-keyconv (1), .IR softhsm2-util (1), .IR softhsm2.conf (5) softhsm-2.0.0/src/bin/migrate/Makefile.in0000664000175000017500000006100512552216620015156 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = softhsm2-migrate$(EXEEXT) subdir = src/bin/migrate DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(dist_man_MANS) ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" PROGRAMS = $(bin_PROGRAMS) am__dirstamp = $(am__leading_dot)dirstamp am_softhsm2_migrate_OBJECTS = softhsm2-migrate.$(OBJEXT) \ ../common/getpw.$(OBJEXT) ../common/library.$(OBJEXT) softhsm2_migrate_OBJECTS = $(am_softhsm2_migrate_OBJECTS) softhsm2_migrate_DEPENDENCIES = AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(softhsm2_migrate_SOURCES) DIST_SOURCES = $(softhsm2_migrate_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 NROFF = nroff MANS = $(dist_man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../../lib/cryptoki_compat \ -I$(srcdir)/../common \ @SQLITE3_INCLUDES@ dist_man_MANS = softhsm2-migrate.1 AUTOMAKE_OPTIONS = subdir-objects softhsm2_migrate_SOURCES = softhsm2-migrate.cpp \ ../common/getpw.cpp \ ../common/library.cpp softhsm2_migrate_LDADD = @SQLITE3_LIBS@ \ @YIELD_LIB@ EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/migrate/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/migrate/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list ../common/$(am__dirstamp): @$(MKDIR_P) ../common @: > ../common/$(am__dirstamp) ../common/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) ../common/$(DEPDIR) @: > ../common/$(DEPDIR)/$(am__dirstamp) ../common/getpw.$(OBJEXT): ../common/$(am__dirstamp) \ ../common/$(DEPDIR)/$(am__dirstamp) ../common/library.$(OBJEXT): ../common/$(am__dirstamp) \ ../common/$(DEPDIR)/$(am__dirstamp) softhsm2-migrate$(EXEEXT): $(softhsm2_migrate_OBJECTS) $(softhsm2_migrate_DEPENDENCIES) $(EXTRA_softhsm2_migrate_DEPENDENCIES) @rm -f softhsm2-migrate$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(softhsm2_migrate_OBJECTS) $(softhsm2_migrate_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) -rm -f ../common/*.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@../common/$(DEPDIR)/getpw.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@../common/$(DEPDIR)/library.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-migrate.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(dist_man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(dist_man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) $(MANS) installdirs: for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f ../common/$(DEPDIR)/$(am__dirstamp) -rm -f ../common/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ../common/$(DEPDIR) ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ../common/$(DEPDIR) ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-man uninstall-man: uninstall-man1 .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-man1 \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-man uninstall-man1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/bin/migrate/softhsm2-migrate.cpp0000664000175000017500000004443112533040716017014 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-migrate.cpp This program can be used for migrating SoftHSM v1 databases to any PKCS#11 library. The default library is the libsofthsm2.so *****************************************************************************/ #include #include "softhsm2-migrate.h" #include "getpw.h" #include "library.h" #include #include #include #include #ifndef _WIN32 #include #endif #include #include #include #ifdef _WIN32 #define sched_yield() SleepEx(0, 0) #endif // Display the usage void usage() { printf("SoftHSM migration tool. From SoftHSM v1 database to PKCS#11.\n"); printf("Usage: softhsm2-migrate [OPTIONS]\n"); printf("Options:\n"); printf(" -h Shows this help screen.\n"); printf(" --help Shows this help screen.\n"); printf(" --db The SoftHSM v1 database that is going to be migrated.\n"); printf(" --module Use another PKCS#11 library than SoftHSM.\n"); printf(" --no-public-key Do not migrate the public key.\n"); printf(" --pin The PIN for the normal user.\n"); printf(" --slot The slot where the token is located.\n"); printf(" -v Show version info.\n"); printf(" --version Show version info.\n"); } // Enumeration of the long options enum { OPT_HELP = 0x100, OPT_DB, OPT_MODULE, OPT_NO_PUBLIC_KEY, OPT_PIN, OPT_SLOT, OPT_VERSION }; // Text representation of the long options static const struct option long_options[] = { { "help", 0, NULL, OPT_HELP }, { "db", 1, NULL, OPT_DB }, { "module", 1, NULL, OPT_MODULE }, { "no-public-key", 0, NULL, OPT_NO_PUBLIC_KEY }, { "pin", 1, NULL, OPT_PIN }, { "slot", 1, NULL, OPT_SLOT }, { "version", 0, NULL, OPT_VERSION }, { NULL, 0, NULL, 0 } }; CK_FUNCTION_LIST_PTR p11; // Prepared statements sqlite3_stmt* select_an_attribute_sql = NULL; sqlite3_stmt* select_object_ids_sql = NULL; sqlite3_stmt* count_object_id_sql = NULL; // The main function int main(int argc, char* argv[]) { int option_index = 0; int opt; char* dbPath = NULL; char* userPIN = NULL; char* module = NULL; char* slot = NULL; char *errMsg = NULL; int noPublicKey = 0; int result = 0; CK_RV rv; moduleHandle = NULL; p11 = NULL; if (argc == 1) { usage(); exit(0); } while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1) { switch (opt) { case OPT_DB: dbPath = optarg; break; case OPT_SLOT: slot = optarg; break; case OPT_MODULE: module = optarg; break; case OPT_NO_PUBLIC_KEY: noPublicKey = 1; break; case OPT_PIN: userPIN = optarg; break; case OPT_VERSION: case 'v': printf("%s\n", PACKAGE_VERSION); exit(0); break; case OPT_HELP: case 'h': default: usage(); exit(0); break; } } // Get a pointer to the function list for PKCS#11 library CK_C_GetFunctionList pGetFunctionList = loadLibrary(module, &moduleHandle, &errMsg); if (pGetFunctionList == NULL) { fprintf(stderr, "ERROR: Could not load the library: %s\n", errMsg); exit(1); } // Load the function list (*pGetFunctionList)(&p11); // Initialize the library rv = p11->C_Initialize(NULL_PTR); if (rv != CKR_OK) { fprintf(stderr, "ERROR: Could not initialize the library.\n"); exit(1); } // Migrate the database result = migrate(dbPath, slot, userPIN, noPublicKey); // Finalize the library p11->C_Finalize(NULL_PTR); unloadLibrary(moduleHandle); return result; } // Migrate the database int migrate(char* dbPath, char* slot, char* userPIN, int noPublicKey) { CK_SESSION_HANDLE hSession; sqlite3* db = NULL; int result; if (dbPath == NULL) { fprintf(stderr, "ERROR: A path to the database must be supplied. " "Use --db \n"); return 1; } if (slot == NULL) { fprintf(stderr, "ERROR: A slot number must be supplied. " "Use --slot \n"); return 1; } // Open the database db = openDB(dbPath); if (db == NULL) { return 1; } // Connect to the PKCS#11 library result = openP11(slot, userPIN, &hSession); if (result) { sqlite3_close(db); return result; } // Prepare the statements if (prepStatements(db)) { fprintf(stderr, "ERROR: Could not prepare the statements\n"); finalStatements(); sqlite3_close(db); return 1; } // Start the migration result = db2session(db, hSession, noPublicKey); // Finalize the statements finalStatements(); sqlite3_close(db); if (result) { fprintf(stderr, "ERROR: Unable to migrate all of the objects.\n"); } else { printf("The database has been migrated to the new HSM\n"); } return result; } // Prepare the statements int prepStatements(sqlite3* db) { select_an_attribute_sql = NULL; select_object_ids_sql = NULL; count_object_id_sql = NULL; const char select_an_attribute_str[] = "SELECT value,length FROM Attributes WHERE objectID = ? AND type = ?;"; const char select_object_ids_str[] = "SELECT objectID FROM Objects;"; const char count_object_id_str[] = "SELECT COUNT(objectID) FROM Objects;"; if ( sqlite3_prepare_v2(db, select_an_attribute_str, -1, &select_an_attribute_sql, NULL) || sqlite3_prepare_v2(db, select_object_ids_str, -1, &select_object_ids_sql, NULL) || sqlite3_prepare_v2(db, count_object_id_str, -1, &count_object_id_sql, NULL) ) { return 1; } return 0; } // Finalize the statements void finalStatements() { if (select_an_attribute_sql) sqlite3_finalize(select_an_attribute_sql); if (select_object_ids_sql) sqlite3_finalize(select_object_ids_sql); if (count_object_id_sql) sqlite3_finalize(count_object_id_sql); } // Open a connection to a valid SoftHSM v1 database sqlite3* openDB(char* dbPath) { int result; sqlite3* db = NULL; sqlite3_stmt* pragStatem = NULL; int dbVersion; // Open the database result = sqlite3_open(dbPath, &db); if (result) { fprintf(stderr, "ERROR: Could not open token database. " "Probably wrong path or privileges: %s\n", dbPath); return NULL; } // Check the schema version if (sqlite3_prepare_v2(db, "PRAGMA user_version;", -1, &pragStatem, NULL)) { fprintf(stderr, "ERROR: Could not prepare a SQL statement\n"); sqlite3_close(db); return NULL; } if (sqlite3_step(pragStatem) == SQLITE_ROW) { dbVersion = sqlite3_column_int(pragStatem, 0); sqlite3_finalize(pragStatem); if (dbVersion != 100) { fprintf(stderr, "ERROR: Wrong database schema version: %s\n", dbPath); sqlite3_close(db); return NULL; } } else { fprintf(stderr, "ERROR: The token database has not been initialized by SoftHSM\n"); sqlite3_finalize(pragStatem); sqlite3_close(db); return NULL; } // Check that the Token table exist result = sqlite3_exec(db, "SELECT COUNT(variableID) FROM Token;", NULL, NULL, NULL); if (result) { fprintf(stderr, "ERROR: The Token table is missing the in database\n"); sqlite3_close(db); return NULL; } // Check that the Objects table exist result = sqlite3_exec(db, "SELECT COUNT(objectID) FROM Objects;", NULL, NULL, NULL); if (result) { fprintf(stderr, "ERROR: The Objects table is missing the in database\n"); sqlite3_close(db); return NULL; } // Check that the Attributes table exist result = sqlite3_exec(db, "SELECT COUNT(attributeID) FROM Attributes;", NULL, NULL, NULL); if (result) { fprintf(stderr, "ERROR: The Attributes table is missing in the database\n"); sqlite3_close(db); return NULL; } return db; } // Connect and login to the token int openP11(char* slot, char* userPIN, CK_SESSION_HANDLE* hSession) { char user_pin_copy[MAX_PIN_LEN+1]; CK_RV rv; CK_SLOT_ID slotID; // Load the variable slotID = atoi(slot); rv = p11->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, hSession); if (rv != CKR_OK) { if (rv == CKR_SLOT_ID_INVALID) { fprintf(stderr, "ERROR: The given slot does not exist.\n"); } else { fprintf(stderr, "ERROR: Could not open a session on the given slot.\n"); } return 1; } // Get the password getPW(userPIN, user_pin_copy, CKU_USER); rv = p11->C_Login(*hSession, CKU_USER, (CK_UTF8CHAR_PTR)user_pin_copy, strlen(user_pin_copy)); if (rv != CKR_OK) { if (rv == CKR_PIN_INCORRECT) { fprintf(stderr, "ERROR: The given user PIN does not match the one in the token.\n"); } else { fprintf(stderr, "ERROR: Could not log in on the token.\n"); } return 1; } return 0; } // Migrate the database to the session int db2session(sqlite3* db, CK_SESSION_HANDLE hSession, int noPublicKey) { CK_ULONG objectCount; int result = 0, rv; CK_OBJECT_HANDLE* objects = NULL; CK_OBJECT_CLASS ckClass; // Get all objects objects = getObjects(db, &objectCount); if (objects == NULL) { fprintf(stderr, "ERROR: Could not find any objects in the database.\n"); return 1; } // Loop over all objects for (unsigned i = 0; i < objectCount; i++) { ckClass = getObjectClass(objects[i]); switch (ckClass) { case CKO_PUBLIC_KEY: if (noPublicKey) continue; if (getKeyType(objects[i]) != CKK_RSA) { fprintf(stderr, "ERROR: Cannot export object %lu. Only supporting RSA keys. " "Continuing.\n", objects[i]); result = 1; break; } rv = dbRSAPub2session(db, objects[i], hSession); if (rv) result = 1; break; case CKO_PRIVATE_KEY: if (getKeyType(objects[i]) != CKK_RSA) { fprintf(stderr, "ERROR: Cannot export object %lu. Only supporting RSA keys. " "Continuing.\n", objects[i]); result = 1; break; } rv = dbRSAPriv2session(db, objects[i], hSession); if (rv) result = 1; break; case CKO_VENDOR_DEFINED: fprintf(stderr, "ERROR: Could not get the class of object %lu. " "Continuing.\n", objects[i]); result = 1; break; default: fprintf(stderr, "ERROR: Not supporting class %lu in object %lu. " "Continuing.\n", ckClass, objects[i]); result = 1; break; } } free(objects); return result; } // Get the key type from key objects CK_KEY_TYPE getKeyType(CK_OBJECT_HANDLE objectRef) { int retSQL = 0; CK_KEY_TYPE retVal = CKK_VENDOR_DEFINED; sqlite3_bind_int(select_an_attribute_sql, 1, objectRef); sqlite3_bind_int(select_an_attribute_sql, 2, CKA_KEY_TYPE); // Get result while ((retSQL = sqlite3_step(select_an_attribute_sql)) == SQLITE_BUSY) { sched_yield(); } // Get attribute if (retSQL == SQLITE_ROW) { CK_VOID_PTR pValue = (CK_VOID_PTR)sqlite3_column_blob(select_an_attribute_sql, 0); CK_ULONG length = sqlite3_column_int(select_an_attribute_sql, 1); if (pValue != NULL_PTR && length == sizeof(CK_KEY_TYPE)) { retVal = *(CK_KEY_TYPE*)pValue; } } sqlite3_reset(select_an_attribute_sql); return retVal; } // Get the class of the object CK_OBJECT_CLASS getObjectClass(CK_OBJECT_HANDLE objectRef) { int retSQL = 0; CK_OBJECT_CLASS retVal = CKO_VENDOR_DEFINED; sqlite3_bind_int(select_an_attribute_sql, 1, objectRef); sqlite3_bind_int(select_an_attribute_sql, 2, CKA_CLASS); // Get the result while ((retSQL = sqlite3_step(select_an_attribute_sql)) == SQLITE_BUSY) { sched_yield(); } // Get attribute if (retSQL == SQLITE_ROW) { CK_VOID_PTR pValue = (CK_VOID_PTR)sqlite3_column_blob(select_an_attribute_sql, 0); CK_ULONG length = sqlite3_column_int(select_an_attribute_sql, 1); if (pValue != NULL_PTR && length == sizeof(CK_OBJECT_CLASS)) { retVal = *(CK_OBJECT_CLASS*)pValue; } } sqlite3_reset(select_an_attribute_sql); return retVal; } // Get all object IDs CK_OBJECT_HANDLE* getObjects(sqlite3* /*db*/, CK_ULONG* objectCount) { CK_ULONG objectsInDB; CK_ULONG counter = 0; CK_OBJECT_HANDLE* objectRefs = NULL; int retSQL = 0; *objectCount = 0; // Find out how many objects we have. while ((retSQL = sqlite3_step(count_object_id_sql)) == SQLITE_BUSY) { sched_yield(); } if (retSQL != SQLITE_ROW) { fprintf(stderr, "ERROR: Could not count the number of objects in the database\n"); sqlite3_reset(count_object_id_sql); return NULL; } // Get the number of objects objectsInDB = sqlite3_column_int(count_object_id_sql, 0); sqlite3_reset(count_object_id_sql); if (!objectsInDB) { fprintf(stderr, "ERROR: There are not objects in the database\n"); return NULL; } // Create the object-reference buffer objectRefs = (CK_OBJECT_HANDLE*)malloc(objectsInDB * sizeof(CK_OBJECT_HANDLE)); if (objectRefs == NULL) { fprintf(stderr, "ERROR: Could not allocate memory\n"); return NULL; } // Get all the object ids while ( ((retSQL = sqlite3_step(select_object_ids_sql)) == SQLITE_BUSY || retSQL == SQLITE_ROW) && counter < objectsInDB ) { if(retSQL == SQLITE_BUSY) { sched_yield(); continue; } objectRefs[counter++] = sqlite3_column_int(select_object_ids_sql, 0); } *objectCount = counter; sqlite3_reset(select_object_ids_sql); return objectRefs; } // Extract the information about the public RSA key and save it in the token int dbRSAPub2session(sqlite3* /*db*/, CK_OBJECT_HANDLE objectID, CK_SESSION_HANDLE hSession) { int result = 0; int i; CK_OBJECT_HANDLE hKey; CK_RV rv; CK_ATTRIBUTE pubTemplate[] = { { CKA_CLASS, NULL, 0 }, { CKA_KEY_TYPE, NULL, 0 }, { CKA_TOKEN, NULL, 0 }, { CKA_PRIVATE, NULL, 0 }, { CKA_MODIFIABLE, NULL, 0 }, { CKA_LABEL, NULL, 0 }, { CKA_ID, NULL, 0 }, { CKA_START_DATE, NULL, 0 }, { CKA_END_DATE, NULL, 0 }, { CKA_DERIVE, NULL, 0 }, { CKA_SUBJECT, NULL, 0 }, { CKA_ENCRYPT, NULL, 0 }, { CKA_VERIFY, NULL, 0 }, { CKA_VERIFY_RECOVER, NULL, 0 }, { CKA_WRAP, NULL, 0 }, { CKA_MODULUS, NULL, 0 }, { CKA_PUBLIC_EXPONENT, NULL, 0 } }; for (i = 0; i < 17; i++) { result = getAttribute(objectID, &pubTemplate[i]); if (result) { freeTemplate(pubTemplate, 17); return 1; } } rv = p11->C_CreateObject(hSession, pubTemplate, 17, &hKey); if (rv != CKR_OK) { fprintf(stderr, "ERROR %X: Could not save the public key in the token. " "Skipping object %lu\n", (unsigned int)rv, objectID); result = 1; } else { printf("Object %lu has been migrated\n", objectID); } freeTemplate(pubTemplate, 17); return result; } // Extract the information about the private RSA key and save it in the token int dbRSAPriv2session(sqlite3* /*db*/, CK_OBJECT_HANDLE objectID, CK_SESSION_HANDLE hSession) { int result = 0; int i; CK_OBJECT_HANDLE hKey; CK_RV rv; CK_ATTRIBUTE privTemplate[] = { { CKA_CLASS, NULL, 0 }, { CKA_TOKEN, NULL, 0 }, { CKA_PRIVATE, NULL, 0 }, { CKA_MODIFIABLE, NULL, 0 }, { CKA_LABEL, NULL, 0 }, { CKA_KEY_TYPE, NULL, 0 }, { CKA_ID, NULL, 0 }, { CKA_START_DATE, NULL, 0 }, { CKA_END_DATE, NULL, 0 }, { CKA_DERIVE, NULL, 0 }, { CKA_SUBJECT, NULL, 0 }, { CKA_SENSITIVE, NULL, 0 }, { CKA_DECRYPT, NULL, 0 }, { CKA_SIGN, NULL, 0 }, { CKA_SIGN_RECOVER, NULL, 0 }, { CKA_UNWRAP, NULL, 0 }, { CKA_EXTRACTABLE, NULL, 0 }, { CKA_WRAP_WITH_TRUSTED, NULL, 0 }, { CKA_MODULUS, NULL, 0 }, { CKA_PUBLIC_EXPONENT, NULL, 0 }, { CKA_PRIVATE_EXPONENT, NULL, 0 }, { CKA_PRIME_1, NULL, 0 }, { CKA_PRIME_2, NULL, 0 } // SoftHSM v1 did not store these values // { CKA_EXPONENT_1, NULL, 0 }, // { CKA_EXPONENT_2, NULL, 0 }, // { CKA_COEFFICIENT, NULL, 0 } }; for (i = 0; i < 23; i++) { result = getAttribute(objectID, &privTemplate[i]); if (result) { freeTemplate(privTemplate, 23); return 1; } } rv = p11->C_CreateObject(hSession, privTemplate, 23, &hKey); if (rv != CKR_OK) { fprintf(stderr, "ERROR %X: Could not save the private key in the token. " "Skipping object %lu\n", (unsigned int)rv, objectID); result = 1; } else { printf("Object %lu has been migrated\n", objectID); } freeTemplate(privTemplate, 23); return result; } // Get the value of the given attribute int getAttribute(CK_OBJECT_HANDLE objectRef, CK_ATTRIBUTE* attTemplate) { int retSQL = 0; int retVal = 0; sqlite3_bind_int(select_an_attribute_sql, 1, objectRef); sqlite3_bind_int(select_an_attribute_sql, 2, attTemplate->type); // Get result while ((retSQL = sqlite3_step(select_an_attribute_sql)) == SQLITE_BUSY) { sched_yield(); } // Get the attribute if (retSQL == SQLITE_ROW) { CK_VOID_PTR pValue = (CK_VOID_PTR)sqlite3_column_blob(select_an_attribute_sql, 0); CK_ULONG length = sqlite3_column_int(select_an_attribute_sql, 1); if (length) { attTemplate->pValue = malloc(length); if (!attTemplate->pValue) { fprintf(stderr, "ERROR: Could not allocate memory. " "Skipping object %lu\n", objectRef); retVal = 1; } else { // Copy data memcpy(attTemplate->pValue, pValue, length); } } attTemplate->ulValueLen = length; } else { fprintf(stderr, "ERROR: Do not have attribute %lu. " "Skipping object %lu\n", attTemplate->type, objectRef); retVal = 1; } sqlite3_reset(select_an_attribute_sql); return retVal; } // Free allocated memory in the template void freeTemplate(CK_ATTRIBUTE* attTemplate, int size) { int i; if (!attTemplate) return; for (i = 0; i < size; i++) { if(attTemplate[i].pValue) { free(attTemplate[i].pValue); } } } softhsm-2.0.0/src/bin/migrate/softhsm2-migrate.h0000664000175000017500000000532012533040716016453 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-migrate.h This program can be used for migrating SoftHSM v1 databases to any PKCS#11 library. The default library is the libsofthsm2.so *****************************************************************************/ #ifndef _SOFTHSM_V2_SOFTHSM2_MIGRATE_H #define _SOFTHSM_V2_SOFTHSM2_MIGRATE_H #include "pkcs11.h" #include // Main functions void usage(); int migrate(char* dbPath, char* slot, char* userPIN, int noPublicKey); // Support functions sqlite3* openDB(char* dbPath); int openP11(char* slot, char* userPIN, CK_SESSION_HANDLE* hSession); int db2session(sqlite3* db, CK_SESSION_HANDLE hSession, int noPublicKey); int dbRSAPub2session(sqlite3* db, CK_OBJECT_HANDLE objectID, CK_SESSION_HANDLE hSession); int dbRSAPriv2session(sqlite3* db, CK_OBJECT_HANDLE objectID, CK_SESSION_HANDLE hSession); void freeTemplate(CK_ATTRIBUTE* attTemplate, int size); // Database functions CK_OBJECT_HANDLE* getObjects(sqlite3* db, CK_ULONG* objectCount); CK_OBJECT_CLASS getObjectClass(CK_OBJECT_HANDLE objectRef); CK_KEY_TYPE getKeyType(CK_OBJECT_HANDLE objectRef); int getAttribute(CK_OBJECT_HANDLE objectRef, CK_ATTRIBUTE* attTemplate); int prepStatements(sqlite3* db); void finalStatements(); // Library static void* moduleHandle; extern CK_FUNCTION_LIST_PTR p11; #endif // !_SOFTHSM_V2_SOFTHSM2_MIGRATE_H softhsm-2.0.0/src/bin/dump/0000775000175000017500000000000012552220146012502 500000000000000softhsm-2.0.0/src/bin/dump/softhsm2-dump-db.10000664000175000017500000000061212533040716015600 00000000000000.TH SOFTHSM2-DUMP-DB 1 "20 March 2014" "SoftHSM" .SH NAME softhsm2-dump-db \- SoftHSM database dump .SH SYNOPSIS .PP .B softhsm2-dump-db .I path .SH DESCRIPTION .B softhsm2-dump is a tool that can dump SoftHSM v2 database for debugging purposes. .LP .SH OPTIONS .TP .B \fIpath\fR The SoftHSM v2 database file that is going to be dumped. .TP .B \-\-help\fR, \fB\-h\fR Show the help information. softhsm-2.0.0/src/bin/dump/common.h0000664000175000017500000002242612533040716014073 00000000000000/* * Copyright (c) 2013 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** common.h Common definitions for SoftHSMv2 dump. *****************************************************************************/ #ifndef _SOFTHSM_V2_COMMON_H #define _SOFTHSM_V2_COMMON_H #include #include #include #include #include #include #include #include #include "tables.h" // Table of attribute types std::map CKA_table; // Dump an attribute type void dumpCKA(unsigned long cka, int size) { // Lazy fill if (CKA_table.empty()) { fill_CKA_table(CKA_table); } std::string msg; try { msg = CKA_table.at(cka); printf("%.*s", size, msg.c_str()); } catch (const std::out_of_range&) { if (cka & CKA_VENDOR_DEFINED) { cka &= ~CKA_VENDOR_DEFINED; printf("CKA_VENDOR_DEFINED | 0x%lx", cka); } else { printf("unknown 0x%lx", cka); } } } // Table of mechanism types std::map CKM_table; // Dump a mechanism type void dumpCKM(unsigned long cka, int size) { // Lazy fill if (CKM_table.empty()) { fill_CKM_table(CKM_table); } std::string msg; try { msg = CKM_table.at(cka); printf("%.*s", size, msg.c_str()); } catch (const std::out_of_range&) { if (cka & CKM_VENDOR_DEFINED) { cka &= ~CKM_VENDOR_DEFINED; printf("CKM_VENDOR_DEFINED | 0x%lx", cka); } else { printf("unknown 0x%lx", cka); } } } // Table of object classes std::map CKO_table; // Dump a object class void dumpCKO(unsigned long cka, int size) { // Lazy fill if (CKO_table.empty()) { fill_CKO_table(CKO_table); } std::string msg; try { msg = CKO_table.at(cka); printf("%.*s", size, msg.c_str()); } catch (const std::out_of_range&) { if (cka & CKO_VENDOR_DEFINED) { cka &= ~CKO_VENDOR_DEFINED; printf("CKO_VENDOR_DEFINED | 0x%lx", cka); } else { printf("unknown 0x%lx", cka); } } } // Table of hw feature types std::map CKH_table; // Dump a hw feature type void dumpCKH(unsigned long cka, int size) { // Lazy fill if (CKH_table.empty()) { fill_CKH_table(CKH_table); } std::string msg; try { msg = CKH_table.at(cka); printf("%.*s", size, msg.c_str()); } catch (const std::out_of_range&) { if (cka & CKH_VENDOR_DEFINED) { cka &= ~CKH_VENDOR_DEFINED; printf("CKH_VENDOR_DEFINED | 0x%lx", cka); } else { printf("unknown 0x%lx", cka); } } } // Table of key types std::map CKK_table; // Dump a key type void dumpCKK(unsigned long cka, int size) { // Lazy fill if (CKK_table.empty()) { fill_CKK_table(CKK_table); } std::string msg; try { msg = CKK_table.at(cka); printf("%.*s", size, msg.c_str()); } catch (const std::out_of_range&) { if (cka & CKK_VENDOR_DEFINED) { cka &= ~CKK_VENDOR_DEFINED; printf("CKK_VENDOR_DEFINED | 0x%lx", cka); } else { printf("unknown 0x%lx", cka); } } } // Table of certificate types std::map CKC_table; // Dump a certificate type void dumpCKC(unsigned long cka, int size) { // Lazy fill if (CKC_table.empty()) { fill_CKC_table(CKC_table); } std::string msg; try { msg = CKC_table.at(cka); printf("%.*s", size, msg.c_str()); } catch (const std::out_of_range&) { if (cka & CKC_VENDOR_DEFINED) { cka &= ~CKC_VENDOR_DEFINED; printf("CKC_VENDOR_DEFINED | 0x%lx", cka); } else { printf("unknown 0x%lx", cka); } } } // Dump a PKCS#11 integer type void dumpCKx(uint64_t cka, uint64_t value, int size) { if ((uint32_t)value == (uint32_t)~0) { printf("CK_UNAVAILABLE_INFORMATION"); return; } switch ((unsigned long) cka) { case CKA_CLASS: if ((uint64_t)((uint32_t)value) != value) { printf("overflow object class"); break; } dumpCKO((unsigned long) value, size); break; case CKA_CERTIFICATE_TYPE: if ((uint64_t)((uint32_t)value) != value) { printf("overflow certificate type"); break; } dumpCKC((unsigned long) value, size); break; case CKA_KEY_TYPE: if ((uint64_t)((uint32_t)value) != value) { printf("overflow key type"); break; } dumpCKK((unsigned long) value, size); break; case CKA_KEY_GEN_MECHANISM: if ((uint64_t)((uint32_t)value) != value) { printf("overflow mechanism type"); break; } dumpCKM((unsigned long) value, size); break; case CKA_HW_FEATURE_TYPE: if ((uint64_t)((uint32_t)value) != value) { printf("overflow hw feature type"); break; } dumpCKH((unsigned long) value, size); break; default: printf("CK_ULONG %lu(0x%lx)", (unsigned long) value, (unsigned long) value); break; } } // Dump a boolean (in fact unsigned 8 bit long) value, true is 0xff void dumpBool(uint8_t value, bool inArray = false) { printf("%02hhx %s", value, inArray ? " " : ""); switch (value) { case 0: printf("FALSE"); break; case 0xff: printf("TRUE"); break; default: printf("(invalid) TRUE"); break; } } // Dump a boolean (in fact unsigned 8 bit long) value, true is 1 void dumpBool1(uint8_t value, bool inArray = false) { printf("%02hhx %s", value, inArray ? " " : ""); switch (value) { case 0: printf("FALSE"); break; case 1: printf("TRUE"); break; default: printf("(invalid) TRUE"); break; } } // Dump an unsigned 64 bit long value void dumpULong(uint64_t value, bool inArray = false) { for (int i = 56; i >= 0; i -= 8) { uint8_t v; v = (value >> i) & 0xff; printf("%02hhx ", v); } if (inArray) { printf(" "); } } // Dump an unsigned 32 bit long value void dumpU32(uint32_t value, bool inArray = false) { for (int i = 24; i >= 0; i -= 8) { uint8_t v; v = (value >> i) & 0xff; printf("%02hhx ", v); } printf(" "); if (inArray) { printf(" "); } } // Dump a byte string (aka uint8_t vector) value void dumpBytes(const std::vector& value, bool inArray = false) { size_t len = value.size(); size_t i = 0; while (i + 8 <= len) { for (size_t j = 0; j < 8; j++) { printf("%02hhx ", value[i + j]); } if (inArray) { printf(" "); } printf("<"); for (size_t j = 0; j < 8; j++) { uint8_t c = value[i + j]; if (isgraph((int) c) == 0) { printf("."); } else { printf("%c", (int) c); } } printf(">\n"); i += 8; } len -= i; if (len == 0) { return; } for (size_t j = 0; j < len; j++) { printf("%02hhx ", value[i + j]); } for (size_t j = len; j < 8; j++) { printf(" "); } if (inArray) { printf(" "); } printf("<"); for (size_t j = 0; j < len; j++) { uint8_t c = value[i + j]; if (isgraph((int) c) == 0) { printf("."); } else { printf("%c", (int) c); } } for (size_t j =len; j < 8; j++) { printf(" "); } printf(">\n"); } // Attribute (in an array) template template class AttributeTK { public: T type; K kind; uint8_t boolValue; I ulongValue; std::vector bytestrValue; // Dump an array (in fact an Attribute vector) value void dumpType() const; void dumpKind() const; void dumpBoolValue() const; void dumpULongValue(I value) const; bool isBoolean() const; bool isInteger() const; bool isBinary() const; void dump() const { dumpType(); if ((sizeof(type) > 4) && ((uint64_t)((uint32_t)type) != type)) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) type, 47); printf("\n"); } dumpKind(); if (isBoolean()) { printf("boolean attribute\n"); dumpBoolValue(); printf("\n"); } else if (isInteger()) { printf("unsigned long attribute\n"); dumpULongValue(ulongValue); dumpCKx(type, ulongValue, 47); printf("\n"); } else if (isBinary()) { printf("byte string attribute\n"); I size = bytestrValue.size(); dumpULongValue(size); printf("(length %lu)\n", (unsigned long) size); dumpBytes(bytestrValue, true); } else { printf("unknown attribute format\n"); } } }; #endif // !_SOFTHSM_V2_COMMON_H softhsm-2.0.0/src/bin/dump/Makefile.am0000664000175000017500000000110712533040716014457 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../../lib/cryptoki_compat \ -I$(srcdir)/../../lib/object_store \ -I$(srcdir)/../../lib \ @SQLITE3_INCLUDES@ dist_man_MANS = softhsm2-dump-file.1 bin_PROGRAMS = softhsm2-dump-file if BUILD_OBJECTSTORE_BACKEND_DB dist_man_MANS += softhsm2-dump-db.1 bin_PROGRAMS += softhsm2-dump-db endif softhsm2_dump_file_SOURCES = softhsm2-dump-file.cpp softhsm2_dump_db_SOURCES = softhsm2-dump-db.cpp softhsm2_dump_db_LDADD = @SQLITE3_LIBS@ @YIELD_LIB@ EXTRA_DIST = $(srcdir)/*.h \ softhsm2-dump-db.1 softhsm-2.0.0/src/bin/dump/softhsm2-dump-file.cpp0000664000175000017500000002060212533040716016555 00000000000000/* * Copyright (c) 2013 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-dump-file.cpp This program can be used for dumping SoftHSM v2 object files. *****************************************************************************/ #include #include "common.h" // Attribute types on disk #define BOOLEAN_ATTR 0x1 #define ULONG_ATTR 0x2 #define BYTES_ATTR 0x3 #define ARRAY_ATTR 0x4 // Maximum byte string length (1Gib) #define MAX_BYTES 0x3fffffff typedef AttributeTK Attribute; // Attribute specialization template<> bool Attribute::isBoolean() const { return kind == BOOLEAN_ATTR; } template<> bool Attribute::isInteger() const { return kind == ULONG_ATTR; } template<> bool Attribute::isBinary() const { return kind == BYTES_ATTR; } template<> void Attribute::dumpType() const { dumpULong(type, true); } template<> void Attribute::dumpKind() const { dumpULong(kind, true); } template<> void Attribute::dumpBoolValue() const { dumpBool(boolValue, true); } template<> void Attribute::dumpULongValue(uint64_t value) const { dumpULong(value, true); } // dumpArray specialization typedef std::vector va_type; void dumpArray(const va_type& value) { for (va_type::const_iterator attr = value.begin(); attr != value.end(); ++attr) attr->dump(); } // Read a boolean (in fact unsigned 8 bit long) value bool readBool(FILE* stream, uint8_t& value) { value = 0; fpos_t pos; if (fgetpos(stream, &pos) != 0) { return false; } uint8_t v; if (fread(&v, 1, 1, stream) != 1) { (void) fsetpos(stream, &pos); return false; } value = v; return true; } // Read an unsigned 64 bit long value bool readULong(FILE* stream, uint64_t& value) { value = 0; fpos_t pos; if (fgetpos(stream, &pos) != 0) { return false; } uint8_t v[8]; if (fread(v, 1, 8, stream) != 8) { (void) fsetpos(stream, &pos); return false; } for (size_t i = 0; i < 8; i++) { value <<= 8; value += v[i]; } return true; } // Read a byte string (aka uint8_t vector) value bool readBytes(FILE* stream, std::vector& value) { size_t len = value.size(); fpos_t pos; if (fgetpos(stream, &pos) != 0) { return false; } if (fread(&value[0], 1, len, stream) != len) { (void) fsetpos(stream, &pos); return false; } return true; } // Read an array (aka Attribute vector) value bool readArray(FILE* stream, uint64_t len, std::vector& value) { fpos_t pos; if (fgetpos(stream, &pos) != 0) { return false; } while (len != 0) { Attribute attr; if (len < 8) { (void) fsetpos(stream, &pos); return false; } if (!readULong(stream, attr.type)) { (void) fsetpos(stream, &pos); return false; } len -= 8; if (len < 8) { (void) fsetpos(stream, &pos); return false; } if (!readULong(stream, attr.kind)) { (void) fsetpos(stream, &pos); return false; } len -= 8; if (attr.kind == BOOLEAN_ATTR) { if (len < 1) { (void) fsetpos(stream, &pos); return false; } len -= 1; if (!readBool(stream, attr.boolValue)) { (void) fsetpos(stream, &pos); return false; } } else if (attr.kind == ULONG_ATTR) { if (len < 8) { (void) fsetpos(stream, &pos); return false; } if (!readULong(stream, attr.ulongValue)) { (void) fsetpos(stream, &pos); return false; } len -= 8; } else if (attr.kind == BYTES_ATTR) { uint64_t size; if (len < 8) { (void) fsetpos(stream, &pos); return false; } if (!readULong(stream, size)) { (void) fsetpos(stream, &pos); return false; } len -= 8; if (len < size) { (void) fsetpos(stream, &pos); return false; } attr.bytestrValue.resize((size_t)size); if (!readBytes(stream, attr.bytestrValue)) { (void) fsetpos(stream, &pos); return false; } len -= size; } else { (void) fsetpos(stream, &pos); return false; } value.push_back(attr); } return true; } // Error case void corrupt(FILE* stream) { uint8_t v; for (size_t i = 0; i < 8; i++) { if (fread(&v, 1, 1, stream) != 1) { if (ferror(stream)) { printf("get an error...\n"); } return; } if (i != 0) { printf(" "); } printf("%02hhx", v); } if (fread(&v, 1, 1, stream) != 1) { if (ferror(stream)) { printf("\nget an error...\n"); } return; } printf("...\n"); } // Core function void dump(FILE* stream) { uint64_t gen; if (!readULong(stream, gen)) { if (feof(stream)) { printf("empty file\n"); } else { corrupt(stream); } return; } dumpULong(gen); printf("generation %lu\n", (unsigned long) gen); while (!feof(stream)) { uint64_t p11type; if (!readULong(stream, p11type)) { corrupt(stream); return; } dumpULong(p11type); if ((uint64_t)((uint32_t)p11type) != p11type) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) p11type, 48); printf("\n"); } uint64_t disktype; if (!readULong(stream, disktype)) { corrupt(stream); return; } dumpULong(disktype); switch (disktype) { case BOOLEAN_ATTR: printf("boolean attribute\n"); break; case ULONG_ATTR: printf("unsigned long attribute\n"); break; case BYTES_ATTR: printf("byte string attribute\n"); break; case ARRAY_ATTR: printf("attribute array attribute\n"); break; default: printf("unknown attribute format\n"); break; } if (disktype == BOOLEAN_ATTR) { uint8_t value; if (!readBool(stream, value)) { corrupt(stream); return; } dumpBool(value); printf("\n"); } else if (disktype == ULONG_ATTR) { uint64_t value; if (!readULong(stream, value)) { corrupt(stream); return; } dumpULong(value); dumpCKx(p11type, value, 48); printf("\n"); } else if (disktype == BYTES_ATTR) { uint64_t len; if (!readULong(stream, len)) { corrupt(stream); return; } dumpULong(len); if (len > MAX_BYTES) { printf("overflow length...\n"); return; } printf("(length %lu)\n", (unsigned long) len); std::vector value((size_t) len); if (!readBytes(stream, value)) { corrupt(stream); return; } dumpBytes(value); } else if (disktype == ARRAY_ATTR) { uint64_t len; if (!readULong(stream, len)) { corrupt(stream); return; } dumpULong(len); if (len > MAX_BYTES) { printf("overflow length...\n"); return; } printf("(length %lu)\n", (unsigned long) len); std::vector value; if (!readArray(stream, len, value)) { corrupt(stream); return; } dumpArray(value); } else { corrupt(stream); return; } } } // Display the usage void usage() { printf("SoftHSM dump tool. From SoftHSM v2 object file.\n"); printf("Usage: softhsm2-dump-file path\n"); } // The main function int main(int argc, char* argv[]) { FILE* stream; if (argc != 2) { usage(); exit(0); } stream = fopen(argv[1], "r"); if (stream == NULL) { fprintf(stderr, "can't open object file %s\n", argv[1]); exit(0); } printf("Dump of object file \"%s\"\n", argv[1]); dump(stream); exit(1); } softhsm-2.0.0/src/bin/dump/softhsm2-dump-file.10000664000175000017500000000063112533040716016133 00000000000000.TH SOFTHSM2-DUMP-FILE 1 "20 March 2014" "SoftHSM" .SH NAME softhsm2-dump-file \- SoftHSM object file dump .SH SYNOPSIS .PP .B softhsm2-dump-file .I path .SH DESCRIPTION .B softhsm2-dump-file is a tool that can dump SoftHSM v2 object file for debugging purposes. .LP .SH OPTIONS .TP .B \fIpath\fR The SoftHSM v2 object file that is going to be dumped. .TP .B \-\-help\fR, \fB\-h\fR Show the help information. softhsm-2.0.0/src/bin/dump/Makefile.in0000664000175000017500000006061212552216620014476 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = softhsm2-dump-file$(EXEEXT) $(am__EXEEXT_1) @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__append_1 = softhsm2-dump-db.1 @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__append_2 = softhsm2-dump-db subdir = src/bin/dump DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(dist_man_MANS) ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__EXEEXT_1 = \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ softhsm2-dump-db$(EXEEXT) am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" PROGRAMS = $(bin_PROGRAMS) am_softhsm2_dump_db_OBJECTS = softhsm2-dump-db.$(OBJEXT) softhsm2_dump_db_OBJECTS = $(am_softhsm2_dump_db_OBJECTS) softhsm2_dump_db_DEPENDENCIES = AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = am_softhsm2_dump_file_OBJECTS = softhsm2-dump-file.$(OBJEXT) softhsm2_dump_file_OBJECTS = $(am_softhsm2_dump_file_OBJECTS) softhsm2_dump_file_LDADD = $(LDADD) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(softhsm2_dump_db_SOURCES) $(softhsm2_dump_file_SOURCES) DIST_SOURCES = $(softhsm2_dump_db_SOURCES) \ $(softhsm2_dump_file_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 NROFF = nroff MANS = $(dist_man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../../lib/cryptoki_compat \ -I$(srcdir)/../../lib/object_store \ -I$(srcdir)/../../lib \ @SQLITE3_INCLUDES@ dist_man_MANS = softhsm2-dump-file.1 $(am__append_1) softhsm2_dump_file_SOURCES = softhsm2-dump-file.cpp softhsm2_dump_db_SOURCES = softhsm2-dump-db.cpp softhsm2_dump_db_LDADD = @SQLITE3_LIBS@ @YIELD_LIB@ EXTRA_DIST = $(srcdir)/*.h \ softhsm2-dump-db.1 all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/dump/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/dump/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list softhsm2-dump-db$(EXEEXT): $(softhsm2_dump_db_OBJECTS) $(softhsm2_dump_db_DEPENDENCIES) $(EXTRA_softhsm2_dump_db_DEPENDENCIES) @rm -f softhsm2-dump-db$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(softhsm2_dump_db_OBJECTS) $(softhsm2_dump_db_LDADD) $(LIBS) softhsm2-dump-file$(EXEEXT): $(softhsm2_dump_file_OBJECTS) $(softhsm2_dump_file_DEPENDENCIES) $(EXTRA_softhsm2_dump_file_DEPENDENCIES) @rm -f softhsm2-dump-file$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(softhsm2_dump_file_OBJECTS) $(softhsm2_dump_file_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-dump-db.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-dump-file.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(dist_man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(dist_man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) $(MANS) installdirs: for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-man uninstall-man: uninstall-man1 .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-man1 \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-man uninstall-man1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/bin/dump/softhsm2-dump-db.cpp0000664000175000017500000005335412533040716016235 00000000000000/* * Copyright (c) 2013 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-dump-db.cpp This program can be used for dumping SoftHSM v2 database. *****************************************************************************/ #include #include #include #include #include "common.h" // Attribute types in database arrays enum AttributeKind { akUnknown, akBoolean, akInteger, akBinary, akArray }; // Attribute specialization typedef AttributeTK Attribute; template<> bool Attribute::isBoolean() const { return kind == akBoolean; } template<> bool Attribute::isInteger() const { return kind == akInteger; } template<> bool Attribute::isBinary() const { return kind == akBinary; } template<> void Attribute::dumpType() const { if (sizeof(type) == 4) { dumpU32((uint32_t)type, true); } else { dumpULong(type, true); } } template<> void Attribute::dumpKind() const { dumpU32((uint32_t) kind, true); } template<> void Attribute::dumpBoolValue() const { dumpBool1(boolValue, true); } template<> void Attribute::dumpULongValue(unsigned long value) const { if (sizeof(unsigned long) == 4) { dumpU32(value, true); } else { dumpULong(value, true); } } // dumpArray specialization typedef std::vector va_type; void dumpArray(const va_type& value) { for (va_type::const_iterator attr = value.begin(); attr != value.end(); ++attr) attr->dump(); } // Get a boolean (in fact unsigned 8 bit long) value bool getBool(sqlite3* db, long long oid, long long id, uint64_t& type, uint8_t& value) { int rv; sqlite3_stmt* sql = NULL; std::string command = "select type,value from attribute_boolean where object_id=? and id=?;"; value = 0; rv = sqlite3_prepare_v2(db, command.c_str(), -1, &sql, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't find boolean attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } rv = sqlite3_bind_int64(sql, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } sqlite3_bind_int64(sql, 2, id); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the attribute id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } while ((rv = sqlite3_step(sql)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't read boolean attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } type = sqlite3_column_int64(sql, 0); value = sqlite3_column_int(sql, 1); sqlite3_finalize(sql); return true; } // Get an unsigned 64 bit long value bool getULong(sqlite3* db, long long oid, long long id, uint64_t& type, uint64_t& value) { int rv; sqlite3_stmt* sql = NULL; std::string command = "select type,value from attribute_integer where object_id=? and id=?;"; value = 0ULL; rv = sqlite3_prepare_v2(db, command.c_str(), -1, &sql, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't find integer attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } rv = sqlite3_bind_int64(sql, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } sqlite3_bind_int64(sql, 2, id); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the attribute id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } while ((rv = sqlite3_step(sql)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't read integer attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } type = sqlite3_column_int64(sql, 0); value = sqlite3_column_int64(sql, 1); sqlite3_finalize(sql); return true; } // Get a byte string (aka uint8_t vector) value bool getBytes(sqlite3* db, long long oid, long long id, uint64_t& type, std::vector& value) { int rv; sqlite3_stmt* sql = NULL; std::string command = "select type,value from attribute_binary where object_id=? and id=?;"; size_t len; const uint8_t* val; value.clear(); rv = sqlite3_prepare_v2(db, command.c_str(), -1, &sql, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't find binary attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } rv = sqlite3_bind_int64(sql, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } sqlite3_bind_int64(sql, 2, id); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the attribute id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } while ((rv = sqlite3_step(sql)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't read binary attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } type = sqlite3_column_int64(sql, 0); len = sqlite3_column_bytes(sql, 1); val = (const uint8_t*) sqlite3_column_blob(sql, 1); for (size_t i = 0; i < len; ++i) { value.push_back(val[i]); } sqlite3_finalize(sql); return true; } // Get an array (aka Attribute vector) value bool getArray(sqlite3* db, long long oid, long long id, uint64_t& type, std::vector& value) { int rv; sqlite3_stmt* sql = NULL; std::string command = "select type,value from attribute_array where object_id=? and id=?;"; size_t len; const uint8_t* val; value.clear(); rv = sqlite3_prepare_v2(db, command.c_str(), -1, &sql, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't find array attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } rv = sqlite3_bind_int64(sql, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } sqlite3_bind_int64(sql, 2, id); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the attribute id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } while ((rv = sqlite3_step(sql)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't read array attribute id=%lld object=%lld: %d(%s)\n", id, oid, rv, sqlite3_errmsg(db)); sqlite3_finalize(sql); return false; } type = sqlite3_column_int64(sql, 0); len = sqlite3_column_bytes(sql, 1); val = (const uint8_t*) sqlite3_column_blob(sql, 1); // CK_ATTRIBUTE_TYPE type, AttributeKind kind // bool -> int, integer -> unsigned long, binary -> unsigned long + vector for (size_t pos = 0; pos < len; ) { // finished? if (pos == len) break; Attribute attr; if (pos + sizeof(attr.type) > len) { fprintf(stderr, "overflow array item type\n"); sqlite3_finalize(sql); return false; } memcpy(&attr.type, val + pos, sizeof(attr.type)); pos += sizeof(attr.type); if (pos + sizeof(attr.kind) > len) { fprintf(stderr, "overflow array item kind\n"); sqlite3_finalize(sql); return false; } memcpy(&attr.kind, val + pos, sizeof(attr.kind)); pos += sizeof(attr.kind); if (attr.kind == akBoolean) { if (pos + sizeof(attr.boolValue) > len) { fprintf(stderr, "overflow array boolean item\n"); sqlite3_finalize(sql); return false; } memcpy(&attr.boolValue, val + pos, sizeof(attr.boolValue)); pos += sizeof(attr.boolValue); } else if (attr.kind == akInteger) { if (pos + sizeof(attr.ulongValue) > len) { fprintf(stderr, "overflow array integer item\n"); sqlite3_finalize(sql); return false; } memcpy(&attr.ulongValue, val + pos, sizeof(attr.ulongValue)); pos += sizeof(attr.ulongValue); } else if (attr.kind == akBinary) { unsigned long size; if (pos + sizeof(size) > len) { fprintf(stderr, "overflow array binary item\n"); sqlite3_finalize(sql); return false; } memcpy(&size, val + pos, sizeof(size)); pos += sizeof(size); if (pos + size > len) { fprintf(stderr, "overflow array binary item\n"); sqlite3_finalize(sql); return false; } attr.bytestrValue.resize(size); for (unsigned long i = 0; i < size; ++i) { attr.bytestrValue[i] = val[pos + i]; } pos += size; } else { fprintf(stderr, "unknown array item\n"); sqlite3_finalize(sql); return false; } value.push_back(attr); } sqlite3_finalize(sql); return true; } // Dump boolean attributes of an object void dump_booleans(sqlite3* db, long long oid) { int rv; unsigned long count; sqlite3_stmt* sqlcnt = NULL; sqlite3_stmt* sqlid = NULL; std::string commandcnt = "select count(id) from attribute_boolean where object_id=?;"; std::string commandid = "select id from attribute_boolean where object_id=?;"; rv = sqlite3_prepare_v2(db, commandcnt.c_str(), -1, &sqlcnt, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } rv = sqlite3_bind_int64(sqlcnt, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } while ((rv = sqlite3_step(sqlcnt)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } count = sqlite3_column_int(sqlcnt, 0); sqlite3_finalize(sqlcnt); if (count == 0) return; printf("%lu boolean attributes for object %lld\n", count, oid); rv = sqlite3_prepare_v2(db, commandid.c_str(), -1, &sqlid, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } rv = sqlite3_bind_int64(sqlid, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } while (count-- > 0) { while ((rv = sqlite3_step(sqlid)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { if (rv != SQLITE_DONE) { fprintf(stderr, "can't get next object id: %d(%s)\n", rv, sqlite3_errmsg(db)); } sqlite3_finalize(sqlid); return; } long long id = sqlite3_column_int64(sqlid, 0); uint64_t type; uint8_t value; if (!getBool(db, oid, id, type, value)) { return; } dumpULong(type); if ((uint64_t)((uint32_t)type) != type) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) type, 48); printf("\n"); } dumpBool1(value); printf("\n"); } } // Dump integer attributes of an object void dump_integers(sqlite3* db, long long oid) { int rv; unsigned long count; sqlite3_stmt* sqlcnt = NULL; sqlite3_stmt* sqlid = NULL; std::string commandcnt = "select count(id) from attribute_integer where object_id=?;"; std::string commandid = "select id from attribute_integer where object_id=?;"; rv = sqlite3_prepare_v2(db, commandcnt.c_str(), -1, &sqlcnt, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } rv = sqlite3_bind_int64(sqlcnt, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } while ((rv = sqlite3_step(sqlcnt)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } count = sqlite3_column_int(sqlcnt, 0); sqlite3_finalize(sqlcnt); if (count == 0) return; printf("%lu integer attributes for object %lld\n", count, oid); rv = sqlite3_prepare_v2(db, commandid.c_str(), -1, &sqlid, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } rv = sqlite3_bind_int64(sqlid, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } while (count-- > 0) { while ((rv = sqlite3_step(sqlid)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { if (rv != SQLITE_DONE) { fprintf(stderr, "can't get next object id: %d(%s)\n", rv, sqlite3_errmsg(db)); } sqlite3_finalize(sqlid); return; } long long id = sqlite3_column_int64(sqlid, 0); uint64_t type; uint64_t value; if (!getULong(db, oid, id, type, value)) { return; } dumpULong(type); if ((uint64_t)((uint32_t)type) != type) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) type, 48); printf("\n"); } dumpULong(value); dumpCKx(type, value, 48); printf("\n"); } } // Dump binary attributes of an object void dump_binaries(sqlite3* db, long long oid) { int rv; unsigned long count; sqlite3_stmt* sqlcnt = NULL; sqlite3_stmt* sqlid = NULL; std::string commandcnt = "select count(id) from attribute_binary where object_id=?;"; std::string commandid = "select id from attribute_binary where object_id=?;"; rv = sqlite3_prepare_v2(db, commandcnt.c_str(), -1, &sqlcnt, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } rv = sqlite3_bind_int64(sqlcnt, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } while ((rv = sqlite3_step(sqlcnt)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } count = sqlite3_column_int(sqlcnt, 0); sqlite3_finalize(sqlcnt); if (count == 0) return; printf("%lu binary attributes for object %lld\n", count, oid); rv = sqlite3_prepare_v2(db, commandid.c_str(), -1, &sqlid, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } rv = sqlite3_bind_int64(sqlid, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } while (count-- > 0) { while ((rv = sqlite3_step(sqlid)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { if (rv != SQLITE_DONE) { fprintf(stderr, "can't get next object id: %d(%s)\n", rv, sqlite3_errmsg(db)); } sqlite3_finalize(sqlid); return; } long long id = sqlite3_column_int64(sqlid, 0); uint64_t type; std::vector value; if (!getBytes(db, oid, id, type, value)) { return; } dumpULong(type); if ((uint64_t)((uint32_t)type) != type) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) type, 48); printf("\n"); } dumpULong((uint64_t) value.size()); printf("(length %lu)\n", (unsigned long) value.size()); dumpBytes(value); } } // Dump array attributes of an object void dump_arrays(sqlite3* db, long long oid) { int rv; unsigned long count; sqlite3_stmt* sqlcnt = NULL; sqlite3_stmt* sqlid = NULL; std::string commandcnt = "select count(id) from attribute_array where object_id=?;"; std::string commandid = "select id from attribute_array where object_id=?;"; rv = sqlite3_prepare_v2(db, commandcnt.c_str(), -1, &sqlcnt, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } rv = sqlite3_bind_int64(sqlcnt, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } while ((rv = sqlite3_step(sqlcnt)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } count = sqlite3_column_int(sqlcnt, 0); sqlite3_finalize(sqlcnt); if (count == 0) return; printf("%lu array attributes for object %lld\n", count, oid); rv = sqlite3_prepare_v2(db, commandid.c_str(), -1, &sqlid, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } rv = sqlite3_bind_int64(sqlid, 1, oid); if (rv != SQLITE_OK) { fprintf(stderr, "can't bind the object id: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } while (count-- > 0) { while ((rv = sqlite3_step(sqlid)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { if (rv != SQLITE_DONE) { fprintf(stderr, "can't get next object id: %d(%s)\n", rv, sqlite3_errmsg(db)); } sqlite3_finalize(sqlid); return; } long long id = sqlite3_column_int64(sqlid, 0); uint64_t type; std::vector value; if (!getArray(db, oid, id, type, value)) { return; } dumpULong(type); if ((uint64_t)((uint32_t)type) != type) { printf("overflow attribute type\n"); } else { dumpCKA((unsigned long) type, 48); printf("\n"); } dumpULong((uint64_t) value.size()); printf("(length %lu)\n", (unsigned long) value.size()); dumpArray(value); } } // Dump an object void dump_object(sqlite3* db, long long oid) { printf("dump object id=%lld\n", oid); dump_booleans(db, oid); dump_integers(db, oid); dump_binaries(db, oid); dump_arrays(db, oid); } // Core function void dump(sqlite3* db) { int rv; unsigned long count; sqlite3_stmt* sqlcnt = NULL; sqlite3_stmt* sqlid = NULL; std::string commandcnt = "select count(id) from object;"; std::string commandid = "select id from object;"; rv = sqlite3_prepare_v2(db, commandcnt.c_str(), -1, &sqlcnt, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } while ((rv = sqlite3_step(sqlcnt)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlcnt); return; } count = sqlite3_column_int(sqlcnt, 0); sqlite3_finalize(sqlcnt); printf("%lu objects\n", count); rv = sqlite3_prepare_v2(db, commandid.c_str(), -1, &sqlid, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't count the object table: %d(%s)\n", rv, sqlite3_errmsg(db)); sqlite3_finalize(sqlid); return; } while (count-- > 0) { while ((rv = sqlite3_step(sqlid)) == SQLITE_BUSY) { sched_yield(); } if (rv != SQLITE_ROW) { if (rv != SQLITE_DONE) { fprintf(stderr, "can't get next object id: %d(%s)\n", rv, sqlite3_errmsg(db)); } sqlite3_finalize(sqlid); return; } long long oid = sqlite3_column_int64(sqlid, 0); dump_object(db, oid); } } // Display the usage void usage() { printf("SoftHSM dump tool. From SoftHSM v2 database.\n"); printf("Usage: softhsm2-dump-db path\n"); } // Check the existence of a table void check_table_exist(sqlite3* db, std::string name) { int rv; std::string command = "select count(id) from " + name + ";"; rv = sqlite3_exec(db, command.c_str(), NULL, NULL, NULL); if (rv != SQLITE_OK) { fprintf(stderr, "can't find '%s' table\n", name.c_str()); sqlite3_close(db); exit(0); } } // The main function int main(int argc, char* argv[]) { int rv; sqlite3* db = NULL; if (argc != 2) { usage(); exit(0); } rv = sqlite3_open_v2(argv[1], &db, SQLITE_OPEN_READONLY, NULL); if (rv != SQLITE_OK) { if (db == NULL) { fprintf(stderr, "can't open database file %s\n", argv[1]); } else { fprintf(stderr, "can't open database file %s: %d(%s)\n", argv[1], rv, sqlite3_errmsg(db)); } sqlite3_close(db); exit(0); } // No user version to check check_table_exist(db, "object"); check_table_exist(db, "attribute_boolean"); check_table_exist(db, "attribute_integer"); check_table_exist(db, "attribute_binary"); check_table_exist(db, "attribute_array"); printf("Dump of object file \"%s\"\n", argv[1]); dump(db); sqlite3_close(db); exit(1); } softhsm-2.0.0/src/bin/dump/tables.h0000664000175000017500000005437312533040716014063 00000000000000/* * Copyright (c) 2013 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** tables.h Tables from PKCS#11 specs. *****************************************************************************/ #ifndef _SOFTHSM_V2_TABLES_H #define _SOFTHSM_V2_TABLES_H #include "OSAttributes.h" // Attribute types void fill_CKA_table(std::map &t) { t[CKA_CLASS] = "CKA_CLASS"; t[CKA_TOKEN] = "CKA_TOKEN"; t[CKA_PRIVATE] = "CKA_PRIVATE"; t[CKA_LABEL] = "CKA_LABEL"; t[CKA_APPLICATION] = "CKA_APPLICATION"; t[CKA_VALUE] = "CKA_VALUE"; t[CKA_OBJECT_ID] = "CKA_OBJECT_ID"; t[CKA_CERTIFICATE_TYPE] = "CKA_CERTIFICATE_TYPE"; t[CKA_ISSUER] = "CKA_ISSUER"; t[CKA_SERIAL_NUMBER] = "CKA_SERIAL_NUMBER"; t[CKA_AC_ISSUER] = "CKA_AC_ISSUER"; t[CKA_OWNER] = "CKA_OWNER"; t[CKA_ATTR_TYPES] = "CKA_ATTR_TYPES"; t[CKA_TRUSTED] = "CKA_TRUSTED"; t[CKA_CERTIFICATE_CATEGORY] = "CKA_CERTIFICATE_CATEGORY"; t[CKA_JAVA_MIDP_SECURITY_DOMAIN] = "CKA_JAVA_MIDP_SECURITY_DOMAIN"; t[CKA_URL] = "CKA_URL"; t[CKA_HASH_OF_SUBJECT_PUBLIC_KEY] = "CKA_HASH_OF_SUBJECT_PUBLIC_KEY"; t[CKA_HASH_OF_ISSUER_PUBLIC_KEY] = "CKA_HASH_OF_ISSUER_PUBLIC_KEY"; t[CKA_NAME_HASH_ALGORITHM] = "CKA_NAME_HASH_ALGORITHM"; t[CKA_CHECK_VALUE] = "CKA_CHECK_VALUE"; t[CKA_KEY_TYPE] = "CKA_KEY_TYPE"; t[CKA_SUBJECT] = "CKA_SUBJECT"; t[CKA_ID] = "CKA_ID"; t[CKA_SENSITIVE] = "CKA_SENSITIVE"; t[CKA_ENCRYPT] = "CKA_ENCRYPT"; t[CKA_DECRYPT] = "CKA_DECRYPT"; t[CKA_WRAP] = "CKA_WRAP"; t[CKA_UNWRAP] = "CKA_UNWRAP"; t[CKA_SIGN] = "CKA_SIGN"; t[CKA_SIGN_RECOVER] = "CKA_SIGN_RECOVER"; t[CKA_VERIFY] = "CKA_VERIFY"; t[CKA_VERIFY_RECOVER] = "CKA_VERIFY_RECOVER"; t[CKA_DERIVE] = "CKA_DERIVE"; t[CKA_START_DATE] = "CKA_START_DATE"; t[CKA_END_DATE] = "CKA_END_DATE"; t[CKA_MODULUS] = "CKA_MODULUS"; t[CKA_MODULUS_BITS] = "CKA_MODULUS_BITS"; t[CKA_PUBLIC_EXPONENT] = "CKA_PUBLIC_EXPONENT"; t[CKA_PRIVATE_EXPONENT] = "CKA_PRIVATE_EXPONENT"; t[CKA_PRIME_1] = "CKA_PRIME_1"; t[CKA_PRIME_2] = "CKA_PRIME_2"; t[CKA_EXPONENT_1] = "CKA_EXPONENT_1"; t[CKA_EXPONENT_2] = "CKA_EXPONENT_2"; t[CKA_COEFFICIENT] = "CKA_COEFFICIENT"; t[CKA_PRIME] = "CKA_PRIME"; t[CKA_SUBPRIME] = "CKA_SUBPRIME"; t[CKA_BASE] = "CKA_BASE"; t[CKA_PRIME_BITS] = "CKA_PRIME_BITS"; t[CKA_SUBPRIME_BITS] = "CKA_SUBPRIME_BITS"; t[CKA_VALUE_BITS] = "CKA_VALUE_BITS"; t[CKA_VALUE_LEN] = "CKA_VALUE_LEN"; t[CKA_EXTRACTABLE] = "CKA_EXTRACTABLE"; t[CKA_LOCAL] = "CKA_LOCAL"; t[CKA_NEVER_EXTRACTABLE] = "CKA_NEVER_EXTRACTABLE"; t[CKA_ALWAYS_SENSITIVE] = "CKA_ALWAYS_SENSITIVE"; t[CKA_KEY_GEN_MECHANISM] = "CKA_KEY_GEN_MECHANISM"; t[CKA_MODIFIABLE] = "CKA_MODIFIABLE"; t[CKA_COPYABLE] = "CKA_COPYABLE"; t[CKA_EC_PARAMS] = "CKA_EC_PARAMS"; t[CKA_EC_POINT] = "CKA_EC_POINT"; t[CKA_SECONDARY_AUTH] = "CKA_SECONDARY_AUTH"; t[CKA_AUTH_PIN_FLAGS] = "CKA_AUTH_PIN_FLAGS"; t[CKA_ALWAYS_AUTHENTICATE] = "CKA_ALWAYS_AUTHENTICATE"; t[CKA_WRAP_WITH_TRUSTED] = "CKA_WRAP_WITH_TRUSTED"; t[CKA_OTP_FORMAT] = "CKA_OTP_FORMAT"; t[CKA_OTP_LENGTH] = "CKA_OTP_LENGTH"; t[CKA_OTP_TIME_INTERVAL] = "CKA_OTP_TIME_INTERVAL"; t[CKA_OTP_USER_FRIENDLY_MODE] = "CKA_OTP_USER_FRIENDLY_MODE"; t[CKA_OTP_CHALLENGE_REQUIREMENT] = "CKA_OTP_CHALLENGE_REQUIREMENT"; t[CKA_OTP_TIME_REQUIREMENT] = "CKA_OTP_TIME_REQUIREMENT"; t[CKA_OTP_COUNTER_REQUIREMENT] = "CKA_OTP_COUNTER_REQUIREMENT"; t[CKA_OTP_PIN_REQUIREMENT] = "CKA_OTP_PIN_REQUIREMENT"; t[CKA_OTP_COUNTER] = "CKA_OTP_COUNTER"; t[CKA_OTP_TIME] = "CKA_OTP_TIME"; t[CKA_OTP_USER_IDENTIFIER] = "CKA_OTP_USER_IDENTIFIER"; t[CKA_OTP_SERVICE_IDENTIFIER] = "CKA_OTP_SERVICE_IDENTIFIER"; t[CKA_OTP_SERVICE_LOGO] = "CKA_OTP_SERVICE_LOGO"; t[CKA_OTP_SERVICE_LOGO_TYPE] = "CKA_OTP_SERVICE_LOGO_TYPE"; t[CKA_GOSTR3410_PARAMS] = "CKA_GOSTR3410_PARAMS"; t[CKA_GOSTR3411_PARAMS] = "CKA_GOSTR3411_PARAMS"; t[CKA_GOST28147_PARAMS] = "CKA_GOST28147_PARAMS"; t[CKA_HW_FEATURE_TYPE] = "CKA_HW_FEATURE_TYPE"; t[CKA_RESET_ON_INIT] = "CKA_RESET_ON_INIT"; t[CKA_HAS_RESET] = "CKA_HAS_RESET"; t[CKA_PIXEL_X] = "CKA_PIXEL_X"; t[CKA_PIXEL_Y] = "CKA_PIXEL_Y"; t[CKA_RESOLUTION] = "CKA_RESOLUTION"; t[CKA_CHAR_ROWS] = "CKA_CHAR_ROWS"; t[CKA_CHAR_COLUMNS] = "CKA_CHAR_COLUMNS"; t[CKA_COLOR] = "CKA_COLOR"; t[CKA_BITS_PER_PIXEL] = "CKA_BITS_PER_PIXEL"; t[CKA_CHAR_SETS] = "CKA_CHAR_SETS"; t[CKA_ENCODING_METHODS] = "CKA_ENCODING_METHODS"; t[CKA_MIME_TYPES] = "CKA_MIME_TYPES"; t[CKA_MECHANISM_TYPE] = "CKA_MECHANISM_TYPE"; t[CKA_REQUIRED_CMS_ATTRIBUTES] = "CKA_REQUIRED_CMS_ATTRIBUTES"; t[CKA_DEFAULT_CMS_ATTRIBUTES] = "CKA_DEFAULT_CMS_ATTRIBUTES"; t[CKA_SUPPORTED_CMS_ATTRIBUTES] = "CKA_SUPPORTED_CMS_ATTRIBUTES"; t[CKA_WRAP_TEMPLATE] = "CKA_WRAP_TEMPLATE"; t[CKA_UNWRAP_TEMPLATE] = "CKA_UNWRAP_TEMPLATE"; t[CKA_DERIVE_TEMPLATE] = "CKA_DERIVE_TEMPLATE"; t[CKA_ALLOWED_MECHANISMS] = "CKA_ALLOWED_MECHANISMS"; // local extensions t[CKA_VENDOR_SOFTHSM] = "CKA_VENDOR_SOFTHSM"; t[CKA_OS_TOKENLABEL] = "CKA_OS_TOKENLABEL"; t[CKA_OS_TOKENSERIAL] = "CKA_OS_TOKENSERIAL"; t[CKA_OS_TOKENFLAGS] = "CKA_OS_TOKENFLAGS"; t[CKA_OS_SOPIN] = "CKA_OS_SOPIN"; t[CKA_OS_USERPIN] = "CKA_OS_USERPIN"; } void fill_CKM_table(std::map &t) { t[CKM_RSA_PKCS_KEY_PAIR_GEN] = "CKM_RSA_PKCS_KEY_PAIR_GEN"; t[CKM_RSA_PKCS] = "CKM_RSA_PKCS"; t[CKM_RSA_9796] = "CKM_RSA_9796"; t[CKM_RSA_X_509] = "CKM_RSA_X_509"; t[CKM_MD2_RSA_PKCS] = "CKM_MD2_RSA_PKCS"; t[CKM_MD5_RSA_PKCS] = "CKM_MD5_RSA_PKCS"; t[CKM_SHA1_RSA_PKCS] = "CKM_SHA1_RSA_PKCS"; t[CKM_RIPEMD128_RSA_PKCS] = "CKM_RIPEMD128_RSA_PKCS"; t[CKM_RIPEMD160_RSA_PKCS] = "CKM_RIPEMD160_RSA_PKCS"; t[CKM_RSA_PKCS_OAEP] = "CKM_RSA_PKCS_OAEP"; t[CKM_RSA_X9_31_KEY_PAIR_GEN] = "CKM_RSA_X9_31_KEY_PAIR_GEN"; t[CKM_RSA_X9_31] = "CKM_RSA_X9_31"; t[CKM_SHA1_RSA_X9_31] = "CKM_SHA1_RSA_X9_31"; t[CKM_RSA_PKCS_PSS] = "CKM_RSA_PKCS_PSS"; t[CKM_SHA1_RSA_PKCS_PSS] = "CKM_SHA1_RSA_PKCS_PSS"; t[CKM_DSA_KEY_PAIR_GEN] = "CKM_DSA_KEY_PAIR_GEN"; t[CKM_DSA] = "CKM_DSA"; t[CKM_DSA_SHA1] = "CKM_DSA_SHA1"; t[CKM_DSA_SHA224] = "CKM_DSA_SHA224"; t[CKM_DSA_SHA256] = "CKM_DSA_SHA256"; t[CKM_DSA_SHA384] = "CKM_DSA_SHA384"; t[CKM_DSA_SHA512] = "CKM_DSA_SHA512"; t[CKM_DH_PKCS_KEY_PAIR_GEN] = "CKM_DH_PKCS_KEY_PAIR_GEN"; t[CKM_DH_PKCS_DERIVE] = "CKM_DH_PKCS_DERIVE"; t[CKM_X9_42_DH_KEY_PAIR_GEN] = "CKM_X9_42_DH_KEY_PAIR_GEN"; t[CKM_X9_42_DH_DERIVE] = "CKM_X9_42_DH_DERIVE"; t[CKM_X9_42_DH_HYBRID_DERIVE] = "CKM_X9_42_DH_HYBRID_DERIVE"; t[CKM_X9_42_MQV_DERIVE] = "CKM_X9_42_MQV_DERIVE"; t[CKM_SHA256_RSA_PKCS] = "CKM_SHA256_RSA_PKCS"; t[CKM_SHA384_RSA_PKCS] = "CKM_SHA384_RSA_PKCS"; t[CKM_SHA512_RSA_PKCS] = "CKM_SHA512_RSA_PKCS"; t[CKM_SHA256_RSA_PKCS_PSS] = "CKM_SHA256_RSA_PKCS_PSS"; t[CKM_SHA384_RSA_PKCS_PSS] = "CKM_SHA384_RSA_PKCS_PSS"; t[CKM_SHA512_RSA_PKCS_PSS] = "CKM_SHA512_RSA_PKCS_PSS"; t[CKM_SHA224_RSA_PKCS] = "CKM_SHA224_RSA_PKCS"; t[CKM_SHA224_RSA_PKCS_PSS] = "CKM_SHA224_RSA_PKCS_PSS"; t[CKM_RC2_KEY_GEN] = "CKM_RC2_KEY_GEN"; t[CKM_RC2_ECB] = "CKM_RC2_ECB"; t[CKM_RC2_CBC] = "CKM_RC2_CBC"; t[CKM_RC2_MAC] = "CKM_RC2_MAC"; t[CKM_RC2_MAC_GENERAL] = "CKM_RC2_MAC_GENERAL"; t[CKM_RC2_CBC_PAD] = "CKM_RC2_CBC_PAD"; t[CKM_RC4_KEY_GEN] = "CKM_RC4_KEY_GEN"; t[CKM_RC4] = "CKM_RC4"; t[CKM_DES_KEY_GEN] = "CKM_DES_KEY_GEN"; t[CKM_DES_ECB] = "CKM_DES_ECB"; t[CKM_DES_CBC] = "CKM_DES_CBC"; t[CKM_DES_MAC] = "CKM_DES_MAC"; t[CKM_DES_MAC_GENERAL] = "CKM_DES_MAC_GENERAL"; t[CKM_DES_CBC_PAD] = "CKM_DES_CBC_PAD"; t[CKM_DES2_KEY_GEN] = "CKM_DES2_KEY_GEN"; t[CKM_DES3_KEY_GEN] = "CKM_DES3_KEY_GEN"; t[CKM_DES3_ECB] = "CKM_DES3_ECB"; t[CKM_DES3_CBC] = "CKM_DES3_CBC"; t[CKM_DES3_MAC] = "CKM_DES3_MAC"; t[CKM_DES3_MAC_GENERAL] = "CKM_DES3_MAC_GENERAL"; t[CKM_DES3_CBC_PAD] = "CKM_DES3_CBC_PAD"; t[CKM_DES3_CMAC_GENERAL] = "CKM_DES3_CMAC_GENERAL"; t[CKM_DES3_CMAC] = "CKM_DES3_CMAC"; t[CKM_CDMF_KEY_GEN] = "CKM_CDMF_KEY_GEN"; t[CKM_CDMF_ECB] = "CKM_CDMF_ECB"; t[CKM_CDMF_CBC] = "CKM_CDMF_CBC"; t[CKM_CDMF_MAC] = "CKM_CDMF_MAC"; t[CKM_CDMF_MAC_GENERAL] = "CKM_CDMF_MAC_GENERAL"; t[CKM_CDMF_CBC_PAD] = "CKM_CDMF_CBC_PAD"; t[CKM_DES_OFB64] = "CKM_DES_OFB64"; t[CKM_DES_OFB8] = "CKM_DES_OFB8"; t[CKM_DES_CFB64] = "CKM_DES_CFB64"; t[CKM_DES_CFB8] = "CKM_DES_CFB8"; t[CKM_MD2] = "CKM_MD2"; t[CKM_MD2_HMAC] = "CKM_MD2_HMAC"; t[CKM_MD2_HMAC_GENERAL] = "CKM_MD2_HMAC_GENERAL"; t[CKM_MD5] = "CKM_MD5"; t[CKM_MD5_HMAC] = "CKM_MD5_HMAC"; t[CKM_MD5_HMAC_GENERAL] = "CKM_MD5_HMAC_GENERAL"; t[CKM_SHA_1] = "CKM_SHA_1"; t[CKM_SHA_1_HMAC] = "CKM_SHA_1_HMAC"; t[CKM_SHA_1_HMAC_GENERAL] = "CKM_SHA_1_HMAC_GENERAL"; t[CKM_RIPEMD128] = "CKM_RIPEMD128"; t[CKM_RIPEMD128_HMAC] = "CKM_RIPEMD128_HMAC"; t[CKM_RIPEMD128_HMAC_GENERAL] = "CKM_RIPEMD128_HMAC_GENERAL"; t[CKM_RIPEMD160] = "CKM_RIPEMD160"; t[CKM_RIPEMD160_HMAC] = "CKM_RIPEMD160_HMAC"; t[CKM_RIPEMD160_HMAC_GENERAL] = "CKM_RIPEMD160_HMAC_GENERAL"; t[CKM_SHA256] = "CKM_SHA256"; t[CKM_SHA256_HMAC] = "CKM_SHA256_HMAC"; t[CKM_SHA256_HMAC_GENERAL] = "CKM_SHA256_HMAC_GENERAL"; t[CKM_SHA224] = "CKM_SHA224"; t[CKM_SHA224_HMAC] = "CKM_SHA224_HMAC"; t[CKM_SHA224_HMAC_GENERAL] = "CKM_SHA224_HMAC_GENERAL"; t[CKM_SHA384] = "CKM_SHA384"; t[CKM_SHA384_HMAC] = "CKM_SHA384_HMAC"; t[CKM_SHA384_HMAC_GENERAL] = "CKM_SHA384_HMAC_GENERAL"; t[CKM_SHA512] = "CKM_SHA512"; t[CKM_SHA512_HMAC] = "CKM_SHA512_HMAC"; t[CKM_SHA512_HMAC_GENERAL] = "CKM_SHA512_HMAC_GENERAL"; t[CKM_SECURID_KEY_GEN] = "CKM_SECURID_KEY_GEN"; t[CKM_SECURID] = "CKM_SECURID"; t[CKM_HOTP_KEY_GEN] = "CKM_HOTP_KEY_GEN"; t[CKM_HOTP] = "CKM_HOTP"; t[CKM_ACTI] = "CKM_ACTI"; t[CKM_ACTI_KEY_GEN] = "CKM_ACTI_KEY_GEN"; t[CKM_CAST_KEY_GEN] = "CKM_CAST_KEY_GEN"; t[CKM_CAST_ECB] = "CKM_CAST_ECB"; t[CKM_CAST_CBC] = "CKM_CAST_CBC"; t[CKM_CAST_MAC] = "CKM_CAST_MAC"; t[CKM_CAST_MAC_GENERAL] = "CKM_CAST_MAC_GENERAL"; t[CKM_CAST_CBC_PAD] = "CKM_CAST_CBC_PAD"; t[CKM_CAST3_KEY_GEN] = "CKM_CAST3_KEY_GEN"; t[CKM_CAST3_ECB] = "CKM_CAST3_ECB"; t[CKM_CAST3_CBC] = "CKM_CAST3_CBC"; t[CKM_CAST3_MAC] = "CKM_CAST3_MAC"; t[CKM_CAST3_MAC_GENERAL] = "CKM_CAST3_MAC_GENERAL"; t[CKM_CAST3_CBC_PAD] = "CKM_CAST3_CBC_PAD"; t[CKM_CAST5_KEY_GEN] = "CKM_CAST5_KEY_GEN"; t[CKM_CAST128_KEY_GEN] = "CKM_CAST128_KEY_GEN"; t[CKM_CAST5_ECB] = "CKM_CAST5_ECB"; t[CKM_CAST128_ECB] = "CKM_CAST128_ECB"; t[CKM_CAST5_CBC] = "CKM_CAST5_CBC"; t[CKM_CAST128_CBC] = "CKM_CAST128_CBC"; t[CKM_CAST5_MAC] = "CKM_CAST5_MAC"; t[CKM_CAST128_MAC] = "CKM_CAST128_MAC"; t[CKM_CAST5_MAC_GENERAL] = "CKM_CAST5_MAC_GENERAL"; t[CKM_CAST128_MAC_GENERAL] = "CKM_CAST128_MAC_GENERAL"; t[CKM_CAST5_CBC_PAD] = "CKM_CAST5_CBC_PAD"; t[CKM_CAST128_CBC_PAD] = "CKM_CAST128_CBC_PAD"; t[CKM_RC5_KEY_GEN] = "CKM_RC5_KEY_GEN"; t[CKM_RC5_ECB] = "CKM_RC5_ECB"; t[CKM_RC5_CBC] = "CKM_RC5_CBC"; t[CKM_RC5_MAC] = "CKM_RC5_MAC"; t[CKM_RC5_MAC_GENERAL] = "CKM_RC5_MAC_GENERAL"; t[CKM_RC5_CBC_PAD] = "CKM_RC5_CBC_PAD"; t[CKM_IDEA_KEY_GEN] = "CKM_IDEA_KEY_GEN"; t[CKM_IDEA_ECB] = "CKM_IDEA_ECB"; t[CKM_IDEA_CBC] = "CKM_IDEA_CBC"; t[CKM_IDEA_MAC] = "CKM_IDEA_MAC"; t[CKM_IDEA_MAC_GENERAL] = "CKM_IDEA_MAC_GENERAL"; t[CKM_IDEA_CBC_PAD] = "CKM_IDEA_CBC_PAD"; t[CKM_GENERIC_SECRET_KEY_GEN] = "CKM_GENERIC_SECRET_KEY_GEN"; t[CKM_CONCATENATE_BASE_AND_KEY] = "CKM_CONCATENATE_BASE_AND_KEY"; t[CKM_CONCATENATE_BASE_AND_DATA] = "CKM_CONCATENATE_BASE_AND_DATA"; t[CKM_CONCATENATE_DATA_AND_BASE] = "CKM_CONCATENATE_DATA_AND_BASE"; t[CKM_XOR_BASE_AND_DATA] = "CKM_XOR_BASE_AND_DATA"; t[CKM_EXTRACT_KEY_FROM_KEY] = "CKM_EXTRACT_KEY_FROM_KEY"; t[CKM_SSL3_PRE_MASTER_KEY_GEN] = "CKM_SSL3_PRE_MASTER_KEY_GEN"; t[CKM_SSL3_MASTER_KEY_DERIVE] = "CKM_SSL3_MASTER_KEY_DERIVE"; t[CKM_SSL3_KEY_AND_MAC_DERIVE] = "CKM_SSL3_KEY_AND_MAC_DERIVE"; t[CKM_SSL3_MASTER_KEY_DERIVE_DH] = "CKM_SSL3_MASTER_KEY_DERIVE_DH"; t[CKM_TLS_PRE_MASTER_KEY_GEN] = "CKM_TLS_PRE_MASTER_KEY_GEN"; t[CKM_TLS_MASTER_KEY_DERIVE] = "CKM_TLS_MASTER_KEY_DERIVE"; t[CKM_TLS_KEY_AND_MAC_DERIVE] = "CKM_TLS_KEY_AND_MAC_DERIVE"; t[CKM_TLS_MASTER_KEY_DERIVE_DH] = "CKM_TLS_MASTER_KEY_DERIVE_DH"; t[CKM_TLS_PRF] = "CKM_TLS_PRF"; t[CKM_SSL3_MD5_MAC] = "CKM_SSL3_MD5_MAC"; t[CKM_SSL3_SHA1_MAC] = "CKM_SSL3_SHA1_MAC"; t[CKM_MD5_KEY_DERIVATION] = "CKM_MD5_KEY_DERIVATION"; t[CKM_MD2_KEY_DERIVATION] = "CKM_MD2_KEY_DERIVATION"; t[CKM_SHA1_KEY_DERIVATION] = "CKM_SHA1_KEY_DERIVATION"; t[CKM_SHA256_KEY_DERIVATION] = "CKM_SHA256_KEY_DERIVATION"; t[CKM_SHA384_KEY_DERIVATION] = "CKM_SHA384_KEY_DERIVATION"; t[CKM_SHA512_KEY_DERIVATION] = "CKM_SHA512_KEY_DERIVATION"; t[CKM_SHA224_KEY_DERIVATION] = "CKM_SHA224_KEY_DERIVATION"; t[CKM_PBE_MD2_DES_CBC] = "CKM_PBE_MD2_DES_CBC"; t[CKM_PBE_MD5_DES_CBC] = "CKM_PBE_MD5_DES_CBC"; t[CKM_PBE_MD5_CAST_CBC] = "CKM_PBE_MD5_CAST_CBC"; t[CKM_PBE_MD5_CAST3_CBC] = "CKM_PBE_MD5_CAST3_CBC"; t[CKM_PBE_MD5_CAST5_CBC] = "CKM_PBE_MD5_CAST5_CBC"; t[CKM_PBE_MD5_CAST128_CBC] = "CKM_PBE_MD5_CAST128_CBC"; t[CKM_PBE_SHA1_CAST5_CBC] = "CKM_PBE_SHA1_CAST5_CBC"; t[CKM_PBE_SHA1_CAST128_CBC] = "CKM_PBE_SHA1_CAST128_CBC"; t[CKM_PBE_SHA1_RC4_128] = "CKM_PBE_SHA1_RC4_128"; t[CKM_PBE_SHA1_RC4_40] = "CKM_PBE_SHA1_RC4_40"; t[CKM_PBE_SHA1_DES3_EDE_CBC] = "CKM_PBE_SHA1_DES3_EDE_CBC"; t[CKM_PBE_SHA1_DES2_EDE_CBC] = "CKM_PBE_SHA1_DES2_EDE_CBC"; t[CKM_PBE_SHA1_RC2_128_CBC] = "CKM_PBE_SHA1_RC2_128_CBC"; t[CKM_PBE_SHA1_RC2_40_CBC] = "CKM_PBE_SHA1_RC2_40_CBC"; t[CKM_PKCS5_PBKD2] = "CKM_PKCS5_PBKD2"; t[CKM_PBA_SHA1_WITH_SHA1_HMAC] = "CKM_PBA_SHA1_WITH_SHA1_HMAC"; t[CKM_WTLS_PRE_MASTER_KEY_GEN] = "CKM_WTLS_PRE_MASTER_KEY_GEN"; t[CKM_WTLS_MASTER_KEY_DERIVE] = "CKM_WTLS_MASTER_KEY_DERIVE"; t[CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC] = "CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC"; t[CKM_WTLS_PRF] = "CKM_WTLS_PRF"; t[CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE] = "CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE"; t[CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE] = "CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE"; t[CKM_KEY_WRAP_LYNKS] = "CKM_KEY_WRAP_LYNKS"; t[CKM_KEY_WRAP_SET_OAEP] = "CKM_KEY_WRAP_SET_OAEP"; t[CKM_CMS_SIG] = "CKM_CMS_SIG"; t[CKM_KIP_DERIVE] = "CKM_KIP_DERIVE"; t[CKM_KIP_WRAP] = "CKM_KIP_WRAP"; t[CKM_KIP_MAC] = "CKM_KIP_MAC"; t[CKM_CAMELLIA_KEY_GEN] = "CKM_CAMELLIA_KEY_GEN"; t[CKM_CAMELLIA_ECB] = "CKM_CAMELLIA_ECB"; t[CKM_CAMELLIA_CBC] = "CKM_CAMELLIA_CBC"; t[CKM_CAMELLIA_MAC] = "CKM_CAMELLIA_MAC"; t[CKM_CAMELLIA_MAC_GENERAL] = "CKM_CAMELLIA_MAC_GENERAL"; t[CKM_CAMELLIA_CBC_PAD] = "CKM_CAMELLIA_CBC_PAD"; t[CKM_CAMELLIA_ECB_ENCRYPT_DATA] = "CKM_CAMELLIA_ECB_ENCRYPT_DATA"; t[CKM_CAMELLIA_CBC_ENCRYPT_DATA] = "CKM_CAMELLIA_CBC_ENCRYPT_DATA"; t[CKM_CAMELLIA_CTR] = "CKM_CAMELLIA_CTR"; t[CKM_ARIA_KEY_GEN] = "CKM_ARIA_KEY_GEN"; t[CKM_ARIA_ECB] = "CKM_ARIA_ECB"; t[CKM_ARIA_CBC] = "CKM_ARIA_CBC"; t[CKM_ARIA_MAC] = "CKM_ARIA_MAC"; t[CKM_ARIA_MAC_GENERAL] = "CKM_ARIA_MAC_GENERAL"; t[CKM_ARIA_CBC_PAD] = "CKM_ARIA_CBC_PAD"; t[CKM_ARIA_ECB_ENCRYPT_DATA] = "CKM_ARIA_ECB_ENCRYPT_DATA"; t[CKM_ARIA_CBC_ENCRYPT_DATA] = "CKM_ARIA_CBC_ENCRYPT_DATA"; t[CKM_SEED_KEY_GEN] = "CKM_SEED_KEY_GEN"; t[CKM_SEED_ECB] = "CKM_SEED_ECB"; t[CKM_SEED_CBC] = "CKM_SEED_CBC"; t[CKM_SEED_MAC] = "CKM_SEED_MAC"; t[CKM_SEED_MAC_GENERAL] = "CKM_SEED_MAC_GENERAL"; t[CKM_SEED_CBC_PAD] = "CKM_SEED_CBC_PAD"; t[CKM_SEED_ECB_ENCRYPT_DATA] = "CKM_SEED_ECB_ENCRYPT_DATA"; t[CKM_SEED_CBC_ENCRYPT_DATA] = "CKM_SEED_CBC_ENCRYPT_DATA"; t[CKM_SKIPJACK_KEY_GEN] = "CKM_SKIPJACK_KEY_GEN"; t[CKM_SKIPJACK_ECB64] = "CKM_SKIPJACK_ECB64"; t[CKM_SKIPJACK_CBC64] = "CKM_SKIPJACK_CBC64"; t[CKM_SKIPJACK_OFB64] = "CKM_SKIPJACK_OFB64"; t[CKM_SKIPJACK_CFB64] = "CKM_SKIPJACK_CFB64"; t[CKM_SKIPJACK_CFB32] = "CKM_SKIPJACK_CFB32"; t[CKM_SKIPJACK_CFB16] = "CKM_SKIPJACK_CFB16"; t[CKM_SKIPJACK_CFB8] = "CKM_SKIPJACK_CFB8"; t[CKM_SKIPJACK_WRAP] = "CKM_SKIPJACK_WRAP"; t[CKM_SKIPJACK_PRIVATE_WRAP] = "CKM_SKIPJACK_PRIVATE_WRAP"; t[CKM_SKIPJACK_RELAYX] = "CKM_SKIPJACK_RELAYX"; t[CKM_KEA_KEY_PAIR_GEN] = "CKM_KEA_KEY_PAIR_GEN"; t[CKM_KEA_KEY_DERIVE] = "CKM_KEA_KEY_DERIVE"; t[CKM_FORTEZZA_TIMESTAMP] = "CKM_FORTEZZA_TIMESTAMP"; t[CKM_BATON_KEY_GEN] = "CKM_BATON_KEY_GEN"; t[CKM_BATON_ECB128] = "CKM_BATON_ECB128"; t[CKM_BATON_ECB96] = "CKM_BATON_ECB96"; t[CKM_BATON_CBC128] = "CKM_BATON_CBC128"; t[CKM_BATON_COUNTER] = "CKM_BATON_COUNTER"; t[CKM_BATON_SHUFFLE] = "CKM_BATON_SHUFFLE"; t[CKM_BATON_WRAP] = "CKM_BATON_WRAP"; t[CKM_ECDSA_KEY_PAIR_GEN] = "CKM_ECDSA_KEY_PAIR_GEN"; t[CKM_EC_KEY_PAIR_GEN] = "CKM_EC_KEY_PAIR_GEN"; t[CKM_ECDSA] = "CKM_ECDSA"; t[CKM_ECDSA_SHA1] = "CKM_ECDSA_SHA1"; t[CKM_ECDSA_SHA224] = "CKM_ECDSA_SHA224"; t[CKM_ECDSA_SHA256] = "CKM_ECDSA_SHA256"; t[CKM_ECDSA_SHA384] = "CKM_ECDSA_SHA384"; t[CKM_ECDSA_SHA512] = "CKM_ECDSA_SHA512"; t[CKM_ECDH1_DERIVE] = "CKM_ECDH1_DERIVE"; t[CKM_ECDH1_COFACTOR_DERIVE] = "CKM_ECDH1_COFACTOR_DERIVE"; t[CKM_ECMQV_DERIVE] = "CKM_ECMQV_DERIVE"; t[CKM_JUNIPER_KEY_GEN] = "CKM_JUNIPER_KEY_GEN"; t[CKM_JUNIPER_ECB128] = "CKM_JUNIPER_ECB128"; t[CKM_JUNIPER_CBC128] = "CKM_JUNIPER_CBC128"; t[CKM_JUNIPER_COUNTER] = "CKM_JUNIPER_COUNTER"; t[CKM_JUNIPER_SHUFFLE] = "CKM_JUNIPER_SHUFFLE"; t[CKM_JUNIPER_WRAP] = "CKM_JUNIPER_WRAP"; t[CKM_FASTHASH] = "CKM_FASTHASH"; t[CKM_AES_KEY_GEN] = "CKM_AES_KEY_GEN"; t[CKM_AES_ECB] = "CKM_AES_ECB"; t[CKM_AES_CBC] = "CKM_AES_CBC"; t[CKM_AES_MAC] = "CKM_AES_MAC"; t[CKM_AES_MAC_GENERAL] = "CKM_AES_MAC_GENERAL"; t[CKM_AES_CBC_PAD] = "CKM_AES_CBC_PAD"; t[CKM_AES_CTR] = "CKM_AES_CTR"; t[CKM_AES_GCM] = "CKM_AES_GCM"; t[CKM_AES_CCM] = "CKM_AES_CCM"; t[CKM_AES_CTS] = "CKM_AES_CTS"; t[CKM_AES_CMAC] = "CKM_AES_CMAC"; t[CKM_AES_CMAC_GENERAL] = "CKM_AES_CMAC_GENERAL"; t[CKM_AES_KEY_WRAP] = "CKM_AES_KEY_WRAP"; t[CKM_BLOWFISH_KEY_GEN] = "CKM_BLOWFISH_KEY_GEN"; t[CKM_AES_KEY_WRAP_PAD] = "CKM_AES_KEY_WRAP_PAD"; t[CKM_BLOWFISH_CBC] = "CKM_BLOWFISH_CBC"; t[CKM_TWOFISH_KEY_GEN] = "CKM_TWOFISH_KEY_GEN"; t[CKM_TWOFISH_CBC] = "CKM_TWOFISH_CBC"; t[CKM_BLOWFISH_CBC_PAD] = "CKM_BLOWFISH_CBC_PAD"; t[CKM_TWOFISH_CBC_PAD] = "CKM_TWOFISH_CBC_PAD"; t[CKM_DES_ECB_ENCRYPT_DATA] = "CKM_DES_ECB_ENCRYPT_DATA"; t[CKM_DES_CBC_ENCRYPT_DATA] = "CKM_DES_CBC_ENCRYPT_DATA"; t[CKM_DES3_ECB_ENCRYPT_DATA] = "CKM_DES3_ECB_ENCRYPT_DATA"; t[CKM_DES3_CBC_ENCRYPT_DATA] = "CKM_DES3_CBC_ENCRYPT_DATA"; t[CKM_AES_ECB_ENCRYPT_DATA] = "CKM_AES_ECB_ENCRYPT_DATA"; t[CKM_AES_CBC_ENCRYPT_DATA] = "CKM_AES_CBC_ENCRYPT_DATA"; t[CKM_GOSTR3410_KEY_PAIR_GEN] = "CKM_GOSTR3410_KEY_PAIR_GEN"; t[CKM_GOSTR3410] = "CKM_GOSTR3410"; t[CKM_GOSTR3410_WITH_GOSTR3411] = "CKM_GOSTR3410_WITH_GOSTR3411"; t[CKM_GOSTR3410_KEY_WRAP] = "CKM_GOSTR3410_KEY_WRAP"; t[CKM_GOSTR3410_DERIVE] = "CKM_GOSTR3410_DERIVE"; t[CKM_GOSTR3411] = "CKM_GOSTR3411"; t[CKM_GOSTR3411_HMAC] = "CKM_GOSTR3411_HMAC"; t[CKM_GOST28147_KEY_GEN] = "CKM_GOST28147_KEY_GEN"; t[CKM_GOST28147_ECB] = "CKM_GOST28147_ECB"; t[CKM_GOST28147] = "CKM_GOST28147"; t[CKM_GOST28147_MAC] = "CKM_GOST28147_MAC"; t[CKM_GOST28147_KEY_WRAP] = "CKM_GOST28147_KEY_WRAP"; t[CKM_DSA_PARAMETER_GEN] = "CKM_DSA_PARAMETER_GEN"; t[CKM_DH_PKCS_PARAMETER_GEN] = "CKM_DH_PKCS_PARAMETER_GEN"; t[CKM_X9_42_DH_PARAMETER_GEN] = "CKM_X9_42_DH_PARAMETER_GEN"; t[CKM_AES_OFB] = "CKM_AES_OFB"; t[CKM_AES_CFB64] = "CKM_AES_CFB64"; t[CKM_AES_CFB8] = "CKM_AES_CFB8"; t[CKM_AES_CFB128] = "CKM_AES_CFB128"; t[CKM_RSA_PKCS_TPM_1_1] = "CKM_RSA_PKCS_TPM_1_1"; t[CKM_RSA_PKCS_OAEPTPM_1_1] = "CKM_RSA_PKCS_OAEPTPM_1_1"; } void fill_CKO_table(std::map &t) { t[CKO_DATA] = "CKO_DATA"; t[CKO_CERTIFICATE] = "CKO_CERTIFICATE"; t[CKO_PUBLIC_KEY] = "CKO_PUBLIC_KEY"; t[CKO_PRIVATE_KEY] = "CKO_PRIVATE_KEY"; t[CKO_SECRET_KEY] = "CKO_SECRET_KEY"; t[CKO_HW_FEATURE] = "CKO_HW_FEATURE"; t[CKO_DOMAIN_PARAMETERS] = "CKO_DOMAIN_PARAMETERS"; t[CKO_MECHANISM] = "CKO_MECHANISM"; t[CKO_OTP_KEY] = "CKO_OTP_KEY"; } void fill_CKH_table(std::map &t) { t[CKH_MONOTONIC_COUNTER] = "CKH_MONOTONIC_COUNTER"; t[CKH_CLOCK] = "CKH_CLOCK"; t[CKH_USER_INTERFACE] = "CKH_USER_INTERFACE"; } void fill_CKK_table(std::map &t) { t[CKK_RSA] = "CKK_RSA"; t[CKK_DSA] = "CKK_DSA"; t[CKK_DH] = "CKK_DH"; t[CKK_EC] = "CKK_EC"; t[CKK_X9_42_DH] = "CKK_X9_42_DH"; t[CKK_KEA] = "CKK_KEA"; t[CKK_GENERIC_SECRET] = "CKK_GENERIC_SECRET"; t[CKK_RC2] = "CKK_RC2"; t[CKK_RC4] = "CKK_RC4"; t[CKK_DES] = "CKK_DES"; t[CKK_DES2] = "CKK_DES2"; t[CKK_DES3] = "CKK_DES3"; t[CKK_CAST] = "CKK_CAST"; t[CKK_CAST3] = "CKK_CAST3"; t[CKK_CAST5] = "CKK_CAST5"; t[CKK_CAST128] = "CKK_CAST128"; t[CKK_RC5] = "CKK_RC5"; t[CKK_IDEA] = "CKK_IDEA"; t[CKK_SKIPJACK] = "CKK_SKIPJACK"; t[CKK_BATON] = "CKK_BATON"; t[CKK_JUNIPER] = "CKK_JUNIPER"; t[CKK_CDMF] = "CKK_CDMF"; t[CKK_AES] = "CKK_AES"; t[CKK_BLOWFISH] = "CKK_BLOWFISH"; t[CKK_TWOFISH] = "CKK_TWOFISH"; t[CKK_SECURID] = "CKK_SECURID"; t[CKK_HOTP] = "CKK_HOTP"; t[CKK_ACTI] = "CKK_ACTI"; t[CKK_CAMELLIA] = "CKK_CAMELLIA"; t[CKK_ARIA] = "CKK_ARIA"; t[CKK_MD5_HMAC] = "CKK_MD5_HMAC"; t[CKK_SHA_1_HMAC] = "CKK_SHA_1_HMAC"; t[CKK_RIPEMD128_HMAC] = "CKK_RIPEMD128_HMAC"; t[CKK_RIPEMD160_HMAC] = "CKK_RIPEMD160_HMAC"; t[CKK_SHA256_HMAC] = "CKK_SHA256_HMAC"; t[CKK_SHA384_HMAC] = "CKK_SHA384_HMAC"; t[CKK_SHA512_HMAC] = "CKK_SHA512_HMAC"; t[CKK_SHA224_HMAC] = "CKK_SHA224_HMAC"; t[CKK_SEED] = "CKK_SEED"; t[CKK_GOSTR3410] = "CKK_GOSTR3410"; t[CKK_GOSTR3411] = "CKK_GOSTR3411"; t[CKK_GOST28147] = "CKK_GOST28147"; } void fill_CKC_table(std::map &t) { t[CKC_X_509] = "CKC_X_509"; t[CKC_X_509_ATTR_CERT] = "CKC_X_509_ATTR_CERT"; t[CKC_WTLS] = "CKC_WTLS"; t[CKC_OPENPGP] = "CKC_OPENPGP"; } #endif // !_SOFTHSM_V2_TABLES_H softhsm-2.0.0/src/bin/keyconv/0000775000175000017500000000000012552220146013213 500000000000000softhsm-2.0.0/src/bin/keyconv/softhsm2-keyconv.cpp0000664000175000017500000002042712533040716017067 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /************************************************************ * * softhsm2-keyconv * * This program is for converting from BIND .private-key * format to PKCS#8 key file format. So that keys can be * imported from BIND to SoftHSM. * * Some of the design/code is from keyconv.c written by * Hakan Olsson and Jakob Schlyter in 2000 and 2001. * ************************************************************/ #include #include "softhsm2-keyconv.h" #include #include #include #include #ifndef _WIN32 #include #else #include #define S_IRUSR 0400 #define S_IWUSR 0200 #define open _open #define close _close #endif #include #include #include #include #include #include #include void usage() { printf("Converting from BIND .private-key format to PKCS#8 key file format.\n"); printf("Usage: softhsm2-keyconv [OPTIONS]\n"); printf("Options:\n"); printf(" -h Shows this help screen.\n"); printf(" --help Shows this help screen.\n"); printf(" --in The path to the input file.\n"); printf(" --out The path to the output file.\n"); printf(" --pin To encrypt PKCS#8 file. Optional.\n"); printf(" -v Show version info.\n"); printf(" --version Show version info.\n"); } // Give a number to each option enum { OPT_HELP = 0x100, OPT_IN, OPT_OUT, OPT_PIN, OPT_VERSION }; // Define the options static const struct option long_options[] = { { "help", 0, NULL, OPT_HELP }, { "in", 1, NULL, OPT_IN }, { "out", 1, NULL, OPT_OUT }, { "pin", 1, NULL, OPT_PIN }, { "version", 0, NULL, OPT_VERSION }, { NULL, 0, NULL, 0 } }; int main(int argc, char* argv[]) { int option_index = 0; int opt, result; char* in_path = NULL; char* out_path = NULL; char* file_pin = NULL; if (argc == 1) { usage(); exit(0); } while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1) { switch (opt) { case OPT_IN: in_path = optarg; break; case OPT_OUT: out_path = optarg; break; case OPT_PIN: file_pin = optarg; break; case OPT_VERSION: case 'v': printf("%s\n", PACKAGE_VERSION); exit(0); break; case OPT_HELP: case 'h': default: usage(); exit(0); break; } } // We should convert to PKCS#8 result = to_pkcs8(in_path, out_path, file_pin); return result; } // Convert from BIND to PKCS#8 int to_pkcs8(char* in_path, char* out_path, char* file_pin) { FILE* file_pointer = NULL; char line[MAX_LINE], data[MAX_LINE]; char* value_pointer = NULL; int lineno = 0, m, n, error = 0, found, algorithm = DNS_KEYALG_ERROR, data_length; uint32_t bitfield = 0; key_material_t pkey[TAG_MAX]; if (in_path == NULL) { fprintf(stderr, "ERROR: A path to the input file must be supplied. Use --in \n"); return 1; } if (out_path == NULL) { fprintf(stderr, "ERROR: A path to the output file must be supplied. Use --out \n"); return 1; } file_pointer = fopen(in_path, "r"); if (file_pointer == NULL) { fprintf(stderr, "ERROR: Could not open input file %.100s for reading.\n", in_path); return 1; } // Loop over all of the lines while (fgets(line, MAX_LINE, file_pointer) != NULL) { lineno++; // Find the current text field in the BIND file. for (m = 0, found = -1; found == -1 && file_tags[m]; m++) { if (strncasecmp(line, file_tags[m], strlen(file_tags[m])) == 0) { found = m; } } // The text files is not recognized. if (found == -1) { fprintf(stderr, "ERROR: Unrecognized input line %i\n", lineno); fprintf(stderr, "ERROR: --> %s", line); continue; } // Point to the data for this text field. value_pointer = line + strlen(file_tags[found]) + 1; // Continue if we are at the end of the string if (*value_pointer == 0) { continue; } // Check that we do not get duplicates. if (bitfield & (1 << found)) { fprintf(stderr, "ERROR: Duplicate \"%s\" field, line %i - ignored\n", file_tags[found], lineno); continue; } bitfield |= (1 << found); // Handle the data for this text field. switch (found) { case TAG_VERSION: if (sscanf(value_pointer, "v%i.%i", &m, &n) != 2) { fprintf(stderr, "ERROR: Invalid/unknown version string " "(%.100s).\n", value_pointer); error = 1; break; } if (m > FILE_MAJOR_VERSION || (m == FILE_MAJOR_VERSION && n > FILE_MINOR_VERSION)) { fprintf(stderr, "ERROR: Cannot parse this version of file format, " "v%i.%i.\n", m, n); error = 1; } break; case TAG_ALGORITHM: algorithm = strtol(value_pointer, NULL, 10); break; // RSA case TAG_MODULUS: case TAG_PUBEXP: case TAG_PRIVEXP: case TAG_PRIME1: case TAG_PRIME2: case TAG_EXP1: case TAG_EXP2: case TAG_COEFF: // DSA case TAG_PRIME: case TAG_SUBPRIME: case TAG_BASE: case TAG_PRIVVAL: case TAG_PUBVAL: data_length = b64_pton(value_pointer, (unsigned char*)data, MAX_LINE); if (data_length == -1) { error = 1; fprintf(stderr, "ERROR: Could not parse the base64 string on line %i.\n", lineno); } else { pkey[found].big = malloc(data_length); if (!pkey[found].big) { fprintf(stderr, "ERROR: Could not allocate memory.\n"); error = 1; break; } memcpy(pkey[found].big, data, data_length); pkey[found].size = data_length; } break; // Do not need these case TAG_CREATED: case TAG_PUBLISH: case TAG_ACTIVATE: default: break; } } fclose(file_pointer); // Something went wrong. Clean up and quit. if (error) { free_key_material(pkey); return error; } // Create and set file permissions if the file does not exist. int fd = open(out_path, O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { fprintf(stderr, "ERROR: Could not open the output file: %s (errno %i)\n", out_path, errno); free_key_material(pkey); return 1; } ::close(fd); crypto_init(); // Save the the key to the disk switch (algorithm) { case DNS_KEYALG_ERROR: fprintf(stderr, "ERROR: The algorithm %i was not given in the file.\n", algorithm); error = 1; break; case DNS_KEYALG_RSAMD5: case DNS_KEYALG_RSASHA1: case DNS_KEYALG_RSASHA1_NSEC3_SHA1: case DNS_KEYALG_RSASHA256: case DNS_KEYALG_RSASHA512: error = save_rsa_pkcs8(out_path, file_pin, pkey); break; case DNS_KEYALG_DSA: case DNS_KEYALG_DSA_NSEC3_SHA1: error = save_dsa_pkcs8(out_path, file_pin, pkey); break; case DNS_KEYALG_ECC: case DNS_KEYALG_ECC_GOST: default: fprintf(stderr, "ERROR: The algorithm %i is not supported.\n", algorithm); error = 1; break; } crypto_final(); free_key_material(pkey); return error; } // Free allocated memory void free_key_material(key_material_t* pkey) { int i; if (!pkey) { return; } for (i = 0; i < TAG_MAX; i++) { if (pkey[i].big) { free(pkey[i].big); } } } softhsm-2.0.0/src/bin/keyconv/softhsm2-keyconv-ossl.cpp0000664000175000017500000001601112533040716020037 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-keyconv-ossl.cpp Code specific for OpenSSL *****************************************************************************/ #include #define KEYCONV_OSSL #include "softhsm2-keyconv.h" #include #include #include #include #include #include #include #include #include #include #include // Init OpenSSL void crypto_init() { OpenSSL_add_all_algorithms(); #ifdef WITH_FIPS if (!FIPS_mode_set(1)) { fprintf(stderr, "ERROR: can't enter into FIPS mode.\n"); exit(0); } #endif } // Final OpenSSL void crypto_final() { EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); } // Save the RSA key as a PKCS#8 file int save_rsa_pkcs8(char* out_path, char* file_pin, key_material_t* pkey) { RSA* rsa = NULL; EVP_PKEY* ossl_pkey = NULL; PKCS8_PRIV_KEY_INFO* p8inf = NULL; BIO* out = NULL; X509_SIG* p8 = NULL; int result = 0; // See if the key material was found. if ( pkey[TAG_MODULUS].size <= 0 || pkey[TAG_PUBEXP].size <= 0 || pkey[TAG_PRIVEXP].size <= 0 || pkey[TAG_PRIME1].size <= 0 || pkey[TAG_PRIME2].size <= 0 || pkey[TAG_EXP1].size <= 0 || pkey[TAG_EXP2].size <= 0 || pkey[TAG_COEFF].size <= 0 ) { fprintf(stderr, "ERROR: Some parts of the key material is missing in the input file.\n"); return 1; } rsa = RSA_new(); rsa->p = BN_bin2bn((unsigned char*)pkey[TAG_PRIME1].big, pkey[TAG_PRIME1].size, NULL); rsa->q = BN_bin2bn((unsigned char*)pkey[TAG_PRIME2].big, pkey[TAG_PRIME2].size, NULL); rsa->d = BN_bin2bn((unsigned char*)pkey[TAG_PRIVEXP].big, pkey[TAG_PRIVEXP].size, NULL); rsa->n = BN_bin2bn((unsigned char*)pkey[TAG_MODULUS].big, pkey[TAG_MODULUS].size, NULL); rsa->e = BN_bin2bn((unsigned char*)pkey[TAG_PUBEXP].big, pkey[TAG_PUBEXP].size, NULL); rsa->dmp1 = BN_bin2bn((unsigned char*)pkey[TAG_EXP1].big, pkey[TAG_EXP1].size, NULL); rsa->dmq1 = BN_bin2bn((unsigned char*)pkey[TAG_EXP2].big, pkey[TAG_EXP2].size, NULL); rsa->iqmp = BN_bin2bn((unsigned char*)pkey[TAG_COEFF].big, pkey[TAG_COEFF].size, NULL); ossl_pkey = EVP_PKEY_new(); // Convert RSA to EVP_PKEY if (!EVP_PKEY_set1_RSA(ossl_pkey, rsa)) { fprintf(stderr, "ERROR: Could not convert RSA key to EVP_PKEY.\n"); RSA_free(rsa); EVP_PKEY_free(ossl_pkey); return 1; } RSA_free(rsa); // Convert EVP_PKEY to PKCS#8 if (!(p8inf = EVP_PKEY2PKCS8(ossl_pkey))) { fprintf(stderr, "ERROR: Could not convert EVP_PKEY to PKCS#8.\n"); EVP_PKEY_free(ossl_pkey); return 1; } EVP_PKEY_free(ossl_pkey); // Open output file if (!(out = BIO_new_file (out_path, "wb"))) { fprintf(stderr, "ERROR: Could not open the output file.\n"); PKCS8_PRIV_KEY_INFO_free(p8inf); return 1; } // Write to disk if (file_pin == NULL) { PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf); printf("The key has been written to %s\n", out_path); } else { // Encrypt p8 if (!(p8 = PKCS8_encrypt(NID_pbeWithMD5AndDES_CBC, NULL, file_pin, strlen(file_pin), NULL, 0, PKCS12_DEFAULT_ITER, p8inf))) { fprintf(stderr, "ERROR: Could not encrypt the PKCS#8 file\n"); result = 1; } else { PEM_write_bio_PKCS8(out, p8); X509_SIG_free(p8); printf("The key has been written to %s\n", out_path); } } PKCS8_PRIV_KEY_INFO_free(p8inf); BIO_free_all(out); return result; } // Save the DSA key as a PKCS#8 file int save_dsa_pkcs8(char* out_path, char* file_pin, key_material_t* pkey) { DSA* dsa = NULL; EVP_PKEY* ossl_pkey = NULL; PKCS8_PRIV_KEY_INFO* p8inf = NULL; BIO* out = NULL; X509_SIG* p8 = NULL; int result = 0; // See if the key material was found. if ( pkey[TAG_PRIME].size <= 0 || pkey[TAG_SUBPRIME].size <= 0 || pkey[TAG_BASE].size <= 0 || pkey[TAG_PRIVVAL].size <= 0 || pkey[TAG_PUBVAL].size <= 0 ) { fprintf(stderr, "ERROR: Some parts of the key material is missing in the input file.\n"); return 1; } dsa = DSA_new(); dsa->p = BN_bin2bn((unsigned char*)pkey[TAG_PRIME].big, pkey[TAG_PRIME].size, NULL); dsa->q = BN_bin2bn((unsigned char*)pkey[TAG_SUBPRIME].big, pkey[TAG_SUBPRIME].size, NULL); dsa->g = BN_bin2bn((unsigned char*)pkey[TAG_BASE].big, pkey[TAG_BASE].size, NULL); dsa->priv_key = BN_bin2bn((unsigned char*)pkey[TAG_PRIVVAL].big, pkey[TAG_PRIVVAL].size, NULL); dsa->pub_key = BN_bin2bn((unsigned char*)pkey[TAG_PUBVAL].big, pkey[TAG_PUBVAL].size, NULL); ossl_pkey = EVP_PKEY_new(); // Convert DSA to EVP_PKEY if (!EVP_PKEY_set1_DSA(ossl_pkey, dsa)) { fprintf(stderr, "ERROR: Could not convert DSA key to EVP_PKEY.\n"); DSA_free(dsa); EVP_PKEY_free(ossl_pkey); return 1; } DSA_free(dsa); // Convert EVP_PKEY to PKCS#8 if (!(p8inf = EVP_PKEY2PKCS8(ossl_pkey))) { fprintf(stderr, "ERROR: Could not convert EVP_PKEY to PKCS#8.\n"); EVP_PKEY_free(ossl_pkey); return 1; } EVP_PKEY_free(ossl_pkey); // Open output file if (!(out = BIO_new_file (out_path, "wb"))) { fprintf(stderr, "ERROR: Could not open the output file.\n"); PKCS8_PRIV_KEY_INFO_free(p8inf); return 1; } // Write to disk if (file_pin == NULL) { PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf); printf("The key has been written to %s\n", out_path); } else { // Encrypt p8 if (!(p8 = PKCS8_encrypt(NID_pbeWithMD5AndDES_CBC, NULL, file_pin, strlen(file_pin), NULL, 0, PKCS12_DEFAULT_ITER, p8inf))) { fprintf(stderr, "ERROR: Could not encrypt the PKCS#8 file\n"); result = 1; } else { PEM_write_bio_PKCS8(out, p8); X509_SIG_free(p8); printf("The key has been written to %s\n", out_path); } } PKCS8_PRIV_KEY_INFO_free(p8inf); BIO_free_all(out); return result; } softhsm-2.0.0/src/bin/keyconv/base64.c0000664000175000017500000002432112533040716014367 00000000000000/* $OpenBSD: base64.c,v 1.3 2002/06/09 08:13:07 todd Exp $ */ /* * Copyright (c) 1996-1999 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ /* * Portions Copyright (c) 1995 by International Business Machines, Inc. * * International Business Machines, Inc. (hereinafter called IBM) grants * permission under its copyrights to use, copy, modify, and distribute this * Software with or without fee, provided that the above copyright notice and * all paragraphs of this notice appear in all copies, and that the name of IBM * not be used in connection with the marketing of any product incorporating * the Software or modifications thereof, without specific, written prior * permission. * * To the extent it has a right to do so, IBM grants an immunity from suit * under its patents, if any, for the use, sale or manufacture of products to * the extent that such products are used for performing Domain Name System * dynamic updates in TCP/IP networks by means of the Software. No immunity is * granted for any product per se or for any other function of any product. * * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. */ #if !defined(LINT) && !defined(CODECENTER) static const char rcsid[] = "$ISC: base64.c,v 8.6 1999/01/08 19:25:18 vixie Exp $"; #endif /* not lint */ #include #ifndef _WIN32 #include #include #endif #include #include #include #include #define Assert(Cond) if (!(Cond)) abort() static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char Pad64 = '='; /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) The following encoding technique is taken from RFC 1521 by Borenstein and Freed. It is reproduced here in a slightly edited form for convenience. A 65-character subset of US-ASCII is used, enabling 6 bits to be represented per printable character. (The extra 65th character, "=", is used to signify a special processing function.) The encoding process represents 24-bit groups of input bits as output strings of 4 encoded characters. Proceeding from left to right, a 24-bit input group is formed by concatenating 3 8-bit input groups. These 24 bits are then treated as 4 concatenated 6-bit groups, each of which is translated into a single digit in the base64 alphabet. Each 6-bit group is used as an index into an array of 64 printable characters. The character referenced by the index is placed in the output string. Table 1: The Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y Special processing is performed if fewer than 24 bits are available at the end of the data being encoded. A full encoding quantum is always completed at the end of a quantity. When fewer than 24 input bits are available in an input group, zero bits are added (on the right) to form an integral number of 6-bit groups. Padding at the end of the data is performed using the '=' character. Since all base64 input is an integral number of octets, only the ------------------------------------------------- following cases can arise: (1) the final quantum of encoding input is an integral multiple of 24 bits; here, the final unit of encoded output will be an integral multiple of 4 characters with no "=" padding, (2) the final quantum of encoding input is exactly 8 bits; here, the final unit of encoded output will be two characters followed by two "=" padding characters, or (3) the final quantum of encoding input is exactly 16 bits; here, the final unit of encoded output will be three characters followed by one "=" padding character. */ int b64_ntop(unsigned char const *src, size_t srclength, char *target, size_t targsize) { size_t datalength = 0; unsigned char input[3]; unsigned char output[4]; size_t i; while (2 < srclength) { input[0] = *src++; input[1] = *src++; input[2] = *src++; srclength -= 3; output[0] = input[0] >> 2; output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); output[3] = input[2] & 0x3f; Assert(output[0] < 64); Assert(output[1] < 64); Assert(output[2] < 64); Assert(output[3] < 64); if (datalength + 4 > targsize) return (-1); target[datalength++] = Base64[output[0]]; target[datalength++] = Base64[output[1]]; target[datalength++] = Base64[output[2]]; target[datalength++] = Base64[output[3]]; } /* Now we worry about padding. */ if (0 != srclength) { /* Get what's left. */ input[0] = input[1] = input[2] = '\0'; for (i = 0; i < srclength; i++) input[i] = *src++; output[0] = input[0] >> 2; output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); Assert(output[0] < 64); Assert(output[1] < 64); Assert(output[2] < 64); if (datalength + 4 > targsize) return (-1); target[datalength++] = Base64[output[0]]; target[datalength++] = Base64[output[1]]; if (srclength == 1) target[datalength++] = Pad64; else target[datalength++] = Base64[output[2]]; target[datalength++] = Pad64; } if (datalength >= targsize) return (-1); target[datalength] = '\0'; /* Returned value doesn't count \0. */ return (datalength); } /* skips all whitespace anywhere. converts characters, four at a time, starting at (or after) src from base - 64 numbers into three 8 bit bytes in the target area. it returns the number of data bytes stored at the target, or -1 on error. */ int b64_pton(char const *src, unsigned char *target, size_t targsize) { int tarindex, state, ch; char *pos; state = 0; tarindex = 0; while ((ch = *src++) != '\0') { if (isspace(ch)) /* Skip whitespace anywhere. */ continue; if (ch == Pad64) break; pos = strchr(Base64, ch); if (pos == 0) /* A non-base64 character. */ return (-1); switch (state) { case 0: if (target) { if ((size_t)tarindex >= targsize) return (-1); target[tarindex] = (pos - Base64) << 2; } state = 1; break; case 1: if (target) { if ((size_t)tarindex + 1 >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 4; target[tarindex+1] = ((pos - Base64) & 0x0f) << 4 ; } tarindex++; state = 2; break; case 2: if (target) { if ((size_t)tarindex + 1 >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 2; target[tarindex+1] = ((pos - Base64) & 0x03) << 6; } tarindex++; state = 3; break; case 3: if (target) { if ((size_t)tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64); } tarindex++; state = 0; break; default: abort(); } } /* * We are done decoding Base-64 chars. Let's see if we ended * on a byte boundary, and/or with erroneous trailing characters. */ if (ch == Pad64) { /* We got a pad char. */ ch = *src++; /* Skip it, get next. */ switch (state) { case 0: /* Invalid = in first position */ case 1: /* Invalid = in second position */ return (-1); case 2: /* Valid, means one byte of info */ /* Skip any number of spaces. */ for ((void)NULL; ch != '\0'; ch = *src++) if (!isspace(ch)) break; /* Make sure there is another trailing = sign. */ if (ch != Pad64) return (-1); ch = *src++; /* Skip the = */ /* Fall through to "single trailing =" case. */ /* FALLTHROUGH */ case 3: /* Valid, means two bytes of info */ /* * We know this char is an =. Is there anything but * whitespace after it? */ for ((void)NULL; ch != '\0'; ch = *src++) if (!isspace(ch)) return (-1); /* * Now make sure for cases 2 and 3 that the "extra" * bits that slopped past the last full byte were * zeros. If we don't check them, they become a * subliminal channel. */ if (target && target[tarindex] != 0) return (-1); } } else { /* * We ended by seeing the end of the string. Make sure we * have no partial bytes lying around. */ if (state != 0) return (-1); } return (tarindex); } softhsm-2.0.0/src/bin/keyconv/Makefile.am0000664000175000017500000000101112533040716015162 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = @CRYPTO_INCLUDES@ dist_man_MANS = softhsm2-keyconv.1 bin_PROGRAMS = softhsm2-keyconv softhsm2_keyconv_SOURCES = softhsm2-keyconv.cpp \ base64.c softhsm2_keyconv_LDADD = @CRYPTO_LIBS@ # Compile with OpenSSL support if WITH_OPENSSL softhsm2_keyconv_SOURCES += softhsm2-keyconv-ossl.cpp endif # Compile with Botan support if WITH_BOTAN softhsm2_keyconv_SOURCES += softhsm2-keyconv-botan.cpp endif EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/*.cpp softhsm-2.0.0/src/bin/keyconv/softhsm2-keyconv.10000664000175000017500000000253012533040716016440 00000000000000.TH SOFTHSM2-KEYCONV 1 "20 March 2014" "SoftHSM" .SH NAME softhsm2-keyconv \- converting from BIND to PKCS#8 key file format .SH SYNOPSIS .B softhsm2-keyconv .B \-\-in .I path .B \-\-out .I path .RB [ \-\-pin .IR PIN ] .SH DESCRIPTION .B softhsm2-keyconv can convert BIND .private-key files to the PKCS#8 file format. This is so that you can import the PKCS#8 file into libsofthsm using the command .BR softhsm2\-util . If you have another file format, then .B openssl probably can help you to convert it into the PKCS#8 file format. .SH OPTIONS .B \-\-help\fR, \fB\-h\fR Shows the help screen. .TP .B \-\-in \fIpath\fR The .I path to the input file. .TP .B \-\-out \fIpath\fR The .I path to the output file. .TP .B \-\-pin \fIPIN\fR The .I PIN will be used to encrypt the PKCS#8 file. If not given then the PKCS#8 file will be unencrypted. .TP .B \-\-version\fR, \fB\-v\fR Show the version info. .SH EXAMPLES The following command can be used to convert a BIND .private-key file to a PKCS#8 file: .LP .RS .nf softhsm2-keyconv \-\-in Kexample.com.+007+05474.private \\ .ti +0.7i \-\-out rsa.pem .fi .RE .LP .SH AUTHORS Written by Rickard Bellgrim, Francis Dupont, René Post, and Roland van Rijswijk. .SH "SEE ALSO" .IR softhsm2-migrate (1), .IR softhsm2-util (1), .IR softhsm2.conf (5), .IR openssl (1), .IR named (1), .IR dnssec-keygen (1), .IR dnssec-signzone (1) softhsm-2.0.0/src/bin/keyconv/softhsm2-keyconv-botan.cpp0000664000175000017500000001406512533040716020171 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** softhsm2-keyconv-botan.cpp Code specific for Botan *****************************************************************************/ #include #define KEYCONV_BOTAN #include "softhsm2-keyconv.h" #include #include #include #include #include #include #include #include #include #include #include // Init Botan void crypto_init() { Botan::LibraryInitializer::initialize(); } // Final Botan void crypto_final() { Botan::LibraryInitializer::deinitialize(); } // Save the RSA key as a PKCS#8 file int save_rsa_pkcs8(char* out_path, char* file_pin, key_material_t* pkey) { int result = 0; Botan::Private_Key* priv_key = NULL; Botan::AutoSeeded_RNG* rng = NULL; Botan::BigInt bigE, bigP, bigQ, bigN, bigD; // See if the key material was found. if ( pkey[TAG_MODULUS].size <= 0 || pkey[TAG_PUBEXP].size <= 0 || pkey[TAG_PRIVEXP].size <= 0 || pkey[TAG_PRIME1].size <= 0 || pkey[TAG_PRIME2].size <= 0 ) { fprintf(stderr, "ERROR: Some parts of the key material is missing in the input file.\n"); return 1; } bigE = Botan::BigInt((Botan::byte*)pkey[TAG_PUBEXP].big, pkey[TAG_PUBEXP].size); bigP = Botan::BigInt((Botan::byte*)pkey[TAG_PRIME1].big, pkey[TAG_PRIME1].size); bigQ = Botan::BigInt((Botan::byte*)pkey[TAG_PRIME2].big, pkey[TAG_PRIME2].size); bigN = Botan::BigInt((Botan::byte*)pkey[TAG_MODULUS].big, pkey[TAG_MODULUS].size); bigD = Botan::BigInt((Botan::byte*)pkey[TAG_PRIVEXP].big, pkey[TAG_PRIVEXP].size); rng = new Botan::AutoSeeded_RNG(); try { priv_key = new Botan::RSA_PrivateKey(*rng, bigP, bigQ, bigE, bigD, bigN); } catch(std::exception& e) { fprintf(stderr, "%s\n", e.what()); fprintf(stderr, "ERROR: Could not extract the private key from the file.\n"); delete rng; return 1; } std::ofstream priv_file(out_path); if (!priv_file.is_open()) { fprintf(stderr, "ERROR: Could not open file for output.\n"); delete rng; delete priv_key; return 1; } try { if (file_pin == NULL) { priv_file << Botan::PKCS8::PEM_encode(*priv_key); } else { #if BOTAN_VERSION_MINOR == 11 priv_file << Botan::PKCS8::PEM_encode(*priv_key, *rng, file_pin, std::chrono::milliseconds(300), "PBE-PKCS5v15(MD5,DES/CBC)"); #else priv_file << Botan::PKCS8::PEM_encode(*priv_key, *rng, file_pin, "PBE-PKCS5v15(MD5,DES/CBC)"); #endif } printf("The key has been written to %s\n", out_path); } catch(std::exception& e) { fprintf(stderr, "%s\n", e.what()); fprintf(stderr, "ERROR: Could not write to file.\n"); result = 1; } delete rng; delete priv_key; priv_file.close(); return result; } // Save the DSA key as a PKCS#8 file int save_dsa_pkcs8(char* out_path, char* file_pin, key_material_t* pkey) { int result = 0; Botan::Private_Key* priv_key = NULL; Botan::AutoSeeded_RNG* rng = NULL; Botan::BigInt bigDP, bigDQ, bigDG, bigDX; // See if the key material was found. if ( pkey[TAG_PRIME].size <= 0 || pkey[TAG_SUBPRIME].size <= 0 || pkey[TAG_BASE].size <= 0 || pkey[TAG_PRIVVAL].size <= 0 ) { fprintf(stderr, "ERROR: Some parts of the key material is missing in the input file.\n"); return 1; } bigDP = Botan::BigInt((Botan::byte*)pkey[TAG_PRIME].big, pkey[TAG_PRIME].size); bigDQ = Botan::BigInt((Botan::byte*)pkey[TAG_SUBPRIME].big, pkey[TAG_SUBPRIME].size); bigDG = Botan::BigInt((Botan::byte*)pkey[TAG_BASE].big, pkey[TAG_BASE].size); bigDX = Botan::BigInt((Botan::byte*)pkey[TAG_PRIVVAL].big, pkey[TAG_PRIVVAL].size); rng = new Botan::AutoSeeded_RNG(); try { priv_key = new Botan::DSA_PrivateKey(*rng, Botan::DL_Group(bigDP, bigDQ, bigDG), bigDX); } catch (std::exception& e) { fprintf(stderr, "%s\n", e.what()); fprintf(stderr, "ERROR: Could not extract the private key from the file.\n"); delete rng; return 1; } std::ofstream priv_file(out_path); if (!priv_file.is_open()) { fprintf(stderr, "ERROR: Could not open file for output.\n"); delete rng; delete priv_key; return 1; } try { if (file_pin == NULL) { priv_file << Botan::PKCS8::PEM_encode(*priv_key); } else { #if BOTAN_VERSION_MINOR == 11 priv_file << Botan::PKCS8::PEM_encode(*priv_key, *rng, file_pin, std::chrono::milliseconds(300), "PBE-PKCS5v15(MD5,DES/CBC)"); #else priv_file << Botan::PKCS8::PEM_encode(*priv_key, *rng, file_pin, "PBE-PKCS5v15(MD5,DES/CBC)"); #endif } printf("The key has been written to %s\n", out_path); } catch (std::exception& e) { fprintf(stderr, "%s\n", e.what()); fprintf(stderr, "ERROR: Could not write to file.\n"); result = 1; } delete rng; delete priv_key; priv_file.close(); return result; } softhsm-2.0.0/src/bin/keyconv/Makefile.in0000664000175000017500000006422312552216620015211 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ bin_PROGRAMS = softhsm2-keyconv$(EXEEXT) # Compile with OpenSSL support @WITH_OPENSSL_TRUE@am__append_1 = softhsm2-keyconv-ossl.cpp # Compile with Botan support @WITH_BOTAN_TRUE@am__append_2 = softhsm2-keyconv-botan.cpp subdir = src/bin/keyconv DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(dist_man_MANS) ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__installdirs = "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)" PROGRAMS = $(bin_PROGRAMS) am__softhsm2_keyconv_SOURCES_DIST = softhsm2-keyconv.cpp base64.c \ softhsm2-keyconv-ossl.cpp softhsm2-keyconv-botan.cpp @WITH_OPENSSL_TRUE@am__objects_1 = softhsm2-keyconv-ossl.$(OBJEXT) @WITH_BOTAN_TRUE@am__objects_2 = softhsm2-keyconv-botan.$(OBJEXT) am_softhsm2_keyconv_OBJECTS = softhsm2-keyconv.$(OBJEXT) \ base64.$(OBJEXT) $(am__objects_1) $(am__objects_2) softhsm2_keyconv_OBJECTS = $(am_softhsm2_keyconv_OBJECTS) softhsm2_keyconv_DEPENDENCIES = AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(softhsm2_keyconv_SOURCES) DIST_SOURCES = $(am__softhsm2_keyconv_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man1dir = $(mandir)/man1 NROFF = nroff MANS = $(dist_man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = @CRYPTO_INCLUDES@ dist_man_MANS = softhsm2-keyconv.1 softhsm2_keyconv_SOURCES = softhsm2-keyconv.cpp base64.c \ $(am__append_1) $(am__append_2) softhsm2_keyconv_LDADD = @CRYPTO_LIBS@ EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/*.cpp all: all-am .SUFFIXES: .SUFFIXES: .c .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/keyconv/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/keyconv/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-binPROGRAMS: $(bin_PROGRAMS) @$(NORMAL_INSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ if test -n "$$list"; then \ echo " $(MKDIR_P) '$(DESTDIR)$(bindir)'"; \ $(MKDIR_P) "$(DESTDIR)$(bindir)" || exit 1; \ fi; \ for p in $$list; do echo "$$p $$p"; done | \ sed 's/$(EXEEXT)$$//' | \ while read p p1; do if test -f $$p \ || test -f $$p1 \ ; then echo "$$p"; echo "$$p"; else :; fi; \ done | \ sed -e 'p;s,.*/,,;n;h' \ -e 's|.*|.|' \ -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ sed 'N;N;N;s,\n, ,g' | \ $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ if ($$2 == $$4) files[d] = files[d] " " $$1; \ else { print "f", $$3 "/" $$4, $$1; } } \ END { for (d in files) print "f", d, files[d] }' | \ while read type dir files; do \ if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ test -z "$$files" || { \ echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ } \ ; done uninstall-binPROGRAMS: @$(NORMAL_UNINSTALL) @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ files=`for p in $$list; do echo "$$p"; done | \ sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ -e 's/$$/$(EXEEXT)/' \ `; \ test -n "$$list" || exit 0; \ echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ cd "$(DESTDIR)$(bindir)" && rm -f $$files clean-binPROGRAMS: @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list softhsm2-keyconv$(EXEEXT): $(softhsm2_keyconv_OBJECTS) $(softhsm2_keyconv_DEPENDENCIES) $(EXTRA_softhsm2_keyconv_DEPENDENCIES) @rm -f softhsm2-keyconv$(EXEEXT) $(AM_V_CXXLD)$(CXXLINK) $(softhsm2_keyconv_OBJECTS) $(softhsm2_keyconv_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/base64.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-keyconv-botan.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-keyconv-ossl.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/softhsm2-keyconv.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man1: $(dist_man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(dist_man_MANS)'; \ test -n "$(man1dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man1dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man1dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.1[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man1dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man1dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man1dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man1dir)" || exit $$?; }; \ done; } uninstall-man1: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man1dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(dist_man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.1[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^1][0-9a-z]*$$,1,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man1dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(PROGRAMS) $(MANS) installdirs: for dir in "$(DESTDIR)$(bindir)" "$(DESTDIR)$(man1dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-binPROGRAMS install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man1 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-binPROGRAMS uninstall-man uninstall-man: uninstall-man1 .MAKE: install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean \ clean-binPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-binPROGRAMS \ install-data install-data-am install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-man1 \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-binPROGRAMS uninstall-man uninstall-man1 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/bin/keyconv/softhsm2-keyconv.h0000664000175000017500000000663312533040716016537 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ #ifndef _SOFTHSM_V2_SOFTHSM2_KEYCONV_H #define _SOFTHSM_V2_SOFTHSM2_KEYCONV_H 1 #include typedef struct key_material_t { unsigned long size; void* big; key_material_t() { size = 0; big = NULL; } } key_material_t; // Main functions void usage(); int to_pkcs8(char* in_path, char* out_path, char* file_pin); // Support functions int save_rsa_pkcs8(char* out_path, char* file_pin, key_material_t* pkey); int save_dsa_pkcs8(char* out_path, char* file_pin, key_material_t* pkey); void free_key_material(key_material_t* pkey); void crypto_init(); void crypto_final(); // base64.c prototypes #ifdef __cplusplus extern "C" { #endif int b64_pton(const char* , unsigned char*, size_t); int b64_ntop(const unsigned char*, size_t, char*, size_t); #ifdef __cplusplus } #endif // The BIND file version number. #define FILE_MAJOR_VERSION 1 #define FILE_MINOR_VERSION 3 // Key algorithm number #define DNS_KEYALG_ERROR -1 #define DNS_KEYALG_RSAMD5 1 #define DNS_KEYALG_DSA 3 #define DNS_KEYALG_ECC 4 #define DNS_KEYALG_RSASHA1 5 #define DNS_KEYALG_DSA_NSEC3_SHA1 6 #define DNS_KEYALG_RSASHA1_NSEC3_SHA1 7 #define DNS_KEYALG_RSASHA256 8 #define DNS_KEYALG_RSASHA512 10 #define DNS_KEYALG_ECC_GOST 12 // Maximum number of lines / line length #define MAX_LINE 4096 // The text fields supported #if !defined(KEYCONV_BOTAN) && !defined(KEYCONV_OSSL) static const char* file_tags[] = { "Private-key-format:", "Algorithm:", "Modulus:", "PublicExponent:", "PrivateExponent:", "Prime1:", "Prime2:", "Exponent1:", "Exponent2:", "Coefficient:", "Prime(p):", "Private_value(x):", "Public_value(y):", "Subprime(q):", "Base(g):", "Created:", "Publish:", "Activate:", NULL }; #endif // The number of each text field. // Must match the tags above. enum FILE_TAGS { TAG_VERSION = 0, TAG_ALGORITHM, TAG_MODULUS, TAG_PUBEXP, TAG_PRIVEXP, TAG_PRIME1, TAG_PRIME2, TAG_EXP1, TAG_EXP2, TAG_COEFF, TAG_PRIME, TAG_PRIVVAL, TAG_PUBVAL, TAG_SUBPRIME, TAG_BASE, TAG_CREATED, TAG_PUBLISH, TAG_ACTIVATE, // So we know how long this list is TAG_MAX }; #endif /* _SOFTHSM_V2_SOFTHSM2_KEYCONV_H */ softhsm-2.0.0/src/bin/Makefile.in0000664000175000017500000004637712552216620013545 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @BUILD_MIGRATE_TRUE@am__append_1 = migrate subdir = src/bin DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = common keyconv util dump migrate DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in SUBDIRS = common keyconv util dump $(am__append_1) EXTRA_DIST = $(srcdir)/win32/*.cpp \ $(srcdir)/win32/*.h all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/bin/common/0000775000175000017500000000000012552220146013025 500000000000000softhsm-2.0.0/src/bin/common/Makefile.am0000664000175000017500000000011212533040716014775 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/bin/common/library.cpp0000664000175000017500000000724212533040716015124 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** library.cpp Support function for handling PKCS#11 libraries *****************************************************************************/ #include #include "library.h" #include #include #if defined(HAVE_DLOPEN) #include #endif // Load the PKCS#11 library CK_C_GetFunctionList loadLibrary(char* module, void** moduleHandle, char **pErrMsg) { CK_C_GetFunctionList pGetFunctionList = NULL; #if defined(HAVE_LOADLIBRARY) HINSTANCE hDLL = NULL; DWORD dw = NULL; static const char errMsg[100]; // Load PKCS #11 library if (module) { hDLL = LoadLibraryA(module); } else { hDLL = LoadLibraryA(DEFAULT_PKCS11_LIB); } if (hDLL == NULL) { // Failed to load the PKCS #11 library dw = GetLastError(); snprintf(errMsg, sizeof(errMsg), "LoadLibraryA failed: 0x%x", dw); pErrMsg = &errMsg; return NULL; } else { pErrMsg = NULL; } // Retrieve the entry point for C_GetFunctionList pGetFunctionList = (CK_C_GetFunctionList) GetProcAddress(hDLL, "C_GetFunctionList"); if (pGetFunctionList == NULL) { dw = GetLastError(); snprintf(errMsg, sizeof(errMsg), "getProcAddress failed: 0x%x", dw); pErrMsg = &errMsg; } // Store the handle so we can FreeLibrary it later *moduleHandle = hDLL; #elif defined(HAVE_DLOPEN) void* pDynLib = NULL; // Load PKCS #11 library if (module) { pDynLib = dlopen(module, RTLD_NOW | RTLD_LOCAL); } else { pDynLib = dlopen(DEFAULT_PKCS11_LIB, RTLD_NOW | RTLD_LOCAL); } *pErrMsg = dlerror(); if (pDynLib == NULL || *pErrMsg != NULL) { if (pDynLib != NULL) dlclose(pDynLib); // Failed to load the PKCS #11 library return NULL; } // Retrieve the entry point for C_GetFunctionList pGetFunctionList = (CK_C_GetFunctionList) dlsym(pDynLib, "C_GetFunctionList"); // Store the handle so we can dlclose it later *pErrMsg = dlerror(); if (*pErrMsg != NULL) { dlclose(pDynLib); // An error occured during dlsym() return NULL; } *moduleHandle = pDynLib; #else fprintf(stderr, "ERROR: Not compiled with library support.\n"); return NULL; #endif return pGetFunctionList; } void unloadLibrary(void* moduleHandle) { if (moduleHandle) { #if defined(HAVE_LOADLIBRARY) FreeLibrary((HMODULE) moduleHandle); #elif defined(HAVE_DLOPEN) dlclose(moduleHandle); #endif } } softhsm-2.0.0/src/bin/common/library.h0000664000175000017500000000344612533040716014573 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** library.h Support function for handling PKCS#11 libraries *****************************************************************************/ #ifndef _SOFTHSM_V2_BIN_LIBRARY_H #define _SOFTHSM_V2_BIN_LIBRARY_H #include "pkcs11.h" CK_C_GetFunctionList loadLibrary(char* module, void** moduleHandle, char **pErrMsg); void unloadLibrary(void* moduleHandle); #endif // !_SOFTHSM_V2_BIN_LIBRARY_H softhsm-2.0.0/src/bin/common/getpw.cpp0000664000175000017500000000635012533040716014605 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** getpw.cpp Helper function to get a password from the user *****************************************************************************/ #include #include "getpw.h" #include #include #include #ifndef _WIN32 #include #endif // Get a password from the user void getPW(char* pin, char* newPIN, CK_ULONG userType) { // Keep a copy of the PIN because getpass/getpassphrase // will overwrite the previous PIN. char password[MAX_PIN_LEN+1]; int length = 0; if (pin) { length = strlen(pin); } while (length < MIN_PIN_LEN || length > MAX_PIN_LEN) { if (userType == CKU_SO) { printf("*** SO PIN (%i-%i characters) ***\n", MIN_PIN_LEN, MAX_PIN_LEN); } else { printf("*** User PIN (%i-%i characters) ***\n", MIN_PIN_LEN, MAX_PIN_LEN); } #ifdef HAVE_GETPASSPHRASE if (userType == CKU_SO) { pin = getpassphrase("Please enter SO PIN: "); } else { pin = getpassphrase("Please enter user PIN: "); } #else if (userType == CKU_SO) { pin = getpass("Please enter SO PIN: "); } else { pin = getpass("Please enter user PIN: "); } #endif length = strlen(pin); if (length < MIN_PIN_LEN || length > MAX_PIN_LEN) { fprintf(stderr, "ERROR: The length of the PIN is out of range.\n"); length = 0; continue; } memcpy(password, pin, length+1); #ifdef HAVE_GETPASSPHRASE if (userType == CKU_SO) { pin = getpassphrase("Please reenter SO PIN: "); } else { pin = getpassphrase("Please reenter user PIN: "); } #else if (userType == CKU_SO) { pin = getpass("Please reenter SO PIN: "); } else { pin = getpass("Please reenter user PIN: "); } #endif if (strcmp(password, pin)) { fprintf(stderr, "ERROR: The entered PINs are not equal.\n"); length = 0; continue; } } memcpy(newPIN, pin, length+1); } softhsm-2.0.0/src/bin/common/getpw.h0000664000175000017500000000332512533040716014251 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** getpw.h Helper function to get a password from the user *****************************************************************************/ #ifndef _SOFTHSM_V2_BIN_GETPW_H #define _SOFTHSM_V2_BIN_GETPW_H #include "pkcs11.h" void getPW(char* pin, char* newPIN, CK_ULONG userType); #endif // !_SOFTHSM_V2_BIN_GETPW_H softhsm-2.0.0/src/bin/common/Makefile.in0000664000175000017500000003162212552216620015020 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/bin/common DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/bin/common/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/bin/common/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs tags TAGS: ctags CTAGS: cscope cscopelist: distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-am -rm -f Makefile distclean-am: clean-am distclean-generic dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: install-am install-strip .PHONY: all all-am check check-am clean clean-generic clean-libtool \ cscopelist-am ctags-am distclean distclean-generic \ distclean-libtool distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/bin/win32/0000775000175000017500000000000012552220146012477 500000000000000softhsm-2.0.0/src/bin/win32/getopt.h0000664000175000017500000000670312533040716014102 00000000000000/*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * 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 acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION 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. */ #ifndef _GETOPT_H_ #define _GETOPT_H_ #ifdef _WIN32 /* from */ # ifdef __cplusplus # define __BEGIN_DECLS extern "C" { # define __END_DECLS } # else # define __BEGIN_DECLS # define __END_DECLS # endif # define __P(args) args #endif /*#ifndef _WIN32 #include #include #endif*/ /* * Gnu like getopt_long() and BSD4.4 getsubopt()/optreset extensions */ #if !defined(_POSIX_SOURCE) && !defined(_XOPEN_SOURCE) #define no_argument 0 #define required_argument 1 #define optional_argument 2 struct option { /* name of long option */ const char *name; /* * one of no_argument, required_argument, and optional_argument: * whether option takes an argument */ int has_arg; /* if not NULL, set *flag to val when option found */ int *flag; /* if flag not NULL, value to set *flag to; else return value */ int val; }; __BEGIN_DECLS int getopt_long __P((int, char * const *, const char *, const struct option *, int *)); __END_DECLS #endif #ifdef _WIN32 /* These are global getopt variables */ __BEGIN_DECLS extern int opterr, /* if error message should be printed */ optind, /* index into parent argv vector */ optopt, /* character checked for validity */ optreset; /* reset getopt */ extern char* optarg; /* argument associated with option */ /* Original getopt */ int getopt __P((int, char * const *, const char *)); __END_DECLS #endif #endif /* !_GETOPT_H_ */ softhsm-2.0.0/src/bin/win32/getpassphase.cpp0000664000175000017500000000117312533040716015616 00000000000000/* WIN32 getpassphrase */ #include #include char * getpassphrase(const char *prompt) { static char buf[128]; HANDLE h; DWORD cc, mode; int cnt; h = GetStdHandle(STD_INPUT_HANDLE); fputs(prompt, stderr); fflush(stderr); fflush(stdout); FlushConsoleInputBuffer(h); GetConsoleMode(h, &mode); SetConsoleMode(h, ENABLE_PROCESSED_INPUT); for (cnt = 0; cnt < sizeof(buf) - 1; cnt++) { ReadFile(h, buf + cnt, 1, &cc, NULL); if (buf[cnt] == '\r') break; fputc('*', stdout); fflush(stderr); fflush(stdout); } SetConsoleMode(h, mode); buf[cnt] = '\0'; fputs("\n", stderr); return (buf); } softhsm-2.0.0/src/bin/win32/getopt.cpp0000664000175000017500000003261512533040716014436 00000000000000/*- * Copyright (c) 2000 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Dieter Baron and Thomas Klausner. * * 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 acknowledgement: * This product includes software developed by the NetBSD * Foundation, Inc. and its contributors. * 4. Neither the name of The NetBSD Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION 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. */ #include #include #include #include #ifdef _WIN32 /* Windows needs warnx(). We change the definition though: * 1. (another) global is defined, opterrmsg, which holds the error message * 2. errors are always printed out on stderr w/o the program name * Note that opterrmsg always gets set no matter what opterr is set to. The * error message will not be printed if opterr is 0 as usual. */ #include #include extern char opterrmsg[128]; char opterrmsg[128]; /* last error message is stored here */ static void warnx(int print_error, const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (fmt != NULL) _vsnprintf(opterrmsg, 128, fmt, ap); else opterrmsg[0]='\0'; va_end(ap); if (print_error) { fprintf(stderr, opterrmsg); fprintf(stderr, "\n"); } } #endif /*_WIN32*/ /* not part of the original file */ #ifndef _DIAGASSERT #define _DIAGASSERT(X) #endif #if HAVE_CONFIG_H && !HAVE_GETOPT_LONG && !HAVE_DECL_OPTIND #define REPLACE_GETOPT #endif int opterr = 1; /* if error message should be printed */ int optind = 1; /* index into parent argv vector */ int optopt = '?'; /* character checked for validity */ int optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #if !HAVE_GETOPT_LONG #define IGNORE_FIRST (*options == '-' || *options == '+') #define PRINT_ERROR ((opterr) && ((*options != ':') \ || (IGNORE_FIRST && options[1] != ':'))) #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL) #define PERMUTE (!IS_POSIXLY_CORRECT && !IGNORE_FIRST) /* XXX: GNU ignores PC if *options == '-' */ #define IN_ORDER (!IS_POSIXLY_CORRECT && *options == '-') /* return values */ #define BADCH (int)'?' #define BADARG ((IGNORE_FIRST && options[1] == ':') \ || (*options == ':') ? (int)':' : (int)'?') #define INORDER (int)1 #define EMSG "" static int getopt_internal(int, char * const *, const char *); static int gcd(int, int); static void permute_args(int, int, int, char * const *); static char *place = EMSG; /* option letter processing */ /* XXX: set optreset to 1 rather than these two */ static int nonopt_start = -1; /* first non option argument (for permute) */ static int nonopt_end = -1; /* first option after non options (for permute) */ /* Error messages */ static const char recargchar[] = "option requires an argument -- %c"; static const char recargstring[] = "option requires an argument -- %s"; static const char ambig[] = "ambiguous option -- %.*s"; static const char noarg[] = "option doesn't take an argument -- %.*s"; static const char illoptchar[] = "unknown option -- %c"; static const char illoptstring[] = "unknown option -- %s"; /* * Compute the greatest common divisor of a and b. */ static int gcd(int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return b; } /* * Exchange the block from nonopt_start to nonopt_end with the block * from nonopt_end to opt_end (keeping the same order of arguments * in each block). */ static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char * const *nargv) { int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; char *swap; _DIAGASSERT(nargv != NULL); /* * compute lengths of blocks and number and size of cycles */ nnonopts = panonopt_end - panonopt_start; nopts = opt_end - panonopt_end; ncycle = gcd(nnonopts, nopts); cyclelen = (opt_end - panonopt_start) / ncycle; for (i = 0; i < ncycle; i++) { cstart = panonopt_end+i; pos = cstart; for (j = 0; j < cyclelen; j++) { if (pos >= panonopt_end) pos -= nnonopts; else pos += nopts; swap = nargv[pos]; /* LINTED const cast */ ((char **) nargv)[pos] = nargv[cstart]; /* LINTED const cast */ ((char **)nargv)[cstart] = swap; } } } /* * getopt_internal -- * Parse argc/argv argument vector. Called by user level routines. * Returns -2 if -- is found (can be long option or end of options marker). */ static int getopt_internal(int nargc, char * const *nargv, const char *options) { char *oli; /* option letter list index */ int optchar; _DIAGASSERT(nargv != NULL); _DIAGASSERT(options != NULL); optarg = NULL; /* * XXX Some programs (like rsyncd) expect to be able to * XXX re-initialize optind to 0 and have getopt_long(3) * XXX properly function again. Work around this braindamage. */ if (optind == 0) optind = 1; if (optreset) nonopt_start = nonopt_end = -1; start: if (optreset || !*place) { /* update scanning pointer */ optreset = 0; if (optind >= nargc) { /* end of argument vector */ place = EMSG; if (nonopt_end != -1) { /* do permutation, if we have to */ permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } else if (nonopt_start != -1) { /* * If we skipped non-options, set optind * to the first of them. */ optind = nonopt_start; } nonopt_start = nonopt_end = -1; return -1; } if ((*(place = nargv[optind]) != '-') || (place[1] == '\0')) { /* found non-option */ place = EMSG; if (IN_ORDER) { /* * GNU extension: * return non-option as argument to option 1 */ optarg = nargv[optind++]; return INORDER; } if (!PERMUTE) { /* * if no permutation wanted, stop parsing * at first non-option */ return -1; } /* do permutation */ if (nonopt_start == -1) nonopt_start = optind; else if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); nonopt_start = optind - (nonopt_end - nonopt_start); nonopt_end = -1; } optind++; /* process next argument */ goto start; } if (nonopt_start != -1 && nonopt_end == -1) nonopt_end = optind; if (place[1] && *++place == '-') { /* found "--" */ place++; return -2; } } if ((optchar = (int)*place++) == (int)':' || (oli = (char *) strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) { /* option letter unknown or ':' */ if (!*place) ++optind; #ifndef _WIN32 if (PRINT_ERROR) warnx(illoptchar, optchar); #else warnx(PRINT_ERROR, illoptchar, optchar); #endif optopt = optchar; return BADCH; } if (optchar == 'W' && oli[1] == ';') { /* -W long-option */ /* XXX: what if no long options provided (called by getopt)? */ if (*place) return -2; if (++optind >= nargc) { /* no arg */ place = EMSG; #ifndef _WIN32 if (PRINT_ERROR) warnx(recargchar, optchar); #else warnx(PRINT_ERROR, recargchar, optchar); #endif optopt = optchar; return BADARG; } else /* white space */ place = nargv[optind]; /* * Handle -W arg the same as --arg (which causes getopt to * stop parsing). */ return -2; } if (*++oli != ':') { /* doesn't take argument */ if (!*place) ++optind; } else { /* takes (optional) argument */ optarg = NULL; if (*place) /* no white space */ optarg = place; /* XXX: disable test for :: if PC? (GNU doesn't) */ else if (oli[1] != ':') { /* arg not optional */ if (++optind >= nargc) { /* no arg */ place = EMSG; #ifndef _WIN32 if (PRINT_ERROR) warnx(recargchar, optchar); #else warnx(PRINT_ERROR, recargchar, optchar); #endif optopt = optchar; return BADARG; } else optarg = nargv[optind]; } place = EMSG; ++optind; } /* dump back option letter */ return optchar; } /* * getopt -- * Parse argc/argv argument vector. * * [eventually this will replace the real getopt] */ int getopt(int nargc, char * const *nargv, const char *options) { int retval; _DIAGASSERT(nargv != NULL); _DIAGASSERT(options != NULL); if ((retval = getopt_internal(nargc, nargv, options)) == -2) { ++optind; /* * We found an option (--), so if we skipped non-options, * we have to permute. */ if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; retval = -1; } return retval; } /* * getopt_long -- * Parse argc/argv argument vector. */ int getopt_long(int nargc, char * const *nargv, const char *options, const struct option *long_options, int *idx) { int retval; _DIAGASSERT(nargv != NULL); _DIAGASSERT(options != NULL); _DIAGASSERT(long_options != NULL); /* idx may be NULL */ if ((retval = getopt_internal(nargc, nargv, options)) == -2) { char *current_argv, *has_equal; size_t current_argv_len; int i, match; current_argv = place; match = -1; optind++; place = EMSG; if (*current_argv == '\0') { /* found "--" */ /* * We found an option (--), so if we skipped * non-options, we have to permute. */ if (nonopt_end != -1) { permute_args(nonopt_start, nonopt_end, optind, nargv); optind -= nonopt_end - nonopt_start; } nonopt_start = nonopt_end = -1; return -1; } if ((has_equal = strchr(current_argv, '=')) != NULL) { /* argument found (--option=arg) */ current_argv_len = has_equal - current_argv; has_equal++; } else current_argv_len = strlen(current_argv); for (i = 0; long_options[i].name; i++) { /* find matching long option */ if (strncmp(current_argv, long_options[i].name, current_argv_len)) continue; if (strlen(long_options[i].name) == (unsigned)current_argv_len) { /* exact match */ match = i; break; } if (match == -1) /* partial match */ match = i; else { /* ambiguous abbreviation */ #ifndef _WIN32 if (PRINT_ERROR) warnx(ambig, (int)current_argv_len, current_argv); #else warnx(PRINT_ERROR, ambig, (int)current_argv_len, current_argv); #endif optopt = 0; return BADCH; } } if (match != -1) { /* option found */ if (long_options[match].has_arg == no_argument && has_equal) { #ifndef _WIN32 if (PRINT_ERROR) warnx(noarg, (int)current_argv_len, current_argv); #else warnx(PRINT_ERROR, noarg, (int)current_argv_len, current_argv); #endif /* * XXX: GNU sets optopt to val regardless of * flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; return BADARG; } if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) { if (has_equal) optarg = has_equal; else if (long_options[match].has_arg == required_argument) { /* * optional argument doesn't use * next nargv */ optarg = nargv[optind++]; } } if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) { /* * Missing argument; leading ':' * indicates no error should be generated */ #ifndef _WIN32 if (PRINT_ERROR) warnx(recargstring, current_argv); #else warnx(PRINT_ERROR, recargstring, current_argv); #endif /* * XXX: GNU sets optopt to val regardless * of flag */ if (long_options[match].flag == NULL) optopt = long_options[match].val; else optopt = 0; --optind; return BADARG; } } else { /* unknown option */ #ifndef _WIN32 if (PRINT_ERROR) warnx(illoptstring, current_argv); #else warnx(PRINT_ERROR, illoptstring, current_argv); #endif optopt = 0; return BADCH; } if (long_options[match].flag) { *long_options[match].flag = long_options[match].val; retval = 0; } else retval = long_options[match].val; if (idx) *idx = match; } return retval; } #endif /* !GETOPT_LONG */ softhsm-2.0.0/src/lib/0000775000175000017500000000000012552220147011534 500000000000000softhsm-2.0.0/src/lib/main.cpp0000664000175000017500000006225712533040716013121 00000000000000/* * Copyright (c)2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** main.cpp This file contains the main entry point to the PKCS #11 library. All it does is dispatch calls to the actual implementation and check for fatal exceptions on the boundary of the library. *****************************************************************************/ #include "config.h" #include "log.h" #include "fatal.h" #include "cryptoki.h" #include "SoftHSM.h" // PKCS #11 function list // // TODO: contrary to the SoftHSM v2 requirements, PKCS #11 v2.20 is still // implemented in stead of PKCS #11 v2.30 because the header files // for PKCS #11 v2.30 are not yet available static CK_FUNCTION_LIST functionList = { // Version information { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR }, // Function pointers C_Initialize, C_Finalize, C_GetInfo, C_GetFunctionList, C_GetSlotList, C_GetSlotInfo, C_GetTokenInfo, C_GetMechanismList, C_GetMechanismInfo, C_InitToken, C_InitPIN, C_SetPIN, C_OpenSession, C_CloseSession, C_CloseAllSessions, C_GetSessionInfo, C_GetOperationState, C_SetOperationState, C_Login, C_Logout, C_CreateObject, C_CopyObject, C_DestroyObject, C_GetObjectSize, C_GetAttributeValue, C_SetAttributeValue, C_FindObjectsInit, C_FindObjects, C_FindObjectsFinal, C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinal, C_DecryptInit, C_Decrypt, C_DecryptUpdate, C_DecryptFinal, C_DigestInit, C_Digest, C_DigestUpdate, C_DigestKey, C_DigestFinal, C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, C_SignRecoverInit, C_SignRecover, C_VerifyInit, C_Verify, C_VerifyUpdate, C_VerifyFinal, C_VerifyRecoverInit, C_VerifyRecover, C_DigestEncryptUpdate, C_DecryptDigestUpdate, C_SignEncryptUpdate, C_DecryptVerifyUpdate, C_GenerateKey, C_GenerateKeyPair, C_WrapKey, C_UnwrapKey, C_DeriveKey, C_SeedRandom, C_GenerateRandom, C_GetFunctionStatus, C_CancelFunction, C_WaitForSlotEvent }; // PKCS #11 initialisation function CK_RV C_Initialize(CK_VOID_PTR pInitArgs) { try { return SoftHSM::i()->C_Initialize(pInitArgs); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // PKCS #11 finalisation function CK_RV C_Finalize(CK_VOID_PTR pReserved) { try { return SoftHSM::i()->C_Finalize(pReserved); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return information about the PKCS #11 module CK_RV C_GetInfo(CK_INFO_PTR pInfo) { try { return SoftHSM::i()->C_GetInfo(pInfo); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return the list of PKCS #11 functions CK_RV C_GetFunctionList(CK_FUNCTION_LIST_PTR_PTR ppFunctionList) { try { if (ppFunctionList == NULL_PTR) return CKR_ARGUMENTS_BAD; *ppFunctionList = &functionList; return CKR_OK; } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return a list of available slots CK_RV C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { try { return SoftHSM::i()->C_GetSlotList(tokenPresent, pSlotList, pulCount); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return information about a slot CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { try { return SoftHSM::i()->C_GetSlotInfo(slotID, pInfo); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return information about a token in a slot CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) { try { return SoftHSM::i()->C_GetTokenInfo(slotID, pInfo); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return the list of supported mechanisms for a given slot CK_RV C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) { try { return SoftHSM::i()->C_GetMechanismList(slotID, pMechanismList, pulCount); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Return more information about a mechanism for a given slot CK_RV C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo) { try { return SoftHSM::i()->C_GetMechanismInfo(slotID, type, pInfo); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise the token in the specified slot CK_RV C_InitToken(CK_SLOT_ID slotID, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen, CK_UTF8CHAR_PTR pLabel) { try { return SoftHSM::i()->C_InitToken(slotID, pPin, ulPinLen, pLabel); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise the user PIN CK_RV C_InitPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { try { return SoftHSM::i()->C_InitPIN(hSession, pPin, ulPinLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Change the PIN CK_RV C_SetPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pOldPin, CK_ULONG ulOldLen, CK_UTF8CHAR_PTR pNewPin, CK_ULONG ulNewLen) { try { return SoftHSM::i()->C_SetPIN(hSession, pOldPin, ulOldLen, pNewPin, ulNewLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Open a new session to the specified slot CK_RV C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY notify, CK_SESSION_HANDLE_PTR phSession) { try { return SoftHSM::i()->C_OpenSession(slotID, flags, pApplication, notify, phSession); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Close the given session CK_RV C_CloseSession(CK_SESSION_HANDLE hSession) { try { return SoftHSM::i()->C_CloseSession(hSession); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Close all open sessions CK_RV C_CloseAllSessions(CK_SLOT_ID slotID) { try { return SoftHSM::i()->C_CloseAllSessions(slotID); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Retrieve information about the specified session CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo) { try { return SoftHSM::i()->C_GetSessionInfo(hSession, pInfo); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Determine the state of a running operation in a session CK_RV C_GetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen) { try { return SoftHSM::i()->C_GetOperationState(hSession, pOperationState, pulOperationStateLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Set the operation sate in a session CK_RV C_SetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey) { try { return SoftHSM::i()->C_SetOperationState(hSession, pOperationState, ulOperationStateLen, hEncryptionKey, hAuthenticationKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Login on the token in the specified session CK_RV C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { try { return SoftHSM::i()->C_Login(hSession, userType, pPin, ulPinLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Log out of the token in the specified session CK_RV C_Logout(CK_SESSION_HANDLE hSession) { try { return SoftHSM::i()->C_Logout(hSession); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Create a new object on the token in the specified session using the given attribute template CK_RV C_CreateObject(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject) { try { return SoftHSM::i()->C_CreateObject(hSession, pTemplate, ulCount, phObject); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Create a copy of the object with the specified handle CK_RV C_CopyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phNewObject) { try { return SoftHSM::i()->C_CopyObject(hSession, hObject, pTemplate, ulCount, phNewObject); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Destroy the specified object CK_RV C_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { try { return SoftHSM::i()->C_DestroyObject(hSession, hObject); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Determine the size of the specified object CK_RV C_GetObjectSize(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { try { return SoftHSM::i()->C_GetObjectSize(hSession, hObject, pulSize); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Retrieve the specified attributes for the given object CK_RV C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { try { return SoftHSM::i()->C_GetAttributeValue(hSession, hObject, pTemplate, ulCount); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Change or set the value of the specified attributes on the specified object CK_RV C_SetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { try { return SoftHSM::i()->C_SetAttributeValue(hSession, hObject, pTemplate, ulCount); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise object search in the specified session using the specified attribute template as search parameters CK_RV C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { try { return SoftHSM::i()->C_FindObjectsInit(hSession, pTemplate, ulCount); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Continue the search for objects in the specified session CK_RV C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount) { try { return SoftHSM::i()->C_FindObjects(hSession, phObject, ulMaxObjectCount, pulObjectCount); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Finish searching for objects CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession) { try { return SoftHSM::i()->C_FindObjectsFinal(hSession); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise encryption using the specified object and mechanism CK_RV C_EncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hObject) { try { return SoftHSM::i()->C_EncryptInit(hSession, pMechanism, hObject); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Perform a single operation encryption operation in the specified session CK_RV C_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { try { return SoftHSM::i()->C_Encrypt(hSession, pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Feed data to the running encryption operation in a session CK_RV C_EncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { try { return SoftHSM::i()->C_EncryptUpdate(hSession, pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Finalise the encryption operation CK_RV C_EncryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { try { return SoftHSM::i()->C_EncryptFinal(hSession, pEncryptedData, pulEncryptedDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise decryption using the specified object CK_RV C_DecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hObject) { try { return SoftHSM::i()->C_DecryptInit(hSession, pMechanism, hObject); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Perform a single operation decryption in the given session CK_RV C_Decrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { try { return SoftHSM::i()->C_Decrypt(hSession, pEncryptedData, ulEncryptedDataLen, pData, pulDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Feed data to the running decryption operation in a session CK_RV C_DecryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { try { return SoftHSM::i()->C_DecryptUpdate(hSession, pEncryptedData, ulEncryptedDataLen, pData, pDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Finalise the decryption operation CK_RV C_DecryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { try { return SoftHSM::i()->C_DecryptFinal(hSession, pData, pDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise digesting using the specified mechanism in the specified session CK_RV C_DigestInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism) { try { return SoftHSM::i()->C_DigestInit(hSession, pMechanism); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Digest the specified data in a one-pass operation and return the resulting digest CK_RV C_Digest(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen) { try { return SoftHSM::i()->C_Digest(hSession, pData, ulDataLen, pDigest, pulDigestLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running digest operation CK_RV C_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { try { return SoftHSM::i()->C_DigestUpdate(hSession, pPart, ulPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running digest operation by digesting a secret key with the specified handle CK_RV C_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { try { return SoftHSM::i()->C_DigestKey(hSession, hObject); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Finalise the digest operation in the specified session and return the digest CK_RV C_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen) { try { return SoftHSM::i()->C_DigestFinal(hSession, pDigest, pulDigestLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise a signing operation using the specified key and mechanism CK_RV C_SignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { try { return SoftHSM::i()->C_SignInit(hSession, pMechanism, hKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Sign the data in a single pass operation CK_RV C_Sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { try { return SoftHSM::i()->C_Sign(hSession, pData, ulDataLen, pSignature, pulSignatureLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running signing operation with additional data CK_RV C_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { try { return SoftHSM::i()->C_SignUpdate(hSession, pPart, ulPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Finalise a running signing operation and return the signature CK_RV C_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { try { return SoftHSM::i()->C_SignFinal(hSession, pSignature, pulSignatureLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise a signing operation that allows recovery of the signed data CK_RV C_SignRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { try { return SoftHSM::i()->C_SignRecoverInit(hSession, pMechanism, hKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Perform a single part signing operation that allows recovery of the signed data CK_RV C_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { try { return SoftHSM::i()->C_SignRecover(hSession, pData, ulDataLen, pSignature, pulSignatureLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise a verification operation using the specified key and mechanism CK_RV C_VerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { try { return SoftHSM::i()->C_VerifyInit(hSession, pMechanism, hKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Perform a single pass verification operation CK_RV C_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { try { return SoftHSM::i()->C_Verify(hSession, pData, ulDataLen, pSignature, ulSignatureLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running verification operation with additional data CK_RV C_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { try { return SoftHSM::i()->C_VerifyUpdate(hSession, pPart, ulPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Finalise the verification operation and check the signature CK_RV C_VerifyFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { try { return SoftHSM::i()->C_VerifyFinal(hSession, pSignature, ulSignatureLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Initialise a verification operation the allows recovery of the signed data from the signature CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { try { return SoftHSM::i()->C_VerifyRecoverInit(hSession, pMechanism, hKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Perform a single part verification operation and recover the signed data CK_RV C_VerifyRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { try { return SoftHSM::i()->C_VerifyRecover(hSession, pSignature, ulSignatureLen, pData, pulDataLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running multi-part encryption and digesting operation CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen) { try { return SoftHSM::i()->C_DigestEncryptUpdate(hSession, pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running multi-part decryption and digesting operation CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pDecryptedPart, CK_ULONG_PTR pulDecryptedPartLen) { try { return SoftHSM::i()->C_DecryptDigestUpdate(hSession, pPart, ulPartLen, pDecryptedPart, pulDecryptedPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running multi-part signing and encryption operation CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen) { try { return SoftHSM::i()->C_SignEncryptUpdate(hSession, pPart, ulPartLen, pEncryptedPart, pulEncryptedPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Update a running multi-part decryption and verification operation CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen) { try { return SoftHSM::i()->C_DecryptVerifyUpdate(hSession, pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Generate a secret key using the specified mechanism CK_RV C_GenerateKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey) { try { return SoftHSM::i()->C_GenerateKey(hSession, pMechanism, pTemplate, ulCount, phKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Generate a key-pair using the specified mechanism CK_RV C_GenerateKeyPair ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey ) { try { return SoftHSM::i()->C_GenerateKeyPair(hSession, pMechanism, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, phPublicKey, phPrivateKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Wrap the specified key using the specified wrapping key and mechanism CK_RV C_WrapKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, CK_ULONG_PTR pulWrappedKeyLen ) { try { return SoftHSM::i()->C_WrapKey(hSession, pMechanism, hWrappingKey, hKey, pWrappedKey, pulWrappedKeyLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Unwrap the specified key using the specified unwrapping key CK_RV C_UnwrapKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey ) { try { return SoftHSM::i()->C_UnwrapKey(hSession, pMechanism, hUnwrappingKey, pWrappedKey, ulWrappedKeyLen, pTemplate, ulCount, phKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Derive a key from the specified base key CK_RV C_DeriveKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey ) { try { return SoftHSM::i()->C_DeriveKey(hSession, pMechanism, hBaseKey, pTemplate, ulCount, phKey); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Seed the random number generator with new data CK_RV C_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, CK_ULONG ulSeedLen) { try { return SoftHSM::i()->C_SeedRandom(hSession, pSeed, ulSeedLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Generate the specified amount of random data CK_RV C_GenerateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) { try { return SoftHSM::i()->C_GenerateRandom(hSession, pRandomData, ulRandomLen); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Legacy function CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE hSession) { try { return SoftHSM::i()->C_GetFunctionStatus(hSession); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Legacy function CK_RV C_CancelFunction(CK_SESSION_HANDLE hSession) { try { return SoftHSM::i()->C_CancelFunction(hSession); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } // Wait or poll for a slot even on the specified slot CK_RV C_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, CK_VOID_PTR pReserved) { try { return SoftHSM::i()->C_WaitForSlotEvent(flags, pSlot, pReserved); } catch (...) { FatalException(); } return CKR_FUNCTION_FAILED; } softhsm-2.0.0/src/lib/Makefile.am0000664000175000017500000000256312533040716013517 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/cryptoki_compat \ -I$(srcdir)/common \ -I$(srcdir)/object_store \ -I$(srcdir)/slot_mgr \ -I$(srcdir)/session_mgr \ -I$(srcdir)/data_mgr \ -I$(srcdir)/handle_mgr \ -I$(srcdir)/crypto lib_LTLIBRARIES = libsofthsm2.la libsofthsm2_la_SOURCES = access.cpp \ main.cpp \ P11Attributes.cpp \ P11Objects.cpp \ SoftHSM.cpp libsofthsm2_la_LIBADD = common/libsofthsm_common.la \ crypto/libsofthsm_crypto.la \ data_mgr/libsofthsm_datamgr.la \ handle_mgr/libsofthsm_handlemgr.la \ object_store/libsofthsm_objectstore.la \ session_mgr/libsofthsm_sessionmgr.la \ slot_mgr/libsofthsm_slotmgr.la libsofthsm2_la_LDFLAGS = -version-info @VERSION_INFO@ \ -avoid-version -module # Create a convenience library from all the other convenience library; this is # necessary to resolve circular dependencies when statically linking the test # executables noinst_LTLIBRARIES = libsofthsm_convarch.la libsofthsm_convarch_la_SOURCES = libsofthsm_convarch_la_LIBADD = $(libsofthsm2_la_LIBADD) SUBDIRS = common \ crypto \ data_mgr \ object_store \ session_mgr \ slot_mgr \ handle_mgr \ test EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/cryptoki_compat/*.h \ $(srcdir)/win32/*.cc \ $(srcdir)/win32/*.cpp \ $(srcdir)/win32/*.h softhsm-2.0.0/src/lib/access.h0000664000175000017500000000347512533040716013100 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** access.h Implements the access rules. *****************************************************************************/ #ifndef _SOFTHSM_V2_ACCESS_H #define _SOFTHSM_V2_ACCESS_H #include "cryptoki.h" CK_RV haveRead(CK_STATE sessionState, CK_BBOOL isTokenObject, CK_BBOOL isPrivateObject); CK_RV haveWrite(CK_STATE sessionState, CK_BBOOL isTokenObject, CK_BBOOL isPrivateObject); #endif /* !_SOFTHSM_V2_ACCESS_H */ softhsm-2.0.0/src/lib/session_mgr/0000775000175000017500000000000012552220147014064 500000000000000softhsm-2.0.0/src/lib/session_mgr/SessionManager.h0000664000175000017500000000456012533040716017101 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionManager.h Keeps track of the sessions within SoftHSM *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONMANAGER_H #define _SOFTHSM_V2_SESSIONMANAGER_H #include "Slot.h" #include "Session.h" #include "MutexFactory.h" #include "config.h" #include "cryptoki.h" #include #include class SessionManager { public: SessionManager(); virtual ~SessionManager(); CK_RV openSession(Slot* slot, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY Notify, CK_SESSION_HANDLE_PTR phSession); CK_RV closeSession(CK_SESSION_HANDLE hSession); CK_RV closeAllSessions(Slot* slot); CK_RV getSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo); Session* getSession(CK_SESSION_HANDLE hSession); bool haveSession(size_t slotID); bool haveROSession(size_t slotID); private: // The sessions std::vector sessions; Mutex* sessionsMutex; }; #endif // !_SOFTHSM_V2_SESSIONMANAGER_H softhsm-2.0.0/src/lib/session_mgr/Session.cpp0000664000175000017500000002024412533040716016136 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Session.h This class represents a single session *****************************************************************************/ #include "CryptoFactory.h" #include "Session.h" // Constructor Session::Session(Slot* inSlot, bool inIsReadWrite, CK_VOID_PTR inPApplication, CK_NOTIFY inNotify) { slot = inSlot; token = slot->getToken(); isReadWrite = inIsReadWrite; hSession = CK_INVALID_HANDLE; pApplication = inPApplication; notify = inNotify; operation = SESSION_OP_NONE; findOp = NULL; digestOp = NULL; macOp = NULL; asymmetricCryptoOp = NULL; symmetricCryptoOp = NULL; mechanism = AsymMech::Unknown; allowSinglePartOp = false; allowMultiPartOp = false; publicKey = NULL; privateKey = NULL; symmetricKey = NULL; param = NULL; paramLen = 0; } // Constructor Session::Session() { slot = NULL; token = NULL; isReadWrite = false; hSession = CK_INVALID_HANDLE; pApplication = NULL; notify = NULL; operation = SESSION_OP_NONE; findOp = NULL; digestOp = NULL; macOp = NULL; asymmetricCryptoOp = NULL; symmetricCryptoOp = NULL; mechanism = AsymMech::Unknown; allowSinglePartOp = false; allowMultiPartOp = false; publicKey = NULL; privateKey = NULL; symmetricKey = NULL; param = NULL; paramLen = 0; } // Destructor Session::~Session() { resetOp(); } // Get session info CK_RV Session::getInfo(CK_SESSION_INFO_PTR pInfo) { if (pInfo == NULL_PTR) return CKR_ARGUMENTS_BAD; pInfo->slotID = slot->getSlotID(); pInfo->state = getState(); pInfo->flags = CKF_SERIAL_SESSION; if (isRW()) { pInfo->flags |= CKF_RW_SESSION; } pInfo->ulDeviceError = 0; return CKR_OK; } // Is a read and write session bool Session::isRW() { return isReadWrite; } // Get session state CK_STATE Session::getState() { if (token->isSOLoggedIn()) { return CKS_RW_SO_FUNCTIONS; } if (token->isUserLoggedIn()) { if (isRW()) { return CKS_RW_USER_FUNCTIONS; } else { return CKS_RO_USER_FUNCTIONS; } } if (isRW()) { return CKS_RW_PUBLIC_SESSION; } else { return CKS_RO_PUBLIC_SESSION; } } void Session::setHandle(CK_SESSION_HANDLE inHSession) { hSession = inHSession; } CK_SESSION_HANDLE Session::getHandle() { return hSession; } // Return the slot that the session is connected to Slot* Session::getSlot() { return slot; } // Return the token that the session is connected to Token* Session::getToken() { return token; } // Set the operation type void Session::setOpType(int inOperation) { operation = inOperation; } // Get the operation type int Session::getOpType() { return operation; } // Reset the operations void Session::resetOp() { if (param != NULL) { free(param); param = NULL; paramLen = 0; } if (digestOp != NULL) { CryptoFactory::i()->recycleHashAlgorithm(digestOp); digestOp = NULL; } else if (findOp != NULL) { findOp->recycle(); findOp = NULL; } else if (asymmetricCryptoOp != NULL) { if (publicKey != NULL) { asymmetricCryptoOp->recyclePublicKey(publicKey); publicKey = NULL; } if (privateKey != NULL) { asymmetricCryptoOp->recyclePrivateKey(privateKey); privateKey = NULL; } CryptoFactory::i()->recycleAsymmetricAlgorithm(asymmetricCryptoOp); asymmetricCryptoOp = NULL; } else if (symmetricCryptoOp != NULL) { if (symmetricKey != NULL) { symmetricCryptoOp->recycleKey(symmetricKey); symmetricKey = NULL; } CryptoFactory::i()->recycleSymmetricAlgorithm(symmetricCryptoOp); symmetricCryptoOp = NULL; } else if (macOp != NULL) { if (symmetricKey != NULL) { macOp->recycleKey(symmetricKey); symmetricKey = NULL; } CryptoFactory::i()->recycleMacAlgorithm(macOp); macOp = NULL; } operation = SESSION_OP_NONE; } void Session::setFindOp(FindOperation *inFindOp) { if (findOp != NULL) { delete findOp; } findOp = inFindOp; } FindOperation *Session::getFindOp() { return findOp; } // Set the digesting operator void Session::setDigestOp(HashAlgorithm* inDigestOp) { if (digestOp != NULL) { CryptoFactory::i()->recycleHashAlgorithm(digestOp); } digestOp = inDigestOp; } // Get the digesting operator HashAlgorithm* Session::getDigestOp() { return digestOp; } // Set the MACing operator void Session::setMacOp(MacAlgorithm *inMacOp) { if (macOp != NULL) { setSymmetricKey(NULL); CryptoFactory::i()->recycleMacAlgorithm(macOp); } macOp = inMacOp; } // Get the MACing operator MacAlgorithm *Session::getMacOp() { return macOp; } void Session::setAsymmetricCryptoOp(AsymmetricAlgorithm *inAsymmetricCryptoOp) { if (asymmetricCryptoOp != NULL) { setPublicKey(NULL); setPrivateKey(NULL); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymmetricCryptoOp); } asymmetricCryptoOp = inAsymmetricCryptoOp; } AsymmetricAlgorithm *Session::getAsymmetricCryptoOp() { return asymmetricCryptoOp; } void Session::setSymmetricCryptoOp(SymmetricAlgorithm *inSymmetricCryptoOp) { if (symmetricCryptoOp != NULL) { setSymmetricKey(NULL); CryptoFactory::i()->recycleSymmetricAlgorithm(symmetricCryptoOp); } symmetricCryptoOp = inSymmetricCryptoOp; } SymmetricAlgorithm *Session::getSymmetricCryptoOp() { return symmetricCryptoOp; } void Session::setMechanism(AsymMech::Type inMechanism) { mechanism = inMechanism; } AsymMech::Type Session::getMechanism() { return mechanism; } void Session::setParameters(void* inParam, size_t inParamLen) { if (inParam == NULL || inParamLen == 0) return; if (param != NULL) { free(param); paramLen = 0; } param = malloc(inParamLen); if (param != NULL) { memcpy(param, inParam, inParamLen); paramLen = inParamLen; } } void* Session::getParameters(size_t& inParamLen) { inParamLen = paramLen; return param; } void Session::setAllowMultiPartOp(bool inAllowMultiPartOp) { allowMultiPartOp = inAllowMultiPartOp; } bool Session::getAllowMultiPartOp() { return allowMultiPartOp; } void Session::setAllowSinglePartOp(bool inAllowSinglePartOp) { allowSinglePartOp = inAllowSinglePartOp; } bool Session::getAllowSinglePartOp() { return allowSinglePartOp; } void Session::setPublicKey(PublicKey* inPublicKey) { if (asymmetricCryptoOp == NULL) return; if (publicKey != NULL) { asymmetricCryptoOp->recyclePublicKey(publicKey); } publicKey = inPublicKey; } PublicKey* Session::getPublicKey() { return publicKey; } void Session::setPrivateKey(PrivateKey* inPrivateKey) { if (asymmetricCryptoOp == NULL) return; if (privateKey != NULL) { asymmetricCryptoOp->recyclePrivateKey(privateKey); } privateKey = inPrivateKey; } PrivateKey* Session::getPrivateKey() { return privateKey; } void Session::setSymmetricKey(SymmetricKey* inSymmetricKey) { if (symmetricKey != NULL) { if (macOp) { macOp->recycleKey(symmetricKey); } else if (symmetricCryptoOp) { symmetricCryptoOp->recycleKey(symmetricKey); } else { return; } } symmetricKey = inSymmetricKey; } SymmetricKey* Session::getSymmetricKey() { return symmetricKey; } softhsm-2.0.0/src/lib/session_mgr/Makefile.am0000664000175000017500000000067612533040716016052 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../slot_mgr \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../object_store \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_sessionmgr.la libsofthsm_sessionmgr_la_SOURCES = SessionManager.cpp \ Session.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/session_mgr/SessionManager.cpp0000664000175000017500000001514012533040716017430 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionManager.cpp Keeps track of the sessions within SoftHSM. The sessions are stored in a vector. When a session is closed, its spot in the vector will be replaced with NULL. Because we want to keep track of the session ID which is equal to its location in the vector. New sessions will first fill up the NULL locations and if there is no empty spots, then they are added to the end. *****************************************************************************/ #include "SessionManager.h" #include "log.h" // Constructor SessionManager::SessionManager() { sessionsMutex = MutexFactory::i()->getMutex(); } // Destructor SessionManager::~SessionManager() { std::vector toDelete = sessions; sessions.clear(); for (std::vector::iterator i = toDelete.begin(); i != toDelete.end(); i++) { if (*i != NULL) delete *i; } MutexFactory::i()->recycleMutex(sessionsMutex); } // Open a new session CK_RV SessionManager::openSession ( Slot* slot, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY notify, CK_SESSION_HANDLE_PTR phSession ) { if (phSession == NULL_PTR) return CKR_ARGUMENTS_BAD; if (slot == NULL) return CKR_SLOT_ID_INVALID; if ((flags & CKF_SERIAL_SESSION) == 0) return CKR_SESSION_PARALLEL_NOT_SUPPORTED; // Lock access to the vector MutexLocker lock(sessionsMutex); // Get the token Token* token = slot->getToken(); if (token == NULL) return CKR_TOKEN_NOT_PRESENT; if (!token->isInitialized()) return CKR_TOKEN_NOT_RECOGNIZED; // Can not open a Read-Only session when in SO mode if ((flags & CKF_RW_SESSION) == 0 && token->isSOLoggedIn()) return CKR_SESSION_READ_WRITE_SO_EXISTS; // TODO: Do we want to check for maximum number of sessions? // return CKR_SESSION_COUNT // Create the session bool rwSession = ((flags & CKF_RW_SESSION) == CKF_RW_SESSION) ? true : false; Session* session = new Session(slot, rwSession, pApplication, notify); // First fill any empty spot in the list for (size_t i = 0; i < sessions.size(); i++) { if (sessions[i] != NULL) { continue; } sessions[i] = session; session->setHandle(i + 1); *phSession = session->getHandle(); return CKR_OK; } // Or add it to the end sessions.push_back(session); session->setHandle(sessions.size()); *phSession = session->getHandle(); return CKR_OK; } // Close a session CK_RV SessionManager::closeSession(CK_SESSION_HANDLE hSession) { if (hSession == CK_INVALID_HANDLE) return CKR_SESSION_HANDLE_INVALID; // Lock access to the vector MutexLocker lock(sessionsMutex); // Check if we are out of range if (hSession > sessions.size()) return CKR_SESSION_HANDLE_INVALID; // Check if it is a closed session unsigned long sessionID = hSession - 1; if (sessions[sessionID] == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if this is the last session on the token bool lastSession = true; CK_ULONG slotID = sessions[sessionID]->getSlot()->getSlotID(); for (size_t i = 0; i < sessions.size(); i++) { if (sessions[i] == NULL) continue; if (sessions[i]->getSlot()->getSlotID() == slotID && i != sessionID) { lastSession = false; break; } } // Logout if this is the last session on the token if (lastSession) { sessions[sessionID]->getSlot()->getToken()->logout(); } // Close the session delete sessions[sessionID]; sessions[sessionID] = NULL; return CKR_OK; } // Close all sessions CK_RV SessionManager::closeAllSessions(Slot* slot) { if (slot == NULL) return CKR_SLOT_ID_INVALID; // Lock access to the vector MutexLocker lock(sessionsMutex); // Get the token Token* token = slot->getToken(); if (token == NULL) return CKR_TOKEN_NOT_PRESENT; // Close all sessions on this slot CK_ULONG slotID = slot->getSlotID(); for (std::vector::iterator i = sessions.begin(); i != sessions.end(); i++) { if (*i == NULL) continue; if ((*i)->getSlot()->getSlotID() == slotID) { delete *i; *i = NULL; } } // Logout from the token token->logout(); return CKR_OK; } // Get session info CK_RV SessionManager::getSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo) { // Get the session Session* session = getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return session->getInfo(pInfo); } // Get the session Session* SessionManager::getSession(CK_SESSION_HANDLE hSession) { // Lock access to the vector MutexLocker lock(sessionsMutex); // We do not want to get a negative number below if (hSession == CK_INVALID_HANDLE) return NULL; // Check if we are out of range if (hSession > sessions.size()) return NULL; return sessions[hSession - 1]; } bool SessionManager::haveSession(size_t slotID) { // Lock access to the vector MutexLocker lock(sessionsMutex); for (std::vector::iterator i = sessions.begin(); i != sessions.end(); i++) { if (*i == NULL) continue; if ((*i)->getSlot()->getSlotID() == slotID) { return true; } } return false; } bool SessionManager::haveROSession(size_t slotID) { // Lock access to the vector MutexLocker lock(sessionsMutex); for (std::vector::iterator i = sessions.begin(); i != sessions.end(); i++) { if (*i == NULL) continue; if ((*i)->getSlot()->getSlotID() != slotID) continue; if ((*i)->isRW() == false) return true; } return false; } softhsm-2.0.0/src/lib/session_mgr/Session.h0000664000175000017500000001066312533040716015607 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Session.h This class represents a single session *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSION_H #define _SOFTHSM_V2_SESSION_H #include "Slot.h" #include "FindOperation.h" #include "HashAlgorithm.h" #include "MacAlgorithm.h" #include "AsymmetricAlgorithm.h" #include "SymmetricAlgorithm.h" #include "Token.h" #include "cryptoki.h" #define SESSION_OP_NONE 0x0 #define SESSION_OP_FIND 0x1 #define SESSION_OP_ENCRYPT 0x2 #define SESSION_OP_DECRYPT 0x3 #define SESSION_OP_DIGEST 0x4 #define SESSION_OP_SIGN 0x5 #define SESSION_OP_VERIFY 0x6 #define SESSION_OP_DIGEST_ENCRYPT 0x7 #define SESSION_OP_DECRYPT_DIGEST 0x8 #define SESSION_OP_SIGN_ENCRYPT 0x9 #define SESSION_OP_DECRYPT_VERIFY 0x10 class Session { public: Session(Slot* inSlot, bool inIsReadWrite, CK_VOID_PTR inPApplication, CK_NOTIFY inNotify); // Destructor virtual ~Session(); // Slot and token Slot* getSlot(); Token* getToken(); // Session properties CK_RV getInfo(CK_SESSION_INFO_PTR pInfo); bool isRW(); CK_STATE getState(); void setHandle(CK_SESSION_HANDLE inHSession); CK_SESSION_HANDLE getHandle(); // Operations int getOpType(); void setOpType(int inOperation); void resetOp(); // Find void setFindOp(FindOperation *inFindOp); FindOperation *getFindOp(); // Digest void setDigestOp(HashAlgorithm* inDigestOp); HashAlgorithm* getDigestOp(); // Mac void setMacOp(MacAlgorithm* inMacOp); MacAlgorithm* getMacOp(); // Asymmetric Crypto void setAsymmetricCryptoOp(AsymmetricAlgorithm* inAsymmetricCryptoOp); AsymmetricAlgorithm* getAsymmetricCryptoOp(); // Symmetric Crypto void setSymmetricCryptoOp(SymmetricAlgorithm* inSymmetricCryptoOp); SymmetricAlgorithm* getSymmetricCryptoOp(); void setMechanism(AsymMech::Type inMechanism); AsymMech::Type getMechanism(); void setParameters(void* inParam, size_t inParamLen); void* getParameters(size_t& inParamLen); void setAllowMultiPartOp(bool inAllowMultiPartOp); bool getAllowMultiPartOp(); void setAllowSinglePartOp(bool inAllowSinglePartOp); bool getAllowSinglePartOp(); void setPublicKey(PublicKey* inPublicKey); PublicKey* getPublicKey(); void setPrivateKey(PrivateKey* inPrivateKey); PrivateKey* getPrivateKey(); void setSymmetricKey(SymmetricKey* inSymmetricKey); SymmetricKey* getSymmetricKey(); private: // Constructor Session(); // Slot and token Slot* slot; Token* token; // Application data (not in use) CK_VOID_PTR pApplication; CK_NOTIFY notify; // Session properties bool isReadWrite; CK_SESSION_HANDLE hSession; // Operations int operation; // Find FindOperation *findOp; // Digest HashAlgorithm* digestOp; // Mac MacAlgorithm* macOp; // Asymmetric Crypto AsymmetricAlgorithm* asymmetricCryptoOp; // Symmetric Crypto SymmetricAlgorithm* symmetricCryptoOp; AsymMech::Type mechanism; void* param; size_t paramLen; bool allowMultiPartOp; bool allowSinglePartOp; PublicKey* publicKey; PrivateKey* privateKey; // Symmetric Crypto SymmetricKey* symmetricKey; }; #endif // !_SOFTHSM_V2_SESSION_H softhsm-2.0.0/src/lib/session_mgr/test/0000775000175000017500000000000012552220147015043 500000000000000softhsm-2.0.0/src/lib/session_mgr/test/Makefile.am0000664000175000017500000000125312533040716017021 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../data_mgr \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ -I$(srcdir)/../../object_store \ `cppunit-config --cflags` check_PROGRAMS = sessionmgrtest sessionmgrtest_SOURCES = sessionmgrtest.cpp \ SessionManagerTests.cpp sessionmgrtest_LDADD = ../../libsofthsm_convarch.la sessionmgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread TESTS = sessionmgrtest EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/session_mgr/test/SessionManagerTests.cpp0000664000175000017500000000402312533040716021430 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionManagerTests.cpp Contains test cases for SessionManager *****************************************************************************/ #include #include #include #include "SessionManagerTests.h" #include "SessionManager.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(SessionManagerTests); void SessionManagerTests::setUp() { } void SessionManagerTests::tearDown() { } void SessionManagerTests::testOpenClose() { // TODO ??? // CK_SESSION_HANDLE hSession; // CK_RV rv; // rv = SessionManager::i()->openSession() // CPPUNIT_ASSERT(rv == CKR_OK); } softhsm-2.0.0/src/lib/session_mgr/test/sessionmgrtest.cpp0000664000175000017500000000362312533040716020565 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** sessionmgrtest.cpp The main test executor for tests on the session manager in SoftHSM v2 *****************************************************************************/ #include #include int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/session_mgr/test/SessionManagerTests.h0000664000175000017500000000367312533040716021107 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionManagerTests.h Contains test cases for SessionManager *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONMANAGERTESTS_H #define _SOFTHSM_V2_SESSIONMANAGERTESTS_H #include class SessionManagerTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SessionManagerTests); CPPUNIT_TEST(testOpenClose); CPPUNIT_TEST_SUITE_END(); public: void testOpenClose(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_SESSIONMANAGERTESTS_H softhsm-2.0.0/src/lib/session_mgr/test/Makefile.in0000664000175000017500000010135212552216620017033 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = sessionmgrtest$(EXEEXT) TESTS = sessionmgrtest$(EXEEXT) subdir = src/lib/session_mgr/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am_sessionmgrtest_OBJECTS = sessionmgrtest.$(OBJEXT) \ SessionManagerTests.$(OBJEXT) sessionmgrtest_OBJECTS = $(am_sessionmgrtest_OBJECTS) sessionmgrtest_DEPENDENCIES = ../../libsofthsm_convarch.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = sessionmgrtest_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(sessionmgrtest_LDFLAGS) \ $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(sessionmgrtest_SOURCES) DIST_SOURCES = $(sessionmgrtest_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../data_mgr \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ -I$(srcdir)/../../object_store \ `cppunit-config --cflags` sessionmgrtest_SOURCES = sessionmgrtest.cpp \ SessionManagerTests.cpp sessionmgrtest_LDADD = ../../libsofthsm_convarch.la sessionmgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/session_mgr/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/session_mgr/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list sessionmgrtest$(EXEEXT): $(sessionmgrtest_OBJECTS) $(sessionmgrtest_DEPENDENCIES) $(EXTRA_sessionmgrtest_DEPENDENCIES) @rm -f sessionmgrtest$(EXEEXT) $(AM_V_CXXLD)$(sessionmgrtest_LINK) $(sessionmgrtest_OBJECTS) $(sessionmgrtest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionManagerTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/sessionmgrtest.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? sessionmgrtest.log: sessionmgrtest$(EXEEXT) @p='sessionmgrtest$(EXEEXT)'; \ b='sessionmgrtest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/session_mgr/Makefile.in0000664000175000017500000005620212552216620016057 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/lib/session_mgr DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_sessionmgr_la_LIBADD = am_libsofthsm_sessionmgr_la_OBJECTS = SessionManager.lo Session.lo libsofthsm_sessionmgr_la_OBJECTS = \ $(am_libsofthsm_sessionmgr_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_sessionmgr_la_SOURCES) DIST_SOURCES = $(libsofthsm_sessionmgr_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../slot_mgr \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../object_store \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_sessionmgr.la libsofthsm_sessionmgr_la_SOURCES = SessionManager.cpp \ Session.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/session_mgr/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/session_mgr/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_sessionmgr.la: $(libsofthsm_sessionmgr_la_OBJECTS) $(libsofthsm_sessionmgr_la_DEPENDENCIES) $(EXTRA_libsofthsm_sessionmgr_la_DEPENDENCIES) $(AM_V_CXXLD)$(CXXLINK) $(libsofthsm_sessionmgr_la_OBJECTS) $(libsofthsm_sessionmgr_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Session.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionManager.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/slot_mgr/0000775000175000017500000000000012552220147013362 500000000000000softhsm-2.0.0/src/lib/slot_mgr/Makefile.am0000664000175000017500000000067112533040716015343 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../session_mgr \ -I$(srcdir)/../object_store \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_slotmgr.la libsofthsm_slotmgr_la_SOURCES = SlotManager.cpp \ Slot.cpp \ Token.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/slot_mgr/SlotManager.cpp0000664000175000017500000000704312533040716016227 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SlotManager.cpp The slot manager is a class that forms part of the PKCS #11 core. It manages all the slots that SoftHSM is aware of. To make it possible to add new tokens, SoftHSM always has one slot available that contains an uninitialised token. Users can choose to initialise this token to create a new token. *****************************************************************************/ #include "config.h" #include "log.h" #include "SlotManager.h" // Constructor SlotManager::SlotManager(ObjectStore* objectStore) { // Add a slot for each token that already exists for (size_t i = 0; i < objectStore->getTokenCount(); i++) { Slot* newSlot = new Slot(objectStore, i, objectStore->getToken(i)); slots.push_back(newSlot); } // Add an empty slot slots.push_back(new Slot(objectStore, objectStore->getTokenCount())); } // Destructor SlotManager::~SlotManager() { std::vector toDelete = slots; slots.clear(); for (std::vector::iterator i = toDelete.begin(); i != toDelete.end(); i++) { delete *i; } } // Get the slot list CK_RV SlotManager::getSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { CK_ULONG size = 0; if (pulCount == NULL) return CKR_ARGUMENTS_BAD; // Calculate the size of the list for (std::vector::iterator i = slots.begin(); i != slots.end(); i++) { if ((tokenPresent == CK_FALSE) || (*i)->isTokenPresent()) { size++; } } // The user wants the size of the list if (pSlotList == NULL) { *pulCount = size; return CKR_OK; } // Is the given buffer too small? if (*pulCount < size) { *pulCount = size; return CKR_BUFFER_TOO_SMALL; } size = 0; for (std::vector::iterator i = slots.begin(); i != slots.end(); i++) { if ((tokenPresent == CK_FALSE) || (*i)->isTokenPresent()) { pSlotList[size++] = (CK_ULONG)(*i)->getSlotID(); } } *pulCount = size; return CKR_OK; } // Get the slots std::vector SlotManager::getSlots() { return slots; } // Get one slot Slot* SlotManager::getSlot(CK_SLOT_ID slotID) { for (std::vector::iterator i = slots.begin(); i != slots.end(); i++) { if ((*i)->getSlotID() == slotID) { return *i; } } return NULL; } softhsm-2.0.0/src/lib/slot_mgr/test/0000775000175000017500000000000012552220147014341 500000000000000softhsm-2.0.0/src/lib/slot_mgr/test/slotmgrtest.cpp0000664000175000017500000000361512533040716017362 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** slotmgrtest.cpp The main test executor for tests on the slot manager in SoftHSM v2 *****************************************************************************/ #include #include int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/slot_mgr/test/SlotManagerTests.h0000664000175000017500000000422412533040716017674 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SlotManagerTests.h Contains test cases to test the slot manager implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_SLOTMANAGERTESTS_H #define _SOFTHSM_V2_SLOTMANAGERTESTS_H #include class SlotManagerTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SlotManagerTests); CPPUNIT_TEST(testNoExistingTokens); CPPUNIT_TEST(testExistingTokens); CPPUNIT_TEST(testInitialiseTokenInLastSlot); CPPUNIT_TEST(testReinitialiseExistingToken); CPPUNIT_TEST_SUITE_END(); public: void testNoExistingTokens(); void testExistingTokens(); void testInitialiseTokenInLastSlot(); void testReinitialiseExistingToken(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_SLOTMANAGERTESTS_H softhsm-2.0.0/src/lib/slot_mgr/test/Makefile.am0000664000175000017500000000117012533040716016315 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../data_mgr \ `cppunit-config --cflags` check_PROGRAMS = slotmgrtest slotmgrtest_SOURCES = slotmgrtest.cpp \ SlotManagerTests.cpp slotmgrtest_LDADD = ../../libsofthsm_convarch.la slotmgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread TESTS = slotmgrtest EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/slot_mgr/test/SlotManagerTests.cpp0000664000175000017500000003350412533040716020232 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SlotManagerTests.cpp Contains test cases to test the object store implementation *****************************************************************************/ #include #include #include #include "SlotManagerTests.h" #include "SlotManager.h" #include "Token.h" #include "ObjectStore.h" #include "ObjectFile.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "CryptoFactory.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(SlotManagerTests); void SlotManagerTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void SlotManagerTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif CryptoFactory::reset(); SecureMemoryRegistry::reset(); } void SlotManagerTests::testNoExistingTokens() { // Create an empty object store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif // Create the slot manager SlotManager slotManager(&store); CPPUNIT_ASSERT(slotManager.getSlots().size() == 1); // Test C_GetSlotList CK_SLOT_ID testList[10]; CK_ULONG ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_FALSE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 1); ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_TRUE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 1); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotID() == testList[0]); // Retrieve slot information about the first slot CK_SLOT_INFO slotInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CK_TOKEN_INFO tokenInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) != CKF_TOKEN_INITIALIZED); } void SlotManagerTests::testExistingTokens() { // Create an empty object store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif // Create two tokens ByteString label1 = "DEADBEEF"; ByteString label2 = "DEADC0FFEE"; CPPUNIT_ASSERT(store.newToken(label1) != NULL); CPPUNIT_ASSERT(store.newToken(label2) != NULL); // Now attach the slot manager SlotManager slotManager(&store); CPPUNIT_ASSERT(slotManager.getSlots().size() == 3); // Test C_GetSlotList CK_SLOT_ID testList[10]; CK_ULONG ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_FALSE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 3); ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_TRUE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 3); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotID() == testList[0]); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotID() == testList[1]); CPPUNIT_ASSERT(slotManager.getSlots()[2]->getSlotID() == testList[2]); // Retrieve slot information about the first slot CK_SLOT_INFO slotInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CK_TOKEN_INFO tokenInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CPPUNIT_ASSERT(!memcmp(tokenInfo.label, &label1[0], label1.size()) || !memcmp(tokenInfo.label, &label2[0], label2.size())); // Retrieve slot information about the second slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the second slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CPPUNIT_ASSERT(!memcmp(tokenInfo.label, &label1[0], label1.size()) || !memcmp(tokenInfo.label, &label2[0], label2.size())); // Retrieve slot information about the third slot CPPUNIT_ASSERT(slotManager.getSlots()[2]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the third slot CPPUNIT_ASSERT(slotManager.getSlots()[2]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[2]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) != CKF_TOKEN_INITIALIZED); } void SlotManagerTests::testInitialiseTokenInLastSlot() { { // Create an empty object store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif // Create the slot manager SlotManager slotManager(&store); CPPUNIT_ASSERT(slotManager.getSlots().size() == 1); // Test C_GetSlotList CK_SLOT_ID testList[10]; CK_ULONG ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_FALSE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 1); ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_TRUE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 1); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotID() == testList[0]); // Retrieve slot information about the first slot CK_SLOT_INFO slotInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CK_TOKEN_INFO tokenInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) != CKF_TOKEN_INITIALIZED); // Now initialise the token in the first slot ByteString soPIN((unsigned char*)"1234", 4); CK_UTF8CHAR label[33] = "My test token "; CPPUNIT_ASSERT(slotManager.getSlots()[0]->initToken(soPIN, label) == CKR_OK); // Retrieve slot information about the first slot CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CPPUNIT_ASSERT(!memcmp(tokenInfo.label, label, 32)); } // Attach a fresh slot manager #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif SlotManager slotManager(&store); CPPUNIT_ASSERT(slotManager.getSlots().size() == 2); // Test C_GetSlotList CK_SLOT_ID testList[10]; CK_ULONG ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_FALSE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 2); ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_TRUE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 2); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotID() == testList[0]); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotID() == testList[1]); // Retrieve slot information about the first slot CK_SLOT_INFO slotInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CK_TOKEN_INFO tokenInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CK_UTF8CHAR label[33] = "My test token "; CPPUNIT_ASSERT(!memcmp(tokenInfo.label, label, 32)); // Retrieve slot information about the second slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the second slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) != CKF_TOKEN_INITIALIZED); } void SlotManagerTests::testReinitialiseExistingToken() { // Create an empty object store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif // Create two tokens ByteString label1 = "DEADBEEF"; ByteString label2 = "DEADC0FFEE"; CPPUNIT_ASSERT(store.newToken(label1) != NULL); CPPUNIT_ASSERT(store.newToken(label2) != NULL); // Now attach the slot manager SlotManager slotManager(&store); CPPUNIT_ASSERT(slotManager.getSlots().size() == 3); // Test C_GetSlotList CK_SLOT_ID testList[10]; CK_ULONG ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_FALSE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 3); ulCount = 10; CPPUNIT_ASSERT(slotManager.getSlotList(CK_TRUE, testList, &ulCount) == CKR_OK); CPPUNIT_ASSERT(ulCount == 3); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotID() == testList[0]); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotID() == testList[1]); CPPUNIT_ASSERT(slotManager.getSlots()[2]->getSlotID() == testList[2]); // Retrieve slot information about the first slot CK_SLOT_INFO slotInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CK_TOKEN_INFO tokenInfo; CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[0]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CPPUNIT_ASSERT(!memcmp(tokenInfo.label, &label1[0], label1.size()) || !memcmp(tokenInfo.label, &label2[0], label2.size())); // Retrieve slot information about the second slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the second slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CPPUNIT_ASSERT(!memcmp(tokenInfo.label, &label1[0], label1.size()) || !memcmp(tokenInfo.label, &label2[0], label2.size())); // Retrieve slot information about the third slot CPPUNIT_ASSERT(slotManager.getSlots()[2]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the third slot CPPUNIT_ASSERT(slotManager.getSlots()[2]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[2]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) != CKF_TOKEN_INITIALIZED); // Now reinitialise the token in the second slot ByteString soPIN((unsigned char*)"1234", 4); CK_UTF8CHAR label[33] = "My test token "; CPPUNIT_ASSERT(slotManager.getSlots()[1]->initToken(soPIN, label) == CKR_OK); // Retrieve slot information about the first slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getSlotInfo(&slotInfo) == CKR_OK); CPPUNIT_ASSERT((slotInfo.flags & CKF_TOKEN_PRESENT) == CKF_TOKEN_PRESENT); // Retrieve token information about the token in the first slot CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken() != NULL); CPPUNIT_ASSERT(slotManager.getSlots()[1]->getToken()->getTokenInfo(&tokenInfo) == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); CPPUNIT_ASSERT(!memcmp(tokenInfo.label, label, 32)); } softhsm-2.0.0/src/lib/slot_mgr/test/Makefile.in0000664000175000017500000010114012552216620016324 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = slotmgrtest$(EXEEXT) TESTS = slotmgrtest$(EXEEXT) subdir = src/lib/slot_mgr/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am_slotmgrtest_OBJECTS = slotmgrtest.$(OBJEXT) \ SlotManagerTests.$(OBJEXT) slotmgrtest_OBJECTS = $(am_slotmgrtest_OBJECTS) slotmgrtest_DEPENDENCIES = ../../libsofthsm_convarch.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = slotmgrtest_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(slotmgrtest_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(slotmgrtest_SOURCES) DIST_SOURCES = $(slotmgrtest_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../data_mgr \ `cppunit-config --cflags` slotmgrtest_SOURCES = slotmgrtest.cpp \ SlotManagerTests.cpp slotmgrtest_LDADD = ../../libsofthsm_convarch.la slotmgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/slot_mgr/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/slot_mgr/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list slotmgrtest$(EXEEXT): $(slotmgrtest_OBJECTS) $(slotmgrtest_DEPENDENCIES) $(EXTRA_slotmgrtest_DEPENDENCIES) @rm -f slotmgrtest$(EXEEXT) $(AM_V_CXXLD)$(slotmgrtest_LINK) $(slotmgrtest_OBJECTS) $(slotmgrtest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SlotManagerTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/slotmgrtest.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? slotmgrtest.log: slotmgrtest$(EXEEXT) @p='slotmgrtest$(EXEEXT)'; \ b='slotmgrtest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/slot_mgr/SlotManager.h0000664000175000017500000000457012533040716015676 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SlotManager.h The slot manager is a class that forms part of the PKCS #11 core. It manages all the slots that SoftHSM is aware of. To make it possible to add new tokens, SoftHSM always has one slot available that contains an uninitialised token. Users can choose to initialise this token to create a new token. *****************************************************************************/ #ifndef _SOFTHSM_V2_SLOTMANAGER_H #define _SOFTHSM_V2_SLOTMANAGER_H #include "config.h" #include "ByteString.h" #include "ObjectStore.h" #include "Slot.h" #include #include class SlotManager { public: // Constructor SlotManager(ObjectStore* objectStore); // Destructor virtual ~SlotManager(); // Get the slots std::vector getSlots(); // Get the slot list CK_RV getSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount); // Get one slot Slot* getSlot(CK_SLOT_ID slotID); private: // The slots std::vector slots; }; #endif // !_SOFTHSM_V2_SLOTMANAGER_H softhsm-2.0.0/src/lib/slot_mgr/Makefile.in0000664000175000017500000005622412552216620015361 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/lib/slot_mgr DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_slotmgr_la_LIBADD = am_libsofthsm_slotmgr_la_OBJECTS = SlotManager.lo Slot.lo Token.lo libsofthsm_slotmgr_la_OBJECTS = $(am_libsofthsm_slotmgr_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_slotmgr_la_SOURCES) DIST_SOURCES = $(libsofthsm_slotmgr_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../session_mgr \ -I$(srcdir)/../object_store \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_slotmgr.la libsofthsm_slotmgr_la_SOURCES = SlotManager.cpp \ Slot.cpp \ Token.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/slot_mgr/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/slot_mgr/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_slotmgr.la: $(libsofthsm_slotmgr_la_OBJECTS) $(libsofthsm_slotmgr_la_DEPENDENCIES) $(EXTRA_libsofthsm_slotmgr_la_DEPENDENCIES) $(AM_V_CXXLD)$(CXXLINK) $(libsofthsm_slotmgr_la_OBJECTS) $(libsofthsm_slotmgr_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Slot.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SlotManager.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Token.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/slot_mgr/Slot.cpp0000664000175000017500000000602312533040716014731 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Slot.h This class represents a single PKCS #11 slot *****************************************************************************/ #include "config.h" #include "log.h" #include "SessionManager.h" #include "SlotManager.h" #include "Token.h" #include #include // Constructor Slot::Slot(ObjectStore* inObjectStore, size_t inSlotID, ObjectStoreToken* inToken /* = NULL */) { objectStore = inObjectStore; slotID = inSlotID; if (inToken != NULL) { token = new Token(inToken); } else { token = new Token(); } } // Destructor Slot::~Slot() { delete token; } // Retrieve the token in the slot Token* Slot::getToken() { return token; } // Initialise the token in the slot CK_RV Slot::initToken(ByteString& soPIN, CK_UTF8CHAR_PTR label) { return token->createToken(objectStore, soPIN, label); } // Retrieve slot information for the slot CK_RV Slot::getSlotInfo(CK_SLOT_INFO_PTR info) { if (info == NULL) { return CKR_ARGUMENTS_BAD; } char description[65]; char mfgID[33]; snprintf(description, 65, "SoftHSM slot %d", (int) slotID); snprintf(mfgID, 33, "SoftHSM project"); memset(info->slotDescription, ' ', 64); memset(info->manufacturerID, ' ', 32); memcpy(info->slotDescription, description, strlen(description)); memcpy(info->manufacturerID, mfgID, strlen(mfgID)); info->flags = CKF_TOKEN_PRESENT; info->hardwareVersion.major = VERSION_MAJOR; info->hardwareVersion.minor = VERSION_MINOR; info->firmwareVersion.major = VERSION_MAJOR; info->firmwareVersion.minor = VERSION_MINOR; return CKR_OK; } // Get the slot ID size_t Slot::getSlotID() { return slotID; } // Is a token present? bool Slot::isTokenPresent() { return true; } softhsm-2.0.0/src/lib/slot_mgr/Slot.h0000664000175000017500000000460312533040716014400 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Slot.h This class represents a single PKCS #11 slot *****************************************************************************/ #ifndef _SOFTHSM_V2_SLOT_H #define _SOFTHSM_V2_SLOT_H #include "config.h" #include "ByteString.h" #include "ObjectStore.h" #include "ObjectStoreToken.h" #include "Token.h" #include "cryptoki.h" #include #include class Slot { public: // Constructor Slot(ObjectStore* inObjectStore, size_t inSlotID, ObjectStoreToken *inToken = NULL); // Destructor virtual ~Slot(); // Retrieve the token in the slot Token* getToken(); // Initialise the token in the slot CK_RV initToken(ByteString& pin, CK_UTF8CHAR_PTR label); // Retrieve slot information for the slot CK_RV getSlotInfo(CK_SLOT_INFO_PTR info); // Get the slot ID size_t getSlotID(); // Is a token present? bool isTokenPresent(); private: // A reference to the object store ObjectStore* objectStore; // The token in the slot Token* token; // The slot ID size_t slotID; }; #endif // !_SOFTHSM_V2_SLOT_H softhsm-2.0.0/src/lib/slot_mgr/Token.cpp0000664000175000017500000002663212533040716015100 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ #include "config.h" #include "log.h" #include "ObjectStore.h" #include "Token.h" #include "OSAttribute.h" #include "ByteString.h" #include "SecureDataManager.h" #include #ifndef _WIN32 #include #else #include #endif // Constructor Token::Token() { tokenMutex = MutexFactory::i()->getMutex(); token = NULL; sdm = NULL; valid = false; } // Constructor Token::Token(ObjectStoreToken* inToken) { tokenMutex = MutexFactory::i()->getMutex(); token = inToken; ByteString soPINBlob, userPINBlob; valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob); sdm = new SecureDataManager(soPINBlob, userPINBlob); } // Destructor Token::~Token() { if (sdm != NULL) delete sdm; MutexFactory::i()->recycleMutex(tokenMutex); } // Check if the token is still valid bool Token::isValid() { // Lock access to the token MutexLocker lock(tokenMutex); return (valid && token->isValid()); } // Check if the token is initialized bool Token::isInitialized() { if (token == NULL) return false; return true; } // Check if SO is logged in bool Token::isSOLoggedIn() { // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return false; return sdm->isSOLoggedIn(); } // Check if user is logged in bool Token::isUserLoggedIn() { // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return false; return sdm->isUserLoggedIn(); } // Login SO CK_RV Token::loginSO(ByteString& pin) { CK_ULONG flags; // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return CKR_GENERAL_ERROR; // User cannot be logged in if (sdm->isUserLoggedIn()) return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; // SO cannot be logged in if (sdm->isSOLoggedIn()) return CKR_USER_ALREADY_LOGGED_IN; // Get token flags if (!token->getTokenFlags(flags)) { ERROR_MSG("Could not get the token flags"); return CKR_GENERAL_ERROR; } // Login if (!sdm->loginSO(pin)) { flags |= CKF_SO_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_PIN_INCORRECT; } flags &= ~CKF_SO_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_OK; } // Login user CK_RV Token::loginUser(ByteString& pin) { CK_ULONG flags; // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return CKR_GENERAL_ERROR; // SO cannot be logged in if (sdm->isSOLoggedIn()) return CKR_USER_ANOTHER_ALREADY_LOGGED_IN; // User cannot be logged in if (sdm->isUserLoggedIn()) return CKR_USER_ALREADY_LOGGED_IN; // The user PIN has to be initialized; if (sdm->getUserPINBlob().size() == 0) return CKR_USER_PIN_NOT_INITIALIZED; // Get token flags if (!token->getTokenFlags(flags)) { ERROR_MSG("Could not get the token flags"); return CKR_GENERAL_ERROR; } // Login if (!sdm->loginUser(pin)) { flags |= CKF_USER_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_PIN_INCORRECT; } flags &= ~CKF_USER_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_OK; } // Logout any user on this token; void Token::logout() { // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return; sdm->logout(); } // Change SO PIN CK_RV Token::setSOPIN(ByteString& oldPIN, ByteString& newPIN) { CK_ULONG flags; // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return CKR_GENERAL_ERROR; // Get token flags if (!token->getTokenFlags(flags)) { ERROR_MSG("Could not get the token flags"); return CKR_GENERAL_ERROR; } // Verify oldPIN SecureDataManager* verifier = new SecureDataManager(sdm->getSOPINBlob(), sdm->getUserPINBlob()); bool result = verifier->loginSO(oldPIN); delete verifier; if (result == false) { flags |= CKF_SO_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_PIN_INCORRECT; } if (sdm->setSOPIN(newPIN) == false) return CKR_GENERAL_ERROR; // Save PIN to token file if (token->setSOPIN(sdm->getSOPINBlob()) == false) return CKR_GENERAL_ERROR; ByteString soPINBlob, userPINBlob; valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob); flags &= ~CKF_SO_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_OK; } // Change the user PIN CK_RV Token::setUserPIN(ByteString& oldPIN, ByteString& newPIN) { CK_ULONG flags; // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return CKR_GENERAL_ERROR; // Check if user should stay logged in bool stayLoggedIn = sdm->isUserLoggedIn(); // Get token flags if (!token->getTokenFlags(flags)) { ERROR_MSG("Could not get the token flags"); return CKR_GENERAL_ERROR; } // Verify oldPIN SecureDataManager* newSdm = new SecureDataManager(sdm->getSOPINBlob(), sdm->getUserPINBlob()); if (newSdm->loginUser(oldPIN) == false) { flags |= CKF_USER_PIN_COUNT_LOW; token->setTokenFlags(flags); delete newSdm; return CKR_PIN_INCORRECT; } // Set the new user PIN if (newSdm->setUserPIN(newPIN) == false) { delete newSdm; return CKR_GENERAL_ERROR; } // Save PIN to token file if (token->setUserPIN(newSdm->getUserPINBlob()) == false) { delete newSdm; return CKR_GENERAL_ERROR; } // Restore previous login state if (!stayLoggedIn) newSdm->logout(); // Switch sdm delete sdm; sdm = newSdm; ByteString soPINBlob, userPINBlob; valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob); flags &= ~CKF_USER_PIN_COUNT_LOW; token->setTokenFlags(flags); return CKR_OK; } // Init the user PIN CK_RV Token::initUserPIN(ByteString& pin) { // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return CKR_GENERAL_ERROR; if (sdm->setUserPIN(pin) == false) return CKR_GENERAL_ERROR; // Save PIN to token file if (token->setUserPIN(sdm->getUserPINBlob()) == false) return CKR_GENERAL_ERROR; ByteString soPINBlob, userPINBlob; valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob); return CKR_OK; } // Create a new token CK_RV Token::createToken(ObjectStore* objectStore, ByteString& soPIN, CK_UTF8CHAR_PTR label) { CK_ULONG flags; // Lock access to the token MutexLocker lock(tokenMutex); if (objectStore == NULL) return CKR_GENERAL_ERROR; if (label == NULL_PTR) return CKR_ARGUMENTS_BAD; if (token != NULL) { // Get token flags if (!token->getTokenFlags(flags)) { ERROR_MSG("Could not get the token flags"); return CKR_GENERAL_ERROR; } if (sdm->getSOPINBlob().size() > 0 && !sdm->loginSO(soPIN)) { flags |= CKF_SO_PIN_COUNT_LOW; token->setTokenFlags(flags); ERROR_MSG("Incorrect SO PIN"); return CKR_PIN_INCORRECT; } // The token is already initialised. Destroy it first. if (!objectStore->destroyToken(token)) { ERROR_MSG("Failed to destroy existing token"); return CKR_DEVICE_ERROR; } token = NULL; } // Generate the SO PIN blob SecureDataManager soPINBlobGen; if (!soPINBlobGen.setSOPIN(soPIN)) { return CKR_GENERAL_ERROR; } // Convert the label ByteString labelByteStr((const unsigned char*) label, 32); // Create the token ObjectStoreToken* newToken = objectStore->newToken(labelByteStr); if (newToken == NULL) { return CKR_DEVICE_ERROR; } // Set the SO PIN on the token if (!newToken->setSOPIN(soPINBlobGen.getSOPINBlob())) { ERROR_MSG("Failed to set SO PIN on new token"); if (!objectStore->destroyToken(newToken)) { ERROR_MSG("Failed to destroy incomplete token"); } return CKR_DEVICE_ERROR; } token = newToken; ByteString soPINBlob, userPINBlob; valid = token->getSOPIN(soPINBlob) && token->getUserPIN(userPINBlob); if (sdm != NULL) delete sdm; sdm = new SecureDataManager(soPINBlob, userPINBlob); return CKR_OK; } // Retrieve token information for the token CK_RV Token::getTokenInfo(CK_TOKEN_INFO_PTR info) { // Lock access to the token MutexLocker lock(tokenMutex); ByteString label, serial; if (info == NULL) { return CKR_ARGUMENTS_BAD; } memset(info->label, ' ', 32); memset(info->serialNumber, ' ', 16); // Token specific information if (token) { if (!token->getTokenFlags(info->flags)) { ERROR_MSG("Could not get the token flags"); return CKR_GENERAL_ERROR; } if (token->getTokenLabel(label)) { strncpy((char*) info->label, (char*) label.byte_str(), label.size()); } if (token->getTokenSerial(serial)) { strncpy((char*) info->serialNumber, (char*) serial.byte_str(), serial.size()); } } else { info->flags = CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED; } // Information shared by all tokens char mfgID[33]; char model[17]; snprintf(mfgID, 33, "SoftHSM project"); snprintf(model, 17, "SoftHSM v2"); memset(info->manufacturerID, ' ', 32); memset(info->model, ' ', 16); memcpy(info->manufacturerID, mfgID, strlen(mfgID)); memcpy(info->model, model, strlen(model)); // TODO: Can we set these? info->ulSessionCount = CK_UNAVAILABLE_INFORMATION; info->ulRwSessionCount = CK_UNAVAILABLE_INFORMATION; info->ulMaxRwSessionCount = CK_EFFECTIVELY_INFINITE; info->ulMaxSessionCount = CK_EFFECTIVELY_INFINITE; info->ulMaxPinLen = MAX_PIN_LEN; info->ulMinPinLen = MIN_PIN_LEN; info->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION; info->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION; info->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION; info->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION; info->hardwareVersion.major = VERSION_MAJOR; info->hardwareVersion.minor = VERSION_MINOR; info->firmwareVersion.major = VERSION_MAJOR; info->firmwareVersion.minor = VERSION_MINOR; // Current time time_t rawtime; time(&rawtime); char dateTime[17]; strftime(dateTime, 17, "%Y%m%d%H%M%S00", gmtime(&rawtime)); memcpy(info->utcTime, dateTime, 16); return CKR_OK; } // Create an object OSObject* Token::createObject() { return token->createObject(); } void Token::getObjects(std::set &objects) { token->getObjects(objects); } bool Token::decrypt(const ByteString &encrypted, ByteString &plaintext) { // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return false; return sdm->decrypt(encrypted,plaintext); } bool Token::encrypt(const ByteString &plaintext, ByteString &encrypted) { // Lock access to the token MutexLocker lock(tokenMutex); if (sdm == NULL) return false; return sdm->encrypt(plaintext,encrypted); } softhsm-2.0.0/src/lib/slot_mgr/Token.h0000664000175000017500000000612012533040716014533 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Token.h This class represents a single PKCS #11 token *****************************************************************************/ #ifndef _SOFTHSM_V2_TOKEN_H #define _SOFTHSM_V2_TOKEN_H #include "config.h" #include "ByteString.h" #include "ObjectStore.h" #include "ObjectStoreToken.h" #include "SecureDataManager.h" #include "cryptoki.h" #include #include class Token { public: // Constructor Token(); Token(ObjectStoreToken *inToken); // Destructor virtual ~Token(); // Create a new token CK_RV createToken(ObjectStore* objectStore, ByteString& soPIN, CK_UTF8CHAR_PTR label); // Is the token valid? bool isValid(); // Is the token initialized? bool isInitialized(); // Is SO or user logged in? bool isSOLoggedIn(); bool isUserLoggedIn(); // Login CK_RV loginSO(ByteString& pin); CK_RV loginUser(ByteString& pin); // Logout any user on this token; void logout(); // Change PIN CK_RV setSOPIN(ByteString& oldPIN, ByteString& newPIN); CK_RV setUserPIN(ByteString& oldPIN, ByteString& newPIN); CK_RV initUserPIN(ByteString& pin); // Retrieve token information for the token CK_RV getTokenInfo(CK_TOKEN_INFO_PTR info); // Create object OSObject *createObject(); // Insert all token objects into the given set. void getObjects(std::set &objects); // Decrypt the supplied data bool decrypt(const ByteString& encrypted, ByteString& plaintext); // Encrypt the supplied data bool encrypt(const ByteString& plaintext, ByteString& encrypted); private: // Token validity bool valid; // A reference to the object store token ObjectStoreToken* token; // The secure data manager for this token SecureDataManager* sdm; Mutex* tokenMutex; }; #endif // !_SOFTHSM_V2_TOKEN_H softhsm-2.0.0/src/lib/P11Attributes.h0000664000175000017500000010634312533040716014245 00000000000000/* * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** P11Attributes.h This file contains classes for controlling attributes *****************************************************************************/ #ifndef _SOFTHSM_V2_P11ATTRIBUTES_H #define _SOFTHSM_V2_P11ATTRIBUTES_H #include "cryptoki.h" #include "OSObject.h" #include "Token.h" // The operation types #define OBJECT_OP_NONE 0x0 #define OBJECT_OP_COPY 0x1 #define OBJECT_OP_CREATE 0x2 #define OBJECT_OP_DERIVE 0x3 #define OBJECT_OP_GENERATE 0x4 #define OBJECT_OP_SET 0x5 #define OBJECT_OP_UNWRAP 0x6 class P11Attribute { public: // Destructor virtual ~P11Attribute(); // Initialize the attribute bool init(); // Return the attribute type CK_ATTRIBUTE_TYPE getType(); // Return the attribute checks CK_ULONG getChecks(); // Retrieve the value if allowed CK_RV retrieve(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG_PTR pulValueLen); // Update the value if allowed CK_RV update(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); // Checks are determined by footnotes from table 15 on page 62 in the PKCS#11 v2.3 spec. // Table 15 contains common footnotes for object attribute tables that determine the checks to perform on attributes. // There are also checks not in table 15 that have been added here to allow enforcing additional contraints. enum { ck1=1, // 1 Must be specified when object is created with C_CreateObject. ck2=2, // 2 Must not be specified when object is created with C_CreateObject. ck3=4, // 3 Must be specified when object is generated with C_GenerateKey or C_GenerateKeyPair. ck4=8, // 4 Must not be specified when object is generated with C_GenerateKey or C_GenerateKeyPair. ck5=0x10, // 5 Must be specified when object is unwrapped with C_UnwrapKey. ck6=0x20, // 6 Must not be specified when object is unwrapped with C_UnwrapKey. ck7=0x40, // 7 Cannot be revealed if object has its CKA_SENSITIVE attribute set to CK_TRUE or // its CKA_EXTRACTABLE attribute set to CK_FALSE. ck8=0x80, // 8 May be modified after object is created with a C_SetAttributeValue call // or in the process of copying an object with a C_CopyObject call. // However, it is possible that a particular token may not permit modification of // the attribute during the course of a C_CopyObject call. ck9=0x100, // 9 Default value is token-specific, and may depend on the values of other attributes. ck10=0x200, // 10 Can only be set to CK_TRUE by the SO user. ck11=0x400, // 11 Attribute cannot be changed once set to CK_TRUE. It becomes a read only attribute. ck12=0x800, // 12 Attribute cannot be changed once set to CK_FALSE. It becomes a read only attribute. ck13=0x1000, // Intentionally not defined ck14=0x2000, // 14 Must be non-empty if CKA_URL is empty (CKA_VALUE) ck15=0x4000, // 15 Must be non-empty if CKA_VALUE is empty (CKA_URL) ck16=0x8000, // 16 Can only be empty if CKA_URL is empty ck17=0x10000, // 17 Can be changed in the process of copying the object using C_CopyObject. ck18=0x20000, ck19=0x40000, ck20=0x80000, ck21=0x100000, ck22=0x200000, ck23=0x400000, ck24=0x800000 }; protected: // Constructor P11Attribute(OSObject* inobject); // The object OSObject* osobject; // The attribute type CK_ATTRIBUTE_TYPE type; // The checks to perform when the attribute is accessed. CK_ULONG checks; // The attribute fixed size contains (CK_ULONG)-1 when size is variable. CK_ULONG size; // Set the default value of the attribute virtual bool setDefault() = 0; // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); // Helper functions bool isModifiable(); bool isSensitive(); bool isExtractable(); bool isTrusted(); }; /***************************************** * CKA_CLASS *****************************************/ class P11AttrClass : public P11Attribute { public: // Constructor P11AttrClass(OSObject* inobject) : P11Attribute(inobject) { type = CKA_CLASS; size = sizeof(CK_OBJECT_CLASS); checks = ck1; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_KEY_TYPE *****************************************/ class P11AttrKeyType : public P11Attribute { public: // Constructor P11AttrKeyType(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_KEY_TYPE; size = sizeof(CK_KEY_TYPE); checks = ck1|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_CERTIFICATE_TYPE *****************************************/ class P11AttrCertificateType : public P11Attribute { public: // Constructor P11AttrCertificateType(OSObject* inobject) : P11Attribute(inobject) { type = CKA_CERTIFICATE_TYPE; size = sizeof(CK_CERTIFICATE_TYPE); checks = ck1; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_TOKEN *****************************************/ class P11AttrToken : public P11Attribute { public: // Constructor P11AttrToken(OSObject* inobject) : P11Attribute(inobject) { type = CKA_TOKEN; size = sizeof(CK_BBOOL); checks = ck17; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_PRIVATE *****************************************/ class P11AttrPrivate : public P11Attribute { public: // Constructor P11AttrPrivate(OSObject* inobject) : P11Attribute(inobject) { type = CKA_PRIVATE; size = sizeof(CK_BBOOL); checks = ck17; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_MODIFIABLE *****************************************/ class P11AttrModifiable : public P11Attribute { public: // Constructor P11AttrModifiable(OSObject* inobject) : P11Attribute(inobject) { type = CKA_MODIFIABLE; size = sizeof(CK_BBOOL); checks = ck17; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_LABEL *****************************************/ class P11AttrLabel : public P11Attribute { public: // Constructor P11AttrLabel(OSObject* inobject) : P11Attribute(inobject) { type = CKA_LABEL; checks = ck8; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_COPYABLE *****************************************/ class P11AttrCopyable : public P11Attribute { public: // Constructor P11AttrCopyable(OSObject* inobject) : P11Attribute(inobject) { type = CKA_COPYABLE; size = sizeof(CK_BBOOL); checks = ck12; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_APPLICATION *****************************************/ class P11AttrApplication : public P11Attribute { public: // Constructor P11AttrApplication(OSObject* inobject) : P11Attribute(inobject) { type = CKA_APPLICATION; checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_OBJECT_ID *****************************************/ class P11AttrObjectID : public P11Attribute { public: // Constructor P11AttrObjectID(OSObject* inobject) : P11Attribute(inobject) { type = CKA_OBJECT_ID; checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_CHECK_VALUE *****************************************/ class P11AttrCheckValue : public P11Attribute { public: // Constructor P11AttrCheckValue(OSObject* inobject) : P11Attribute(inobject) { type = CKA_CHECK_VALUE; checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_ID *****************************************/ class P11AttrID : public P11Attribute { public: // Constructor P11AttrID(OSObject* inobject) : P11Attribute(inobject) { type = CKA_ID; checks = ck8; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_VALUE *****************************************/ class P11AttrValue : public P11Attribute { public: // Constructor P11AttrValue(OSObject* inobject, CK_ULONG inchecks) : P11Attribute(inobject) { type = CKA_VALUE; checks = inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_SUBJECT *****************************************/ class P11AttrSubject : public P11Attribute { public: // Constructor P11AttrSubject(OSObject* inobject, CK_ULONG inchecks) : P11Attribute(inobject) { type = CKA_SUBJECT; checks = inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_ISSUER *****************************************/ class P11AttrIssuer : public P11Attribute { public: // Constructor P11AttrIssuer(OSObject* inobject) : P11Attribute(inobject) { type = CKA_ISSUER; checks = ck8; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_TRUSTED *****************************************/ class P11AttrTrusted : public P11Attribute { public: // Constructor P11AttrTrusted(OSObject* inobject) : P11Attribute(inobject) { type = CKA_TRUSTED; size = sizeof(CK_BBOOL); checks = ck10; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_CERTIFICATE_CATEGORY *****************************************/ class P11AttrCertificateCategory : public P11Attribute { public: // Constructor P11AttrCertificateCategory(OSObject* inobject) : P11Attribute(inobject) { type = CKA_CERTIFICATE_CATEGORY; size = sizeof(CK_ULONG); checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_START_DATE *****************************************/ class P11AttrStartDate : public P11Attribute { public: // Constructor P11AttrStartDate(OSObject* inobject, CK_ULONG inchecks) : P11Attribute(inobject) { type = CKA_START_DATE; checks = inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_END_DATE *****************************************/ class P11AttrEndDate : public P11Attribute { public: // Constructor P11AttrEndDate(OSObject* inobject, CK_ULONG inchecks) : P11Attribute(inobject) { type = CKA_END_DATE; checks = inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_SERIAL_NUMBER *****************************************/ class P11AttrSerialNumber : public P11Attribute { public: // Constructor P11AttrSerialNumber(OSObject* inobject) : P11Attribute(inobject) { type = CKA_SERIAL_NUMBER; checks = ck8; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_URL *****************************************/ class P11AttrURL : public P11Attribute { public: // Constructor P11AttrURL(OSObject* inobject) : P11Attribute(inobject) { type = CKA_URL; checks = ck15; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_HASH_OF_SUBJECT_PUBLIC_KEY *****************************************/ class P11AttrHashOfSubjectPublicKey : public P11Attribute { public: // Constructor P11AttrHashOfSubjectPublicKey(OSObject* inobject) : P11Attribute(inobject) { type = CKA_HASH_OF_SUBJECT_PUBLIC_KEY; checks = ck16; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_HASH_OF_ISSUER_PUBLIC_KEY *****************************************/ class P11AttrHashOfIssuerPublicKey : public P11Attribute { public: // Constructor P11AttrHashOfIssuerPublicKey(OSObject* inobject) : P11Attribute(inobject) { type = CKA_HASH_OF_ISSUER_PUBLIC_KEY; checks = ck16; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_JAVA_MIDP_SECURITY_DOMAIN *****************************************/ class P11AttrJavaMidpSecurityDomain : public P11Attribute { public: // Constructor P11AttrJavaMidpSecurityDomain(OSObject* inobject) : P11Attribute(inobject) { type = CKA_JAVA_MIDP_SECURITY_DOMAIN; size = sizeof(CK_ULONG); checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_NAME_HASH_ALGORITHM *****************************************/ class P11AttrNameHashAlgorithm : public P11Attribute { public: // Constructor P11AttrNameHashAlgorithm(OSObject* inobject) : P11Attribute(inobject) { type = CKA_NAME_HASH_ALGORITHM; size = sizeof(CK_MECHANISM_TYPE); checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_DERIVE *****************************************/ class P11AttrDerive : public P11Attribute { public: // Constructor P11AttrDerive(OSObject* inobject) : P11Attribute(inobject) { type = CKA_DERIVE; size = sizeof(CK_BBOOL); checks = ck8;} protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_ENCRYPT *****************************************/ class P11AttrEncrypt : public P11Attribute { public: // Constructor P11AttrEncrypt(OSObject* inobject) : P11Attribute(inobject) { type = CKA_ENCRYPT; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_VERIFY *****************************************/ class P11AttrVerify : public P11Attribute { public: // Constructor P11AttrVerify(OSObject* inobject) : P11Attribute(inobject) { type = CKA_VERIFY; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_VERIFY_RECOVER *****************************************/ class P11AttrVerifyRecover : public P11Attribute { public: // Constructor P11AttrVerifyRecover(OSObject* inobject) : P11Attribute(inobject) { type = CKA_VERIFY_RECOVER; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_WRAP *****************************************/ class P11AttrWrap : public P11Attribute { public: // Constructor P11AttrWrap(OSObject* inobject) : P11Attribute(inobject) { type = CKA_WRAP; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_DECRYPT *****************************************/ class P11AttrDecrypt : public P11Attribute { public: // Constructor P11AttrDecrypt(OSObject* inobject) : P11Attribute(inobject) { type = CKA_DECRYPT; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_SIGN *****************************************/ class P11AttrSign : public P11Attribute { public: // Constructor P11AttrSign(OSObject* inobject) : P11Attribute(inobject) { type = CKA_SIGN; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_SIGN_RECOVER *****************************************/ class P11AttrSignRecover : public P11Attribute { public: // Constructor P11AttrSignRecover(OSObject* inobject) : P11Attribute(inobject) { type = CKA_SIGN_RECOVER; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_UNWRAP *****************************************/ class P11AttrUnwrap : public P11Attribute { public: // Constructor P11AttrUnwrap(OSObject* inobject) : P11Attribute(inobject) { type = CKA_UNWRAP; size = sizeof(CK_BBOOL); checks = ck8|ck9; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_LOCAL *****************************************/ class P11AttrLocal : public P11Attribute { public: // Constructor P11AttrLocal(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_LOCAL; size = sizeof(CK_BBOOL); checks = ck2|ck4|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_KEY_GEN_MECHANISM *****************************************/ class P11AttrKeyGenMechanism : public P11Attribute { public: // Constructor P11AttrKeyGenMechanism(OSObject* inobject) : P11Attribute(inobject) { type = CKA_KEY_GEN_MECHANISM; size = sizeof(CK_MECHANISM_TYPE); checks = ck2|ck4|ck6; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_ALWAYS_SENSITIVE *****************************************/ class P11AttrAlwaysSensitive : public P11Attribute { public: // Constructor P11AttrAlwaysSensitive(OSObject* inobject) : P11Attribute(inobject) { type = CKA_ALWAYS_SENSITIVE; size = sizeof(CK_BBOOL); checks = ck2|ck4|ck6; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_NEVER_EXTRACTABLE *****************************************/ class P11AttrNeverExtractable : public P11Attribute { public: // Constructor P11AttrNeverExtractable(OSObject* inobject) : P11Attribute(inobject) { type = CKA_NEVER_EXTRACTABLE; size = sizeof(CK_BBOOL); checks = ck2|ck4|ck6; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_SENSITIVE *****************************************/ class P11AttrSensitive : public P11Attribute { public: // Constructor P11AttrSensitive(OSObject* inobject) : P11Attribute(inobject) { type = CKA_SENSITIVE; size = sizeof(CK_BBOOL); checks = ck8|ck9|ck11; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_EXTRACTABLE *****************************************/ class P11AttrExtractable : public P11Attribute { public: // Constructor P11AttrExtractable(OSObject* inobject) : P11Attribute(inobject) { type = CKA_EXTRACTABLE; size = sizeof(CK_BBOOL); checks = ck8|ck9|ck12; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_WRAP_WITH_TRUSTED *****************************************/ class P11AttrWrapWithTrusted : public P11Attribute { public: // Constructor P11AttrWrapWithTrusted(OSObject* inobject) : P11Attribute(inobject) { type = CKA_WRAP_WITH_TRUSTED; size = sizeof(CK_BBOOL); checks = ck11; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_ALWAYS_AUTHENTICATE *****************************************/ class P11AttrAlwaysAuthenticate : public P11Attribute { public: // Constructor P11AttrAlwaysAuthenticate(OSObject* inobject) : P11Attribute(inobject) { type = CKA_ALWAYS_AUTHENTICATE; size = sizeof(CK_BBOOL); checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_MODULUS *****************************************/ class P11AttrModulus : public P11Attribute { public: // Constructor P11AttrModulus(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_MODULUS; checks = ck1|ck4|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_PUBLIC_EXPONENT *****************************************/ class P11AttrPublicExponent : public P11Attribute { public: // Constructor P11AttrPublicExponent(OSObject* inobject, CK_ULONG inchecks) : P11Attribute(inobject) { type = CKA_PUBLIC_EXPONENT; checks = inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_PRIVATE_EXPONENT *****************************************/ class P11AttrPrivateExponent : public P11Attribute { public: // Constructor P11AttrPrivateExponent(OSObject* inobject) : P11Attribute(inobject) { type = CKA_PRIVATE_EXPONENT; checks = ck1|ck4|ck6|ck7; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_PRIME_1 *****************************************/ class P11AttrPrime1 : public P11Attribute { public: // Constructor P11AttrPrime1(OSObject* inobject) : P11Attribute(inobject) { type = CKA_PRIME_1; checks = ck4|ck6|ck7; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_PRIME_2 *****************************************/ class P11AttrPrime2 : public P11Attribute { public: // Constructor P11AttrPrime2(OSObject* inobject) : P11Attribute(inobject) { type = CKA_PRIME_2; checks = ck4|ck6|ck7; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_EXPONENT_1 *****************************************/ class P11AttrExponent1 : public P11Attribute { public: // Constructor P11AttrExponent1(OSObject* inobject) : P11Attribute(inobject) { type = CKA_EXPONENT_1; checks = ck4|ck6|ck7; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_EXPONENT_2 *****************************************/ class P11AttrExponent2 : public P11Attribute { public: // Constructor P11AttrExponent2(OSObject* inobject) : P11Attribute(inobject) { type = CKA_EXPONENT_2; checks = ck4|ck6|ck7; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_COEFFICIENT *****************************************/ class P11AttrCoefficient : public P11Attribute { public: // Constructor P11AttrCoefficient(OSObject* inobject) : P11Attribute(inobject) { type = CKA_COEFFICIENT; checks = ck4|ck6|ck7; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_MODULUS_BITS *****************************************/ class P11AttrModulusBits : public P11Attribute { public: // Constructor P11AttrModulusBits(OSObject* inobject) : P11Attribute(inobject) { type = CKA_MODULUS_BITS; size = sizeof(CK_ULONG); checks = ck2|ck3;} protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_PRIME *****************************************/ class P11AttrPrime : public P11Attribute { public: // Constructor P11AttrPrime(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_PRIME; checks = ck1|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_SUBPRIME *****************************************/ class P11AttrSubPrime : public P11Attribute { public: // Constructor P11AttrSubPrime(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_SUBPRIME; checks = ck1|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_BASE *****************************************/ class P11AttrBase : public P11Attribute { public: // Constructor P11AttrBase(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_BASE; checks = ck1|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_PRIME_BITS *****************************************/ class P11AttrPrimeBits : public P11Attribute { public: // Constructor P11AttrPrimeBits(OSObject* inobject) : P11Attribute(inobject) { type = CKA_PRIME_BITS; size = sizeof(CK_ULONG); checks = ck2|ck3;} protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_VALUE_BITS *****************************************/ class P11AttrValueBits : public P11Attribute { public: // Constructor P11AttrValueBits(OSObject* inobject) : P11Attribute(inobject) { type = CKA_VALUE_BITS; size = sizeof(CK_ULONG); checks = ck2|ck6;} protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_EC_PARAMS *****************************************/ class P11AttrEcParams : public P11Attribute { public: // Constructor P11AttrEcParams(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_EC_PARAMS; checks = ck1|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_EC_POINT *****************************************/ class P11AttrEcPoint : public P11Attribute { public: // Constructor P11AttrEcPoint(OSObject* inobject) : P11Attribute(inobject) { type = CKA_EC_POINT; checks = ck1|ck4; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_GOSTR3410_PARAMS *****************************************/ class P11AttrGostR3410Params : public P11Attribute { public: // Constructor P11AttrGostR3410Params(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_GOSTR3410_PARAMS; checks = ck1|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_GOSTR3411_PARAMS *****************************************/ class P11AttrGostR3411Params : public P11Attribute { public: // Constructor P11AttrGostR3411Params(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_GOSTR3411_PARAMS; checks = ck1|ck8|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_GOST28147_PARAMS *****************************************/ class P11AttrGost28147Params : public P11Attribute { public: // Constructor P11AttrGost28147Params(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_GOST28147_PARAMS; checks = inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); }; /***************************************** * CKA_VALUE_LEN *****************************************/ class P11AttrValueLen : public P11Attribute { public: // Constructor P11AttrValueLen(OSObject* inobject, CK_ULONG inchecks = 0) : P11Attribute(inobject) { type = CKA_VALUE_LEN; size = sizeof(CK_ULONG); checks = ck2|ck3|inchecks; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_WRAP_TEMPLATE *****************************************/ class P11AttrWrapTemplate : public P11Attribute { public: // Constructor P11AttrWrapTemplate(OSObject* inobject) : P11Attribute(inobject) { type = CKA_WRAP_TEMPLATE; checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; /***************************************** * CKA_UNWRAP_TEMPLATE *****************************************/ class P11AttrUnwrapTemplate : public P11Attribute { public: // Constructor P11AttrUnwrapTemplate(OSObject* inobject) : P11Attribute(inobject) { type = CKA_UNWRAP_TEMPLATE; checks = 0; } protected: // Set the default value of the attribute virtual bool setDefault(); // Update the value if allowed virtual CK_RV updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op); }; #endif // !_SOFTHSM_V2_P11ATTRIBUTES_H softhsm-2.0.0/src/lib/P11Attributes.cpp0000664000175000017500000015272512533040716014605 00000000000000/* * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** P11Attributes.h This file contains classes for controlling attributes *****************************************************************************/ #include "config.h" #include "P11Attributes.h" #include "ByteString.h" #include #include // Constructor P11Attribute::P11Attribute(OSObject* inobject) { osobject = inobject; type = CKA_VENDOR_DEFINED; size = (CK_ULONG)-1; checks = 0; } // Destructor P11Attribute::~P11Attribute() { } CK_RV P11Attribute::updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { ByteString value; if (isPrivate) { if (!token->encrypt(ByteString((unsigned char*)pValue, ulValueLen),value)) return CKR_GENERAL_ERROR; } else value = ByteString((unsigned char*)pValue, ulValueLen); if (value.size() < ulValueLen) return CKR_GENERAL_ERROR; osobject->setAttribute(type, value); return CKR_OK; } bool P11Attribute::isModifiable() { // Get the CKA_MODIFIABLE attribute, when the attribute is // not present return the default value which is CK_TRUE. if (!osobject->attributeExists(CKA_MODIFIABLE)) return true; return osobject->getBooleanValue(CKA_MODIFIABLE, true); } bool P11Attribute::isSensitive() { // Get the CKA_SENSITIVE attribute, when the attribute is not present // assume the object is not sensitive. if (!osobject->attributeExists(CKA_SENSITIVE)) return false; return osobject->getBooleanValue(CKA_SENSITIVE, false); } bool P11Attribute::isExtractable() { // Get the CKA_EXTRACTABLE attribute, when the attribute is // not present assume the object allows extraction. if (!osobject->attributeExists(CKA_EXTRACTABLE)) return true; return osobject->getBooleanValue(CKA_EXTRACTABLE, true); } bool P11Attribute::isTrusted() { // Get the CKA_TRUSTED attribute, when the attribute is // not present assume the object is not trusted. if (!osobject->attributeExists(CKA_TRUSTED)) return false; return osobject->getBooleanValue(CKA_TRUSTED, false); } // Initialize the attribute bool P11Attribute::init() { if (osobject == NULL) return false; // Create a default value if the attribute does not exist if (osobject->attributeExists(type) == false) { return setDefault(); } return true; } // Return the attribute type CK_ATTRIBUTE_TYPE P11Attribute::getType() { return type; } // Return the attribute checks CK_ATTRIBUTE_TYPE P11Attribute::getChecks() { return checks; } // Retrieve a template array static CK_RV retrieveArray(CK_ATTRIBUTE_PTR pTemplate, const std::map& array) { size_t nullcnt = 0; for (size_t i = 0; i < array.size(); ++i) { if (pTemplate[i].pValue == NULL_PTR) ++nullcnt; } // Caller wants type & size if (nullcnt == array.size()) { std::map::const_iterator a = array.begin(); for (size_t i = 0; i < array.size(); ++i, ++a) { pTemplate[i].type = a->first; const OSAttribute& attr = a->second; if (attr.isBooleanAttribute()) { pTemplate[i].ulValueLen = sizeof(CK_BBOOL); } else if (attr.isUnsignedLongAttribute()) { pTemplate[i].ulValueLen = sizeof(CK_ULONG); } else if (attr.isByteStringAttribute()) { pTemplate[i].ulValueLen = attr.getByteStringValue().size(); } else { // Impossible ERROR_MSG("Internal error: bad attribute in array"); return CKR_GENERAL_ERROR; } } return CKR_OK; } // Callers wants to get values for (size_t i = 0; i < array.size(); ++i) { std::map::const_iterator a = array.find(pTemplate[i].type); if (a == array.end()) { pTemplate[i].ulValueLen = (CK_ULONG)-1; return CKR_ATTRIBUTE_TYPE_INVALID; } const OSAttribute& attr = a->second; if (attr.isBooleanAttribute()) { if (pTemplate[i].ulValueLen < sizeof(CK_BBOOL)) { pTemplate[i].ulValueLen = (CK_ULONG)-1; return CKR_BUFFER_TOO_SMALL; } pTemplate[i].ulValueLen = sizeof(CK_BBOOL); *(CK_BBOOL*)pTemplate[i].pValue = attr.getBooleanValue() ? CK_TRUE : CK_FALSE; } else if (attr.isUnsignedLongAttribute()) { if (pTemplate[i].ulValueLen < sizeof(CK_ULONG)) { pTemplate[i].ulValueLen= (CK_ULONG)-1; return CKR_BUFFER_TOO_SMALL; } pTemplate[i].ulValueLen = sizeof(CK_ULONG); *(CK_ULONG_PTR)pTemplate[i].pValue= attr.getUnsignedLongValue(); } else if (attr.isByteStringAttribute()) { ByteString value = attr.getByteStringValue(); if (pTemplate[i].ulValueLen < value.size()) { pTemplate[i].ulValueLen= (CK_ULONG)-1; return CKR_BUFFER_TOO_SMALL; } pTemplate[i].ulValueLen = value.size(); memcpy(pTemplate[i].pValue, value.const_byte_str(), value.size()); } else { // Impossible ERROR_MSG("Internal error: bad attribute in array"); return CKR_GENERAL_ERROR; } } return CKR_OK; } // Retrieve the value if allowed CK_RV P11Attribute::retrieve(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG_PTR pulValueLen) { if (osobject == NULL) { ERROR_MSG("Internal error: osobject field contains NULL_PTR"); return CKR_GENERAL_ERROR; } if (pulValueLen == NULL) { ERROR_MSG("Internal error: pulValueLen contains NULL_PTR"); return CKR_GENERAL_ERROR; } // [PKCS#11 v2.3 pg.131 C_GetAttributeValue] // 1. If the specified attribute (i.e. the attribute specified by the // type field) for the object cannot be revealed because the object // is sensitive or unextractable, then the ulValueLen field in that // tripple is modified to hold the value -1 (i.e., when it is cast // to a CK_LONG, it holds -1). // // [PKCS#11 v2.3 pg. 62 table 15] // 7 Cannot be revealed if object has its CKA_SENSITIVE attribute // set to CK_TRUE or its CKA_EXTRACTABLE attribute set to CK_FALSE. if ((checks & ck7) == ck7 && (isSensitive() || !isExtractable())) { *pulValueLen = (CK_ULONG)-1; return CKR_ATTRIBUTE_SENSITIVE; } // Retrieve the lower level attribute. if (!osobject->attributeExists(type)) { // Should be impossible. ERROR_MSG("Internal error: attribute not present"); return CKR_GENERAL_ERROR; } OSAttribute attr = osobject->getAttribute(type); // Get the actual attribute size. CK_ULONG attrSize = size; if (size == (CK_ULONG)-1) { // We don't have a fixed size attribute so we need to consult // the lower level attribute for the exact size. // Lower level attribute has to be variable sized. if (attr.isByteStringAttribute()) { if (isPrivate && attr.getByteStringValue().size() != 0) { ByteString value; if (!token->decrypt(attr.getByteStringValue(),value)) { ERROR_MSG("Internal error: failed to decrypt private attribute value"); return CKR_GENERAL_ERROR; } attrSize = value.size(); } else attrSize = attr.getByteStringValue().size(); } else if (attr.isArrayAttribute()) { attrSize = attr.getArrayValue().size() * sizeof(CK_ATTRIBUTE); } else { // Should be impossible. ERROR_MSG("Internal error: attribute has fixed size"); return CKR_GENERAL_ERROR; } } // [PKCS#11 v2.3 pg.131 C_GetAttributeValue] // 3. Otherwise, if the pValue field has the value NULL_PTR, then the // ulValueLen field is modified to hold the exact length of the // specified attribute for the object. if (pValue == NULL_PTR) { // Return the size of the attribute. *pulValueLen = attrSize; return CKR_OK; } // [PKCS#11 v2.3 pg.131 C_GetAttributeValue] // 4. Otherwise, if the length specified in ulValueLen is large enough // to hold the value of the specified attribute for the object, then // that attribute is copied into the buffer located at pValue, and // the ulValueLen field is modified to hold the exact length of the // attribute. if (*pulValueLen >= attrSize) { // Only copy when there is actually something to copy CK_RV rv = CKR_OK; if (attr.isUnsignedLongAttribute()) { *(CK_ULONG_PTR)pValue = attr.getUnsignedLongValue(); } else if (attr.isBooleanAttribute()) { *(CK_BBOOL*)pValue = attr.getBooleanValue() ? CK_TRUE : CK_FALSE; } else if (attr.isByteStringAttribute()) { if (isPrivate && attr.getByteStringValue().size() != 0) { ByteString value; if (!token->decrypt(attr.getByteStringValue(),value)) { ERROR_MSG("Internal error: failed to decrypt private attribute value"); return CKR_GENERAL_ERROR; } const unsigned char* attrPtr = value.const_byte_str(); memcpy(pValue,attrPtr,attrSize); } else if (attr.getByteStringValue().size() != 0) { const unsigned char* attrPtr = attr.getByteStringValue().const_byte_str(); memcpy(pValue,attrPtr,attrSize); } } else { // attr is already retrieved and verified to be an Array rv = retrieveArray((CK_ATTRIBUTE_PTR)pValue, attr.getArrayValue()); } *pulValueLen = attrSize; return rv; } // [PKCS#11 v2.3 pg.131] // 5. Otherwise, the ulValueLen field is modified to hold the value -1. *pulValueLen = (CK_ULONG)-1; return CKR_BUFFER_TOO_SMALL; } // Update the value if allowed CK_RV P11Attribute::update(Token* token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { if (osobject == NULL) { ERROR_MSG("Internal error: osobject field contains NULL_PTR"); return CKR_GENERAL_ERROR; } // [PKCS#11 v2.3 pg. 60] // 2. If the supplied template specifies an invalid value for a valid attribute, then the // attempt should fail with the error code CKR_ATTRIBUTE_VALUE_INVALID. // The valid values for Cryptoki attributes are described in the Cryptoki specification. // Check for null pointers in values. if (pValue == NULL_PTR && ulValueLen != 0) { ERROR_MSG("The attribute is a NULL_PTR but has a non-zero length") return CKR_ATTRIBUTE_VALUE_INVALID; } // For fixed sized attributes check that the size matches. if (size != ((CK_ULONG)-1) && size != ulValueLen) { ERROR_MSG("The attribute size is different from the expected size") return CKR_ATTRIBUTE_VALUE_INVALID; } // [PKCS#11 v2.3 pg. 60] OBJECT_OP_CREATE | OBJECT_OP_SET | OBJECT_OP_COPY // 3. If the supplied template specifies a value for a read-only attribute, then the attempt // should fail with the error code CKR_ATTRIBUTE_READ_ONLY. // Whether or not a given Cryptoki attribute is read-only is explicitly stated in the Cryptoki // specification; however, a particular library and token may be even more restrictive than // Cryptoki specifies. In other words, an attribute which Cryptoki says is not read-only may // nonetheless be read-only under certain circumstances (i.e., in conjunction with some // combinations of other attributes) for a particular library and token. Whether or not a // given non-Cryptoki attribute is read-only is obviously outside the scope of Cryptoki. // Attributes cannot be changed if CKA_MODIFIABLE is set to false if (!isModifiable() && op != OBJECT_OP_GENERATE && op != OBJECT_OP_CREATE) { ERROR_MSG("An object is with CKA_MODIFIABLE set to false is not modifiable"); return CKR_ATTRIBUTE_READ_ONLY; } // Attributes cannot be modified if CKA_TRUSTED is true on a certificate object. if (isTrusted() && op != OBJECT_OP_GENERATE && op != OBJECT_OP_CREATE) { if (osobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) == CKO_CERTIFICATE) { ERROR_MSG("A trusted certificate cannot be modified"); return CKR_ATTRIBUTE_READ_ONLY; } } // ck2 Must not be specified when object is created with C_CreateObject. if ((checks & ck2) == ck2) { if (OBJECT_OP_CREATE==op) { ERROR_MSG("Prohibited attribute was passed to object creation function"); return CKR_ATTRIBUTE_READ_ONLY; } } // ck4 Must not be specified when object is generated with C_GenerateKey or C_GenerateKeyPair. if ((checks & ck4) == ck4) { if (OBJECT_OP_GENERATE==op) { ERROR_MSG("Prohibited attribute was passed to key generation function"); return CKR_ATTRIBUTE_READ_ONLY; } } // ck6 Must not be specified when object is unwrapped with C_UnwrapKey. if ((checks & ck6) == ck6) { if (OBJECT_OP_UNWRAP==op) { ERROR_MSG("Prohibited attribute was passed to key unwrapping function"); return CKR_ATTRIBUTE_READ_ONLY; } } // ck8 May be modified after object is created with a C_SetAttributeValue call // or in the process of copying an object with a C_CopyObject call. // However, it is possible that a particular token may not permit modification of // the attribute during the course of a C_CopyObject call. if ((checks & ck8) == ck8) { if (OBJECT_OP_SET==op || OBJECT_OP_COPY==op) { return updateAttr(token, isPrivate, pValue, ulValueLen, op); } } // ck17 Can be changed in the process of copying the object using C_CopyObject. if ((checks & ck17) == ck17) { if (OBJECT_OP_COPY==op) { return updateAttr(token, isPrivate, pValue, ulValueLen, op); } } // For attributes that have not been explicitly excluded from modification // during create/derive/generate/unwrap, we allow them to be modified. if (OBJECT_OP_CREATE==op || OBJECT_OP_DERIVE==op || OBJECT_OP_GENERATE==op || OBJECT_OP_UNWRAP==op) { return updateAttr(token, isPrivate, pValue, ulValueLen, op); } return CKR_ATTRIBUTE_READ_ONLY; } /***************************************** * CKA_CLASS *****************************************/ // Set default value bool P11AttrClass::setDefault() { OSAttribute attrClass((unsigned long)CKO_VENDOR_DEFINED); return osobject->setAttribute(type, attrClass); } // Update the value if allowed CK_RV P11AttrClass::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op == OBJECT_OP_SET) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } if (osobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != *(CK_ULONG*)pValue) { return CKR_TEMPLATE_INCONSISTENT; } return CKR_OK; } /***************************************** * CKA_KEY_TYPE *****************************************/ // Set default value bool P11AttrKeyType::setDefault() { OSAttribute attr((unsigned long)CKK_VENDOR_DEFINED); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrKeyType::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op == OBJECT_OP_SET) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } if (osobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != *(CK_ULONG*)pValue) { return CKR_TEMPLATE_INCONSISTENT; } return CKR_OK; } /***************************************** * CKA_CERTIFICATE_TYPE * footnote 1 * 1 Must be specified when object is created with C_CreateObject. *****************************************/ // Set default value bool P11AttrCertificateType::setDefault() { OSAttribute attr((unsigned long)CKC_VENDOR_DEFINED); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrCertificateType::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op == OBJECT_OP_SET) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } if (osobject->getUnsignedLongValue(CKA_CERTIFICATE_TYPE, CKC_VENDOR_DEFINED) != *(CK_ULONG*)pValue) { return CKR_TEMPLATE_INCONSISTENT; } return CKR_OK; } /***************************************** * CKA_TOKEN *****************************************/ // Set default value bool P11AttrToken::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrToken::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op != OBJECT_OP_GENERATE && op != OBJECT_OP_DERIVE && op != OBJECT_OP_CREATE && op != OBJECT_OP_COPY && op != OBJECT_OP_UNWRAP) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_PRIVATE *****************************************/ // Set default value bool P11AttrPrivate::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrPrivate::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op != OBJECT_OP_GENERATE && op != OBJECT_OP_DERIVE && op != OBJECT_OP_CREATE && op != OBJECT_OP_COPY && op != OBJECT_OP_UNWRAP) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_MODIFIABLE *****************************************/ // Set default value bool P11AttrModifiable::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrModifiable::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op != OBJECT_OP_GENERATE && op != OBJECT_OP_DERIVE && op != OBJECT_OP_CREATE && op != OBJECT_OP_COPY && op != OBJECT_OP_UNWRAP) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_LABEL *****************************************/ // Set default value bool P11AttrLabel::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_COPYABLE *****************************************/ // Set default value bool P11AttrCopyable::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrCopyable::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op != OBJECT_OP_GENERATE && op != OBJECT_OP_DERIVE && op != OBJECT_OP_CREATE && op != OBJECT_OP_COPY && op != OBJECT_OP_UNWRAP) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { if (osobject->getBooleanValue(CKA_COPYABLE, true) == false) { return CKR_ATTRIBUTE_READ_ONLY; } } return CKR_OK; } /***************************************** * CKA_APPLICATION *****************************************/ // Set default value bool P11AttrApplication::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_OBJECT_ID *****************************************/ // Set default value bool P11AttrObjectID::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_CHECK_VALUE *****************************************/ // Set default value bool P11AttrCheckValue::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_ID *****************************************/ // Set default value bool P11AttrID::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_VALUE *****************************************/ // Set default value bool P11AttrValue::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrValue::updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { ByteString plaintext((unsigned char*)pValue, ulValueLen); ByteString value; // Encrypt if (isPrivate) { if (!token->encrypt(plaintext, value)) return CKR_GENERAL_ERROR; } else value = plaintext; // Attribute specific checks if (value.size() < ulValueLen) return CKR_GENERAL_ERROR; // Store data osobject->setAttribute(type, value); // Set the size during C_CreateObject and C_UnwrapKey. if (op == OBJECT_OP_CREATE || op == OBJECT_OP_UNWRAP) { // Set the CKA_VALUE_LEN if (osobject->attributeExists(CKA_VALUE_LEN)) { OSAttribute bytes((unsigned long)plaintext.size()); osobject->setAttribute(CKA_VALUE_LEN, bytes); } // Set the CKA_VALUE_BITS if (osobject->attributeExists(CKA_VALUE_BITS)) { OSAttribute bits((unsigned long)plaintext.bits()); osobject->setAttribute(CKA_VALUE_BITS, bits); } } return CKR_OK; } /***************************************** * CKA_SUBJECT *****************************************/ // Set default value bool P11AttrSubject::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_ISSUER *****************************************/ // Set default value bool P11AttrIssuer::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_TRUSTED *****************************************/ // Set default value bool P11AttrTrusted::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrTrusted::updateAttr(Token *token, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { if (!token->isSOLoggedIn()) { ERROR_MSG("CKA_TRUSTED can only be set to true by the SO"); return CKR_ATTRIBUTE_READ_ONLY; } osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_CERTIFICATE_CATEGORY *****************************************/ // Set default value bool P11AttrCertificateCategory::setDefault() { OSAttribute attr((unsigned long)0); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrCertificateCategory::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_SET) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_START_DATE *****************************************/ // Set default value bool P11AttrStartDate::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrStartDate::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { // Attribute specific checks if (ulValueLen !=sizeof(CK_DATE) && ulValueLen !=0) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, ByteString((unsigned char*)pValue, ulValueLen)); return CKR_OK; } /***************************************** * CKA_END_DATE *****************************************/ // Set default value bool P11AttrEndDate::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrEndDate::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { // Attribute specific checks if (ulValueLen !=sizeof(CK_DATE) && ulValueLen !=0) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, ByteString((unsigned char*)pValue, ulValueLen)); return CKR_OK; } /***************************************** * CKA_SERIAL_NUMBER *****************************************/ // Set default value bool P11AttrSerialNumber::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_URL *****************************************/ // Set default value bool P11AttrURL::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_HASH_OF_SUBJECT_PUBLIC_KEY *****************************************/ // Set default value bool P11AttrHashOfSubjectPublicKey::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_HASH_OF_ISSUER_PUBLIC_KEY *****************************************/ // Set default value bool P11AttrHashOfIssuerPublicKey::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_JAVA_MIDP_SECURITY_DOMAIN *****************************************/ // Set default value bool P11AttrJavaMidpSecurityDomain::setDefault() { OSAttribute attr((unsigned long)0); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrJavaMidpSecurityDomain::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_SET) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_NAME_HASH_ALGORITHM *****************************************/ // Set default value bool P11AttrNameHashAlgorithm::setDefault() { OSAttribute attr((unsigned long)CKM_SHA_1); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrNameHashAlgorithm::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_SET) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_DERIVE *****************************************/ // Set default value bool P11AttrDerive::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrDerive::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_ENCRYPT *****************************************/ // Set default value bool P11AttrEncrypt::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrEncrypt::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_VERIFY *****************************************/ // Set default value bool P11AttrVerify::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrVerify::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_VERIFY_RECOVER *****************************************/ // Set default value bool P11AttrVerifyRecover::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrVerifyRecover::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_WRAP *****************************************/ // Set default value bool P11AttrWrap::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrWrap::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_DECRYPT *****************************************/ // Set default value bool P11AttrDecrypt::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrDecrypt::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_SIGN *****************************************/ // Set default value bool P11AttrSign::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrSign::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_SIGN_RECOVER *****************************************/ // Set default value bool P11AttrSignRecover::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrSignRecover::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_UNWRAP *****************************************/ // Set default value bool P11AttrUnwrap::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrUnwrap::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_LOCAL *****************************************/ // Set default value bool P11AttrLocal::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrLocal::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR /*pValue*/, CK_ULONG /*ulValueLen*/, int /*op*/) { return CKR_ATTRIBUTE_READ_ONLY; } /***************************************** * CKA_KEY_GEN_MECHANISM *****************************************/ // Set default value bool P11AttrKeyGenMechanism::setDefault() { OSAttribute attr((unsigned long)CK_UNAVAILABLE_INFORMATION); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrKeyGenMechanism::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR /*pValue*/, CK_ULONG /*ulValueLen*/, int /*op*/) { return CKR_ATTRIBUTE_READ_ONLY; } /***************************************** * CKA_ALWAYS_SENSITIVE *****************************************/ // Set default value bool P11AttrAlwaysSensitive::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrAlwaysSensitive::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR /*pValue*/, CK_ULONG /*ulValueLen*/, int /*op*/) { return CKR_ATTRIBUTE_READ_ONLY; } /***************************************** * CKA_NEVER_EXTRACTABLE *****************************************/ // Set default value bool P11AttrNeverExtractable::setDefault() { OSAttribute attr(true); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrNeverExtractable::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR /*pValue*/, CK_ULONG /*ulValueLen*/, int /*op*/) { return CKR_ATTRIBUTE_READ_ONLY; } /***************************************** * CKA_SENSITIVE *****************************************/ // Set default value bool P11AttrSensitive::setDefault() { // We default to false because we want to handle the secret keys in a correct way OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrSensitive::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op == OBJECT_OP_SET || op == OBJECT_OP_COPY) { if (osobject->getBooleanValue(CKA_SENSITIVE, false)) { return CKR_ATTRIBUTE_READ_ONLY; } } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); osobject->setAttribute(CKA_ALWAYS_SENSITIVE, attrFalse); } else { osobject->setAttribute(type, attrTrue); // This is so that generated keys get the correct value if (op == OBJECT_OP_GENERATE || op == OBJECT_OP_DERIVE) { osobject->setAttribute(CKA_ALWAYS_SENSITIVE, attrTrue); } } return CKR_OK; } /***************************************** * CKA_EXTRACTABLE *****************************************/ // Set default value bool P11AttrExtractable::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrExtractable::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op == OBJECT_OP_SET || op == OBJECT_OP_COPY) { if (osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false) { return CKR_ATTRIBUTE_READ_ONLY; } } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); osobject->setAttribute(CKA_NEVER_EXTRACTABLE, attrFalse); } return CKR_OK; } /***************************************** * CKA_WRAP_WITH_TRUSTED *****************************************/ // Set default value bool P11AttrWrapWithTrusted::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrWrapWithTrusted::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (op == OBJECT_OP_SET || op == OBJECT_OP_COPY) { if (osobject->getBooleanValue(CKA_WRAP_WITH_TRUSTED, false)) { return CKR_ATTRIBUTE_READ_ONLY; } } if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_ALWAYS_AUTHENTICATE *****************************************/ // Set default value bool P11AttrAlwaysAuthenticate::setDefault() { OSAttribute attr(false); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrAlwaysAuthenticate::updateAttr(Token* /*token*/, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { OSAttribute attrTrue(true); OSAttribute attrFalse(false); // Attribute specific checks if (ulValueLen !=sizeof(CK_BBOOL)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data if (*(CK_BBOOL*)pValue == CK_FALSE) { osobject->setAttribute(type, attrFalse); } else { if (!isPrivate) { return CKR_TEMPLATE_INCONSISTENT; } osobject->setAttribute(type, attrTrue); } return CKR_OK; } /***************************************** * CKA_MODULUS *****************************************/ // Set default value bool P11AttrModulus::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrModulus::updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { ByteString plaintext((unsigned char*)pValue, ulValueLen); ByteString value; // Encrypt if (isPrivate) { if (!token->encrypt(plaintext, value)) return CKR_GENERAL_ERROR; } else value = plaintext; // Attribute specific checks if (value.size() < ulValueLen) return CKR_GENERAL_ERROR; // Store data osobject->setAttribute(type, value); // Set the CKA_MODULUS_BITS during C_CreateObject if (op == OBJECT_OP_CREATE && osobject->attributeExists(CKA_MODULUS_BITS)) { OSAttribute bits((unsigned long)plaintext.bits()); osobject->setAttribute(CKA_MODULUS_BITS, bits); } return CKR_OK; } /***************************************** * CKA_PUBLIC_EXPONENT *****************************************/ // Set default value bool P11AttrPublicExponent::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_PRIVATE_EXPONENT *****************************************/ // Set default value bool P11AttrPrivateExponent::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_PRIME_1 *****************************************/ // Set default value bool P11AttrPrime1::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_PRIME_2 *****************************************/ // Set default value bool P11AttrPrime2::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_EXPONENT_1 *****************************************/ // Set default value bool P11AttrExponent1::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_EXPONENT_2 *****************************************/ // Set default value bool P11AttrExponent2::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_COEFFICIENT *****************************************/ // Set default value bool P11AttrCoefficient::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_MODULUS_BITS *****************************************/ // Set default value bool P11AttrModulusBits::setDefault() { OSAttribute attr((unsigned long)0); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrModulusBits::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_GENERATE) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen !=sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_PRIME *****************************************/ // Set default value bool P11AttrPrime::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrPrime::updateAttr(Token *token, bool isPrivate, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { ByteString plaintext((unsigned char*)pValue, ulValueLen); ByteString value; // Encrypt if (isPrivate) { if (!token->encrypt(plaintext, value)) return CKR_GENERAL_ERROR; } else value = plaintext; // Attribute specific checks if (value.size() < ulValueLen) return CKR_GENERAL_ERROR; // Store data osobject->setAttribute(type, value); // Set the CKA_PRIME_BITS during C_CreateObject if (op == OBJECT_OP_CREATE && osobject->attributeExists(CKA_PRIME_BITS)) { OSAttribute bits((unsigned long)plaintext.bits()); osobject->setAttribute(CKA_PRIME_BITS, bits); } return CKR_OK; } /***************************************** * CKA_SUBPRIME *****************************************/ // Set default value bool P11AttrSubPrime::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_BASE *****************************************/ // Set default value bool P11AttrBase::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_PRIME_BITS *****************************************/ // Set default value bool P11AttrPrimeBits::setDefault() { OSAttribute attr((unsigned long)0); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrPrimeBits::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_GENERATE) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen != sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_VALUE_BITS *****************************************/ // Set default value bool P11AttrValueBits::setDefault() { OSAttribute attr((unsigned long)0); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrValueBits::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_GENERATE) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen != sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_EC_PARAMS *****************************************/ // Set default value bool P11AttrEcParams::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_EC_POINT *****************************************/ // Set default value bool P11AttrEcPoint::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_GOSTR3410_PARAMS *****************************************/ // Set default value bool P11AttrGostR3410Params::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_GOSTR3411_PARAMS *****************************************/ // Set default value bool P11AttrGostR3411Params::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_GOST28147_PARAMS *****************************************/ // Set default value bool P11AttrGost28147Params::setDefault() { OSAttribute attr(ByteString("")); return osobject->setAttribute(type, attr); } /***************************************** * CKA_VALUE_LEN *****************************************/ // Set default value bool P11AttrValueLen::setDefault() { OSAttribute attr((unsigned long)0); return osobject->setAttribute(type, attr); } // Update the value if allowed CK_RV P11AttrValueLen::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int op) { // Attribute specific checks if (op != OBJECT_OP_GENERATE && op != OBJECT_OP_DERIVE) { return CKR_ATTRIBUTE_READ_ONLY; } if (ulValueLen != sizeof(CK_ULONG)) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Store data osobject->setAttribute(type, *(CK_ULONG*)pValue); return CKR_OK; } /***************************************** * CKA_WRAP_TEMPLATE *****************************************/ // Set default value bool P11AttrWrapTemplate::setDefault() { std::map empty; OSAttribute attr(empty); return osobject->setAttribute(type, attr); } // Update the value CK_RV P11AttrWrapTemplate::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { // Attribute specific checks if ((ulValueLen % sizeof(CK_ATTRIBUTE)) != 0) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Fill the template vector with elements CK_ATTRIBUTE_PTR attr = (CK_ATTRIBUTE_PTR) pValue; std::map data; for (size_t i = 0; i < ulValueLen / sizeof(CK_ATTRIBUTE); ++i, ++attr) // Specialization for known attributes switch (attr->type) { case CKA_TOKEN: case CKA_PRIVATE: case CKA_MODIFIABLE: case CKA_COPYABLE: case CKA_TRUSTED: case CKA_ENCRYPT: case CKA_DECRYPT: case CKA_SIGN: case CKA_SIGN_RECOVER: case CKA_VERIFY: case CKA_VERIFY_RECOVER: case CKA_WRAP: case CKA_UNWRAP: case CKA_DERIVE: case CKA_LOCAL: case CKA_ALWAYS_SENSITIVE: case CKA_SENSITIVE: case CKA_NEVER_EXTRACTABLE: case CKA_EXTRACTABLE: case CKA_WRAP_WITH_TRUSTED: case CKA_SECONDARY_AUTH: case CKA_ALWAYS_AUTHENTICATE: { // CK_BBOOL if (attr->ulValueLen != sizeof(CK_BBOOL)) return CKR_ATTRIBUTE_VALUE_INVALID; bool elem = (*(CK_BBOOL*)attr->pValue != CK_FALSE); data.insert(std::pair (attr->type, elem)); } break; case CKA_CLASS: case CKA_KEY_TYPE: case CKA_CERTIFICATE_TYPE: case CKA_CERTIFICATE_CATEGORY: case CKA_JAVA_MIDP_SECURITY_DOMAIN: case CKA_NAME_HASH_ALGORITHM: case CKA_KEY_GEN_MECHANISM: case CKA_MODULUS_BITS: case CKA_PRIME_BITS: case CKA_SUBPRIME_BITS: case CKA_VALUE_BITS: case CKA_VALUE_LEN: case CKA_AUTH_PIN_FLAGS: { // CK_ULONG if (attr->ulValueLen != sizeof(CK_ULONG)) return CKR_ATTRIBUTE_VALUE_INVALID; unsigned long elem = *(CK_ULONG*)attr->pValue; data.insert(std::pair (attr->type, elem)); } break; case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: return CKR_ATTRIBUTE_VALUE_INVALID; default: { // CK_BYTE ByteString elem = ByteString((unsigned char*)attr->pValue, attr->ulValueLen); data.insert(std::pair (attr->type, elem)); } } // Store data osobject->setAttribute(type, data); return CKR_OK; } /***************************************** * CKA_UNWRAP_TEMPLATE *****************************************/ // Set default value bool P11AttrUnwrapTemplate::setDefault() { std::map empty; OSAttribute attr(empty); return osobject->setAttribute(type, attr); } // Update the value CK_RV P11AttrUnwrapTemplate::updateAttr(Token* /*token*/, bool /*isPrivate*/, CK_VOID_PTR pValue, CK_ULONG ulValueLen, int /*op*/) { // Attribute specific checks if ((ulValueLen % sizeof(CK_ATTRIBUTE)) != 0) { return CKR_ATTRIBUTE_VALUE_INVALID; } // Fill the template vector with elements CK_ATTRIBUTE_PTR attr = (CK_ATTRIBUTE_PTR) pValue; std::map data; for (size_t i = 0; i < ulValueLen / sizeof(CK_ATTRIBUTE); ++i, ++attr) // Specialization for known attributes switch (attr->type) { case CKA_TOKEN: case CKA_PRIVATE: case CKA_MODIFIABLE: case CKA_COPYABLE: case CKA_TRUSTED: case CKA_ENCRYPT: case CKA_DECRYPT: case CKA_SIGN: case CKA_SIGN_RECOVER: case CKA_VERIFY: case CKA_VERIFY_RECOVER: case CKA_WRAP: case CKA_UNWRAP: case CKA_DERIVE: case CKA_LOCAL: case CKA_ALWAYS_SENSITIVE: case CKA_SENSITIVE: case CKA_NEVER_EXTRACTABLE: case CKA_EXTRACTABLE: case CKA_WRAP_WITH_TRUSTED: case CKA_SECONDARY_AUTH: case CKA_ALWAYS_AUTHENTICATE: { // CK_BBOOL if (attr->ulValueLen != sizeof(CK_BBOOL)) return CKR_ATTRIBUTE_VALUE_INVALID; bool elem = (*(CK_BBOOL*)attr->pValue != CK_FALSE); data.insert(std::pair (attr->type, elem)); } break; case CKA_CLASS: case CKA_KEY_TYPE: case CKA_CERTIFICATE_TYPE: case CKA_CERTIFICATE_CATEGORY: case CKA_JAVA_MIDP_SECURITY_DOMAIN: case CKA_NAME_HASH_ALGORITHM: case CKA_KEY_GEN_MECHANISM: case CKA_MODULUS_BITS: case CKA_PRIME_BITS: case CKA_SUBPRIME_BITS: case CKA_VALUE_BITS: case CKA_VALUE_LEN: case CKA_AUTH_PIN_FLAGS: { // CK_ULONG if (attr->ulValueLen != sizeof(CK_ULONG)) return CKR_ATTRIBUTE_VALUE_INVALID; unsigned long elem = *(CK_ULONG*)attr->pValue; data.insert(std::pair (attr->type, elem)); } break; case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: return CKR_ATTRIBUTE_VALUE_INVALID; default: { // CK_BYTE ByteString elem = ByteString((unsigned char*)attr->pValue, attr->ulValueLen); data.insert(std::pair (attr->type, elem)); } } // Store data osobject->setAttribute(type, data); return CKR_OK; } softhsm-2.0.0/src/lib/data_mgr/0000775000175000017500000000000012552220147013312 500000000000000softhsm-2.0.0/src/lib/data_mgr/salloc.h0000664000175000017500000000353612533040716014670 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** salloc.h Contains an implementation of malloc that allocates memory securely *****************************************************************************/ #ifndef _SOFTHSM_V2_SALLOC_H #define _SOFTHSM_V2_SALLOC_H #include #include "config.h" #include "log.h" #if defined(__cplusplus) extern "C" { #endif /* Allocate memory */ void* salloc(size_t len); /* Free memory */ void sfree(void* ptr); #if defined (__cplusplus) } #endif #endif /* !_SOFTHSM_V2_SALLOC_H */ softhsm-2.0.0/src/lib/data_mgr/ByteString.cpp0000664000175000017500000001773012533040716016041 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ByteString.cpp A string class for byte strings stored in securely allocated memory *****************************************************************************/ #include #include #include #include "config.h" #include "log.h" #include "ByteString.h" // Constructors ByteString::ByteString() { } ByteString::ByteString(const unsigned char* bytes, const size_t bytesLen) { byteString.resize(bytesLen); if (bytesLen > 0) memcpy(&byteString[0], bytes, bytesLen); } ByteString::ByteString(const char* hexString) { std::string hex = std::string(hexString); if (hex.size() % 2 != 0) { hex = "0" + hex; } for (size_t i = 0; i < hex.size(); i += 2) { std::string byteStr; byteStr += hex[i]; byteStr += hex[i+1]; unsigned char byteVal = (unsigned char) strtoul(byteStr.c_str(), NULL, 16); this->operator+=(byteVal); } } ByteString::ByteString(const unsigned long longValue) { unsigned long setValue = longValue; // Convert the value to a big-endian byte string; N.B.: this code assumes that unsigned long // values are stored as a 64-bit value, which is a safe assumption on modern systems. It will // also properly handle a 32-bit value and will simply store 4 zeroes at the front of the // string. If at some point in time we get 128-bit architectures, the top 8 bytes of the value // will be discarded... (but hey, 640K is enough for everybody, right?) // // The reason for coding it this way is that implementations of SoftHSM will maintain // binary compatibility between eachothers background storage (i.e. a 32-bit SoftHSM version can // read the storage of a 64-bit version and vice versa under the assumption that the stored // values never exceed 32-bits, which is likely since these values are only used to encode // byte string lengths) unsigned char byteStrIn[8]; for (size_t i = 0; i < 8; i++) { byteStrIn[7-i] = (unsigned char) (setValue & 0xFF); setValue >>= 8; } byteString.resize(8); memcpy(&byteString[0], byteStrIn, 8); } ByteString::ByteString(const ByteString& in) { this->byteString = in.byteString; } // Append data ByteString& ByteString::operator+=(const ByteString& append) { size_t curLen = byteString.size(); size_t toAdd = append.byteString.size(); size_t newLen = curLen + toAdd; byteString.resize(newLen); if (toAdd > 0) memcpy(&byteString[curLen], &append.byteString[0], toAdd); return *this; } ByteString& ByteString::operator+=(const unsigned char byte) { byteString.push_back(byte); return *this; } // XORing ByteString& ByteString::operator^=(const ByteString& rhs) { size_t xorLen = std::min(this->size(), rhs.size()); for (size_t i = 0; i < xorLen; i++) { byteString[i] ^= rhs.const_byte_str()[i]; } return *this; } // Return a substring ByteString ByteString::substr(const size_t start, const size_t len /* = SIZE_T_MAX */) const { size_t retLen = std::min(len, byteString.size() - start); if (start >= byteString.size()) { return ByteString(); } else { return ByteString(&byteString[start], retLen); } } // Add data ByteString operator+(const ByteString& lhs, const ByteString& rhs) { ByteString rv = lhs; rv += rhs; return rv; } ByteString operator+(const unsigned char lhs, const ByteString& rhs) { ByteString rv(&lhs, 1); rv += rhs; return rv; } ByteString operator+(const ByteString& lhs, const unsigned char rhs) { ByteString rv = lhs; rv += rhs; return rv; } // Array operator unsigned char& ByteString::operator[](size_t pos) { return byteString[pos]; } // Return the byte string data unsigned char* ByteString::byte_str() { return &byteString[0]; } // Return the const byte string const unsigned char* ByteString::const_byte_str() const { return (const unsigned char*) &byteString[0]; } // Return a hexadecimal character representation of the string std::string ByteString::hex_str() const { std::string rv; char hex[3]; for (size_t i = 0; i < byteString.size(); i++) { sprintf(hex, "%02X", byteString[i]); rv += hex; } return rv; } // Return the long value unsigned long ByteString::long_val() const { // Convert the first 8 bytes of the string to an unsigned long value unsigned long rv = 0; for (size_t i = 0; i < std::min(size_t(8), byteString.size()); i++) { rv <<= 8; rv += byteString[i]; } return rv; } // Cut of the first part of the string and convert it to a long value unsigned long ByteString::firstLong() { unsigned long rv = long_val(); split(8); return rv; } // Split of the specified part of the string as a separate byte string ByteString ByteString::split(size_t len) { ByteString rv = substr(0, len); size_t newSize = (byteString.size() > len) ? (byteString.size() - len) : 0; if (newSize > 0) { for (size_t i = 0; i < newSize; i++) { byteString[i] = byteString[i + len]; } } byteString.resize(newSize); return rv; } // The size of the byte string in bits size_t ByteString::bits() const { size_t bits = byteString.size() * 8; if (bits == 0) return 0; for (size_t i = 0; i < byteString.size(); i++) { unsigned char byte = byteString[i]; for (unsigned char mask = 0x80; mask > 0; mask >>= 1) { if ((byte & mask) == 0) { bits--; } else { return bits; } } } return bits; } // The size of the byte string in bytes size_t ByteString::size() const { return byteString.size(); } void ByteString::resize(const size_t newSize) { byteString.resize(newSize); } void ByteString::wipe(const size_t newSize /* = 0 */) { this->resize(newSize); if (!byteString.empty()) memset(&byteString[0], 0x00, byteString.size()); } // Comparison bool ByteString::operator==(const ByteString& compareTo) const { if (compareTo.size() != this->size()) { return false; } else if (this->size() == 0) { return true; } return (memcmp(&byteString[0], &compareTo.byteString[0], this->size()) == 0); } bool ByteString::operator!=(const ByteString& compareTo) const { if (compareTo.size() != this->size()) { return true; } else if (this->size() == 0) { return false; } return (memcmp(&byteString[0], &compareTo.byteString[0], this->size()) != 0); } // XOR data ByteString operator^(const ByteString& lhs, const ByteString& rhs) { size_t xorLen = std::min(lhs.size(), rhs.size()); ByteString rv; for (size_t i = 0; i < xorLen; i++) { rv += lhs.const_byte_str()[i] ^ rhs.const_byte_str()[i]; } return rv; } // Serialisation/deserialisation ByteString ByteString::serialise() const { ByteString len((unsigned long) size()); return len + *this; } /* static */ ByteString ByteString::chainDeserialise(ByteString& serialised) { size_t len = (size_t) serialised.firstLong(); ByteString rv = serialised.split(len); return rv; } softhsm-2.0.0/src/lib/data_mgr/Makefile.am0000664000175000017500000000062612533040716015273 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_datamgr.la libsofthsm_datamgr_la_SOURCES = ByteString.cpp \ RFC4880.cpp \ salloc.cpp \ SecureDataManager.cpp \ SecureMemoryRegistry.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/data_mgr/SecureMemoryRegistry.h0000664000175000017500000000447012533040716017561 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureMemoryRegistry.h Implements a singleton class that keeps track of all securely allocated memory. This registry can be used to wipe securely allocated memory in case of a fatal exception *****************************************************************************/ #ifndef _SOFTHSM_V2_SECUREMEMORYREGISTRY_H #define _SOFTHSM_V2_SECUREMEMORYREGISTRY_H #include #include #include #include "MutexFactory.h" class SecureMemoryRegistry { public: SecureMemoryRegistry(); virtual ~SecureMemoryRegistry(); static SecureMemoryRegistry* i(); static void reset(); void add(void* pointer, size_t blocksize); size_t remove(void* pointer); void wipe(); private: #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif std::map registry; Mutex* SecMemRegistryMutex; }; #endif // !_SOFTHSM_V2_SECUREMEMORYREGISTRY_H softhsm-2.0.0/src/lib/data_mgr/RFC4880.h0000664000175000017500000000423112533040716014342 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RFC4880.h Implements a secure password-based key derivation scheme. It is not a generic implementation of the RFC but only generates 256-bit AES keys according to the "iterated and salted" scheme. *****************************************************************************/ #ifndef _SOFTHSM_V2_RFC4880_H #define _SOFTHSM_V2_RFC4880_H #include "config.h" #include "ByteString.h" #include "log.h" #include "AESKey.h" // This define sets the base PBE iteration count; the lowest byte of the salt is added // to this value as a form of jitter #define PBE_ITERATION_BASE_COUNT 1500 namespace RFC4880 { // This function derives a 256-bit AES key from the supplied password data bool PBEDeriveKey(const ByteString& password, ByteString& salt, AESKey** ppKey); } #endif // !_SOFTHSM_V2_RFC4880_H softhsm-2.0.0/src/lib/data_mgr/salloc.cpp0000664000175000017500000000651612533040716015224 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** salloc.cpp Contains an implementation of malloc that allocates memory securely *****************************************************************************/ #include "config.h" #include "log.h" #include "salloc.h" #include #if defined(SENSITIVE_NON_PAGED) && !defined(_WIN32) #include #endif // SENSITIVE_NON_PAGED #include #include "SecureMemoryRegistry.h" // Allocate memory void* salloc(size_t len) { #ifdef SENSITIVE_NON_PAGED // Allocate memory on a page boundary #ifndef _WIN32 void* ptr = (void*) valloc(len); #else pointer r = (pointer) VirtualAlloc(NULL, n * sizeof(T), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #endif if (ptr == NULL) { ERROR_MSG("Out of memory"); return NULL; } // Lock the memory so it doesn't get swapped out #ifndef _WIN32 if (mlock((const void*) ptr, len) != 0) #else if (VirtualLock((const void*) r, n * sizeof(T)) == 0) #endif { ERROR_MSG("Could not allocate non-paged memory for secure storage"); // Hmmm... best to not return any allocated space in this case #ifndef _WIN32 free(ptr); #else VirtualFree((const void*) pre, MEM_RELEASE); #endif return NULL; } // Register the memory in the secure memory registry SecureMemoryRegistry::i()->add(ptr, len); return ptr; #else void* ptr = (void*) malloc(len); if (ptr == NULL) { ERROR_MSG("Out of memory"); return NULL; } // Register the memory in the secure memory registry SecureMemoryRegistry::i()->add(ptr, len); return ptr; #endif // SENSITIVE_NON_PAGED } // Free memory void sfree(void* ptr) { // Unregister the memory from the secure memory registry size_t len = SecureMemoryRegistry::i()->remove(ptr); #ifdef PARANOID // First toggle all bits on memset(ptr, 0xFF, len); #endif // PARANOID // Toggle all bits off memset(ptr, 0x00, len); #ifdef SENSITIVE_NON_PAGED #ifndef _WIN32 munlock((const void*) ptr, len); #else VirtualFree((const void*) pre, MEM_RELEASE); #endif #endif // SENSITIVE_NON_PAGED free(ptr); } softhsm-2.0.0/src/lib/data_mgr/SecureDataManager.h0000664000175000017500000001143612533040716016724 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureDataManager.h The secure data manager main class. Every token instance has a secure data manager instance member that is used to decrypt and encrypt sensitive object attributes such as key material. The secure data manager maintains a key blob containing a 256-bit AES key that is used in this decryption and encryption process. The key blob itself is encrypted using a PBE derived key that is derived from the user PIN and a PBE key that is derived from the SO PIN. It is up to the token to enforce access control based on which user is logged in; authentication using the SO PIN is required to be able to change the user PIN. The master key that is used to decrypt/encrypt sensitive attributes is stored in memory under a mask that is changed every time the key is used. *****************************************************************************/ #ifndef _SOFTHSM_V2_SECUREDATAMANAGER_H #define _SOFTHSM_V2_SECUREDATAMANAGER_H #include "config.h" #include "ByteString.h" #include "log.h" #include "AESKey.h" #include "RNG.h" #include "SymmetricAlgorithm.h" #include "MutexFactory.h" class SecureDataManager { public: // Constructors // Constructs a new SecureDataManager for a blank token; actual // initialisation is done by setting the SO PIN SecureDataManager(); // Constructs a SecureDataManager using the specified SO PIN and user PIN SecureDataManager(const ByteString& soPINBlob, const ByteString& userPINBlob); // Destructor virtual ~SecureDataManager(); // Set the SO PIN (requires either a blank SecureDataManager or the // SO to have logged in previously) bool setSOPIN(const ByteString& soPIN); // Set the user PIN (requires either the SO or the user to have logged // in previously) bool setUserPIN(const ByteString& userPIN); // Log in using the SO PIN bool loginSO(const ByteString& soPIN); bool isSOLoggedIn(); // Log in using the user PIN bool loginUser(const ByteString& userPIN); bool isUserLoggedIn(); // Log out void logout(); // Decrypt the supplied data bool decrypt(const ByteString& encrypted, ByteString& plaintext); // Encrypt the supplied data bool encrypt(const ByteString& plaintext, ByteString& encrypted); // Returns the key blob for the SO PIN ByteString getSOPINBlob(); // Returns the key blob for the user PIN ByteString getUserPINBlob(); private: // Initialise the object void initObject(); // Generic login function bool login(const ByteString& passphrase, const ByteString& encryptedKey); // Generic function for creating an encrypted version of the key from the specified passphrase bool pbeEncryptKey(const ByteString& passphrase, ByteString& encryptedKey); // Unmask the key void unmask(ByteString& key); // Remask the key void remask(ByteString& key); // The user PIN encrypted key ByteString userEncryptedKey; // The SO PIN encrypted key ByteString soEncryptedKey; // Which users are logged in bool soLoggedIn; bool userLoggedIn; // The masked version of the actual key ByteString maskedKey; // The "magic" data used to detect if a PIN was likely to be correct ByteString magic; // The mask; this is not a stack member but a heap member. This // hopefully ensures that the mask ends up in a memory location // that is not logically linked to the masked key ByteString* mask; // Random number generator instance RNG* rng; // AES instance SymmetricAlgorithm* aes; // Mutex Mutex* dataMgrMutex; }; #endif // !_SOFTHSM_V2_SECUREDATAMANAGER_H softhsm-2.0.0/src/lib/data_mgr/test/0000775000175000017500000000000012552220147014271 500000000000000softhsm-2.0.0/src/lib/data_mgr/test/Makefile.am0000664000175000017500000000124212533040716016245 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ `cppunit-config --cflags` check_PROGRAMS = datamgrtest datamgrtest_SOURCES = datamgrtest.cpp \ ByteStringTests.cpp \ RFC4880Tests.cpp \ SecureDataMgrTests.cpp datamgrtest_LDADD = ../../libsofthsm_convarch.la datamgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` TESTS = datamgrtest EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/data_mgr/test/SecureDataMgrTests.h0000664000175000017500000000372712533040716020105 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureDataMgrTests.h Contains test cases to test the secure data manager *****************************************************************************/ #ifndef _SOFTHSM_V2_SECUREDATAMGRTESTS_H #define _SOFTHSM_V2_SECUREDATAMGRTESTS_H #include #include "RNG.h" class SecureDataMgrTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SecureDataMgrTests); CPPUNIT_TEST(testSecureDataManager); CPPUNIT_TEST_SUITE_END(); public: void testSecureDataManager(); void setUp(); void tearDown(); private: RNG* rng; }; #endif // !_SOFTHSM_V2_SECUREDATAMGRTESTS_H softhsm-2.0.0/src/lib/data_mgr/test/SecureDataMgrTests.cpp0000664000175000017500000001476412533040716020443 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureDataMgrTests.cpp Contains test cases to test the secure data manager *****************************************************************************/ #include #include #include #include "SecureDataMgrTests.h" #include "SecureDataManager.h" #include "CryptoFactory.h" CPPUNIT_TEST_SUITE_REGISTRATION(SecureDataMgrTests); void SecureDataMgrTests::setUp() { CPPUNIT_ASSERT((rng = CryptoFactory::i()->getRNG()) != NULL); } void SecureDataMgrTests::tearDown() { } void SecureDataMgrTests::testSecureDataManager() { ByteString soPIN = "3132333435363738"; // "12345678" ByteString userPIN = "4041424344454647"; // "ABCDEFGH" ByteString newSOPIN = "3837363534333231"; // "87654321" ByteString newUserPIN = "4746454443424140"; // "HGFEDCBA" // Instantiate a blank secure data manager SecureDataManager s1; ByteString plaintext = "010203040506070809"; ByteString emptyPlaintext = ""; ByteString encrypted; // Verify that no function other than setting the SO PIN works CPPUNIT_ASSERT(!s1.setUserPIN(userPIN)); CPPUNIT_ASSERT(!s1.loginSO(soPIN)); CPPUNIT_ASSERT(!s1.loginUser(userPIN)); CPPUNIT_ASSERT(!s1.encrypt(plaintext, encrypted)); CPPUNIT_ASSERT(!s1.decrypt(encrypted, plaintext)); CPPUNIT_ASSERT(s1.getSOPINBlob().size() == 0); CPPUNIT_ASSERT(s1.getUserPINBlob().size() == 0); // Now set the SO PIN CPPUNIT_ASSERT(s1.setSOPIN(soPIN)); // Check that it is still not possible to set the user PIN CPPUNIT_ASSERT(!s1.setUserPIN(userPIN)); // Check that it is possible to log in with the SO PIN CPPUNIT_ASSERT(s1.loginSO(soPIN)); // Check that it is now possible to also set the user PIN CPPUNIT_ASSERT(s1.setUserPIN(userPIN)); // Check that is is now also possible to log in with the user PIN CPPUNIT_ASSERT(s1.loginUser(userPIN)); // Check that it is possible to encrypt and decrypt some data ByteString decrypted; CPPUNIT_ASSERT(s1.encrypt(plaintext, encrypted)); CPPUNIT_ASSERT(encrypted != plaintext); CPPUNIT_ASSERT(s1.decrypt(encrypted, decrypted)); CPPUNIT_ASSERT(decrypted == plaintext); // Log out s1.logout(); // Check that it is no longer possible to set the SO PIN CPPUNIT_ASSERT(!s1.setSOPIN(soPIN)); // Check that it is no longer possible to set the user PIN CPPUNIT_ASSERT(!s1.setUserPIN(userPIN)); // Check that encrypting/decrypting no longer works CPPUNIT_ASSERT(!s1.encrypt(plaintext, encrypted)); CPPUNIT_ASSERT(!s1.decrypt(encrypted, plaintext)); // Export the key blobs ByteString soPINBlob = s1.getSOPINBlob(); ByteString userPINBlob = s1.getUserPINBlob(); // Create a new instance with the exported key blobs SecureDataManager s2(soPINBlob, userPINBlob); // Check that the key blobs match CPPUNIT_ASSERT(s1.getSOPINBlob() == s2.getSOPINBlob()); CPPUNIT_ASSERT(s1.getUserPINBlob() == s2.getUserPINBlob()); // Check that it is not possible to set the SO PIN CPPUNIT_ASSERT(!s2.setSOPIN(soPIN)); // Check that it is possible to log in with the SO PIN CPPUNIT_ASSERT(s2.loginSO(soPIN)); // Check that is is now also possible to log in with the user PIN CPPUNIT_ASSERT(s2.loginUser(userPIN)); // Check that encrypting the data results in different ciphertext because of the random IV ByteString encrypted2; CPPUNIT_ASSERT(s2.encrypt(plaintext, encrypted2)); CPPUNIT_ASSERT(encrypted != encrypted2); // Check that decrypting earlier data can be done with the recreated key CPPUNIT_ASSERT(s2.decrypt(encrypted, decrypted)); CPPUNIT_ASSERT(decrypted == plaintext); // Log in with the SO PIN CPPUNIT_ASSERT(s2.loginSO(soPIN)); // Check that the SO PIN can be changed CPPUNIT_ASSERT(s2.setSOPIN(newSOPIN)); // Check that it is no longer possible to log in with the old SO PIN CPPUNIT_ASSERT(!s2.loginSO(soPIN)); // Check that encrypting/decrypting no longer works CPPUNIT_ASSERT(!s2.encrypt(plaintext, encrypted)); CPPUNIT_ASSERT(!s2.decrypt(encrypted, plaintext)); // Check that the key blobs differ CPPUNIT_ASSERT(s1.getSOPINBlob() != s2.getSOPINBlob()); // Check that it is possible to log in with the new SO PIN CPPUNIT_ASSERT(s2.loginSO(newSOPIN)); // Log in with the user PIN CPPUNIT_ASSERT(s2.loginUser(userPIN)); // Check that it is possible to change the user PIN CPPUNIT_ASSERT(s2.setUserPIN(newUserPIN)); // Check that it is no longer possible to log in with the old user PIN CPPUNIT_ASSERT(!s2.loginUser(userPIN)); // Check that encrypting/decrypting no longer works CPPUNIT_ASSERT(!s2.encrypt(plaintext, encrypted)); CPPUNIT_ASSERT(!s2.decrypt(encrypted, plaintext)); // Check that it is possible to log in with the new user PIN CPPUNIT_ASSERT(s2.loginUser(newUserPIN)); // Check that encrypting the data results in the different ciphertext because of the random IV CPPUNIT_ASSERT(s2.encrypt(plaintext, encrypted2)); CPPUNIT_ASSERT(encrypted != encrypted2); // Check that decrypting earlier data can be done with the recreated key CPPUNIT_ASSERT(s2.decrypt(encrypted, decrypted)); CPPUNIT_ASSERT(decrypted == plaintext); // Check that empty plaintext can be handled CPPUNIT_ASSERT(s2.encrypt(emptyPlaintext, encrypted)); CPPUNIT_ASSERT(s2.decrypt(encrypted, decrypted)); CPPUNIT_ASSERT(decrypted == emptyPlaintext); } softhsm-2.0.0/src/lib/data_mgr/test/RFC4880Tests.h0000664000175000017500000000364212533040716016351 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RFC4880Tests.h Contains test cases to test the RFC4880 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_RFC4880TESTS_H #define _SOFTHSM_V2_RFC4880TESTS_H #include #include "RNG.h" class RFC4880Tests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RFC4880Tests); CPPUNIT_TEST(testRFC4880); CPPUNIT_TEST_SUITE_END(); public: void testRFC4880(); void setUp(); void tearDown(); private: RNG* rng; }; #endif // !_SOFTHSM_V2_RFC4880TESTS_H softhsm-2.0.0/src/lib/data_mgr/test/ByteStringTests.h0000664000175000017500000000451612533040716017506 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ByteStringTests.h Contains test cases to test the ByteString class *****************************************************************************/ #ifndef _SOFTHSM_V2_BYTESTRINGTESTS_H #define _SOFTHSM_V2_BYTESTRINGTESTS_H #include class ByteStringTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ByteStringTests); CPPUNIT_TEST(testIntegrity); CPPUNIT_TEST(testAppend); CPPUNIT_TEST(testSubstr); CPPUNIT_TEST(testFromHexStr); CPPUNIT_TEST(testXOR); CPPUNIT_TEST(testToHexStr); CPPUNIT_TEST(testLongValues); CPPUNIT_TEST(testSplitting); CPPUNIT_TEST(testBits); CPPUNIT_TEST(testSerialising); CPPUNIT_TEST_SUITE_END(); public: void testIntegrity(); void testAppend(); void testSubstr(); void testFromHexStr(); void testXOR(); void testToHexStr(); void testLongValues(); void testSplitting(); void testBits(); void testSerialising(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_BYTESTRINGTESTS_H softhsm-2.0.0/src/lib/data_mgr/test/Makefile.in0000664000175000017500000010153512552216620016264 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = datamgrtest$(EXEEXT) TESTS = datamgrtest$(EXEEXT) subdir = src/lib/data_mgr/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am_datamgrtest_OBJECTS = datamgrtest.$(OBJEXT) \ ByteStringTests.$(OBJEXT) RFC4880Tests.$(OBJEXT) \ SecureDataMgrTests.$(OBJEXT) datamgrtest_OBJECTS = $(am_datamgrtest_OBJECTS) datamgrtest_DEPENDENCIES = ../../libsofthsm_convarch.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = datamgrtest_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(datamgrtest_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(datamgrtest_SOURCES) DIST_SOURCES = $(datamgrtest_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ `cppunit-config --cflags` datamgrtest_SOURCES = datamgrtest.cpp \ ByteStringTests.cpp \ RFC4880Tests.cpp \ SecureDataMgrTests.cpp datamgrtest_LDADD = ../../libsofthsm_convarch.la datamgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/data_mgr/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/data_mgr/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list datamgrtest$(EXEEXT): $(datamgrtest_OBJECTS) $(datamgrtest_DEPENDENCIES) $(EXTRA_datamgrtest_DEPENDENCIES) @rm -f datamgrtest$(EXEEXT) $(AM_V_CXXLD)$(datamgrtest_LINK) $(datamgrtest_OBJECTS) $(datamgrtest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ByteStringTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RFC4880Tests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SecureDataMgrTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/datamgrtest.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? datamgrtest.log: datamgrtest$(EXEEXT) @p='datamgrtest$(EXEEXT)'; \ b='datamgrtest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/data_mgr/test/datamgrtest.cpp0000664000175000017500000000401412533040716017234 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** datamgrtest.cpp The main test executor for tests on the secure data manager in SoftHSM v2 *****************************************************************************/ #include #include #include "CryptoFactory.h" #include "SecureMemoryRegistry.h" int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); CryptoFactory::reset(); SecureMemoryRegistry::reset(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/data_mgr/test/RFC4880Tests.cpp0000664000175000017500000001007112533040716016676 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RFC4880Tests.cpp Contains test cases to test the RFC4880 implementation *****************************************************************************/ #include #include #include #include "RFC4880Tests.h" #include "RFC4880.h" #include "ByteString.h" #include "CryptoFactory.h" #include "AESKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(RFC4880Tests); void RFC4880Tests::setUp() { CPPUNIT_ASSERT((rng = CryptoFactory::i()->getRNG()) != NULL); } void RFC4880Tests::tearDown() { } void RFC4880Tests::testRFC4880() { const unsigned char* pwd1String = (const unsigned char*) "monkey"; const unsigned char* pwd2String = (const unsigned char*) "bicycle"; ByteString pwd1(pwd1String, strlen("monkey")); ByteString pwd2(pwd2String, strlen("bicycle")); // Generate salt and make sure that two different salt values are generated and // that the last byte is also different (resulting in a different iteration jitter // when computing a PBE key using both salt values) ByteString salt1, salt2; do { CPPUNIT_ASSERT(rng->generateRandom(salt1, 8) && rng->generateRandom(salt2, 8)); } while ((salt1 == salt2) || (salt1[salt1.size() - 1] == salt2[salt2.size() - 1])); // Create a password-based encryption key from the first and second password AESKey* key1; AESKey* key2; CPPUNIT_ASSERT(RFC4880::PBEDeriveKey(pwd1, salt1, &key1)); CPPUNIT_ASSERT(RFC4880::PBEDeriveKey(pwd2, salt2, &key2)); // Check that the output keys differ and have the correct length CPPUNIT_ASSERT(key1->getKeyBits().size() == 32); CPPUNIT_ASSERT(key2->getKeyBits().size() == 32); CPPUNIT_ASSERT(key1->getKeyBits() != key2->getKeyBits()); // Rederive the keys to check that the same output is generated every time AESKey* key1_; AESKey* key2_; CPPUNIT_ASSERT(RFC4880::PBEDeriveKey(pwd1, salt1, &key1_)); CPPUNIT_ASSERT(RFC4880::PBEDeriveKey(pwd2, salt2, &key2_)); CPPUNIT_ASSERT(key1->getKeyBits() == key1_->getKeyBits()); CPPUNIT_ASSERT(key2->getKeyBits() == key2_->getKeyBits()); // Now reverse the salts and derive new keys AESKey* key3; AESKey* key4; CPPUNIT_ASSERT(RFC4880::PBEDeriveKey(pwd1, salt2, &key3)); CPPUNIT_ASSERT(RFC4880::PBEDeriveKey(pwd2, salt1, &key4)); // Check that the keys are different and that they differ from the // original keys (because different salts were used) CPPUNIT_ASSERT(key3->getKeyBits() != key4->getKeyBits()); CPPUNIT_ASSERT(key1->getKeyBits() != key3->getKeyBits()); CPPUNIT_ASSERT(key1->getKeyBits() != key4->getKeyBits()); CPPUNIT_ASSERT(key2->getKeyBits() != key3->getKeyBits()); CPPUNIT_ASSERT(key2->getKeyBits() != key4->getKeyBits()); // Clean up delete key1; delete key2; delete key1_; delete key2_; delete key3; delete key4; } softhsm-2.0.0/src/lib/data_mgr/test/ByteStringTests.cpp0000664000175000017500000002306512533040716020041 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ByteStringTests.cpp Contains test cases to test the ByteString class *****************************************************************************/ #include #include #include #include #include "ByteStringTests.h" #include "ByteString.h" CPPUNIT_TEST_SUITE_REGISTRATION(ByteStringTests); void ByteStringTests::setUp() { } void ByteStringTests::tearDown() { fflush(stdout); } void ByteStringTests::testIntegrity() { unsigned char testData[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; ByteString b(testData, sizeof(testData)); // Test if the right data is returned CPPUNIT_ASSERT(memcmp(testData, b.byte_str(), sizeof(testData)) == 0); // Test size CPPUNIT_ASSERT(b.size() == sizeof(testData)); // Test the copy constructor ByteString b2(b); // Test using comparison operator CPPUNIT_ASSERT(b == b2); // Test using memcmp CPPUNIT_ASSERT(memcmp(b.byte_str(), b2.byte_str(), b.size()) == 0); // Modify the copied version and test again b2[1] = 0x20; // Test using comparison operator CPPUNIT_ASSERT(b != b2); // Test using memcmp directly CPPUNIT_ASSERT(memcmp(b.byte_str(), b2.byte_str(), b.size()) != 0); // Verify that b was not affected CPPUNIT_ASSERT(memcmp(b.byte_str(), testData, sizeof(testData)) == 0); // Modify the source data and check if the array operator has functioned correctly testData[1] = 0x20; // Test if the right data is in b2 CPPUNIT_ASSERT(memcmp(b2.byte_str(), testData, sizeof(testData)) == 0); } void ByteStringTests::testAppend() { unsigned char testData[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; ByteString b; ByteString b1(testData, sizeof(testData)); // Test that b is empty and b1 is not CPPUNIT_ASSERT((b.size() == 0) && (b1.size() == sizeof(testData))); // Append 1 byte to b b += 0x01; // Check the contents of b CPPUNIT_ASSERT(b.size() == 1); CPPUNIT_ASSERT(b[0] == 0x01); // Append another byte to b b += 0x02; // Check the contents of b CPPUNIT_ASSERT(b.size() == 2); CPPUNIT_ASSERT((b[0] == 0x01) && (b[1] == 0x02)); // Append b1 to b b += b1; // Check the contents of b CPPUNIT_ASSERT(b.size() == 2 + sizeof(testData)); CPPUNIT_ASSERT((b[0] == 0x01) && (b[1] == 0x02)); CPPUNIT_ASSERT(memcmp(&b[2], testData, sizeof(testData)) == 0); // Append b to b b += b; // Check the contents of b CPPUNIT_ASSERT(b.size() == 2 * (2 + sizeof(testData))); CPPUNIT_ASSERT((b[0] == 0x01) && (b[1] == 0x02) && (b[(2 + sizeof(testData)) + 0] == 0x01) && (b[(2 + sizeof(testData)) + 1] == 0x02)); CPPUNIT_ASSERT((memcmp(&b[2], testData, sizeof(testData)) == 0) && (memcmp(&b[2 + 2 + sizeof(testData)], testData, sizeof(testData)) == 0)); } void ByteStringTests::testSubstr() { unsigned char testData[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; ByteString b; ByteString b1(testData, sizeof(testData)); // Take a substring b = b1.substr(8, 4); // Check b CPPUNIT_ASSERT(b.size() == 4); CPPUNIT_ASSERT(memcmp(b.byte_str(), &testData[8], 4) == 0); // Take another substring b = b1.substr(8); // Check b CPPUNIT_ASSERT(b.size() == 8); CPPUNIT_ASSERT(memcmp(b.byte_str(), &testData[8], 8) == 0); // Two substrings added should yield the original string b = b1.substr(0, 8) + b1.substr(8); // Check b CPPUNIT_ASSERT(b.size() == sizeof(testData)); CPPUNIT_ASSERT(memcmp(b.byte_str(), testData, sizeof(testData)) == 0); } void ByteStringTests::testFromHexStr() { unsigned char testData[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10 }; ByteString b("0102030405060708090a0b0c0d0e0f10"); ByteString b1("0102030405060708090A0B0C0D0E0F10"); CPPUNIT_ASSERT(memcmp(b.byte_str(), testData, sizeof(testData)) == 0); CPPUNIT_ASSERT(memcmp(b1.byte_str(), testData, sizeof(testData)) == 0); } void ByteStringTests::testXOR() { unsigned char left[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; unsigned char right[] = { 0x80, 0x70, 0x60, 0x50, 0x40, 0x30, 0x20, 0x10 }; unsigned char xorred[] = { 0x81, 0x72, 0x63, 0x54, 0x45, 0x36, 0x27, 0x18 }; ByteString l(left, 8); ByteString r(right, 8); ByteString x(xorred, 8); ByteString xed; xed = l ^ r; CPPUNIT_ASSERT(xed == x); ByteString l1(left, 8); ByteString r1(right, 8); l1 ^= r1; CPPUNIT_ASSERT(l1 == x); l1 ^= l; CPPUNIT_ASSERT(l1 == r); ByteString l_(left, 7); xed = l_ ^ r; CPPUNIT_ASSERT((xed.size() == 7) && (xed == x.substr(0, 7))); ByteString r_(right, 7); xed = l ^ r_; CPPUNIT_ASSERT((xed.size() == 7) && (xed == x.substr(0, 7))); ByteString l1_(left, 8); l1_ ^= r_; CPPUNIT_ASSERT((l1.size() == 8) && (l1_.substr(0, 7) == x.substr(0,7)) && (l1_[7] == l[7])); ByteString l1__(left, 7); l1__ ^= r; CPPUNIT_ASSERT((l1__ == x.substr(0,7)) && (l1__.size() == 7)); } void ByteStringTests::testToHexStr() { ByteString b("0102030405060708090A0B0C0D0E0F"); ByteString b1("DEADBEEF"); ByteString b2("deadC0FFEE"); std::string s = b.hex_str(); std::string s1 = b1.hex_str(); std::string s2 = b2.hex_str(); CPPUNIT_ASSERT(s.compare("0102030405060708090A0B0C0D0E0F") == 0); CPPUNIT_ASSERT(s1.compare("DEADBEEF") == 0); CPPUNIT_ASSERT(s2.compare("DEADC0FFEE") == 0); } void ByteStringTests::testLongValues() { unsigned long ul1 = 0x00112233; unsigned long ul2 = 0x10203040; unsigned long ul3 = 0xF0E0D0C0; ByteString b1(ul1); ByteString b2(ul2); ByteString b3(ul3); CPPUNIT_ASSERT(b1 == ByteString("0000000000112233")); CPPUNIT_ASSERT(b2 == ByteString("0000000010203040")); CPPUNIT_ASSERT(b3 == ByteString("00000000F0E0D0C0")); CPPUNIT_ASSERT(b1.long_val() == ul1); CPPUNIT_ASSERT(b2.long_val() == ul2); CPPUNIT_ASSERT(b3.long_val() == ul3); ByteString concat = b1 + b2 + b3; CPPUNIT_ASSERT(concat == ByteString("0000000000112233000000001020304000000000F0E0D0C0")); unsigned long ulr1 = concat.firstLong(); CPPUNIT_ASSERT(ulr1 == ul1); CPPUNIT_ASSERT(concat == ByteString("000000001020304000000000F0E0D0C0")); unsigned long ulr2 = concat.firstLong(); CPPUNIT_ASSERT(ulr2 == ul2); CPPUNIT_ASSERT(concat == ByteString("00000000F0E0D0C0")); unsigned long ulr3 = concat.firstLong(); CPPUNIT_ASSERT(ulr3 == ul3); CPPUNIT_ASSERT(concat.size() == 0); ByteString b4("ABCDEF"); CPPUNIT_ASSERT(b4.long_val() == 0xABCDEF); CPPUNIT_ASSERT(b4.size() == 3); CPPUNIT_ASSERT(b4.firstLong() == 0xABCDEF); CPPUNIT_ASSERT(b4.size() == 0); } void ByteStringTests::testSplitting() { ByteString b("AABBCCDDEEFF112233445566"); ByteString b1 = b.split(6); CPPUNIT_ASSERT(b == ByteString("112233445566")); CPPUNIT_ASSERT(b1 == ByteString("AABBCCDDEEFF")); ByteString b2 = b1.split(8); CPPUNIT_ASSERT(b2 == ByteString("AABBCCDDEEFF")); CPPUNIT_ASSERT(b1.size() == 0); } void ByteStringTests::testBits() { ByteString b1("0"); ByteString b2("08"); ByteString b3("00FFFFF"); ByteString b4("123456"); CPPUNIT_ASSERT(b1.bits() == 0); CPPUNIT_ASSERT(b2.bits() == 4); CPPUNIT_ASSERT(b3.bits() == 20); CPPUNIT_ASSERT(b4.bits() == 21); } void ByteStringTests::testSerialising() { ByteString b1("AA11AA11AA11AA11AA11AA11AA11"); ByteString b2("BB22BB22BB22BB22BB22BB22"); ByteString b3("CC33CC33CC33CC33CC33CC33CC33CC33"); ByteString s1 = b1.serialise(); CPPUNIT_ASSERT(s1.size() == b1.size() + 8); ByteString d1 = ByteString::chainDeserialise(s1); CPPUNIT_ASSERT(s1.size() == 0); CPPUNIT_ASSERT(d1 == b1); ByteString s2 = b3.serialise() + b2.serialise() + b1.serialise(); CPPUNIT_ASSERT(s2.size() == b1.size() + b2.size() + b3.size() + (3*8)); d1 = ByteString::chainDeserialise(s2); CPPUNIT_ASSERT(d1.size() == b3.size()); CPPUNIT_ASSERT(s2.size() == b1.size() + b2.size() + (2*8)); ByteString d2 = ByteString::chainDeserialise(s2); CPPUNIT_ASSERT(d2.size() == b2.size()); CPPUNIT_ASSERT(s2.size() == b1.size() + 8); ByteString d3 = ByteString::chainDeserialise(s2); CPPUNIT_ASSERT(d3.size() == b1.size()); CPPUNIT_ASSERT(s2.size() == 0); CPPUNIT_ASSERT(d1 == b3); CPPUNIT_ASSERT(d2 == b2); CPPUNIT_ASSERT(d3 == b1); } softhsm-2.0.0/src/lib/data_mgr/SecureDataManager.cpp0000664000175000017500000002430712533040716017260 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureDataManager.cpp The secure data manager main class. Every token instance has a secure data manager instance member that is used to decrypt and encrypt sensitive object attributes such as key material. The secure data manager maintains a key blob containing a 256-bit AES key that is used in this decryption and encryption process. The key blob itself is encrypted using a PBE derived key that is derived from the user PIN and a PBE key that is derived from the SO PIN. It is up to the token to enforce access control based on which user is logged in; authentication using the SO PIN is required to be able to change the user PIN. The master key that is used to decrypt/encrypt sensitive attributes is stored in memory under a mask that is changed every time the key is used. *****************************************************************************/ #include "config.h" #include "SecureDataManager.h" #include "CryptoFactory.h" #include "AESKey.h" #include "SymmetricAlgorithm.h" #include "RFC4880.h" // Constructors // Initialise the object; called by all constructors void SecureDataManager::initObject() { // Get an RNG instance rng = CryptoFactory::i()->getRNG(); // Get an AES implementation aes = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::AES); // Initialise masking data mask = new ByteString(); rng->generateRandom(*mask, 32); // Set the initial login state soLoggedIn = userLoggedIn = false; // Set the magic magic = ByteString("524A52"); // RJR // Get a mutex dataMgrMutex = MutexFactory::i()->getMutex(); } // Constructs a new SecureDataManager for a blank token; actual // initialisation is done by setting the SO PIN SecureDataManager::SecureDataManager() { initObject(); } // Constructs a SecureDataManager using the specified key blob SecureDataManager::SecureDataManager(const ByteString& soPINBlob, const ByteString& userPINBlob) { initObject(); // De-serialise the key blob soEncryptedKey = soPINBlob; userEncryptedKey = userPINBlob; } // Destructor SecureDataManager::~SecureDataManager() { // Recycle the AES instance CryptoFactory::i()->recycleSymmetricAlgorithm(aes); // Clean up the mask delete mask; MutexFactory::i()->recycleMutex(dataMgrMutex); } // Generic function for creating an encrypted version of the key from the specified passphrase bool SecureDataManager::pbeEncryptKey(const ByteString& passphrase, ByteString& encryptedKey) { // Generate salt ByteString salt; if (!rng->generateRandom(salt, 8)) return false; // Derive the key using RFC4880 PBE AESKey* pbeKey = NULL; if (!RFC4880::PBEDeriveKey(passphrase, salt, &pbeKey)) { return false; } // Add the salt encryptedKey.wipe(); encryptedKey += salt; // Generate random IV ByteString IV; if (!rng->generateRandom(IV, aes->getBlockSize())) return false; // Add the IV encryptedKey += IV; // Encrypt the data ByteString block; if (!aes->encryptInit(pbeKey, SymMode::CBC, IV)) { delete pbeKey; return false; } // First, add the magic if (!aes->encryptUpdate(magic, block)) { delete pbeKey; return false; } encryptedKey += block; // Then, add the key itself ByteString key; { MutexLocker lock(dataMgrMutex); unmask(key); bool rv = aes->encryptUpdate(key, block); remask(key); if (!rv) { delete pbeKey; return false; } } encryptedKey += block; // And finalise encryption if (!aes->encryptFinal(block)) { delete pbeKey; return false; } encryptedKey += block; delete pbeKey; return true; } // Set the SO PIN (requires either a blank SecureDataManager or the // SO to have logged in previously) bool SecureDataManager::setSOPIN(const ByteString& soPIN) { // Check the new PIN if (soPIN.size() == 0) { DEBUG_MSG("Zero length PIN specified"); return false; } // Check if the SO needs to be logged in if ((soEncryptedKey.size() > 0) && !soLoggedIn) { DEBUG_MSG("SO must be logged in to change the SO PIN"); return false; } // If no SO PIN was set, then this is a SecureDataManager for a blank token. This // means a new key has to be generated if (soEncryptedKey.size() == 0) { ByteString key; rng->generateRandom(key, 32); remask(key); } return pbeEncryptKey(soPIN, soEncryptedKey); } // Set the user PIN (requires either the SO or the user to have logged // in previously) bool SecureDataManager::setUserPIN(const ByteString& userPIN) { // Check if the SO or the user is logged in if (!soLoggedIn && !userLoggedIn) { DEBUG_MSG("Must be logged in to change the user PIN"); return false; } // Check the new PIN if (userPIN.size() == 0) { DEBUG_MSG("Zero length PIN specified"); return false; } return pbeEncryptKey(userPIN, userEncryptedKey); } // Generic login function bool SecureDataManager::login(const ByteString& passphrase, const ByteString& encryptedKey) { // Log out first this->logout(); // First, take the salt from the encrypted key ByteString salt = encryptedKey.substr(0,8); // Then, take the IV from the encrypted key ByteString IV = encryptedKey.substr(8, aes->getBlockSize()); // Now, take the encrypted data from the encrypted key ByteString encryptedKeyData = encryptedKey.substr(8 + aes->getBlockSize()); // Derive the PBE key AESKey* pbeKey = NULL; if (!RFC4880::PBEDeriveKey(passphrase, salt, &pbeKey)) { return false; } // Decrypt the key data ByteString decryptedKeyData; ByteString finalBlock; // NOTE: The login will fail here if incorrect passphrase is supplied if (!aes->decryptInit(pbeKey, SymMode::CBC, IV) || !aes->decryptUpdate(encryptedKeyData, decryptedKeyData) || !aes->decryptFinal(finalBlock)) { delete pbeKey; return false; } delete pbeKey; decryptedKeyData += finalBlock; // Check the magic if (decryptedKeyData.substr(0, 3) != magic) { // The passphrase was incorrect DEBUG_MSG("Incorrect passphrase supplied"); return false; } // Strip off the magic ByteString key = decryptedKeyData.substr(3); // And mask the key decryptedKeyData.wipe(); MutexLocker lock(dataMgrMutex); remask(key); return true; } // Log in using the SO PIN bool SecureDataManager::loginSO(const ByteString& soPIN) { return (soLoggedIn = login(soPIN, soEncryptedKey)); } // Log in using the user PIN bool SecureDataManager::loginUser(const ByteString& userPIN) { return (userLoggedIn = login(userPIN, userEncryptedKey)); } // Log out void SecureDataManager::logout() { MutexLocker lock(dataMgrMutex); // Clear the logged in state soLoggedIn = userLoggedIn = false; // Clear the masked key maskedKey.wipe(); } // Decrypt the supplied data bool SecureDataManager::decrypt(const ByteString& encrypted, ByteString& plaintext) { // Check the object logged in state if ((!userLoggedIn && !soLoggedIn) || (maskedKey.size() != 32)) { return false; } AESKey theKey(256); ByteString unmaskedKey; { MutexLocker lock(dataMgrMutex); unmask(unmaskedKey); theKey.setKeyBits(unmaskedKey); remask(unmaskedKey); } // Take the IV from the input data ByteString IV = encrypted.substr(0, aes->getBlockSize()); if (IV.size() != aes->getBlockSize()) { ERROR_MSG("Invalid IV in encrypted data"); return false; } ByteString finalBlock; if (!aes->decryptInit(&theKey, SymMode::CBC, IV) || !aes->decryptUpdate(encrypted.substr(aes->getBlockSize()), plaintext) || !aes->decryptFinal(finalBlock)) { return false; } plaintext += finalBlock; return true; } // Encrypt the supplied data bool SecureDataManager::encrypt(const ByteString& plaintext, ByteString& encrypted) { // Check the object logged in state if ((!userLoggedIn && !soLoggedIn) || (maskedKey.size() != 32)) { return false; } AESKey theKey(256); ByteString unmaskedKey; { MutexLocker lock(dataMgrMutex); unmask(unmaskedKey); theKey.setKeyBits(unmaskedKey); remask(unmaskedKey); } // Wipe encrypted data block encrypted.wipe(); // Generate random IV ByteString IV; if (!rng->generateRandom(IV, aes->getBlockSize())) return false; ByteString finalBlock; if (!aes->encryptInit(&theKey, SymMode::CBC, IV) || !aes->encryptUpdate(plaintext, encrypted) || !aes->encryptFinal(finalBlock)) { return false; } encrypted += finalBlock; // Add IV to output data encrypted = IV + encrypted; return true; } // Returns the key blob for the SO PIN ByteString SecureDataManager::getSOPINBlob() { return soEncryptedKey; } // Returns the key blob for the user PIN ByteString SecureDataManager::getUserPINBlob() { return userEncryptedKey; } // Unmask the key void SecureDataManager::unmask(ByteString& key) { key = maskedKey; key ^= *mask; } // Remask the key void SecureDataManager::remask(ByteString& key) { // Generate a new mask rng->generateRandom(*mask, 32); key ^= *mask; maskedKey = key; } // Check if the SO is logged in bool SecureDataManager::isSOLoggedIn() { return soLoggedIn; } // Check if the user is logged in bool SecureDataManager::isUserLoggedIn() { return userLoggedIn; } softhsm-2.0.0/src/lib/data_mgr/RFC4880.cpp0000664000175000017500000000652512533040716014705 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RFC4880.cpp Implements a secure password-based key derivation scheme. It is not a generic implementation of the RFC but only generates 256-bit AES keys according to the "iterated and salted" scheme. *****************************************************************************/ #include "config.h" #include "RFC4880.h" #include "CryptoFactory.h" #include "HashAlgorithm.h" // This function derives a 256-bit AES key from the supplied password data bool RFC4880::PBEDeriveKey(const ByteString& password, ByteString& salt, AESKey** ppKey) { // Check that a proper salt value was supplied; it should be at least 8 bytes long if (salt.size() < 8) { ERROR_MSG("Insufficient salt data supplied for password-based encryption"); return false; } // Check other parameters if ((password.size() == 0) || (ppKey == NULL)) { return false; } // Determine the iteration count based on the last byte of the salt unsigned int iter = PBE_ITERATION_BASE_COUNT + salt[salt.size() - 1]; // Get a hash instance HashAlgorithm* hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA256); if (hash == NULL) { ERROR_MSG("Could not get a SHA-256 instance"); return false; } // Perform the first iteration which takes as input the salt value and // the password ByteString intermediate; if (!hash->hashInit() || !hash->hashUpdate(salt) || !hash->hashUpdate(password) || !hash->hashFinal(intermediate)) { ERROR_MSG("Hashing failed"); CryptoFactory::i()->recycleHashAlgorithm(hash); return false; } // Perform the remaining iteration while (--iter > 0) { if (!hash->hashInit() || !hash->hashUpdate(intermediate) || !hash->hashFinal(intermediate)) { ERROR_MSG("Hashing failed"); CryptoFactory::i()->recycleHashAlgorithm(hash); return false; } } // Create the AES key instance *ppKey = new AESKey(256); (*ppKey)->setKeyBits(intermediate); // Release the hash instance CryptoFactory::i()->recycleHashAlgorithm(hash); return true; } softhsm-2.0.0/src/lib/data_mgr/SecureAllocator.h0000664000175000017500000001236012533040716016475 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureAllocator.h Implements a template class for a secure C++ allocator. The allocator will zero all the memory it allocates before releasing it to ensure that the data stored in the memory is destroyed properly to minimise the risk of obtaining sensitive data from memory *****************************************************************************/ #ifndef _SOFTHSM_V2_SECUREALLOCATOR_H #define _SOFTHSM_V2_SECUREALLOCATOR_H #include #include #include #if defined(SENSITIVE_NON_PAGED) && !defined(_WIN32) #include #endif // SENSITIVE_NON_PAGED #include "config.h" #include "log.h" #include "SecureMemoryRegistry.h" template class SecureAllocator { public: // Member types typedef T value_type; typedef T* pointer; typedef T& reference; typedef const T* const_pointer; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; // Rebind to another type template struct rebind { typedef SecureAllocator other; }; // Constructor inline SecureAllocator() { } inline SecureAllocator(const SecureAllocator&) { } template SecureAllocator(const SecureAllocator&) { } // Destructor inline virtual ~SecureAllocator() { } // Return the maximum allocation size size_type max_size() const { return std::numeric_limits::max() / sizeof(T); } // Return the address of values inline pointer address(reference value) const { return &value; } inline const_pointer address(const_reference value) const { return &value; } // Allocate n elements of type T inline pointer allocate(size_type n, const void* = NULL) { #ifdef SENSITIVE_NON_PAGED // Allocate memory on a page boundary #ifndef _WIN32 pointer r = (pointer) valloc(n * sizeof(T)); #else pointer r = (pointer) VirtualAlloc(NULL, n * sizeof(T), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #endif if (r == NULL) { ERROR_MSG("Out of memory"); return NULL; } // Lock the memory so it doesn't get swapped out #ifndef _WIN32 if (mlock((const void*) r, n * sizeof(T)) != 0) #else if (VirtualLock((const void*) r, n * sizeof(T)) == 0) #endif { ERROR_MSG("Could not allocate non-paged memory for secure storage"); // Hmmm... best to not return any allocated space in this case #ifndef _WIN32 free(r); #else VirtualFree((const void*) r, MEM_RELEASE); #endif return NULL; } // Register the memory in the secure memory registry SecureMemoryRegistry::i()->add(r, n * sizeof(T)); return r; #else pointer r = (pointer)(::operator new(n * sizeof(T))); if (r == NULL) { ERROR_MSG("Out of memory"); return NULL; } // Register the memory in the secure memory registry SecureMemoryRegistry::i()->add(r, n * sizeof(T)); return r; #endif // SENSITIVE_NON_PAGED } // Deallocate n elements of type T inline void deallocate(pointer p, size_type n) { #ifdef PARANOID // First toggle all bits on memset(p, 0xFF, n * sizeof(T)); #endif // PARANOID // Toggle all bits off memset(p, 0x00, n * sizeof(T)); // Unregister the memory from the secure memory registry SecureMemoryRegistry::i()->remove(p); #ifdef SENSITIVE_NON_PAGED #ifndef _WIN32 munlock((const void*) p, n * sizeof(T)); #else VirtualUnlock((const void*) p, n * sizeof(T)); #endif #ifndef _WIN32 free(p); #else VirtualFree((const void*) r, MEM_RELEASE); #endif #else // Release the memory ::operator delete((void*) p); #endif // SENSITIVE_NON_PAGED } // Initialise allocate storage with a value void construct(pointer p, const T& value) { new((void*) p)T(value); } // Destroy elements of initialised storage void destroy(pointer p) { // Call destructor p->~T(); } // Comparison operators inline bool operator==(SecureAllocator const&) { return true; } inline bool operator!=(SecureAllocator const&) { return false; } }; #endif // !_SOFTHSM_V2_SECUREALLOCATOR_H softhsm-2.0.0/src/lib/data_mgr/Makefile.in0000664000175000017500000005651612552216620015315 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/lib/data_mgr DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_datamgr_la_LIBADD = am_libsofthsm_datamgr_la_OBJECTS = ByteString.lo RFC4880.lo salloc.lo \ SecureDataManager.lo SecureMemoryRegistry.lo libsofthsm_datamgr_la_OBJECTS = $(am_libsofthsm_datamgr_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_datamgr_la_SOURCES) DIST_SOURCES = $(libsofthsm_datamgr_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_datamgr.la libsofthsm_datamgr_la_SOURCES = ByteString.cpp \ RFC4880.cpp \ salloc.cpp \ SecureDataManager.cpp \ SecureMemoryRegistry.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/data_mgr/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/data_mgr/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_datamgr.la: $(libsofthsm_datamgr_la_OBJECTS) $(libsofthsm_datamgr_la_DEPENDENCIES) $(EXTRA_libsofthsm_datamgr_la_DEPENDENCIES) $(AM_V_CXXLD)$(CXXLINK) $(libsofthsm_datamgr_la_OBJECTS) $(libsofthsm_datamgr_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ByteString.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RFC4880.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SecureDataManager.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SecureMemoryRegistry.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/salloc.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/data_mgr/SecureMemoryRegistry.cpp0000664000175000017500000001010112533040716020100 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SecureMemoryRegistry.cpp Implements a singleton class that keeps track of all securely allocated memory. This registry can be used to wipe securely allocated memory in case of a fatal exception *****************************************************************************/ #include #include #include "log.h" #include "SecureMemoryRegistry.h" // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr SecureMemoryRegistry::instance(nullptr); #else std::auto_ptr SecureMemoryRegistry::instance(NULL); #endif // Constructor SecureMemoryRegistry::SecureMemoryRegistry() { SecMemRegistryMutex = MutexFactory::i()->getMutex(); } // Destructor SecureMemoryRegistry::~SecureMemoryRegistry() { if (!registry.empty()) { ERROR_MSG("SecureMemoryRegistry is not empty: leak!"); } MutexFactory::i()->recycleMutex(SecMemRegistryMutex); } // Return the one-and-only instance SecureMemoryRegistry* SecureMemoryRegistry::i() { if (instance.get() == NULL) { instance.reset(new SecureMemoryRegistry()); if (instance.get() == NULL) { // This is very bad! ERROR_MSG("failed to instantiate SecureMemoryRegistry"); } } return instance.get(); } // This will destroy the one-and-only instance. void SecureMemoryRegistry::reset() { instance.reset(); } // Register a block of memory void SecureMemoryRegistry::add(void* pointer, size_t blocksize) { MutexLocker lock(SecMemRegistryMutex); registry[pointer] = blocksize; //DEBUG_MSG("Registered block of %d bytes at 0x%x", blocksize, pointer); } // Unregister a block of memory size_t SecureMemoryRegistry::remove(void* pointer) { //DEBUG_MSG("Unregistered block of %d bytes at 0x%x", registry[pointer], pointer); MutexLocker lock(SecMemRegistryMutex); size_t rv = registry[pointer]; registry.erase(pointer); return rv; } // Wipe all registered blocks of memory void SecureMemoryRegistry::wipe() { MutexLocker lock(SecMemRegistryMutex); // Be very careful in this method to catch any weird exceptions that // may occur since if we're in this method it means something has already // gone pear shaped once before and we're exiting on a fatal exception try { for (std::map::iterator i = registry.begin(); i != registry.end(); i++) { try { DEBUG_MSG("Wiping block of %d bytes at 0x%x", i->second, i->first); } catch (...) { } try { #ifdef PARANOID memset(i->first, 0xFF, i->second); #endif // PARANOID memset(i->first, 0x00, i->second); } catch (...) { ERROR_MSG("Failed to wipe block of %d bytes at 0x%x", i->second, i->first); } } } catch (...) { ERROR_MSG("Failed to enumerate the secure memory registry"); } } softhsm-2.0.0/src/lib/data_mgr/ByteString.h0000664000175000017500000000744612533040716015511 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ByteString.h A string class for byte strings stored in securely allocated memory *****************************************************************************/ #ifndef _SOFTHSM_V2_BYTESTRING_H #define _SOFTHSM_V2_BYTESTRING_H #include #include #include #include #include #include "config.h" #include "SecureAllocator.h" #include "Serialisable.h" #ifndef SIZE_T_MAX #define SIZE_T_MAX ((size_t) -1) #endif // !SIZE_T_MAX class ByteString { public: // Constructors ByteString(); ByteString(const unsigned char* bytes, const size_t bytesLen); ByteString(const char* hexString); ByteString(const unsigned long longValue); ByteString(const ByteString& in); // Destructor virtual ~ByteString() { } // Append data ByteString& operator+=(const ByteString& append); ByteString& operator+=(const unsigned char byte); // Return a substring ByteString substr(const size_t start, const size_t len = SIZE_T_MAX) const; // Array operator unsigned char& operator[](size_t pos); // Return the byte string unsigned char* byte_str(); // Return the const byte string const unsigned char* const_byte_str() const; // Return a hexadecimal character representation of the string std::string hex_str() const; // Return the long value unsigned long long_val() const; // Cut of the first part of the string and convert it to a long value unsigned long firstLong(); // Split of the specified part of the string as a separate byte string ByteString split(size_t len); // Return the size in bits size_t bits() const; // Return the size in bytes size_t size() const; // Resize void resize(const size_t newSize); // Wipe void wipe(const size_t newSize = 0); // Comparison bool operator==(const ByteString& compareTo) const; bool operator!=(const ByteString& compareTo) const; // XORing ByteString& operator^=(const ByteString& rhs); // Serialisation/deserialisation virtual ByteString serialise() const; static ByteString chainDeserialise(ByteString& serialised); private: std::vector > byteString; }; // Add data ByteString operator+(const ByteString& lhs, const ByteString& rhs); ByteString operator+(const unsigned char lhs, const ByteString& rhs); ByteString operator+(const ByteString& lhs, const unsigned char rhs); // XOR data ByteString operator^(const ByteString& lhs, const ByteString& rhs); #endif // !_SOFTHSM_V2_BYTESTRING_H softhsm-2.0.0/src/lib/test/0000775000175000017500000000000012552220147012513 500000000000000softhsm-2.0.0/src/lib/test/RandomTests.cpp0000664000175000017500000000750712533040716015414 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RandomTests.cpp Contains test cases to C_SeedRandom and C_GenerateRandom *****************************************************************************/ #include #include #include #include #include "RandomTests.h" #include "testconfig.h" CPPUNIT_TEST_SUITE_REGISTRATION(RandomTests); void RandomTests::setUp() { // printf("\nRandomTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token CK_RV rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void RandomTests::tearDown() { C_Finalize(NULL_PTR); } void RandomTests::testSeedRandom() { CK_RV rv; CK_SESSION_HANDLE hSession; CK_BYTE seed[] = {"Some random data"}; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_SeedRandom(CK_INVALID_HANDLE, seed, sizeof(seed)); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SeedRandom(hSession, NULL_PTR, sizeof(seed)); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_SeedRandom(hSession, seed, sizeof(seed)); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SeedRandom(hSession, seed, sizeof(seed)); CPPUNIT_ASSERT(rv == CKR_OK); } void RandomTests::testGenerateRandom() { CK_RV rv; CK_SESSION_HANDLE hSession; CK_BYTE randomData[40]; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_GenerateRandom(CK_INVALID_HANDLE, randomData, 40); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GenerateRandom(hSession, NULL_PTR, 40); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GenerateRandom(hSession, randomData, 40); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GenerateRandom(hSession, randomData, 40); CPPUNIT_ASSERT(rv == CKR_OK); } softhsm-2.0.0/src/lib/test/AsymEncryptDecryptTests.cpp0000664000175000017500000002164512533040716020004 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymEncryptDecryptTests.cpp Contains test cases for C_EncryptInit, C_Encrypt, C_DecryptInit, C_Decrypt using asymmetrical algorithms (i.e., RSA) *****************************************************************************/ #include #include #include #include #include "AsymEncryptDecryptTests.h" #include "testconfig.h" // CKA_TOKEN const CK_BBOOL ON_TOKEN = CK_TRUE; const CK_BBOOL IN_SESSION = CK_FALSE; // CKA_PRIVATE const CK_BBOOL IS_PRIVATE = CK_TRUE; const CK_BBOOL IS_PUBLIC = CK_FALSE; CPPUNIT_TEST_SUITE_REGISTRATION(AsymEncryptDecryptTests); void AsymEncryptDecryptTests::setUp() { // printf("\nObjectTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, sopin,sopinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login SO rv = C_Login(hSession,CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize the user pin rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void AsymEncryptDecryptTests::tearDown() { C_Finalize(NULL_PTR); } CK_RV AsymEncryptDecryptTests::generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk) { CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BYTE pubExp[] = {0x01, 0x00, 0x01}; CK_BYTE subject[] = { 0x12, 0x34 }; // dummy CK_BYTE id[] = { 123 } ; // dummy CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE pukAttribs[] = { { CKA_TOKEN, &bTokenPuk, sizeof(bTokenPuk) }, { CKA_PRIVATE, &bPrivatePuk, sizeof(bPrivatePuk) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_VERIFY, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bFalse, sizeof(bFalse) }, { CKA_MODULUS_BITS, &bits, sizeof(bits) }, { CKA_PUBLIC_EXPONENT, &pubExp[0], sizeof(pubExp) } }; CK_ATTRIBUTE prkAttribs[] = { { CKA_TOKEN, &bTokenPrk, sizeof(bTokenPrk) }, { CKA_PRIVATE, &bPrivatePrk, sizeof(bPrivatePrk) }, { CKA_SUBJECT, &subject[0], sizeof(subject) }, { CKA_ID, &id[0], sizeof(id) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_SIGN, &bTrue, sizeof(bTrue) }, { CKA_UNWRAP, &bFalse, sizeof(bFalse) } }; hPuk = CK_INVALID_HANDLE; hPrk = CK_INVALID_HANDLE; return C_GenerateKeyPair(hSession, &mechanism, pukAttribs, sizeof(pukAttribs)/sizeof(CK_ATTRIBUTE), prkAttribs, sizeof(prkAttribs)/sizeof(CK_ATTRIBUTE), &hPuk, &hPrk); } void AsymEncryptDecryptTests::rsaEncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey) { CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_RSA_PKCS_OAEP_PARAMS oaepParams = { CKM_SHA_1, CKG_MGF1_SHA1, 1, NULL_PTR, 0 }; CK_BYTE plainText[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,0x0C, 0x0D, 0x0F }; CK_BYTE cipherText[256]; CK_ULONG ulCipherTextLen; CK_BYTE recoveredText[256]; CK_ULONG ulRecoveredTextLen; CK_RV rv; if (mechanismType == CKM_RSA_PKCS_OAEP) { mechanism.pParameter = &oaepParams; mechanism.ulParameterLen = sizeof(oaepParams); } rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextLen = sizeof(cipherText); rv =C_Encrypt(hSession,plainText,sizeof(plainText),cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_DecryptInit(hSession,&mechanism,hPrivateKey); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextLen = sizeof(recoveredText); rv = C_Decrypt(hSession,cipherText,ulCipherTextLen,recoveredText,&ulRecoveredTextLen); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(memcmp(plainText, &recoveredText[ulRecoveredTextLen-sizeof(plainText)], sizeof(plainText)) == 0); } // Check that RSA OAEP mechanism properly validates all input parameters void AsymEncryptDecryptTests::rsaOAEPParams(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey) { // This is only supported combination of parameters CK_RSA_PKCS_OAEP_PARAMS oaepParams = { CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED, NULL_PTR, 0 }; CK_MECHANISM mechanism = { CKM_RSA_PKCS_OAEP, NULL, 0 }; CK_RV rv; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); mechanism.pParameter = &oaepParams; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); mechanism.ulParameterLen = sizeof(oaepParams); oaepParams.hashAlg = CKM_AES_CBC; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); oaepParams.hashAlg = CKM_SHA_1; oaepParams.mgf = CKG_MGF1_SHA256; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); oaepParams.mgf = CKG_MGF1_SHA1; oaepParams.source = CKZ_DATA_SPECIFIED - 1; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); oaepParams.source = CKZ_DATA_SPECIFIED; oaepParams.pSourceData = &oaepParams; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); oaepParams.ulSourceDataLen = sizeof(oaepParams); rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); oaepParams.pSourceData = NULL; rv = C_EncryptInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_ARGUMENTS_BAD); } void AsymEncryptDecryptTests::testRsaEncryptDecrypt() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrivateKey = CK_INVALID_HANDLE; // Generate all combinations of session/token public/private key pairs. rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPublicKey,hPrivateKey); CPPUNIT_ASSERT(rv == CKR_OK); rsaOAEPParams(hSessionRO,hPublicKey); rsaEncryptDecrypt(CKM_RSA_PKCS,hSessionRO,hPublicKey,hPrivateKey); rsaEncryptDecrypt(CKM_RSA_X_509,hSessionRO,hPublicKey,hPrivateKey); rsaEncryptDecrypt(CKM_RSA_PKCS_OAEP,hSessionRO,hPublicKey,hPrivateKey); } softhsm-2.0.0/src/lib/test/TokenTests.cpp0000664000175000017500000000657712533040716015262 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** TokenTests.cpp Contains test cases to C_InitToken *****************************************************************************/ #include #include #include #include #include "TokenTests.h" #include "testconfig.h" CPPUNIT_TEST_SUITE_REGISTRATION(TokenTests); void TokenTests::setUp() { // printf("\nTokenTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif } void TokenTests::tearDown() { // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); } void TokenTests::testInitToken() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR label[32]; CK_SESSION_HANDLE hSession; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, NULL_PTR, pinLength, label); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_InitToken(SLOT_INVALID, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); // Initialize rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize with wrong password rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength - 1, label); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_SESSION_EXISTS); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Re-initialize rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } softhsm-2.0.0/src/lib/test/softhsm2.conf.in0000664000175000017500000000016612533040716015460 00000000000000# SoftHSM v2 configuration file directories.tokendir = @builddir@/tokens objectstore.backend = file log.level = INFO softhsm-2.0.0/src/lib/test/SignVerifyTests.h0000664000175000017500000000547512533040716015730 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SignVerifyTests.h Contains test cases to C_SignInit,C_Sign,C_SignUpdate,C_SignFinal, C_VerifyInit, C_Verify, C_VerifyUpdate, C_VerifyFinal *****************************************************************************/ #ifndef _SOFTHSM_V2_SIGNVERIFYTESTS_H #define _SOFTHSM_V2_SIGNVERIFYTESTS_H #include #include "cryptoki.h" class SignVerifyTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SignVerifyTests); CPPUNIT_TEST(testRsaSignVerify); CPPUNIT_TEST(testHmacSignVerify); CPPUNIT_TEST_SUITE_END(); public: void testRsaSignVerify(); void testHmacSignVerify(); void setUp(); void tearDown(); protected: CK_RV generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk); void rsaPkcsSignVerify(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey); void digestRsaPkcsSignVerify(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey, CK_VOID_PTR param = NULL_PTR, CK_ULONG paramLen = 0); CK_RV generateKey(CK_SESSION_HANDLE hSession, CK_KEY_TYPE keyType, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); void hmacSignVerify(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey); }; #endif // !_SOFTHSM_V2_SIGNVERIFYTESTS_H softhsm-2.0.0/src/lib/test/SessionTests.cpp0000664000175000017500000001431612533040716015613 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionTests.cpp Contains test cases to C_OpenSession, C_CloseSession, C_CloseAllSessions, and C_GetSessionInfo *****************************************************************************/ #include #include #include #include #include "SessionTests.h" #include "testconfig.h" CPPUNIT_TEST_SUITE_REGISTRATION(SessionTests); void SessionTests::setUp() { // printf("\nSessionTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token CK_RV rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void SessionTests::tearDown() { C_Finalize(NULL_PTR); } void SessionTests::testOpenSession() { CK_RV rv; CK_SESSION_HANDLE hSession; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_OpenSession(SLOT_INVALID, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); rv = C_OpenSession(SLOT_NO_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_TOKEN_NOT_RECOGNIZED); rv = C_OpenSession(SLOT_INIT_TOKEN, 0, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_SESSION_PARALLEL_NOT_SUPPORTED); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); } void SessionTests::testCloseSession() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_CloseSession(CK_INVALID_HANDLE); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_CloseSession(hSession + 1); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); } void SessionTests::testCloseAllSessions() { CK_RV rv; CK_SESSION_HANDLE hSession; CK_SESSION_INFO info; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_CloseAllSessions(SLOT_INIT_TOKEN); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_CloseAllSessions(SLOT_INVALID); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); rv = C_CloseAllSessions(SLOT_NO_INIT_TOKEN); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetSessionInfo(hSession, &info); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_CloseAllSessions(SLOT_INIT_TOKEN); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); } void SessionTests::testGetSessionInfo() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; CK_SESSION_INFO info; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_GetSessionInfo(hSession, &info); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetSessionInfo(CK_INVALID_HANDLE, &info); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_GetSessionInfo(hSession + 1, &info); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_GetSessionInfo(hSession, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetSessionInfo(hSession, &info); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(info.state == CKS_RO_PUBLIC_SESSION); CPPUNIT_ASSERT(info.flags == CKF_SERIAL_SESSION); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetSessionInfo(hSession, &info); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); } softhsm-2.0.0/src/lib/test/Makefile.am0000664000175000017500000000153412533040716014473 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../common \ `cppunit-config --cflags` check_PROGRAMS = p11test AUTOMAKE_OPTIONS = subdir-objects p11test_SOURCES = p11test.cpp \ SymmetricAlgorithmTests.cpp \ DigestTests.cpp \ InitTests.cpp \ InfoTests.cpp \ RandomTests.cpp \ SessionTests.cpp \ TokenTests.cpp \ UserTests.cpp \ ObjectTests.cpp \ DeriveTests.cpp \ SignVerifyTests.cpp \ AsymEncryptDecryptTests.cpp \ AsymWrapUnwrapTests.cpp \ ../common/osmutex.cpp p11test_LDADD = ../libsofthsm2.la p11test_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread -static TESTS = p11test EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/softhsm2.conf.win32 \ $(srcdir)/tokens/dummy.in softhsm-2.0.0/src/lib/test/UserTests.cpp0000664000175000017500000002362312533040716015107 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** UserTests.cpp Contains test cases to C_InitPIN, C_SetPIN, C_Login, and C_Logout *****************************************************************************/ #include #include #include #include #include "UserTests.h" #include "testconfig.h" CPPUNIT_TEST_SUITE_REGISTRATION(UserTests); void UserTests::setUp() { // printf("\nUserTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token CK_RV rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void UserTests::tearDown() { // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); } void UserTests::testInitPIN() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); rv = C_Login(hSession, CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitPIN(CK_INVALID_HANDLE, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_InitPIN(hSession, pin, 0); CPPUNIT_ASSERT(rv == CKR_PIN_LEN_RANGE); rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void UserTests::testLogin() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession[2]; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Set up user PIN rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession[0]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_USER_PIN_NOT_INITIALIZED); rv = C_Login(hSession[0], CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitPIN(hSession[0], pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); rv = C_Login(hSession[0], CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession[0]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(CK_INVALID_HANDLE, CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_Login(hSession[0], CKU_SO, NULL_PTR, sopinLength); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_Login(hSession[0], CKU_SO, sopin, 0); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession[1]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY_EXISTS); rv = C_CloseSession(hSession[1]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_USER_ANOTHER_ALREADY_LOGGED_IN); rv = C_Logout(hSession[0]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_USER_ALREADY_LOGGED_IN); rv = C_Login(hSession[0], CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_USER_ANOTHER_ALREADY_LOGGED_IN); rv = C_Logout(hSession[0]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_USER, pin, pinLength - 1); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_Login(hSession[0], CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession[0], CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_USER_ALREADY_LOGGED_IN); } void UserTests::testLogout() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_Logout(hSession); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession, CKU_SO, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Logout(CK_INVALID_HANDLE); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_Logout(hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Logout(hSession); CPPUNIT_ASSERT(rv == CKR_OK); } void UserTests::testSetPIN() { CK_RV rv; CK_UTF8CHAR pin1[] = SLOT_0_USER1_PIN; CK_ULONG pin1Length = sizeof(pin1) - 1; CK_UTF8CHAR pin2[] = SLOT_0_USER2_PIN; CK_ULONG pin2Length = sizeof(pin2) - 1; CK_UTF8CHAR so1pin[] = SLOT_0_SO1_PIN; CK_ULONG so1pinLength = sizeof(so1pin) - 1; CK_UTF8CHAR so2pin[] = SLOT_0_SO2_PIN; CK_ULONG so2pinLength = sizeof(so2pin) - 1; CK_SESSION_HANDLE hSession; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Set up user PIN rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession, CKU_SO, so1pin, so1pinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitPIN(hSession, pin1, pin1Length); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); rv = C_SetPIN(hSession, pin1, pin1Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetPIN(CK_INVALID_HANDLE, pin1, pin1Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_SetPIN(hSession, pin1, pin1Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetPIN(hSession, NULL_PTR, pin1Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_SetPIN(hSession, pin1, pin1Length, NULL_PTR, pin2Length); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_SetPIN(hSession, pin1, pin1Length, pin2, 0); CPPUNIT_ASSERT(rv == CKR_PIN_LEN_RANGE); rv = C_SetPIN(hSession, pin2, pin2Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_SetPIN(hSession, pin1, pin1Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession, CKU_USER, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetPIN(hSession, pin1, pin1Length, pin2, pin2Length); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_SetPIN(hSession, pin2, pin2Length, pin1, pin1Length); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession, CKU_SO, so1pin, so1pinLength); CPPUNIT_ASSERT(rv == CKR_USER_ANOTHER_ALREADY_LOGGED_IN); rv = C_Logout(hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Login(hSession, CKU_SO, so1pin, so1pinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetPIN(hSession, so2pin, so2pinLength, so2pin, so2pinLength); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_SetPIN(hSession, so1pin, so1pinLength, so2pin, so2pinLength); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetPIN(hSession, so1pin, so1pinLength, so1pin, so1pinLength); CPPUNIT_ASSERT(rv == CKR_PIN_INCORRECT); rv = C_SetPIN(hSession, so2pin, so2pinLength, so1pin, so1pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } softhsm-2.0.0/src/lib/test/DeriveTests.h0000664000175000017500000000567012533040716015056 00000000000000/* * Copyright (c) 2014 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DeriveTests.h Contains test cases to C_DeriveKey *****************************************************************************/ #ifndef _SOFTHSM_V2_DERIVETESTS_H #define _SOFTHSM_V2_DERIVETESTS_H #include #include "cryptoki.h" class DeriveTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DeriveTests); CPPUNIT_TEST(testDhDerive); CPPUNIT_TEST(testSymDerive); CPPUNIT_TEST_SUITE_END(); public: void testDhDerive(); void testSymDerive(); void setUp(); void tearDown(); protected: CK_RV generateDhKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk); CK_RV generateAesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); #ifndef WITH_FIPS CK_RV generateDesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); #endif CK_RV generateDes2Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); CK_RV generateDes3Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); void dhDerive(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey, CK_OBJECT_HANDLE &hKey); bool compareSecret(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey1, CK_OBJECT_HANDLE hKey2); void symDerive(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey, CK_OBJECT_HANDLE &hDerive, CK_MECHANISM_TYPE mechType, CK_KEY_TYPE keyType); }; #endif // !_SOFTHSM_V2_DERIVETESTS_H softhsm-2.0.0/src/lib/test/AsymWrapUnwrapTests.cpp0000664000175000017500000002320412533040716017124 00000000000000/* * Copyright (c) 2014 Red Hat * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymWrapUnwrapTests.cpp Contains test cases for C_WrapKey and C_UnwrapKey using asymmetrical algorithms (RSA) *****************************************************************************/ #include #include #include #include #include "AsymWrapUnwrapTests.h" #include "testconfig.h" // CKA_TOKEN const CK_BBOOL ON_TOKEN = CK_TRUE; const CK_BBOOL IN_SESSION = CK_FALSE; // CKA_PRIVATE const CK_BBOOL IS_PRIVATE = CK_TRUE; const CK_BBOOL IS_PUBLIC = CK_FALSE; CPPUNIT_TEST_SUITE_REGISTRATION(AsymWrapUnwrapTests); void AsymWrapUnwrapTests::setUp() { // printf("\nObjectTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, sopin,sopinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login SO rv = C_Login(hSession,CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize the user pin rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void AsymWrapUnwrapTests::tearDown() { C_Finalize(NULL_PTR); } // Generate throw-away (session) symmetric key CK_RV AsymWrapUnwrapTests::generateAesKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_AES_KEY_GEN, NULL_PTR, 0 }; CK_ULONG bytes = 16; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bFalse, sizeof(bTrue) }, { CKA_PRIVATE, &bTrue, sizeof(bTrue) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_VALUE_LEN, &bytes, sizeof(bytes) }, }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } CK_RV AsymWrapUnwrapTests::generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk) { CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BYTE pubExp[] = {0x01, 0x00, 0x01}; CK_BYTE subject[] = { 0x12, 0x34 }; // dummy CK_BYTE id[] = { 123 } ; // dummy CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE pukAttribs[] = { { CKA_TOKEN, &bTokenPuk, sizeof(bTokenPuk) }, { CKA_PRIVATE, &bPrivatePuk, sizeof(bPrivatePuk) }, { CKA_ENCRYPT, &bFalse, sizeof(bFalse) }, { CKA_VERIFY, &bFalse, sizeof(bFalse) }, { CKA_WRAP, &bTrue, sizeof(bTrue) }, { CKA_MODULUS_BITS, &bits, sizeof(bits) }, { CKA_PUBLIC_EXPONENT, &pubExp[0], sizeof(pubExp) } }; CK_ATTRIBUTE prkAttribs[] = { { CKA_TOKEN, &bTokenPrk, sizeof(bTokenPrk) }, { CKA_PRIVATE, &bPrivatePrk, sizeof(bPrivatePrk) }, { CKA_SUBJECT, &subject[0], sizeof(subject) }, { CKA_ID, &id[0], sizeof(id) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bFalse, sizeof(bFalse) }, { CKA_SIGN, &bFalse, sizeof(bFalse) }, { CKA_UNWRAP, &bTrue, sizeof(bTrue) }, }; hPuk = CK_INVALID_HANDLE; hPrk = CK_INVALID_HANDLE; return C_GenerateKeyPair(hSession, &mechanism, pukAttribs, sizeof(pukAttribs)/sizeof(CK_ATTRIBUTE), prkAttribs, sizeof(prkAttribs)/sizeof(CK_ATTRIBUTE), &hPuk, &hPrk); } void AsymWrapUnwrapTests::rsaWrapUnwrap(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey) { CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_RSA_PKCS_OAEP_PARAMS oaepParams = { CKM_SHA_1, CKG_MGF1_SHA1, CKZ_DATA_SPECIFIED, NULL_PTR, 0 }; CK_BYTE cipherText[2048]; CK_ULONG ulCipherTextLen; CK_BYTE symValue[64]; CK_ULONG ulSymValueLen = sizeof(symValue); CK_BYTE unwrappedValue[64]; CK_ULONG ulUnwrappedValueLen = sizeof(unwrappedValue); CK_OBJECT_HANDLE symKey = CK_INVALID_HANDLE; CK_OBJECT_HANDLE unwrappedKey = CK_INVALID_HANDLE; CK_RV rv; CK_ULONG wrappedLenEstimation; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_AES; CK_ATTRIBUTE unwrapTemplate[] = { { CKA_CLASS, &keyClass, sizeof(keyClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_TOKEN, &bFalse, sizeof(bFalse) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) } }; CK_ATTRIBUTE valueTemplate[] = { { CKA_VALUE, &symValue, ulSymValueLen } }; CK_MECHANISM_INFO mechInfo; if (mechanismType == CKM_RSA_PKCS_OAEP) { mechanism.pParameter = &oaepParams; mechanism.ulParameterLen = sizeof(oaepParams); } // Generate temporary symmetric key and remember it's value rv = generateAesKey(hSession, symKey); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_GetAttributeValue(hSession, symKey, valueTemplate, sizeof(valueTemplate)/sizeof(CK_ATTRIBUTE)); CPPUNIT_ASSERT(rv==CKR_OK); ulSymValueLen = valueTemplate[0].ulValueLen; // CKM_RSA_PKCS Wrap/Unwrap support rv = C_GetMechanismInfo(SLOT_INIT_TOKEN, CKM_RSA_PKCS, &mechInfo); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(mechInfo.flags&CKF_WRAP); CPPUNIT_ASSERT(mechInfo.flags&CKF_UNWRAP); // Estimate wrapped length rv = C_WrapKey(hSession, &mechanism, hPublicKey, symKey, NULL_PTR, &wrappedLenEstimation); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(wrappedLenEstimation>0); // This should always fail because wrapped data have to be longer than 0 bytes ulCipherTextLen = 0; rv = C_WrapKey(hSession, &mechanism, hPublicKey, symKey, cipherText, &ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_BUFFER_TOO_SMALL); // Do real wrapping ulCipherTextLen = sizeof(cipherText); rv = C_WrapKey(hSession, &mechanism, hPublicKey, symKey, cipherText, &ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_OK); // Check length 'estimation' CPPUNIT_ASSERT(wrappedLenEstimation>=ulCipherTextLen); rv = C_UnwrapKey(hSession, &mechanism, hPrivateKey, cipherText, ulCipherTextLen, unwrapTemplate, sizeof(unwrapTemplate)/sizeof(CK_ATTRIBUTE), &unwrappedKey); CPPUNIT_ASSERT(rv==CKR_OK); valueTemplate[0].pValue = &unwrappedValue; rv = C_GetAttributeValue(hSession, unwrappedKey, valueTemplate, sizeof(valueTemplate)/sizeof(CK_ATTRIBUTE)); CPPUNIT_ASSERT(rv==CKR_OK); ulUnwrappedValueLen = valueTemplate[0].ulValueLen; CPPUNIT_ASSERT(ulSymValueLen == ulUnwrappedValueLen); CPPUNIT_ASSERT(memcmp(symValue, unwrappedValue, ulSymValueLen) == 0); } void AsymWrapUnwrapTests::testRsaWrapUnwrap() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); CK_OBJECT_HANDLE hPublicKey = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrivateKey = CK_INVALID_HANDLE; // Generate all combinations of session/token public/private key pairs. rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPublicKey,hPrivateKey); CPPUNIT_ASSERT(rv == CKR_OK); rsaWrapUnwrap(CKM_RSA_PKCS,hSessionRO,hPublicKey,hPrivateKey); rsaWrapUnwrap(CKM_RSA_PKCS_OAEP,hSessionRO,hPublicKey,hPrivateKey); } softhsm-2.0.0/src/lib/test/SignVerifyTests.cpp0000664000175000017500000005122012533040716016250 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SignVerifyTests.cpp Contains test cases for: C_SignInit C_Sign C_SignUpdate C_SignFinal C_VerifyInit C_Verify C_VerifyUpdate C_VerifyFinal *****************************************************************************/ #include #include #include #include #include "SignVerifyTests.h" #include "testconfig.h" // CKA_TOKEN const CK_BBOOL ON_TOKEN = CK_TRUE; const CK_BBOOL IN_SESSION = CK_FALSE; // CKA_PRIVATE const CK_BBOOL IS_PRIVATE = CK_TRUE; const CK_BBOOL IS_PUBLIC = CK_FALSE; CPPUNIT_TEST_SUITE_REGISTRATION(SignVerifyTests); void SignVerifyTests::setUp() { // printf("\nSignVerifyTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, sopin,sopinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login SO rv = C_Login(hSession,CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize the user pin rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void SignVerifyTests::tearDown() { C_Finalize(NULL_PTR); } CK_RV SignVerifyTests::generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk) { CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BYTE pubExp[] = {0x01, 0x00, 0x01}; CK_BYTE subject[] = { 0x12, 0x34 }; // dummy CK_BYTE id[] = { 123 } ; // dummy CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE pukAttribs[] = { { CKA_TOKEN, &bTokenPuk, sizeof(bTokenPuk) }, { CKA_PRIVATE, &bPrivatePuk, sizeof(bPrivatePuk) }, { CKA_ENCRYPT, &bFalse, sizeof(bFalse) }, { CKA_VERIFY, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bFalse, sizeof(bFalse) }, { CKA_MODULUS_BITS, &bits, sizeof(bits) }, { CKA_PUBLIC_EXPONENT, &pubExp[0], sizeof(pubExp) } }; CK_ATTRIBUTE prkAttribs[] = { { CKA_TOKEN, &bTokenPrk, sizeof(bTokenPrk) }, { CKA_PRIVATE, &bPrivatePrk, sizeof(bPrivatePrk) }, { CKA_SUBJECT, &subject[0], sizeof(subject) }, { CKA_ID, &id[0], sizeof(id) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bFalse, sizeof(bFalse) }, { CKA_SIGN, &bTrue, sizeof(bTrue) }, { CKA_UNWRAP, &bFalse, sizeof(bFalse) } }; hPuk = CK_INVALID_HANDLE; hPrk = CK_INVALID_HANDLE; return C_GenerateKeyPair(hSession, &mechanism, pukAttribs, sizeof(pukAttribs)/sizeof(CK_ATTRIBUTE), prkAttribs, sizeof(prkAttribs)/sizeof(CK_ATTRIBUTE), &hPuk, &hPrk); } void SignVerifyTests::rsaPkcsSignVerify(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey) { CK_RV rv; CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_BYTE data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,0x0C, 0x0D, 0x0F }; CK_BYTE signature[256]; CK_ULONG ulSignatureLen = 0; rv = C_SignInit(hSession,&mechanism,hPrivateKey); CPPUNIT_ASSERT(rv==CKR_OK); ulSignatureLen = sizeof(signature); rv = C_Sign(hSession,data,sizeof(data),signature,&ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_Verify(hSession,data,sizeof(data),signature,ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_OK); } void SignVerifyTests::digestRsaPkcsSignVerify(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey, CK_VOID_PTR param /* = NULL_PTR */, CK_ULONG paramLen /* = 0 */) { CK_RV rv; CK_MECHANISM mechanism = { mechanismType, param, paramLen }; CK_BYTE data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,0x0C, 0x0D, 0x0F }; CK_BYTE signature[256]; CK_ULONG ulSignatureLen = 0; rv = C_SignInit(hSession,&mechanism,hPrivateKey); CPPUNIT_ASSERT(rv==CKR_OK); rv =C_SignUpdate(hSession,data,sizeof(data)); CPPUNIT_ASSERT(rv==CKR_OK); ulSignatureLen = sizeof(signature); rv =C_SignFinal(hSession,signature,&ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyUpdate(hSession,data,sizeof(data)); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyFinal(hSession,signature,ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_OK); // verify again, but now change the input that is being signed. rv = C_VerifyInit(hSession,&mechanism,hPublicKey); CPPUNIT_ASSERT(rv==CKR_OK); data[0] = 0xff; rv = C_VerifyUpdate(hSession,data,sizeof(data)); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyFinal(hSession,signature,ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_SIGNATURE_INVALID); } void SignVerifyTests::testRsaSignVerify() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; CK_RSA_PKCS_PSS_PARAMS params[] = { { CKM_SHA_1, CKG_MGF1_SHA1, 0 }, { CKM_SHA224, CKG_MGF1_SHA224, 28 }, { CKM_SHA256, CKG_MGF1_SHA256, 32 }, { CKM_SHA384, CKG_MGF1_SHA384, 0 }, { CKM_SHA512, CKG_MGF1_SHA512, 0 } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); CK_OBJECT_HANDLE hPuk = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrk = CK_INVALID_HANDLE; // Public Session keys rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rsaPkcsSignVerify(CKM_RSA_PKCS, hSessionRO, hPuk,hPrk); rsaPkcsSignVerify(CKM_RSA_X_509, hSessionRO, hPuk,hPrk); #ifndef WITH_FIPS digestRsaPkcsSignVerify(CKM_MD5_RSA_PKCS, hSessionRO, hPuk,hPrk); #endif digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS, hSessionRO, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS, hSessionRO, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS, hSessionRO, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS, hSessionRO, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS, hSessionRO, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS_PSS, hSessionRO, hPuk,hPrk, ¶ms[0], sizeof(params[0])); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS_PSS, hSessionRO, hPuk,hPrk, ¶ms[1], sizeof(params[1])); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS_PSS, hSessionRO, hPuk,hPrk, ¶ms[2], sizeof(params[2])); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS_PSS, hSessionRO, hPuk,hPrk, ¶ms[3], sizeof(params[3])); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS_PSS, hSessionRO, hPuk,hPrk, ¶ms[4], sizeof(params[4])); // Private Session Keys rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,IN_SESSION,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rsaPkcsSignVerify(CKM_RSA_PKCS, hSessionRW, hPuk,hPrk); rsaPkcsSignVerify(CKM_RSA_X_509, hSessionRW, hPuk,hPrk); #ifndef WITH_FIPS digestRsaPkcsSignVerify(CKM_MD5_RSA_PKCS, hSessionRW, hPuk,hPrk); #endif digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[0], sizeof(params[0])); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[1], sizeof(params[1])); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[2], sizeof(params[2])); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[3], sizeof(params[3])); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[4], sizeof(params[4])); // Public Token Keys rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,ON_TOKEN,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rsaPkcsSignVerify(CKM_RSA_PKCS, hSessionRW, hPuk,hPrk); rsaPkcsSignVerify(CKM_RSA_X_509, hSessionRW, hPuk,hPrk); #ifndef WITH_FIPS digestRsaPkcsSignVerify(CKM_MD5_RSA_PKCS, hSessionRW, hPuk,hPrk); #endif digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[0], sizeof(params[0])); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[1], sizeof(params[1])); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[2], sizeof(params[2])); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[3], sizeof(params[3])); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[4], sizeof(params[4])); // Private Token Keys rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,ON_TOKEN,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rsaPkcsSignVerify(CKM_RSA_PKCS, hSessionRW, hPuk,hPrk); rsaPkcsSignVerify(CKM_RSA_X_509, hSessionRW, hPuk,hPrk); #ifndef WITH_FIPS digestRsaPkcsSignVerify(CKM_MD5_RSA_PKCS, hSessionRW, hPuk,hPrk); #endif digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS, hSessionRW, hPuk,hPrk); digestRsaPkcsSignVerify(CKM_SHA1_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[0], sizeof(params[0])); digestRsaPkcsSignVerify(CKM_SHA224_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[1], sizeof(params[1])); digestRsaPkcsSignVerify(CKM_SHA256_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[2], sizeof(params[2])); digestRsaPkcsSignVerify(CKM_SHA384_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[3], sizeof(params[3])); digestRsaPkcsSignVerify(CKM_SHA512_RSA_PKCS_PSS, hSessionRW, hPuk,hPrk, ¶ms[4], sizeof(params[4])); } CK_RV SignVerifyTests::generateKey(CK_SESSION_HANDLE hSession, CK_KEY_TYPE keyType, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { #ifndef WITH_BOTAN #define GEN_KEY_LEN 75 #else #define GEN_KEY_LEN 55 #endif CK_RV rv; CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY; CK_BYTE val[GEN_KEY_LEN]; //CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_BYTE oid[] = { 0x06, 0x07, 0x2A, 0x85, 0x03, 0x02, 0x02, 0x1F, 0x00 }; CK_ATTRIBUTE kAttribs[] = { { CKA_CLASS, &keyClass, sizeof(keyClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_VERIFY, &bTrue, sizeof(bTrue) }, { CKA_SIGN, &bTrue, sizeof(bTrue) }, { CKA_VALUE, val, sizeof(val) }, { CKA_GOST28147_PARAMS, oid, sizeof(oid) } }; rv = C_GenerateRandom(hSession, val, GEN_KEY_LEN); CPPUNIT_ASSERT(rv == CKR_OK); hKey = CK_INVALID_HANDLE; if (keyType == CKK_GOST28147) { return C_CreateObject(hSession, kAttribs, 9, &hKey); } else { return C_CreateObject(hSession, kAttribs, 8, &hKey); } } void SignVerifyTests::hmacSignVerify(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CK_RV rv; CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_BYTE data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,0x0C, 0x0D, 0x0F }; CK_BYTE signature[256]; CK_ULONG ulSignatureLen = 0; rv = C_SignInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); rv =C_SignUpdate(hSession,data,sizeof(data)); CPPUNIT_ASSERT(rv==CKR_OK); ulSignatureLen = sizeof(signature); rv =C_SignFinal(hSession,signature,&ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyUpdate(hSession,data,sizeof(data)); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyFinal(hSession,signature,ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_OK); // verify again, but now change the input that is being signed. rv = C_VerifyInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); data[0] = 0xff; rv = C_VerifyUpdate(hSession,data,sizeof(data)); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_VerifyFinal(hSession,signature,ulSignatureLen); CPPUNIT_ASSERT(rv==CKR_SIGNATURE_INVALID); } void SignVerifyTests::testHmacSignVerify() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // Public Session keys CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; #ifndef WITH_FIPS rv = generateKey(hSessionRW,CKK_MD5_HMAC,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_MD5_HMAC, hSessionRO, hKey); #endif rv = generateKey(hSessionRW,CKK_SHA_1_HMAC,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA_1_HMAC, hSessionRO, hKey); rv = generateKey(hSessionRW,CKK_SHA224_HMAC,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA224_HMAC, hSessionRO, hKey); rv = generateKey(hSessionRW,CKK_SHA256_HMAC,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA256_HMAC, hSessionRO, hKey); rv = generateKey(hSessionRW,CKK_SHA384_HMAC,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA384_HMAC, hSessionRO, hKey); rv = generateKey(hSessionRW,CKK_SHA512_HMAC,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA512_HMAC, hSessionRO, hKey); #ifdef WITH_GOST rv = generateKey(hSessionRW,CKK_GOST28147,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_GOSTR3411_HMAC, hSessionRO, hKey); #endif // Private Session Keys #ifndef WITH_FIPS rv = generateKey(hSessionRW,CKK_MD5_HMAC,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_MD5_HMAC, hSessionRW, hKey); #endif rv = generateKey(hSessionRW,CKK_SHA_1_HMAC,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA_1_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA224_HMAC,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA256_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA256_HMAC,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA256_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA384_HMAC,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA384_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA512_HMAC,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA512_HMAC, hSessionRW, hKey); #ifdef WITH_GOST rv = generateKey(hSessionRW,CKK_GOST28147,IN_SESSION,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_GOSTR3411_HMAC, hSessionRW, hKey); #endif // Public Token Keys #ifndef WITH_FIPS rv = generateKey(hSessionRW,CKK_MD5_HMAC,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_MD5_HMAC, hSessionRW, hKey); #endif rv = generateKey(hSessionRW,CKK_SHA_1_HMAC,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA_1_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA224_HMAC,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA224_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA256_HMAC,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA256_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA384_HMAC,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA384_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA512_HMAC,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA512_HMAC, hSessionRW, hKey); #ifdef WITH_GOST rv = generateKey(hSessionRW,CKK_GOST28147,ON_TOKEN,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_GOSTR3411_HMAC, hSessionRW, hKey); #endif // Private Token Keys #ifndef WITH_FIPS rv = generateKey(hSessionRW,CKK_MD5_HMAC,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_MD5_HMAC, hSessionRW, hKey); #endif rv = generateKey(hSessionRW,CKK_SHA_1_HMAC,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA_1_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA224_HMAC,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA224_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA256_HMAC,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA256_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA384_HMAC,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA384_HMAC, hSessionRW, hKey); rv = generateKey(hSessionRW,CKK_SHA512_HMAC,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_SHA512_HMAC, hSessionRW, hKey); #ifdef WITH_GOST rv = generateKey(hSessionRW,CKK_GOST28147,ON_TOKEN,IS_PRIVATE,hKey); CPPUNIT_ASSERT(rv == CKR_OK); hmacSignVerify(CKM_GOSTR3411_HMAC, hSessionRW, hKey); #endif } softhsm-2.0.0/src/lib/test/InitTests.cpp0000664000175000017500000001514112533040716015070 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** InitTests.cpp Contains test cases to C_Initialize and C_Finalize *****************************************************************************/ #include #include #include #include "InitTests.h" #include "cryptoki.h" #include "osmutex.h" CPPUNIT_TEST_SUITE_REGISTRATION(InitTests); void InitTests::setUp() { // printf("\nInitTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif } void InitTests::tearDown() { // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); } void InitTests::testInit1() { CK_RV rv; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_ALREADY_INITIALIZED); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } void InitTests::testInit2() { CK_C_INITIALIZE_ARGS InitArgs; CK_RV rv; #ifdef CreateMutex #undef CreateMutex #endif InitArgs.CreateMutex = NULL_PTR; InitArgs.DestroyMutex = NULL_PTR; InitArgs.LockMutex = NULL_PTR; InitArgs.UnlockMutex = NULL_PTR; InitArgs.flags = 0; InitArgs.pReserved = (CK_VOID_PTR)1; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); InitArgs.pReserved = NULL_PTR; rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_ALREADY_INITIALIZED); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } void InitTests::testInit3() { CK_C_INITIALIZE_ARGS InitArgs; CK_RV rv; InitArgs.CreateMutex = NULL_PTR; InitArgs.DestroyMutex = NULL_PTR; InitArgs.LockMutex = NULL_PTR; InitArgs.UnlockMutex = (CK_UNLOCKMUTEX)1; InitArgs.flags = 0; InitArgs.pReserved = NULL_PTR; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); InitArgs.UnlockMutex = NULL_PTR; rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_ALREADY_INITIALIZED); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } void InitTests::testInit4() { CK_C_INITIALIZE_ARGS InitArgs; CK_RV rv; InitArgs.CreateMutex = NULL_PTR; InitArgs.DestroyMutex = NULL_PTR; InitArgs.LockMutex = NULL_PTR; InitArgs.UnlockMutex = (CK_UNLOCKMUTEX)1; InitArgs.flags = CKF_OS_LOCKING_OK; InitArgs.pReserved = NULL_PTR; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); InitArgs.UnlockMutex = NULL_PTR; rv = C_Initialize((CK_VOID_PTR)&InitArgs); // If rv == CKR_CANT_LOCK then we cannot use multiple threads CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_ALREADY_INITIALIZED); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } void InitTests::testInit5() { CK_C_INITIALIZE_ARGS InitArgs; CK_RV rv; InitArgs.CreateMutex = OSCreateMutex; InitArgs.DestroyMutex = OSDestroyMutex; InitArgs.LockMutex = OSLockMutex; InitArgs.UnlockMutex = NULL_PTR; InitArgs.flags = 0; InitArgs.pReserved = NULL_PTR; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); InitArgs.UnlockMutex = OSUnlockMutex; rv = C_Initialize((CK_VOID_PTR)&InitArgs); // If rv == CKR_CANT_LOCK then we cannot use multiple threads CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_ALREADY_INITIALIZED); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } void InitTests::testInit6() { CK_C_INITIALIZE_ARGS InitArgs; CK_RV rv; InitArgs.CreateMutex = OSCreateMutex; InitArgs.DestroyMutex = OSDestroyMutex; InitArgs.LockMutex = OSLockMutex; InitArgs.UnlockMutex = NULL_PTR; InitArgs.flags = CKF_OS_LOCKING_OK; InitArgs.pReserved = NULL_PTR; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); InitArgs.UnlockMutex = OSUnlockMutex; rv = C_Initialize((CK_VOID_PTR)&InitArgs); // If rv == CKR_CANT_LOCK then we cannot use multiple threads CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Initialize((CK_VOID_PTR)&InitArgs); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_ALREADY_INITIALIZED); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } void InitTests::testFinal() { CK_RV rv; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // pReserved is reserved for future versions rv = C_Finalize((CK_VOID_PTR)1); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_Finalize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); } softhsm-2.0.0/src/lib/test/InfoTests.cpp0000664000175000017500000002073412533040716015064 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** InfoTests.cpp Contains test cases to C_GetInfo, C_GetFunctionList, C_GetSlotList, C_GetSlotInfo, C_GetTokenInfo, C_GetMechanismList, and C_GetMechanismInfo *****************************************************************************/ #include #include #include #include #include "InfoTests.h" #include "testconfig.h" CPPUNIT_TEST_SUITE_REGISTRATION(InfoTests); void InfoTests::setUp() { // printf("\nInfoTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token CK_RV rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void InfoTests::tearDown() { // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); } void InfoTests::testGetInfo() { CK_RV rv; CK_INFO ckInfo; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_GetInfo(&ckInfo); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetInfo(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetInfo(&ckInfo); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void InfoTests::testGetFunctionList() { CK_RV rv; CK_FUNCTION_LIST_PTR ckFuncList; rv = C_GetFunctionList(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetFunctionList(&ckFuncList); CPPUNIT_ASSERT(rv == CKR_OK); } void InfoTests::testGetSlotList() { CK_RV rv; CK_ULONG ulSlotCount = 0; CK_SLOT_ID_PTR pSlotList; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetSlotList(CK_FALSE, NULL_PTR, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); // Get the size of the buffer rv = C_GetSlotList(CK_FALSE, NULL_PTR, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_OK); pSlotList = (CK_SLOT_ID_PTR)malloc(ulSlotCount * sizeof(CK_SLOT_ID)); // Check if we have a too small buffer ulSlotCount = 0; rv = C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_BUFFER_TOO_SMALL); // Get the slot list rv = C_GetSlotList(CK_FALSE, pSlotList, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_OK); free(pSlotList); // Get the number of slots with tokens rv = C_GetSlotList(CK_TRUE, NULL_PTR, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_OK); pSlotList = (CK_SLOT_ID_PTR)malloc(ulSlotCount * sizeof(CK_SLOT_ID)); // Check if we have a too small buffer ulSlotCount = 0; rv = C_GetSlotList(CK_TRUE, pSlotList, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_BUFFER_TOO_SMALL); // Get the slot list rv = C_GetSlotList(CK_TRUE, pSlotList, &ulSlotCount); CPPUNIT_ASSERT(rv == CKR_OK); free(pSlotList); C_Finalize(NULL_PTR); } void InfoTests::testGetSlotInfo() { CK_RV rv; CK_SLOT_INFO slotInfo; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_GetSlotInfo(SLOT_NO_INIT_TOKEN, &slotInfo); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetSlotInfo(SLOT_NO_INIT_TOKEN, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetSlotInfo(SLOT_INVALID, &slotInfo); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); rv = C_GetSlotInfo(SLOT_NO_INIT_TOKEN, &slotInfo); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void InfoTests::testGetTokenInfo() { CK_RV rv; CK_TOKEN_INFO tokenInfo; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_GetTokenInfo(SLOT_NO_INIT_TOKEN, &tokenInfo); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetTokenInfo(SLOT_NO_INIT_TOKEN, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetTokenInfo(SLOT_INVALID, &tokenInfo); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); rv = C_GetTokenInfo(SLOT_NO_INIT_TOKEN, &tokenInfo); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == 0); rv = C_GetTokenInfo(SLOT_INIT_TOKEN, &tokenInfo); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT((tokenInfo.flags & CKF_TOKEN_INITIALIZED) == CKF_TOKEN_INITIALIZED); C_Finalize(NULL_PTR); } void InfoTests::testGetMechanismList() { CK_RV rv; CK_ULONG ulMechCount = 0; CK_MECHANISM_TYPE_PTR pMechanismList; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_GetMechanismList(SLOT_INIT_TOKEN, NULL_PTR, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetMechanismList(SLOT_INIT_TOKEN, NULL_PTR, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetMechanismList(SLOT_INVALID, NULL_PTR, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); // Get the size of the buffer rv = C_GetMechanismList(SLOT_INIT_TOKEN, NULL_PTR, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_OK); pMechanismList = (CK_MECHANISM_TYPE_PTR)malloc(ulMechCount * sizeof(CK_MECHANISM_TYPE_PTR)); // Check if we have a too small buffer ulMechCount = 0; rv = C_GetMechanismList(SLOT_INIT_TOKEN, pMechanismList, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_BUFFER_TOO_SMALL); // Get the mechanism list rv = C_GetMechanismList(SLOT_INIT_TOKEN, pMechanismList, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_OK); free(pMechanismList); C_Finalize(NULL_PTR); } void InfoTests::testGetMechanismInfo() { CK_RV rv; CK_MECHANISM_INFO info; CK_ULONG ulMechCount = 0; CK_MECHANISM_TYPE_PTR pMechanismList; // Just make sure that we finalize any previous failed tests C_Finalize(NULL_PTR); rv = C_GetMechanismInfo(SLOT_INIT_TOKEN, CKM_RSA_PKCS, &info); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Get the mechanism list rv = C_GetMechanismList(SLOT_INIT_TOKEN, NULL_PTR, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(ulMechCount != 0); pMechanismList = (CK_MECHANISM_TYPE_PTR)malloc(ulMechCount * sizeof(CK_MECHANISM_TYPE_PTR)); rv = C_GetMechanismList(SLOT_INIT_TOKEN, pMechanismList, &ulMechCount); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GetMechanismInfo(SLOT_INIT_TOKEN, pMechanismList[0], NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_GetMechanismInfo(SLOT_INVALID, pMechanismList[0], &info); CPPUNIT_ASSERT(rv == CKR_SLOT_ID_INVALID); rv = C_GetMechanismInfo(SLOT_INIT_TOKEN, CKM_VENDOR_DEFINED, &info); CPPUNIT_ASSERT(rv == CKR_MECHANISM_INVALID); for (unsigned int i = 0; i < ulMechCount; i++) { rv = C_GetMechanismInfo(SLOT_INIT_TOKEN, pMechanismList[i], &info); CPPUNIT_ASSERT(rv == CKR_OK); } free(pMechanismList); C_Finalize(NULL_PTR); } softhsm-2.0.0/src/lib/test/SymmetricAlgorithmTests.h0000664000175000017500000000655612533040716017467 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SymmetricAlgorithmTests.h Contains test cases for symmetrical algorithms (i.e., AES and DES) *****************************************************************************/ #ifndef _SOFTHSM_V2_SYMENCRYPTDECRYPTTESTS_H #define _SOFTHSM_V2_SYMENCRYPTDECRYPTTESTS_H #include #include "cryptoki.h" class SymmetricAlgorithmTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SymmetricAlgorithmTests); CPPUNIT_TEST(testAesEncryptDecrypt); CPPUNIT_TEST(testDesEncryptDecrypt); #ifdef HAVE_AES_KEY_WRAP CPPUNIT_TEST(testAesWrapUnwrap); #endif CPPUNIT_TEST(testNullTemplate); CPPUNIT_TEST(testNonModifiableDesKeyGeneration); CPPUNIT_TEST_SUITE_END(); public: void testAesEncryptDecrypt(); void testDesEncryptDecrypt(); void testAesWrapUnwrap(); void testNullTemplate(); void testNonModifiableDesKeyGeneration(); void setUp(); void tearDown(); protected: CK_RV generateAesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); #ifndef WITH_FIPS CK_RV generateDesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); CK_RV generateDes2Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); #endif CK_RV generateDes3Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); void aesEncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey); #ifndef WITH_FIPS void desEncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey); #endif void des3EncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey); void aesWrapUnwrap(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey); #ifdef HAVE_AES_KEY_WRAP_PAD CK_RV generateRsaPrivateKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey); #endif }; #endif // !_SOFTHSM_V2_SYMENCRYPTDECRYPTTESTS_H softhsm-2.0.0/src/lib/test/SessionTests.h0000664000175000017500000000424212533040716015255 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionTests.h Contains test cases to C_OpenSession, C_CloseSession, C_CloseAllSessions, and C_GetSessionInfo *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONTESTS_H #define _SOFTHSM_V2_SESSIONTESTS_H #include #include "cryptoki.h" class SessionTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SessionTests); CPPUNIT_TEST(testOpenSession); CPPUNIT_TEST(testCloseSession); CPPUNIT_TEST(testCloseAllSessions); CPPUNIT_TEST(testGetSessionInfo); CPPUNIT_TEST_SUITE_END(); public: void testOpenSession(); void testCloseSession(); void testCloseAllSessions(); void testGetSessionInfo(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_SESSIONTESTS_H softhsm-2.0.0/src/lib/test/SymmetricAlgorithmTests.cpp0000664000175000017500000010753312533040736020021 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SymmetricAlgorithmTests.cpp Contains test cases for symmetrical algorithms (i.e., AES and DES) *****************************************************************************/ #include #include #include #include #include "SymmetricAlgorithmTests.h" #include "testconfig.h" // CKA_TOKEN const CK_BBOOL ON_TOKEN = CK_TRUE; const CK_BBOOL IN_SESSION = CK_FALSE; // CKA_PRIVATE const CK_BBOOL IS_PRIVATE = CK_TRUE; const CK_BBOOL IS_PUBLIC = CK_FALSE; CPPUNIT_TEST_SUITE_REGISTRATION(SymmetricAlgorithmTests); void SymmetricAlgorithmTests::setUp() { // printf("\nObjectTests\n"); setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, sopin,sopinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login SO rv = C_Login(hSession,CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize the user pin rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void SymmetricAlgorithmTests::tearDown() { C_Finalize(NULL_PTR); } CK_RV SymmetricAlgorithmTests::generateAesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_AES_KEY_GEN, NULL_PTR, 0 }; CK_ULONG bytes = 16; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bTrue, sizeof(bTrue) }, { CKA_UNWRAP, &bTrue, sizeof(bTrue) }, { CKA_VALUE_LEN, &bytes, sizeof(bytes) }, }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } #ifndef WITH_FIPS CK_RV SymmetricAlgorithmTests::generateDesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_DES_KEY_GEN, NULL_PTR, 0 }; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } CK_RV SymmetricAlgorithmTests::generateDes2Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_DES2_KEY_GEN, NULL_PTR, 0 }; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } #endif CK_RV SymmetricAlgorithmTests::generateDes3Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_DES3_KEY_GEN, NULL_PTR, 0 }; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } void SymmetricAlgorithmTests::aesEncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_BYTE iv[16]; CK_BYTE plainText[256]; CK_BYTE cipherText[300]; CK_ULONG ulCipherTextLen; CK_BYTE cipherTextMulti[300]; CK_ULONG ulCipherTextMultiLen; CK_ULONG ulCipherTextMultiPartLen; CK_BYTE recoveredText[300]; CK_ULONG ulRecoveredTextLen; CK_BYTE recoveredTextMulti[300]; CK_ULONG ulRecoveredTextMultiLen; CK_ULONG ulRecoveredTextMultiPartLen; CK_RV rv; rv = C_GenerateRandom(hSession, plainText, sizeof(plainText)); CPPUNIT_ASSERT(rv==CKR_OK); if (mechanismType == CKM_AES_CBC || mechanismType == CKM_AES_CBC_PAD) { rv = C_GenerateRandom(hSession, iv, sizeof(iv)); CPPUNIT_ASSERT(rv==CKR_OK); mechanism.pParameter = iv; mechanism.ulParameterLen = sizeof(iv); } // Single-part encryption rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid plain text size if (mechanismType == CKM_AES_ECB || mechanismType == CKM_AES_CBC) { ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,plainText,sizeof(plainText)-1,cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,plainText,sizeof(plainText),cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_OK); if (mechanismType == CKM_AES_CBC_PAD) { CPPUNIT_ASSERT(ulCipherTextLen==(sizeof(plainText)+16)); } else { CPPUNIT_ASSERT(ulCipherTextLen==sizeof(plainText)); } // Multi-part encryption rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid plain text size if (mechanismType == CKM_AES_ECB || mechanismType == CKM_AES_CBC) { ulCipherTextMultiLen = sizeof(cipherTextMulti); rv = C_EncryptUpdate(hSession,plainText,sizeof(plainText)/2-1,cipherTextMulti,&ulCipherTextMultiLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulCipherTextMultiLen = sizeof(cipherTextMulti); rv = C_EncryptUpdate(hSession,plainText,sizeof(plainText)/2,cipherTextMulti,&ulCipherTextMultiLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiPartLen = sizeof(cipherTextMulti) - ulCipherTextMultiLen; rv = C_EncryptUpdate(hSession,plainText+sizeof(plainText)/2,sizeof(plainText)/2,cipherTextMulti+ulCipherTextMultiLen,&ulCipherTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiLen += ulCipherTextMultiPartLen; ulCipherTextMultiPartLen = sizeof(cipherTextMulti) - ulCipherTextMultiLen; rv = C_EncryptFinal(hSession,cipherTextMulti+ulCipherTextMultiLen,&ulCipherTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiLen += ulCipherTextMultiPartLen; CPPUNIT_ASSERT(ulCipherTextLen==ulCipherTextMultiLen); CPPUNIT_ASSERT(memcmp(cipherText, cipherTextMulti, ulCipherTextLen) == 0); // Single-part decryption rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextLen = sizeof(recoveredText); rv = C_Decrypt(hSession,cipherText,ulCipherTextLen,recoveredText,&ulRecoveredTextLen); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(ulRecoveredTextLen==sizeof(plainText)); CPPUNIT_ASSERT(memcmp(plainText, recoveredText, sizeof(plainText)) == 0); // Multi-part decryption rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid cipher text size if (mechanismType == CKM_AES_ECB || mechanismType == CKM_AES_CBC) { ulRecoveredTextMultiLen = sizeof(recoveredTextMulti); rv = C_DecryptUpdate(hSession,cipherText,ulCipherTextLen/2-1,recoveredTextMulti,&ulRecoveredTextMultiLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulRecoveredTextMultiLen = sizeof(recoveredTextMulti); rv = C_DecryptUpdate(hSession,cipherText,ulCipherTextLen/2,recoveredTextMulti,&ulRecoveredTextMultiLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiPartLen = sizeof(recoveredTextMulti) - ulRecoveredTextMultiLen; rv = C_DecryptUpdate(hSession,cipherText+ulCipherTextLen/2,ulCipherTextLen/2,recoveredTextMulti+ulRecoveredTextMultiLen,&ulRecoveredTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiLen += ulRecoveredTextMultiPartLen; ulRecoveredTextMultiPartLen = sizeof(recoveredTextMulti) - ulRecoveredTextMultiLen; rv = C_DecryptFinal(hSession,recoveredTextMulti+ulRecoveredTextMultiLen,&ulRecoveredTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiLen += ulRecoveredTextMultiPartLen; CPPUNIT_ASSERT(ulRecoveredTextLen==ulRecoveredTextMultiLen); CPPUNIT_ASSERT(memcmp(recoveredText, recoveredTextMulti, ulRecoveredTextLen) == 0); } #ifndef WITH_FIPS void SymmetricAlgorithmTests::desEncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_BYTE iv[8]; CK_BYTE plainText[256]; CK_BYTE cipherText[300]; CK_ULONG ulCipherTextLen; CK_BYTE cipherTextMulti[300]; CK_ULONG ulCipherTextMultiLen; CK_ULONG ulCipherTextMultiPartLen; CK_BYTE recoveredText[300]; CK_ULONG ulRecoveredTextLen; CK_BYTE recoveredTextMulti[300]; CK_ULONG ulRecoveredTextMultiLen; CK_ULONG ulRecoveredTextMultiPartLen; CK_RV rv; rv = C_GenerateRandom(hSession, plainText, sizeof(plainText)); CPPUNIT_ASSERT(rv==CKR_OK); if (mechanismType == CKM_DES_CBC || mechanismType == CKM_DES_CBC_PAD) { rv = C_GenerateRandom(hSession, iv, sizeof(iv)); CPPUNIT_ASSERT(rv==CKR_OK); mechanism.pParameter = iv; mechanism.ulParameterLen = sizeof(iv); } // Single-part encryption rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid plain text size if (mechanismType == CKM_DES_ECB || mechanismType == CKM_DES_CBC) { ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,plainText,sizeof(plainText)-1,cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,plainText,sizeof(plainText),cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_OK); if (mechanismType == CKM_DES_CBC_PAD) { CPPUNIT_ASSERT(ulCipherTextLen==(sizeof(plainText)+8)); } else { CPPUNIT_ASSERT(ulCipherTextLen==sizeof(plainText)); } // Multi-part encryption rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid plain text size if (mechanismType == CKM_DES_ECB || mechanismType == CKM_DES_CBC) { ulCipherTextMultiLen = sizeof(cipherTextMulti); rv = C_EncryptUpdate(hSession,plainText,sizeof(plainText)/2-1,cipherTextMulti,&ulCipherTextMultiLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulCipherTextMultiLen = sizeof(cipherTextMulti); rv = C_EncryptUpdate(hSession,plainText,sizeof(plainText)/2,cipherTextMulti,&ulCipherTextMultiLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiPartLen = sizeof(cipherTextMulti) - ulCipherTextMultiLen; rv = C_EncryptUpdate(hSession,plainText+sizeof(plainText)/2,sizeof(plainText)/2,cipherTextMulti+ulCipherTextMultiLen,&ulCipherTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiLen += ulCipherTextMultiPartLen; ulCipherTextMultiPartLen = sizeof(cipherTextMulti) - ulCipherTextMultiLen; rv = C_EncryptFinal(hSession,cipherTextMulti+ulCipherTextMultiLen,&ulCipherTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiLen += ulCipherTextMultiPartLen; CPPUNIT_ASSERT(ulCipherTextLen==ulCipherTextMultiLen); CPPUNIT_ASSERT(memcmp(cipherText, cipherTextMulti, ulCipherTextLen) == 0); // Single-part decryption rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextLen = sizeof(recoveredText); rv = C_Decrypt(hSession,cipherText,ulCipherTextLen,recoveredText,&ulRecoveredTextLen); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(ulRecoveredTextLen==sizeof(plainText)); CPPUNIT_ASSERT(memcmp(plainText, recoveredText, sizeof(plainText)) == 0); // Multi-part decryption rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid cipher text size if (mechanismType == CKM_DES_ECB || mechanismType == CKM_DES_CBC) { ulRecoveredTextMultiLen = sizeof(recoveredTextMulti); rv = C_DecryptUpdate(hSession,cipherText,ulCipherTextLen/2-1,recoveredTextMulti,&ulRecoveredTextMultiLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulRecoveredTextMultiLen = sizeof(recoveredTextMulti); rv = C_DecryptUpdate(hSession,cipherText,ulCipherTextLen/2,recoveredTextMulti,&ulRecoveredTextMultiLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiPartLen = sizeof(recoveredTextMulti) - ulRecoveredTextMultiLen; rv = C_DecryptUpdate(hSession,cipherText+ulCipherTextLen/2,ulCipherTextLen/2,recoveredTextMulti+ulRecoveredTextMultiLen,&ulRecoveredTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiLen += ulRecoveredTextMultiPartLen; ulRecoveredTextMultiPartLen = sizeof(recoveredTextMulti) - ulRecoveredTextMultiLen; rv = C_DecryptFinal(hSession,recoveredTextMulti+ulRecoveredTextMultiLen,&ulRecoveredTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiLen += ulRecoveredTextMultiPartLen; CPPUNIT_ASSERT(ulRecoveredTextLen==ulRecoveredTextMultiLen); CPPUNIT_ASSERT(memcmp(recoveredText, recoveredTextMulti, ulRecoveredTextLen) == 0); } #endif void SymmetricAlgorithmTests::des3EncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_BYTE iv[8]; CK_BYTE plainText[256]; CK_BYTE cipherText[300]; CK_ULONG ulCipherTextLen; CK_BYTE cipherTextMulti[300]; CK_ULONG ulCipherTextMultiLen; CK_ULONG ulCipherTextMultiPartLen; CK_BYTE recoveredText[300]; CK_ULONG ulRecoveredTextLen; CK_BYTE recoveredTextMulti[300]; CK_ULONG ulRecoveredTextMultiLen; CK_ULONG ulRecoveredTextMultiPartLen; CK_RV rv; rv = C_GenerateRandom(hSession, plainText, sizeof(plainText)); CPPUNIT_ASSERT(rv==CKR_OK); if (mechanismType == CKM_DES3_CBC || mechanismType == CKM_DES3_CBC_PAD) { rv = C_GenerateRandom(hSession, iv, sizeof(iv)); CPPUNIT_ASSERT(rv==CKR_OK); mechanism.pParameter = iv; mechanism.ulParameterLen = sizeof(iv); } // Single-part encryption rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid plain text size if (mechanismType == CKM_DES3_ECB || mechanismType == CKM_DES3_CBC) { ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,plainText,sizeof(plainText)-1,cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,plainText,sizeof(plainText),cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_OK); if (mechanismType == CKM_DES3_CBC_PAD) { CPPUNIT_ASSERT(ulCipherTextLen==(sizeof(plainText)+8)); } else { CPPUNIT_ASSERT(ulCipherTextLen==sizeof(plainText)); } // Multi-part encryption rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid plain text size if (mechanismType == CKM_DES3_ECB || mechanismType == CKM_DES3_CBC) { ulCipherTextMultiLen = sizeof(cipherTextMulti); rv = C_EncryptUpdate(hSession,plainText,sizeof(plainText)/2-1,cipherTextMulti,&ulCipherTextMultiLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_EncryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulCipherTextMultiLen = sizeof(cipherTextMulti); rv = C_EncryptUpdate(hSession,plainText,sizeof(plainText)/2,cipherTextMulti,&ulCipherTextMultiLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiPartLen = sizeof(cipherTextMulti) - ulCipherTextMultiLen; rv = C_EncryptUpdate(hSession,plainText+sizeof(plainText)/2,sizeof(plainText)/2,cipherTextMulti+ulCipherTextMultiLen,&ulCipherTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiLen += ulCipherTextMultiPartLen; ulCipherTextMultiPartLen = sizeof(cipherTextMulti) - ulCipherTextMultiLen; rv = C_EncryptFinal(hSession,cipherTextMulti+ulCipherTextMultiLen,&ulCipherTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextMultiLen += ulCipherTextMultiPartLen; CPPUNIT_ASSERT(ulCipherTextLen==ulCipherTextMultiLen); CPPUNIT_ASSERT(memcmp(cipherText, cipherTextMulti, ulCipherTextLen) == 0); // Single-part decryption rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextLen = sizeof(recoveredText); rv = C_Decrypt(hSession,cipherText,ulCipherTextLen,recoveredText,&ulRecoveredTextLen); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(ulRecoveredTextLen==sizeof(plainText)); CPPUNIT_ASSERT(memcmp(plainText, recoveredText, sizeof(plainText)) == 0); // Multi-part decryption rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); // Test invalid cipher text size if (mechanismType == CKM_DES3_ECB || mechanismType == CKM_DES3_CBC) { ulRecoveredTextMultiLen = sizeof(recoveredTextMulti); rv = C_DecryptUpdate(hSession,cipherText,ulCipherTextLen/2-1,recoveredTextMulti,&ulRecoveredTextMultiLen); CPPUNIT_ASSERT(rv==CKR_DATA_LEN_RANGE); rv = C_DecryptInit(hSession,&mechanism,hKey); CPPUNIT_ASSERT(rv==CKR_OK); } ulRecoveredTextMultiLen = sizeof(recoveredTextMulti); rv = C_DecryptUpdate(hSession,cipherText,ulCipherTextLen/2,recoveredTextMulti,&ulRecoveredTextMultiLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiPartLen = sizeof(recoveredTextMulti) - ulRecoveredTextMultiLen; rv = C_DecryptUpdate(hSession,cipherText+ulCipherTextLen/2,ulCipherTextLen/2,recoveredTextMulti+ulRecoveredTextMultiLen,&ulRecoveredTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiLen += ulRecoveredTextMultiPartLen; ulRecoveredTextMultiPartLen = sizeof(recoveredTextMulti) - ulRecoveredTextMultiLen; rv = C_DecryptFinal(hSession,recoveredTextMulti+ulRecoveredTextMultiLen,&ulRecoveredTextMultiPartLen); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextMultiLen += ulRecoveredTextMultiPartLen; CPPUNIT_ASSERT(ulRecoveredTextLen==ulRecoveredTextMultiLen); CPPUNIT_ASSERT(memcmp(recoveredText, recoveredTextMulti, ulRecoveredTextLen) == 0); } #ifdef HAVE_AES_KEY_WRAP_PAD CK_RV SymmetricAlgorithmTests::generateRsaPrivateKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BYTE pubExp[] = {0x01, 0x00, 0x01}; CK_BYTE subject[] = { 0x12, 0x34 }; // dummy CK_BYTE id[] = { 123 } ; // dummy CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE pubAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_ENCRYPT, &bFalse, sizeof(bFalse) }, { CKA_VERIFY, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bFalse, sizeof(bFalse) }, { CKA_MODULUS_BITS, &bits, sizeof(bits) }, { CKA_PUBLIC_EXPONENT, &pubExp[0], sizeof(pubExp) } }; CK_ATTRIBUTE privAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_SUBJECT, &subject[0], sizeof(subject) }, { CKA_ID, &id[0], sizeof(id) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bFalse, sizeof(bFalse) }, { CKA_SIGN, &bTrue, sizeof(bTrue) }, { CKA_UNWRAP, &bFalse, sizeof(bFalse) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) } }; CK_OBJECT_HANDLE hPub = CK_INVALID_HANDLE; hKey = CK_INVALID_HANDLE; CK_RV rv; rv = C_GenerateKeyPair(hSession, &mechanism, pubAttribs, sizeof(pubAttribs)/sizeof(CK_ATTRIBUTE), privAttribs, sizeof(privAttribs)/sizeof(CK_ATTRIBUTE), &hPub, &hKey); if (hPub != CK_INVALID_HANDLE) { C_DestroyObject(hSession, hPub); } return rv; } #endif void SymmetricAlgorithmTests::aesWrapUnwrap(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CK_MECHANISM mechanism = { mechanismType, NULL_PTR, 0 }; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_OBJECT_CLASS secretClass = CKO_SECRET_KEY; CK_KEY_TYPE genKeyType = CKK_GENERIC_SECRET; CK_BYTE keyPtr[128]; CK_ULONG keyLen = mechanismType == CKM_AES_KEY_WRAP_PAD ? 125UL : 128UL; CK_ATTRIBUTE attribs[] = { { CKA_EXTRACTABLE, &bFalse, sizeof(bFalse) }, { CKA_CLASS, &secretClass, sizeof(secretClass) }, { CKA_KEY_TYPE, &genKeyType, sizeof(genKeyType) }, { CKA_TOKEN, &bFalse, sizeof(bFalse) }, { CKA_PRIVATE, &bTrue, sizeof(bTrue) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, // Wrapping is allowed even on sensitive objects { CKA_VALUE, keyPtr, keyLen } }; CK_OBJECT_HANDLE hSecret; CK_RV rv; rv = C_GenerateRandom(hSession, keyPtr, keyLen); CPPUNIT_ASSERT(rv == CKR_OK); hSecret = CK_INVALID_HANDLE; rv = C_CreateObject(hSession, attribs, sizeof(attribs)/sizeof(CK_ATTRIBUTE), &hSecret); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(hSecret != CK_INVALID_HANDLE); CK_BYTE_PTR wrappedPtr = NULL_PTR; CK_ULONG wrappedLen = 0UL; CK_ULONG zero = 0UL; CK_ULONG rndKeyLen = keyLen; if (mechanismType == CKM_AES_KEY_WRAP_PAD) rndKeyLen = (keyLen + 7) & ~7; rv = C_WrapKey(hSession, &mechanism, hKey, hSecret, wrappedPtr, &wrappedLen); CPPUNIT_ASSERT(rv == CKR_KEY_UNEXTRACTABLE); rv = C_DestroyObject(hSession, hSecret); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = &bTrue; hSecret = CK_INVALID_HANDLE; rv = C_CreateObject(hSession, attribs, sizeof(attribs)/sizeof(CK_ATTRIBUTE), &hSecret); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(hSecret != CK_INVALID_HANDLE); // Estimate wrapped length rv = C_WrapKey(hSession, &mechanism, hKey, hSecret, wrappedPtr, &wrappedLen); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(wrappedLen == rndKeyLen + 8); wrappedPtr = (CK_BYTE_PTR) malloc(wrappedLen); CPPUNIT_ASSERT(wrappedPtr != NULL_PTR); rv = C_WrapKey(hSession, &mechanism, hKey, hSecret, wrappedPtr, &wrappedLen); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(wrappedLen == rndKeyLen + 8); // This should always fail because wrapped data have to be longer than 0 bytes zero = 0; rv = C_WrapKey(hSession, &mechanism, hKey, hSecret, wrappedPtr, &zero); CPPUNIT_ASSERT(rv == CKR_BUFFER_TOO_SMALL); CK_ATTRIBUTE nattribs[] = { { CKA_CLASS, &secretClass, sizeof(secretClass) }, { CKA_KEY_TYPE, &genKeyType, sizeof(genKeyType) }, { CKA_TOKEN, &bFalse, sizeof(bFalse) }, { CKA_PRIVATE, &bTrue, sizeof(bTrue) }, { CKA_ENCRYPT, &bFalse, sizeof(bFalse) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_SIGN, &bFalse,sizeof(bFalse) }, { CKA_VERIFY, &bTrue, sizeof(bTrue) } }; CK_OBJECT_HANDLE hNew; hNew = CK_INVALID_HANDLE; rv = C_UnwrapKey(hSession, &mechanism, hKey, wrappedPtr, wrappedLen, nattribs, sizeof(nattribs)/sizeof(CK_ATTRIBUTE), &hNew); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(hNew != CK_INVALID_HANDLE); free(wrappedPtr); wrappedPtr = NULL_PTR; rv = C_DestroyObject(hSession, hSecret); CPPUNIT_ASSERT(rv == CKR_OK); #ifdef HAVE_AES_KEY_WRAP_PAD if (mechanismType != CKM_AES_KEY_WRAP_PAD) return; CK_OBJECT_HANDLE hRsa; hRsa = CK_INVALID_HANDLE; rv = generateRsaPrivateKey(hSession, CK_TRUE, CK_TRUE, hRsa); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(hRsa != CK_INVALID_HANDLE); CK_OBJECT_CLASS privateClass = CKO_PRIVATE_KEY; CK_KEY_TYPE rsaKeyType = CKK_RSA; CK_BYTE_PTR p2Ptr = NULL_PTR; CK_ULONG p2Len = 0UL; CK_ATTRIBUTE rsaAttribs[] = { { CKA_CLASS, &privateClass, sizeof(privateClass) }, { CKA_KEY_TYPE, &rsaKeyType, sizeof(rsaKeyType) }, { CKA_PRIME_2, NULL_PTR, 0UL } }; rv = C_GetAttributeValue(hSession, hRsa, rsaAttribs, sizeof(rsaAttribs)/sizeof(CK_ATTRIBUTE)); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(rsaAttribs[0].ulValueLen == sizeof(CK_OBJECT_CLASS)); CPPUNIT_ASSERT(*(CK_OBJECT_CLASS*)rsaAttribs[0].pValue == CKO_PRIVATE_KEY); CPPUNIT_ASSERT(rsaAttribs[1].ulValueLen == sizeof(CK_KEY_TYPE)); CPPUNIT_ASSERT(*(CK_KEY_TYPE*)rsaAttribs[1].pValue == CKK_RSA); p2Len = rsaAttribs[2].ulValueLen; p2Ptr = (CK_BYTE_PTR) malloc(2 * p2Len); CPPUNIT_ASSERT(p2Ptr != NULL_PTR); rsaAttribs[2].pValue = p2Ptr; rsaAttribs[2].ulValueLen = p2Len; rv = C_GetAttributeValue(hSession, hRsa, rsaAttribs, sizeof(rsaAttribs)/sizeof(CK_ATTRIBUTE)); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(rsaAttribs[2].ulValueLen == p2Len); rv = C_WrapKey(hSession, &mechanism, hKey, hRsa, wrappedPtr, &wrappedLen); CPPUNIT_ASSERT(rv == CKR_OK); wrappedPtr = (CK_BYTE_PTR) malloc(wrappedLen); CPPUNIT_ASSERT(wrappedPtr != NULL_PTR); rv = C_WrapKey(hSession, &mechanism, hKey, hRsa, wrappedPtr, &wrappedLen); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hRsa); CPPUNIT_ASSERT(rv == CKR_OK); CK_ATTRIBUTE nRsaAttribs[] = { { CKA_CLASS, &privateClass, sizeof(privateClass) }, { CKA_KEY_TYPE, &rsaKeyType, sizeof(rsaKeyType) }, { CKA_TOKEN, &bFalse, sizeof(bFalse) }, { CKA_PRIVATE, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_SIGN, &bFalse,sizeof(bFalse) }, { CKA_UNWRAP, &bTrue, sizeof(bTrue) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) } }; hRsa = CK_INVALID_HANDLE; rv = C_UnwrapKey(hSession, &mechanism, hKey, wrappedPtr, wrappedLen, nRsaAttribs, sizeof(nRsaAttribs)/sizeof(CK_ATTRIBUTE), &hRsa); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(hRsa != CK_INVALID_HANDLE); rsaAttribs[2].pValue = p2Ptr + p2Len; rv = C_GetAttributeValue(hSession, hRsa, rsaAttribs, sizeof(rsaAttribs)/sizeof(CK_ATTRIBUTE)); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(rsaAttribs[0].ulValueLen == sizeof(CK_OBJECT_CLASS)); CPPUNIT_ASSERT(*(CK_OBJECT_CLASS*)rsaAttribs[0].pValue == CKO_PRIVATE_KEY); CPPUNIT_ASSERT(rsaAttribs[1].ulValueLen == sizeof(CK_KEY_TYPE)); CPPUNIT_ASSERT(*(CK_KEY_TYPE*)rsaAttribs[1].pValue == CKK_RSA); CPPUNIT_ASSERT(rsaAttribs[2].ulValueLen == p2Len); CPPUNIT_ASSERT(memcmp(p2Ptr, p2Ptr + p2Len, p2Len) == 0); free(wrappedPtr); free(p2Ptr); rv = C_DestroyObject(hSession, hRsa); CPPUNIT_ASSERT(rv == CKR_OK); #endif } void SymmetricAlgorithmTests::testAesEncryptDecrypt() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; // CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; // CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; // Generate all combinations of session/token keys. rv = generateAesKey(hSessionRW,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); aesEncryptDecrypt(CKM_AES_ECB,hSessionRO,hKey); aesEncryptDecrypt(CKM_AES_CBC,hSessionRO,hKey); aesEncryptDecrypt(CKM_AES_CBC_PAD,hSessionRO,hKey); } void SymmetricAlgorithmTests::testAesWrapUnwrap() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; // CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; // CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the session so we can create a private object rv = C_Login(hSession,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; // Generate a wrapping session public key rv = generateAesKey(hSession,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); aesWrapUnwrap(CKM_AES_KEY_WRAP, hSession, hKey); #ifdef HAVE_AES_KEY_WRAP_PAD aesWrapUnwrap(CKM_AES_KEY_WRAP_PAD, hSession, hKey); #endif } void SymmetricAlgorithmTests::testDesEncryptDecrypt() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; // CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; // CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); #ifndef WITH_FIPS CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; // Generate all combinations of session/token keys. rv = generateDesKey(hSessionRW,IN_SESSION,IS_PUBLIC,hKey); CPPUNIT_ASSERT(rv == CKR_OK); desEncryptDecrypt(CKM_DES_ECB,hSessionRO,hKey); desEncryptDecrypt(CKM_DES_CBC,hSessionRO,hKey); desEncryptDecrypt(CKM_DES_CBC_PAD,hSessionRO,hKey); CK_OBJECT_HANDLE hKey2 = CK_INVALID_HANDLE; // Generate all combinations of session/token keys. rv = generateDes2Key(hSessionRW,IN_SESSION,IS_PUBLIC,hKey2); CPPUNIT_ASSERT(rv == CKR_OK); des3EncryptDecrypt(CKM_DES3_ECB,hSessionRO,hKey2); des3EncryptDecrypt(CKM_DES3_CBC,hSessionRO,hKey2); des3EncryptDecrypt(CKM_DES3_CBC_PAD,hSessionRO,hKey2); #endif CK_OBJECT_HANDLE hKey3 = CK_INVALID_HANDLE; // Generate all combinations of session/token keys. rv = generateDes3Key(hSessionRW,IN_SESSION,IS_PUBLIC,hKey3); CPPUNIT_ASSERT(rv == CKR_OK); des3EncryptDecrypt(CKM_DES3_ECB,hSessionRO,hKey3); des3EncryptDecrypt(CKM_DES3_CBC,hSessionRO,hKey3); des3EncryptDecrypt(CKM_DES3_CBC_PAD,hSessionRO,hKey3); } void SymmetricAlgorithmTests::testNullTemplate() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_MECHANISM mechanism1 = { CKM_DES3_KEY_GEN, NULL_PTR, 0 }; CK_MECHANISM mechanism2 = { CKM_AES_KEY_GEN, NULL_PTR, 0 }; CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_GenerateKey(hSession, &mechanism1, NULL_PTR, 0, &hKey); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hKey); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_GenerateKey(hSession, &mechanism2, NULL_PTR, 0, &hKey); CPPUNIT_ASSERT(rv == CKR_TEMPLATE_INCOMPLETE); } void SymmetricAlgorithmTests::testNonModifiableDesKeyGeneration() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_MECHANISM mechanism = { CKM_DES3_KEY_GEN, NULL_PTR, 0 }; CK_OBJECT_HANDLE hKey = CK_INVALID_HANDLE; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_BBOOL bToken = IN_SESSION; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bTrue, sizeof(bTrue) }, { CKA_MODIFIABLE, &bTrue, sizeof(bTrue) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bTrue, sizeof(bTrue) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hKey); CPPUNIT_ASSERT(rv == CKR_OK); // The C_GenerateKey call failed if CKA_MODIFIABLE was bFalse // This was a bug in the SoftHSM implementation keyAttribs[2].pValue = &bFalse; keyAttribs[2].ulValueLen = sizeof(bFalse); rv = C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs) / sizeof(CK_ATTRIBUTE), &hKey); // The call would fail with CKR_ATTRIBUTE_READ_ONLY CPPUNIT_ASSERT(rv == CKR_OK); // Now create a template where the CKA_MODIFIABLE attribute is last in the list CK_ATTRIBUTE keyAttribs1[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bTrue, sizeof(bTrue) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bTrue, sizeof(bTrue) }, { CKA_MODIFIABLE, &bTrue, sizeof(bTrue) } }; rv = C_GenerateKey(hSession, &mechanism, keyAttribs1, sizeof(keyAttribs1) / sizeof(CK_ATTRIBUTE), &hKey); CPPUNIT_ASSERT(rv == CKR_OK); // Now when CKA_MODIFIABLE is bFalse the key generation succeeds keyAttribs1[2].pValue = &bFalse; keyAttribs1[2].ulValueLen = sizeof(bFalse); rv = C_GenerateKey(hSession, &mechanism, keyAttribs1, sizeof(keyAttribs1) / sizeof(CK_ATTRIBUTE), &hKey); CPPUNIT_ASSERT(rv == CKR_OK); } softhsm-2.0.0/src/lib/test/tokens/0000775000175000017500000000000012552220146014015 500000000000000softhsm-2.0.0/src/lib/test/tokens/dummy.in0000664000175000017500000000000012533040716015410 00000000000000softhsm-2.0.0/src/lib/test/InfoTests.h0000664000175000017500000000455712533040716014536 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** InfoTests.h Contains test cases to C_GetInfo, C_GetFunctionList, C_GetSlotList, C_GetSlotInfo, C_GetTokenInfo, C_GetMechanismList, and C_GetMechanismInfo *****************************************************************************/ #ifndef _SOFTHSM_V2_INFOTESTS_H #define _SOFTHSM_V2_INFOTESTS_H #include #include "cryptoki.h" class InfoTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(InfoTests); CPPUNIT_TEST(testGetInfo); CPPUNIT_TEST(testGetFunctionList); CPPUNIT_TEST(testGetSlotList); CPPUNIT_TEST(testGetSlotInfo); CPPUNIT_TEST(testGetTokenInfo); CPPUNIT_TEST(testGetMechanismList); CPPUNIT_TEST(testGetMechanismInfo); CPPUNIT_TEST_SUITE_END(); public: void testGetInfo(); void testGetFunctionList(); void testGetSlotList(); void testGetSlotInfo(); void testGetTokenInfo(); void testGetMechanismList(); void testGetMechanismInfo(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_INFOTESTS_H softhsm-2.0.0/src/lib/test/DigestTests.h0000664000175000017500000000432712533040716015055 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DigestTests.h Contains test cases to C_DigestInit, C_Digest, C_DigestUpdate, C_DigestFinal *****************************************************************************/ #ifndef _SOFTHSM_V2_DIGESTTESTS_H #define _SOFTHSM_V2_DIGESTTESTS_H #include #include "cryptoki.h" class DigestTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DigestTests); CPPUNIT_TEST(testDigestInit); CPPUNIT_TEST(testDigest); CPPUNIT_TEST(testDigestUpdate); CPPUNIT_TEST(testDigestKey); CPPUNIT_TEST(testDigestFinal); CPPUNIT_TEST(testDigestAll); CPPUNIT_TEST_SUITE_END(); public: void testDigestInit(); void testDigest(); void testDigestUpdate(); void testDigestKey(); void testDigestFinal(); void testDigestAll(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_DIGESTTESTS_H softhsm-2.0.0/src/lib/test/DeriveTests.cpp0000664000175000017500000005062612533040716015412 00000000000000/* * Copyright (c) 2014 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DeriveTests.cpp Contains test cases for: C_DeriveKey *****************************************************************************/ #include #include #include #include #include "DeriveTests.h" #include "testconfig.h" // CKA_TOKEN const CK_BBOOL ON_TOKEN = CK_TRUE; const CK_BBOOL IN_SESSION = CK_FALSE; // CKA_PRIVATE const CK_BBOOL IS_PRIVATE = CK_TRUE; const CK_BBOOL IS_PUBLIC = CK_FALSE; CPPUNIT_TEST_SUITE_REGISTRATION(DeriveTests); void DeriveTests::setUp() { // printf("\nDeriveTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, sopin,sopinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login SO rv = C_Login(hSession,CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize the user pin rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void DeriveTests::tearDown() { C_Finalize(NULL_PTR); } CK_RV DeriveTests::generateDhKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk) { CK_MECHANISM mechanism = { CKM_DH_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_BBOOL bTrue = CK_TRUE; CK_BYTE bn1024[] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc9, 0x0f, 0xda, 0xa2, 0x21, 0x68, 0xc2, 0x34, 0xc4, 0xc6, 0x62, 0x8b, 0x80, 0xdc, 0x1c, 0xd1, 0x29, 0x02, 0x4e, 0x08, 0x8a, 0x67, 0xcc, 0x74, 0x02, 0x0b, 0xbe, 0xa6, 0x3b, 0x13, 0x9b, 0x22, 0x51, 0x4a, 0x08, 0x79, 0x8e, 0x34, 0x04, 0xdd, 0xef, 0x95, 0x19, 0xb3, 0xcd, 0x3a, 0x43, 0x1b, 0x30, 0x2b, 0x0a, 0x6d, 0xf2, 0x5f, 0x14, 0x37, 0x4f, 0xe1, 0x35, 0x6d, 0x6d, 0x51, 0xc2, 0x45, 0xe4, 0x85, 0xb5, 0x76, 0x62, 0x5e, 0x7e, 0xc6, 0xf4, 0x4c, 0x42, 0xe9, 0xa6, 0x37, 0xed, 0x6b, 0x0b, 0xff, 0x5c, 0xb6, 0xf4, 0x06, 0xb7, 0xed, 0xee, 0x38, 0x6b, 0xfb, 0x5a, 0x89, 0x9f, 0xa5, 0xae, 0x9f, 0x24, 0x11, 0x7c, 0x4b, 0x1f, 0xe6, 0x49, 0x28, 0x66, 0x51, 0xec, 0xe6, 0x53, 0x81, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; CK_BYTE bn2[] = { 2 }; CK_ATTRIBUTE pukAttribs[] = { { CKA_TOKEN, &bTokenPuk, sizeof(bTokenPuk) }, { CKA_PRIVATE, &bPrivatePuk, sizeof(bPrivatePuk) }, { CKA_PRIME, &bn1024, sizeof(bn1024) }, { CKA_BASE, &bn2, sizeof(bn2) } }; CK_ATTRIBUTE prkAttribs[] = { { CKA_TOKEN, &bTokenPrk, sizeof(bTokenPrk) }, { CKA_PRIVATE, &bPrivatePrk, sizeof(bPrivatePrk) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DERIVE, &bTrue, sizeof(bTrue) } }; hPuk = CK_INVALID_HANDLE; hPrk = CK_INVALID_HANDLE; return C_GenerateKeyPair(hSession, &mechanism, pukAttribs, sizeof(pukAttribs)/sizeof(CK_ATTRIBUTE), prkAttribs, sizeof(prkAttribs)/sizeof(CK_ATTRIBUTE), &hPuk, &hPrk); } CK_RV DeriveTests::generateAesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_AES_KEY_GEN, NULL_PTR, 0 }; CK_ULONG bytes = 16; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DERIVE, &bTrue, sizeof(bTrue) }, { CKA_VALUE_LEN, &bytes, sizeof(bytes) } }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } #ifndef WITH_FIPS CK_RV DeriveTests::generateDesKey(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_DES_KEY_GEN, NULL_PTR, 0 }; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DERIVE, &bTrue, sizeof(bTrue) } }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } #endif CK_RV DeriveTests::generateDes2Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_DES2_KEY_GEN, NULL_PTR, 0 }; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DERIVE, &bTrue, sizeof(bTrue) } }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } CK_RV DeriveTests::generateDes3Key(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hKey) { CK_MECHANISM mechanism = { CKM_DES3_KEY_GEN, NULL_PTR, 0 }; // CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DERIVE, &bTrue, sizeof(bTrue) } }; hKey = CK_INVALID_HANDLE; return C_GenerateKey(hSession, &mechanism, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); } void DeriveTests::dhDerive(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey, CK_OBJECT_HANDLE &hKey) { CK_ATTRIBUTE valAttrib = { CKA_VALUE, NULL_PTR, 0 }; CK_RV rv = C_GetAttributeValue(hSession, hPublicKey, &valAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); valAttrib.pValue = (CK_BYTE_PTR)malloc(valAttrib.ulValueLen); rv = C_GetAttributeValue(hSession, hPublicKey, &valAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); CK_MECHANISM mechanism = { CKM_DH_PKCS_DERIVE, NULL_PTR, 0 }; mechanism.pParameter = valAttrib.pValue; mechanism.ulParameterLen = valAttrib.ulValueLen; CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_GENERIC_SECRET; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ULONG secLen = 100; CK_ATTRIBUTE keyAttribs[] = { { CKA_CLASS, &keyClass, sizeof(keyClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_PRIVATE, &bFalse, sizeof(bFalse) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) }, { CKA_VALUE_LEN, &secLen, sizeof(secLen) } }; hKey = CK_INVALID_HANDLE; rv = C_DeriveKey(hSession, &mechanism, hPrivateKey, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hKey); free(valAttrib.pValue); CPPUNIT_ASSERT(rv == CKR_OK); } bool DeriveTests::compareSecret(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey1, CK_OBJECT_HANDLE hKey2) { CK_ATTRIBUTE valAttrib = { CKA_VALUE, NULL_PTR, 0 }; CK_BYTE val1[128]; valAttrib.pValue = val1; valAttrib.ulValueLen = sizeof(val1); CK_RV rv = C_GetAttributeValue(hSession, hKey1, &valAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(valAttrib.ulValueLen == 100); CK_BYTE val2[128]; valAttrib.pValue = val2; valAttrib.ulValueLen = sizeof(val2); rv = C_GetAttributeValue(hSession, hKey2, &valAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(valAttrib.ulValueLen == 100); return memcmp(val1, val2, 100) == 0; } void DeriveTests::testDhDerive() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Public Session keys CK_OBJECT_HANDLE hPuk1 = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrk1 = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPuk2 = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrk2 = CK_INVALID_HANDLE; rv = generateDhKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPuk1,hPrk1); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateDhKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPuk2,hPrk2); CPPUNIT_ASSERT(rv == CKR_OK); CK_OBJECT_HANDLE hKey1 = CK_INVALID_HANDLE; dhDerive(hSessionRW,hPuk1,hPrk2,hKey1); CK_OBJECT_HANDLE hKey2 = CK_INVALID_HANDLE; dhDerive(hSessionRW,hPuk2,hPrk1,hKey2); CPPUNIT_ASSERT(compareSecret(hSessionRW,hKey1,hKey2)); // Private Session Keys rv = generateDhKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,IN_SESSION,IS_PRIVATE,hPuk1,hPrk1); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateDhKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,IN_SESSION,IS_PRIVATE,hPuk2,hPrk2); CPPUNIT_ASSERT(rv == CKR_OK); dhDerive(hSessionRW,hPuk1,hPrk2,hKey1); dhDerive(hSessionRW,hPuk2,hPrk1,hKey2); CPPUNIT_ASSERT(compareSecret(hSessionRW,hKey1,hKey2)); // Public Token Keys rv = generateDhKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,ON_TOKEN,IS_PUBLIC,hPuk1,hPrk1); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateDhKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,ON_TOKEN,IS_PUBLIC,hPuk2,hPrk2); CPPUNIT_ASSERT(rv == CKR_OK); dhDerive(hSessionRW,hPuk1,hPrk2,hKey1); dhDerive(hSessionRW,hPuk2,hPrk1,hKey2); CPPUNIT_ASSERT(compareSecret(hSessionRW,hKey1,hKey2)); // Private Token Keys rv = generateDhKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,ON_TOKEN,IS_PRIVATE,hPuk1,hPrk1); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateDhKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,ON_TOKEN,IS_PRIVATE,hPuk2,hPrk2); CPPUNIT_ASSERT(rv == CKR_OK); dhDerive(hSessionRW,hPuk1,hPrk2,hKey1); dhDerive(hSessionRW,hPuk2,hPrk1,hKey2); CPPUNIT_ASSERT(compareSecret(hSessionRW,hKey1,hKey2)); } void DeriveTests::symDerive(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey, CK_OBJECT_HANDLE &hDerive, CK_MECHANISM_TYPE mechType, CK_KEY_TYPE keyType) { CK_RV rv; CK_MECHANISM mechanism = { mechType, NULL_PTR, 0 }; CK_MECHANISM mechEncrypt = { CKM_VENDOR_DEFINED, NULL_PTR, 0 }; CK_KEY_DERIVATION_STRING_DATA param1; CK_DES_CBC_ENCRYPT_DATA_PARAMS param2; CK_AES_CBC_ENCRYPT_DATA_PARAMS param3; CK_BYTE data[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x30, 0x31, 0x32 }; CK_ULONG secLen = 0; switch (mechType) { case CKM_DES_ECB_ENCRYPT_DATA: case CKM_DES3_ECB_ENCRYPT_DATA: case CKM_AES_ECB_ENCRYPT_DATA: param1.pData = &data[0]; param1.ulLen = sizeof(data); mechanism.pParameter = ¶m1; mechanism.ulParameterLen = sizeof(param1); break; case CKM_DES_CBC_ENCRYPT_DATA: case CKM_DES3_CBC_ENCRYPT_DATA: memcpy(param2.iv, "12345678", 8); param2.pData = &data[0]; param2.length = sizeof(data); mechanism.pParameter = ¶m2; mechanism.ulParameterLen = sizeof(param2); break; case CKM_AES_CBC_ENCRYPT_DATA: memcpy(param3.iv, "1234567890ABCDEF", 16); param3.pData = &data[0]; param3.length = sizeof(data); mechanism.pParameter = ¶m3; mechanism.ulParameterLen = sizeof(param3); break; default: CPPUNIT_FAIL("Invalid mechanism"); } switch (keyType) { case CKK_GENERIC_SECRET: secLen = 32; break; case CKK_DES: mechEncrypt.mechanism = CKM_DES_ECB; break; case CKK_DES2: case CKK_DES3: mechEncrypt.mechanism = CKM_DES3_ECB; break; case CKK_AES: mechEncrypt.mechanism = CKM_AES_ECB; secLen = 32; break; default: CPPUNIT_FAIL("Invalid key type"); } CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE keyAttribs[] = { { CKA_CLASS, &keyClass, sizeof(keyClass) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, { CKA_PRIVATE, &bFalse, sizeof(bFalse) }, { CKA_ENCRYPT, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bTrue, sizeof(bTrue) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) }, { CKA_VALUE_LEN, &secLen, sizeof(secLen) } }; hDerive = CK_INVALID_HANDLE; if (secLen > 0) { rv = C_DeriveKey(hSession, &mechanism, hKey, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE), &hDerive); } else { rv = C_DeriveKey(hSession, &mechanism, hKey, keyAttribs, sizeof(keyAttribs)/sizeof(CK_ATTRIBUTE) - 1, &hDerive); } CPPUNIT_ASSERT(rv == CKR_OK); if (keyType == CKK_GENERIC_SECRET) return; CK_BYTE cipherText[300]; CK_ULONG ulCipherTextLen; CK_BYTE recoveredText[300]; CK_ULONG ulRecoveredTextLen; rv = C_EncryptInit(hSession,&mechEncrypt,hDerive); CPPUNIT_ASSERT(rv==CKR_OK); ulCipherTextLen = sizeof(cipherText); rv = C_Encrypt(hSession,data,sizeof(data),cipherText,&ulCipherTextLen); CPPUNIT_ASSERT(rv==CKR_OK); rv = C_DecryptInit(hSession,&mechEncrypt,hDerive); CPPUNIT_ASSERT(rv==CKR_OK); ulRecoveredTextLen = sizeof(recoveredText); rv = C_Decrypt(hSession,cipherText,ulCipherTextLen,recoveredText,&ulRecoveredTextLen); CPPUNIT_ASSERT(rv==CKR_OK); CPPUNIT_ASSERT(ulRecoveredTextLen==sizeof(data)); CPPUNIT_ASSERT(memcmp(data, recoveredText, sizeof(data)) == 0); } void DeriveTests::testSymDerive() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Generate base key #ifndef WITH_FIPS CK_OBJECT_HANDLE hKeyDes = CK_INVALID_HANDLE; #endif CK_OBJECT_HANDLE hKeyDes2 = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hKeyDes3 = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hKeyAes = CK_INVALID_HANDLE; #ifndef WITH_FIPS rv = generateDesKey(hSessionRW,IN_SESSION,IS_PUBLIC,hKeyDes); CPPUNIT_ASSERT(rv == CKR_OK); #endif rv = generateDes2Key(hSessionRW,IN_SESSION,IS_PUBLIC,hKeyDes2); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateDes3Key(hSessionRW,IN_SESSION,IS_PUBLIC,hKeyDes3); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateAesKey(hSessionRW,IN_SESSION,IS_PUBLIC,hKeyAes); CPPUNIT_ASSERT(rv == CKR_OK); // Derive keys CK_OBJECT_HANDLE hDerive = CK_INVALID_HANDLE; #ifndef WITH_FIPS symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_ECB_ENCRYPT_DATA,CKK_GENERIC_SECRET); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_ECB_ENCRYPT_DATA,CKK_DES); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_ECB_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_ECB_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_ECB_ENCRYPT_DATA,CKK_AES); #endif symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_GENERIC_SECRET); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_DES); #endif symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_AES); symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_GENERIC_SECRET); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_DES); #endif symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_ECB_ENCRYPT_DATA,CKK_AES); symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_ECB_ENCRYPT_DATA,CKK_GENERIC_SECRET); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_ECB_ENCRYPT_DATA,CKK_DES); #endif symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_ECB_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_ECB_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_ECB_ENCRYPT_DATA,CKK_AES); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_CBC_ENCRYPT_DATA,CKK_GENERIC_SECRET); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_CBC_ENCRYPT_DATA,CKK_DES); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_CBC_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_CBC_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyDes,hDerive,CKM_DES_CBC_ENCRYPT_DATA,CKK_AES); #endif symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_GENERIC_SECRET); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_DES); #endif symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyDes2,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_AES); symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_GENERIC_SECRET); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_DES); #endif symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyDes3,hDerive,CKM_DES3_CBC_ENCRYPT_DATA,CKK_AES); symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_CBC_ENCRYPT_DATA,CKK_GENERIC_SECRET); #ifndef WITH_FIPS symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_CBC_ENCRYPT_DATA,CKK_DES); #endif symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_CBC_ENCRYPT_DATA,CKK_DES2); symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_CBC_ENCRYPT_DATA,CKK_DES3); symDerive(hSessionRW,hKeyAes,hDerive,CKM_AES_CBC_ENCRYPT_DATA,CKK_AES); } softhsm-2.0.0/src/lib/test/UserTests.h0000664000175000017500000000407012533040716014547 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** UserTests.h Contains test cases to C_InitPIN, C_SetPIN, C_Login, and C_Logout *****************************************************************************/ #ifndef _SOFTHSM_V2_USERTESTS_H #define _SOFTHSM_V2_USERTESTS_H #include #include "cryptoki.h" class UserTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(UserTests); CPPUNIT_TEST(testInitPIN); CPPUNIT_TEST(testLogin); CPPUNIT_TEST(testLogout); CPPUNIT_TEST(testSetPIN); CPPUNIT_TEST_SUITE_END(); public: void testInitPIN(); void testLogin(); void testLogout(); void testSetPIN(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_USERTESTS_H softhsm-2.0.0/src/lib/test/ObjectTests.cpp0000664000175000017500000022526612533040716015406 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectTests.cpp Contains test cases for: C_CreateObject C_CopyObject C_DestroyObject C_GetAttributeValue C_SetAttributeValue C_FindObjectsInit C_FindObjects C_FindObjectsFinal C_GenererateKeyPair Below is a list of tests we need to add in order to verify that the PKCS#11 library is working as expected. We want to be sure that order of attributes does not impact the tests, therefore every function involving attributes should have the order of the attributes in the template randomized. We want to be sure that only attributes that are specified as being part of an object class can be used when creating an object. Using other attributes should return an error on creation of the object. We want to be sure that attributes that are required but missing will result in a template incomplete return value. We want to be sure that we get an error when trying to modify an attribute that may not be modified We want to be sure that attributes that may be changed to one value but not back to the previous value are handled correctly. We want to verify that an error is returned when we are trying to modify read-only attributes. We want to verify that sensitive attributes cannot be read. Because the teardown also removes token objects it is not really required to destroy objects created during the test in the CreateObject tests. *****************************************************************************/ #include #include #include #include #include "ObjectTests.h" #include "testconfig.h" // Common object attributes const CK_BBOOL CKA_TOKEN_DEFAULT = CK_FALSE; //const CK_BBOOL CKA_PRIVATE_DEFAULT = const CK_BBOOL CKA_MODIFIABLE_DEFAULT = CK_TRUE; const CK_UTF8CHAR_PTR CKA_LABEL_DEFAULT = NULL; const CK_BBOOL CKA_COPYABLE_DEFAULT = CK_TRUE; // Data Object Attributes const CK_UTF8CHAR_PTR CKA_APPLICATION_DEFAULT = NULL; const CK_BYTE_PTR CKA_OBJECT_ID_DEFAULT = NULL; const CK_BYTE_PTR CKA_VALUE_DEFAULT = NULL; // CKA_TOKEN const CK_BBOOL ON_TOKEN = CK_TRUE; const CK_BBOOL IN_SESSION = CK_FALSE; // CKA_PRIVATE const CK_BBOOL IS_PRIVATE = CK_TRUE; const CK_BBOOL IS_PUBLIC = CK_FALSE; CPPUNIT_TEST_SUITE_REGISTRATION(ObjectTests); void ObjectTests::setUp() { // printf("\nObjectTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, sopin,sopinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); // Open session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login SO rv = C_Login(hSession,CKU_SO, sopin, sopinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Initialize the user pin rv = C_InitPIN(hSession, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::tearDown() { C_Finalize(NULL_PTR); } void ObjectTests::checkCommonObjectAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_OBJECT_CLASS objClass) { CK_RV rv; CK_OBJECT_CLASS obj_class = CKO_VENDOR_DEFINED; CK_ATTRIBUTE attribs[] = { { CKA_CLASS, &obj_class, sizeof(obj_class) } }; rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(obj_class == objClass); } void ObjectTests::checkCommonStorageObjectAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BBOOL bToken, CK_BBOOL /*bPrivate*/, CK_BBOOL bModifiable, CK_UTF8CHAR_PTR pLabel, CK_ULONG ulLabelLen, CK_BBOOL bCopyable) { CK_RV rv; CK_BBOOL obj_token = CK_FALSE; CK_BBOOL obj_private = CK_FALSE; CK_BBOOL obj_modifiable = CK_FALSE; CK_BBOOL obj_copyable = CK_FALSE; CK_ATTRIBUTE attribs[] = { { CKA_LABEL, NULL_PTR, 0 }, { CKA_TOKEN, &obj_token, sizeof(obj_token) }, { CKA_PRIVATE, &obj_private, sizeof(obj_private) }, { CKA_MODIFIABLE, &obj_modifiable, sizeof(obj_modifiable) }, { CKA_COPYABLE, &obj_copyable, sizeof(obj_copyable) } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 1); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 5); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulLabelLen); CPPUNIT_ASSERT(obj_token == bToken); /* Default is token-specifict CPPUNIT_ASSERT(obj_private == bPrivate); */ CPPUNIT_ASSERT(obj_modifiable == bModifiable); CPPUNIT_ASSERT(obj_copyable == bCopyable); if (ulLabelLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pLabel, ulLabelLen) == 0); free(attribs[0].pValue); } void ObjectTests::checkDataObjectAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_UTF8CHAR_PTR pApplication, CK_ULONG ulApplicationLen, CK_BYTE_PTR pObjectID, CK_ULONG ulObjectIdLen, CK_BYTE_PTR pValue, CK_ULONG ulValueLen) { CK_RV rv; CK_ATTRIBUTE attribs[] = { { CKA_APPLICATION, NULL_PTR, 0 }, { CKA_OBJECT_ID, NULL_PTR, 0 }, { CKA_VALUE, NULL_PTR, 0 } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 3); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); attribs[1].pValue = (CK_VOID_PTR)malloc(attribs[1].ulValueLen); attribs[2].pValue = (CK_VOID_PTR)malloc(attribs[2].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 3); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulApplicationLen); CPPUNIT_ASSERT(attribs[1].ulValueLen == ulObjectIdLen); CPPUNIT_ASSERT(attribs[2].ulValueLen == ulValueLen); if (ulApplicationLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pApplication, ulApplicationLen) == 0); if (ulObjectIdLen > 0) CPPUNIT_ASSERT(memcmp(attribs[1].pValue, pObjectID, ulObjectIdLen) == 0); if (ulValueLen > 0) CPPUNIT_ASSERT(memcmp(attribs[2].pValue, pValue, ulValueLen) == 0); free(attribs[0].pValue); free(attribs[1].pValue); free(attribs[2].pValue); } void ObjectTests::checkCommonCertificateObjectAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_CERTIFICATE_TYPE certType, CK_BBOOL bTrusted, CK_ULONG ulCertificateCategory, CK_BYTE_PTR pCheckValue, CK_ULONG ulCheckValueLen, CK_DATE startDate, CK_ULONG ulStartDateLen, CK_DATE endDate, CK_ULONG ulEndDateLen) { CK_RV rv; CK_CERTIFICATE_TYPE obj_type = CKC_X_509; CK_BBOOL obj_trusted = CK_FALSE; CK_ULONG obj_category = 0; CK_DATE obj_start; CK_DATE obj_end; CK_ATTRIBUTE attribs[] = { { CKA_CHECK_VALUE, NULL_PTR, 0 }, { CKA_CERTIFICATE_TYPE, &obj_type, sizeof(obj_type) }, { CKA_TRUSTED, &obj_trusted, sizeof(obj_trusted) }, { CKA_CERTIFICATE_CATEGORY, &obj_category, sizeof(obj_category) }, { CKA_START_DATE, &obj_start, sizeof(obj_start) }, { CKA_END_DATE, &obj_end, sizeof(obj_end) } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 1); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 6); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulCheckValueLen); CPPUNIT_ASSERT(obj_type == certType); CPPUNIT_ASSERT(obj_trusted == bTrusted); CPPUNIT_ASSERT(obj_category == ulCertificateCategory); CPPUNIT_ASSERT(attribs[4].ulValueLen == ulStartDateLen); CPPUNIT_ASSERT(attribs[5].ulValueLen == ulEndDateLen); if (ulCheckValueLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pCheckValue, ulCheckValueLen) == 0); if (ulStartDateLen > 0) CPPUNIT_ASSERT(memcmp(attribs[4].pValue, &startDate, ulStartDateLen) == 0); if (ulEndDateLen > 0) CPPUNIT_ASSERT(memcmp(attribs[5].pValue, &endDate, ulEndDateLen) == 0); free(attribs[0].pValue); } void ObjectTests::checkX509CertificateObjectAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pSubject, CK_ULONG ulSubjectLen, CK_BYTE_PTR pId, CK_ULONG ulIdLen, CK_BYTE_PTR pIssuer, CK_ULONG ulIssuerLen, CK_BYTE_PTR pSerialNumber, CK_ULONG ulSerialNumberLen, CK_BYTE_PTR pValue, CK_ULONG ulValueLen, CK_BYTE_PTR pUrl, CK_ULONG ulUrlLen, CK_BYTE_PTR pHashOfSubjectPublicKey, CK_ULONG ulHashOfSubjectPublicKeyLen, CK_BYTE_PTR pHashOfIssuerPublicKey, CK_ULONG ulHashOfIssuerPublicKeyLen, CK_ULONG ulJavaMidpSecurityDomain, CK_MECHANISM_TYPE nameHashAlgorithm) { CK_RV rv; CK_ULONG obj_java = 0; CK_MECHANISM_TYPE obj_mech = CKM_VENDOR_DEFINED; CK_ATTRIBUTE attribs[] = { { CKA_SUBJECT, NULL_PTR, 0 }, { CKA_ID, NULL_PTR, 0 }, { CKA_ISSUER, NULL_PTR, 0 }, { CKA_SERIAL_NUMBER, NULL_PTR, 0 }, { CKA_VALUE, NULL_PTR, 0 }, { CKA_URL, NULL_PTR, 0 }, { CKA_HASH_OF_SUBJECT_PUBLIC_KEY, NULL_PTR, 0 }, { CKA_HASH_OF_ISSUER_PUBLIC_KEY, NULL_PTR, 0 }, { CKA_JAVA_MIDP_SECURITY_DOMAIN, &obj_java, sizeof(obj_java) }, { CKA_NAME_HASH_ALGORITHM, &obj_mech, sizeof(obj_mech) } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 8); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); attribs[1].pValue = (CK_VOID_PTR)malloc(attribs[1].ulValueLen); attribs[2].pValue = (CK_VOID_PTR)malloc(attribs[2].ulValueLen); attribs[3].pValue = (CK_VOID_PTR)malloc(attribs[3].ulValueLen); attribs[4].pValue = (CK_VOID_PTR)malloc(attribs[4].ulValueLen); attribs[5].pValue = (CK_VOID_PTR)malloc(attribs[5].ulValueLen); attribs[6].pValue = (CK_VOID_PTR)malloc(attribs[6].ulValueLen); attribs[7].pValue = (CK_VOID_PTR)malloc(attribs[7].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 10); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulSubjectLen); CPPUNIT_ASSERT(attribs[1].ulValueLen == ulIdLen); CPPUNIT_ASSERT(attribs[2].ulValueLen == ulIssuerLen); CPPUNIT_ASSERT(attribs[3].ulValueLen == ulSerialNumberLen); CPPUNIT_ASSERT(attribs[4].ulValueLen == ulValueLen); CPPUNIT_ASSERT(attribs[5].ulValueLen == ulUrlLen); CPPUNIT_ASSERT(attribs[6].ulValueLen == ulHashOfSubjectPublicKeyLen); CPPUNIT_ASSERT(attribs[7].ulValueLen == ulHashOfIssuerPublicKeyLen); CPPUNIT_ASSERT(obj_java == ulJavaMidpSecurityDomain); CPPUNIT_ASSERT(obj_mech == nameHashAlgorithm); if (ulSubjectLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pSubject, ulSubjectLen) == 0); if (ulIdLen > 0) CPPUNIT_ASSERT(memcmp(attribs[1].pValue, pId, ulIdLen) == 0); if (ulIssuerLen > 0) CPPUNIT_ASSERT(memcmp(attribs[2].pValue, pIssuer, ulIssuerLen) == 0); if (ulSerialNumberLen > 0) CPPUNIT_ASSERT(memcmp(attribs[3].pValue, pSerialNumber, ulSerialNumberLen) == 0); if (ulValueLen > 0) CPPUNIT_ASSERT(memcmp(attribs[4].pValue, pValue, ulValueLen) == 0); if (ulUrlLen > 0) CPPUNIT_ASSERT(memcmp(attribs[5].pValue, pUrl, ulUrlLen) == 0); if (ulHashOfSubjectPublicKeyLen > 0) CPPUNIT_ASSERT(memcmp(attribs[6].pValue, pHashOfSubjectPublicKey, ulHashOfSubjectPublicKeyLen) == 0); if (ulHashOfIssuerPublicKeyLen > 0) CPPUNIT_ASSERT(memcmp(attribs[7].pValue, pHashOfIssuerPublicKey, ulHashOfIssuerPublicKeyLen) == 0); free(attribs[0].pValue); free(attribs[1].pValue); free(attribs[2].pValue); free(attribs[3].pValue); free(attribs[4].pValue); free(attribs[5].pValue); free(attribs[6].pValue); free(attribs[7].pValue); } void ObjectTests::checkCommonKeyAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_KEY_TYPE keyType, CK_BYTE_PTR pId, CK_ULONG ulIdLen, CK_DATE startDate, CK_ULONG ulStartDateLen, CK_DATE endDate, CK_ULONG ulEndDateLen, CK_BBOOL bDerive, CK_BBOOL bLocal, CK_MECHANISM_TYPE keyMechanismType, CK_MECHANISM_TYPE_PTR /*pAllowedMechanisms*/, CK_ULONG /*ulAllowedMechanismsLen*/) { CK_RV rv; CK_KEY_TYPE obj_type = CKK_VENDOR_DEFINED; CK_DATE obj_start; CK_DATE obj_end; CK_BBOOL obj_derive = CK_FALSE; CK_BBOOL obj_local = CK_FALSE; CK_MECHANISM_TYPE obj_mech = CKM_VENDOR_DEFINED; CK_ATTRIBUTE attribs[] = { { CKA_ID, NULL_PTR, 0 }, /* Not supported { CKA_ALLOWED_MECHANISMS, NULL_PTR, 0 }, */ { CKA_KEY_TYPE, &obj_type, sizeof(obj_type) }, { CKA_START_DATE, &obj_start, sizeof(obj_start) }, { CKA_END_DATE, &obj_end, sizeof(obj_end) }, { CKA_DERIVE, &obj_derive, sizeof(obj_derive) }, { CKA_LOCAL, &obj_local, sizeof(obj_local) }, { CKA_KEY_GEN_MECHANISM, &obj_mech, sizeof(obj_mech) } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 1); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 7); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulIdLen); CPPUNIT_ASSERT(obj_type == keyType); CPPUNIT_ASSERT(attribs[2].ulValueLen == ulStartDateLen); CPPUNIT_ASSERT(attribs[3].ulValueLen == ulEndDateLen); CPPUNIT_ASSERT(obj_derive == bDerive); CPPUNIT_ASSERT(obj_local == bLocal); CPPUNIT_ASSERT(obj_mech == keyMechanismType); if (ulIdLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pId, ulIdLen) == 0); if (ulStartDateLen > 0) CPPUNIT_ASSERT(memcmp(attribs[3].pValue, &startDate, ulStartDateLen) == 0); if (ulEndDateLen > 0) CPPUNIT_ASSERT(memcmp(attribs[4].pValue, &endDate, ulEndDateLen) == 0); free(attribs[0].pValue); } void ObjectTests::checkCommonPublicKeyAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pSubject, CK_ULONG ulSubjectLen, CK_BBOOL /*bEncrypt*/, CK_BBOOL /*bVerify*/, CK_BBOOL /*bVerifyRecover*/, CK_BBOOL /*bWrap*/, CK_BBOOL bTrusted, CK_ATTRIBUTE_PTR pWrapTemplate, CK_ULONG ulWrapTemplateLen) { CK_RV rv; CK_BBOOL obj_encrypt = CK_FALSE; CK_BBOOL obj_verify = CK_FALSE; CK_BBOOL obj_verify_recover = CK_FALSE; CK_BBOOL obj_wrap = CK_FALSE; CK_BBOOL obj_trusted = CK_FALSE; CK_LONG len_wrap_template = ulWrapTemplateLen; CK_ATTRIBUTE attribs[] = { { CKA_SUBJECT, NULL_PTR, 0 }, { CKA_ENCRYPT, &obj_encrypt, sizeof(obj_encrypt) }, { CKA_VERIFY, &obj_verify, sizeof(obj_verify) }, { CKA_VERIFY_RECOVER, &obj_verify_recover, sizeof(obj_verify_recover) }, { CKA_WRAP, &obj_wrap, sizeof(obj_wrap) }, { CKA_TRUSTED, &obj_trusted, sizeof(obj_trusted) }, { CKA_WRAP_TEMPLATE, pWrapTemplate, ulWrapTemplateLen } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 1); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 7); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulSubjectLen); /* Default is token-specifict CPPUNIT_ASSERT(obj_encrypt == bEncrypt); CPPUNIT_ASSERT(obj_verify == bVerify); CPPUNIT_ASSERT(obj_verify_recover == bVerifyRecover); CPPUNIT_ASSERT(obj_wrap == bWrap); */ CPPUNIT_ASSERT(obj_trusted == bTrusted); len_wrap_template = attribs[6].ulValueLen; CPPUNIT_ASSERT(len_wrap_template == 0); if (ulSubjectLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pSubject, ulSubjectLen) == 0); free(attribs[0].pValue); } void ObjectTests::checkCommonPrivateKeyAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pSubject, CK_ULONG ulSubjectLen, CK_BBOOL bSensitive, CK_BBOOL bDecrypt, CK_BBOOL bSign, CK_BBOOL bSignRecover, CK_BBOOL bUnwrap, CK_BBOOL bExtractable, CK_BBOOL bAlwaysSensitive, CK_BBOOL bNeverExtractable, CK_BBOOL bWrapWithTrusted, CK_ATTRIBUTE_PTR pUnwrapTemplate, CK_ULONG ulUnwrapTemplateLen, CK_BBOOL bAlwaysAuthenticate) { CK_RV rv; CK_BBOOL obj_sensitive = CK_FALSE; CK_BBOOL obj_decrypt = CK_FALSE; CK_BBOOL obj_sign = CK_FALSE; CK_BBOOL obj_sign_recover = CK_FALSE; CK_BBOOL obj_unwrap = CK_FALSE; CK_BBOOL obj_extractable = CK_FALSE; CK_BBOOL obj_always_sensitive = CK_FALSE; CK_BBOOL obj_never_extractable = CK_FALSE; CK_BBOOL obj_wrap_with_trusted = CK_FALSE; CK_BBOOL obj_always_authenticate = CK_FALSE; CK_LONG len_unwrap_template = ulUnwrapTemplateLen; CK_ATTRIBUTE attribs[] = { { CKA_SUBJECT, NULL_PTR, 0 }, { CKA_SENSITIVE, &obj_sensitive, sizeof(obj_sensitive) }, { CKA_DECRYPT, &obj_decrypt, sizeof(obj_decrypt) }, { CKA_SIGN, &obj_sign, sizeof(obj_sign) }, { CKA_SIGN_RECOVER, &obj_sign_recover, sizeof(obj_sign_recover) }, { CKA_UNWRAP, &obj_unwrap, sizeof(obj_unwrap) }, { CKA_EXTRACTABLE, &obj_extractable, sizeof(obj_extractable) }, { CKA_ALWAYS_SENSITIVE, &obj_always_sensitive, sizeof(obj_always_sensitive) }, { CKA_NEVER_EXTRACTABLE, &obj_never_extractable, sizeof(obj_never_extractable) }, { CKA_WRAP_WITH_TRUSTED, &obj_wrap_with_trusted, sizeof(obj_wrap_with_trusted) }, { CKA_UNWRAP_TEMPLATE, pUnwrapTemplate, ulUnwrapTemplateLen }, { CKA_ALWAYS_AUTHENTICATE, &obj_always_authenticate, sizeof(obj_always_authenticate) } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 1); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 12); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulSubjectLen); CPPUNIT_ASSERT(obj_sensitive == bSensitive); CPPUNIT_ASSERT(obj_decrypt == bDecrypt); CPPUNIT_ASSERT(obj_sign == bSign); CPPUNIT_ASSERT(obj_sign_recover == bSignRecover); CPPUNIT_ASSERT(obj_unwrap == bUnwrap); CPPUNIT_ASSERT(obj_extractable == bExtractable); CPPUNIT_ASSERT(obj_always_sensitive == bAlwaysSensitive); CPPUNIT_ASSERT(obj_never_extractable == bNeverExtractable); CPPUNIT_ASSERT(obj_wrap_with_trusted == bWrapWithTrusted); CPPUNIT_ASSERT(obj_always_authenticate == bAlwaysAuthenticate); len_unwrap_template = attribs[10].ulValueLen; CPPUNIT_ASSERT(len_unwrap_template == 0); if (ulSubjectLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pSubject, ulSubjectLen) == 0); free(attribs[0].pValue); } void ObjectTests::checkCommonRSAPublicKeyAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pModulus, CK_ULONG ulModulusLen, CK_ULONG ulModulusBits, CK_BYTE_PTR pPublicExponent, CK_ULONG ulPublicExponentLen) { CK_RV rv; CK_ULONG obj_bits = 0; CK_ATTRIBUTE attribs[] = { { CKA_MODULUS, NULL_PTR, 0 }, { CKA_PUBLIC_EXPONENT, NULL_PTR, 0 }, { CKA_MODULUS_BITS, &obj_bits, sizeof(obj_bits) } }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 2); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); attribs[1].pValue = (CK_VOID_PTR)malloc(attribs[1].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 3); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulModulusLen); CPPUNIT_ASSERT(attribs[1].ulValueLen == ulPublicExponentLen); CPPUNIT_ASSERT(obj_bits == ulModulusBits); if (ulModulusLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pModulus, ulModulusLen) == 0); if (ulPublicExponentLen > 0) CPPUNIT_ASSERT(memcmp(attribs[1].pValue, pPublicExponent, ulPublicExponentLen) == 0); free(attribs[0].pValue); free(attribs[1].pValue); } void ObjectTests::checkCommonRSAPrivateKeyAttributes(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pModulus, CK_ULONG ulModulusLen, CK_BYTE_PTR /*pPublicExponent*/, CK_ULONG /*ulPublicExponentLen*/, CK_BYTE_PTR pPrivateExponent, CK_ULONG ulPrivateExponentLen, CK_BYTE_PTR /*pPrime1*/, CK_ULONG /*ulPrime1Len*/, CK_BYTE_PTR /*pPrime2*/, CK_ULONG /*ulPrime2Len*/, CK_BYTE_PTR /*pExponent1*/, CK_ULONG /*ulExponent1Len*/, CK_BYTE_PTR /*pExponent2*/, CK_ULONG /*ulExponent2Len*/, CK_BYTE_PTR /*pCoefficient*/, CK_ULONG /*ulCoefficientLen*/) { CK_RV rv; CK_ATTRIBUTE attribs[] = { { CKA_MODULUS, NULL_PTR, 0 }, { CKA_PRIVATE_EXPONENT, NULL_PTR, 0 } /* Some tokens may only store modulus and private exponent { CKA_PUBLIC_EXPONENT, NULL_PTR, 0 }, { CKA_PRIME_1, NULL_PTR, 0 }, { CKA_PRIME_2, NULL_PTR, 0 }, { CKA_EXPONENT_1, NULL_PTR, 0 }, { CKA_EXPONENT_2, NULL_PTR, 0 }, { CKA_COEFFICIENT, NULL_PTR, 0 }, */ }; // Get length rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 2); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = (CK_VOID_PTR)malloc(attribs[0].ulValueLen); attribs[1].pValue = (CK_VOID_PTR)malloc(attribs[1].ulValueLen); // Check values rv = C_GetAttributeValue(hSession, hObject, &attribs[0], 2); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == ulModulusLen); CPPUNIT_ASSERT(attribs[1].ulValueLen == ulPrivateExponentLen); if (ulModulusLen > 0) CPPUNIT_ASSERT(memcmp(attribs[0].pValue, pModulus, ulModulusLen) == 0); if (ulPrivateExponentLen > 0) CPPUNIT_ASSERT(memcmp(attribs[1].pValue, pPrivateExponent, ulPrivateExponentLen) == 0); free(attribs[0].pValue); free(attribs[1].pValue); } CK_RV ObjectTests::createDataObjectMinimal(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hObject) { CK_OBJECT_CLASS cClass = CKO_DATA; CK_UTF8CHAR label[] = "A data object"; CK_ATTRIBUTE objTemplate[] = { // Common { CKA_CLASS, &cClass, sizeof(cClass) }, // Storage { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, //CKA_MODIFIABLE { CKA_LABEL, label, sizeof(label)-1 }, //CKA_COPYABLE // Data }; hObject = CK_INVALID_HANDLE; return C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE),&hObject); } CK_RV ObjectTests::createDataObjectNormal(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hObject) { CK_OBJECT_CLASS cClass = CKO_DATA; CK_UTF8CHAR label[] = "A data object"; CK_UTF8CHAR application[] = "An application"; CK_BYTE objectID[] = "invalid object id"; CK_BYTE data[] = "Sample data"; CK_ATTRIBUTE objTemplate[] = { // Common { CKA_CLASS, &cClass, sizeof(cClass) }, // Storage { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, //CKA_MODIFIABLE { CKA_LABEL, label, sizeof(label)-1 }, //CKA_COPYABLE // Data { CKA_APPLICATION, application, sizeof(application)-1 }, { CKA_OBJECT_ID, objectID, sizeof(objectID) }, { CKA_VALUE, data, sizeof(data) } }; hObject = CK_INVALID_HANDLE; return C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE),&hObject); } CK_RV ObjectTests::createCertificateObjectIncomplete(CK_SESSION_HANDLE hSession, CK_BBOOL /*bToken*/, CK_BBOOL /*bPrivate*/, CK_OBJECT_HANDLE &hObject) { CK_OBJECT_CLASS cClass = CKO_CERTIFICATE; CK_ATTRIBUTE objTemplate[] = { // Common { CKA_CLASS, &cClass, sizeof(cClass) }, }; hObject = CK_INVALID_HANDLE; return C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE),&hObject); } CK_RV ObjectTests::createCertificateObjectValue(CK_SESSION_HANDLE hSession, CK_BBOOL /*bToken*/, CK_BBOOL /*bPrivate*/, CK_OBJECT_HANDLE &hObject) { CK_OBJECT_CLASS cClass = CKO_CERTIFICATE; CK_CERTIFICATE_TYPE cType = CKC_X_509; const char *pSubject = "invalid subject der"; const char *pValue = "invalid certificate der"; CK_ATTRIBUTE objTemplate[] = { // Common { CKA_CLASS, &cClass, sizeof(cClass) }, // Common Certificate Object Attributes { CKA_CERTIFICATE_TYPE, &cType, sizeof(cType) }, // X.509 Certificate Object Attributes { CKA_SUBJECT, (CK_VOID_PTR)pSubject, strlen(pSubject) }, { CKA_VALUE, (CK_VOID_PTR)pValue, strlen(pValue) } }; hObject = CK_INVALID_HANDLE; return C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE),&hObject); } CK_RV ObjectTests::generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk) { CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BYTE pubExp[] = {0x01, 0x00, 0x01}; CK_BYTE subject[] = { 0x12, 0x34 }; // dummy CK_BYTE id[] = { 123 } ; // dummy CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE pukAttribs[] = { { CKA_TOKEN, &bTokenPuk, sizeof(bTokenPuk) }, { CKA_PRIVATE, &bPrivatePuk, sizeof(bPrivatePuk) }, { CKA_ENCRYPT, &bFalse, sizeof(bFalse) }, { CKA_VERIFY, &bTrue, sizeof(bTrue) }, { CKA_WRAP, &bFalse, sizeof(bFalse) }, { CKA_MODULUS_BITS, &bits, sizeof(bits) }, { CKA_PUBLIC_EXPONENT, &pubExp[0], sizeof(pubExp) } }; CK_ATTRIBUTE prkAttribs[] = { { CKA_TOKEN, &bTokenPrk, sizeof(bTokenPrk) }, { CKA_PRIVATE, &bPrivatePrk, sizeof(bPrivatePrk) }, { CKA_SUBJECT, &subject[0], sizeof(subject) }, { CKA_ID, &id[0], sizeof(id) }, { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_DECRYPT, &bFalse, sizeof(bFalse) }, { CKA_SIGN, &bTrue, sizeof(bTrue) }, { CKA_UNWRAP, &bFalse, sizeof(bFalse) } }; hPuk = CK_INVALID_HANDLE; hPrk = CK_INVALID_HANDLE; return C_GenerateKeyPair(hSession, &mechanism, pukAttribs, sizeof(pukAttribs)/sizeof(CK_ATTRIBUTE), prkAttribs, sizeof(prkAttribs)/sizeof(CK_ATTRIBUTE), &hPuk, &hPrk); } void ObjectTests::testCreateObject() { // printf("\ntestCreateObject\n"); // [PKCS#11 v2.3 p126] // a. Only session objects can be created during read-only session. // b. Only public objects can be created unless the normal user is logged in. // c. TODO: Key object will have CKA_LOCAL == CK_FALSE. // d. TODO: If key object is secret or a private key then both CKA_ALWAYS_SENSITIVE == CK_FALSE and CKA_NEVER_EXTRACTABLE == CKA_FALSE. CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR sopin[] = SLOT_0_SO1_PIN; CK_ULONG sopinLength = sizeof(sopin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); ///////////////////////////////// // READ-ONLY & PUBLIC ///////////////////////////////// // Open read-only session and don't login rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // We should be allowed to create public session objects rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Only public objects can be created unless the normal user is logged in rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PRIVATE, hObject); // [PKCS#11 v2.3 p97] seems to indicate CKR_OK while [PKCS#11 v2.3 p126] clearly indicates CKR_USER_NOT_LOGGED_IN CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); // We should not be allowed to create token objects because the session is read-only rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); ///////////////////////////////// // READ-ONLY & USER ///////////////////////////////// // Login USER into the read-only session rv = C_Login(hSession,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // We should be allowed to create public session objects rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // We should be allowed to create private session objects rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // We should not be allowed to create token objects. rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv==CKR_OK); ///////////////////////////////// // READ-WRITE & PUBLIC ///////////////////////////////// // Open as read-write session but don't login. rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // We should be allowed to create public session objects rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // [PKCS#11 v2.3 p97] seems to indicate CKR_OK while [PKCS#11 v2.3 p126] clearly indicates CKR_USER_NOT_LOGGED_IN rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); // We should be allowed to create public token objects even when not logged in. rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // We should not be able to create private token objects because we are not logged in now rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); ///////////////////////////////// // READ-WRITE & USER ///////////////////////////////// // Open as read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login to the read-write session rv = C_Login(hSession,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // We should always be allowed to create public session objects rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // We should be able allowed to create private session objects because we are logged in. rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // We should be allowed to create public token objects even when not logged in. rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // We should be able to create private token objects because we are logged in now rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); ///////////////////////////////// // READ-WRITE & SO ///////////////////////////////// // Open as read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login to the read-write session rv = C_Login(hSession,CKU_SO,sopin,sopinLength); CPPUNIT_ASSERT(rv==CKR_OK); // We should always be allowed to create public session objects rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Only public objects can be created unless the normal user is logged in. rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); // We should be allowed to create public token objects even when not logged in. rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession,hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Only public objects can be created unless the normal user is logged in. rv = createDataObjectMinimal(hSession, ON_TOKEN, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testCopyObject() { // printf("\ntestCopyObject\n"); CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject; CK_OBJECT_HANDLE hObject1; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session and don't login rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Get a public session object rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Allowed to copy it const char *pLabel = "Label modified via C_CopyObject"; CK_BBOOL bToken = CK_FALSE; CK_BBOOL bPrivate = CK_FALSE; CK_OBJECT_CLASS cClass = CKO_DATA; CK_ATTRIBUTE attribs[] = { { CKA_LABEL, (CK_UTF8CHAR_PTR)pLabel, strlen(pLabel) }, { CKA_TOKEN, &bToken, sizeof(bToken) }, { CKA_PRIVATE, &bPrivate, sizeof(bPrivate) }, { CKA_CLASS, &cClass, sizeof(cClass) } }; rv = C_CopyObject(hSession, hObject, &attribs[0], 1, &hObject1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hObject1); CPPUNIT_ASSERT(rv == CKR_OK); // Still allowed when still session and public rv = C_CopyObject(hSession, hObject, &attribs[0], 3, &hObject1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hObject1); CPPUNIT_ASSERT(rv == CKR_OK); // Not allowed to overwrite an !ck8 attribute rv = C_CopyObject(hSession, hObject, &attribs[0], 4, &hObject1); CPPUNIT_ASSERT(rv == CKR_ATTRIBUTE_READ_ONLY); // Not allowed to go on token bToken = CK_TRUE; rv = C_CopyObject(hSession, hObject, &attribs[0], 3, &hObject1); bToken = CK_FALSE; CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); // Not allowed to go to private bPrivate = CK_TRUE; rv = C_CopyObject(hSession, hObject, &attribs[0], 3, &hObject1); bPrivate = CK_FALSE; CPPUNIT_ASSERT(rv == CKR_USER_NOT_LOGGED_IN); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Create a read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private object rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Get a public session object rv = createDataObjectNormal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Allowed to go on token bToken = CK_TRUE; rv = C_CopyObject(hSession, hObject, &attribs[0], 3, &hObject1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hObject1); CPPUNIT_ASSERT(rv == CKR_OK); // Allowed to go to private bPrivate = CK_TRUE; rv = C_CopyObject(hSession, hObject, &attribs[0], 3, &hObject1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DestroyObject(hSession, hObject1); CPPUNIT_ASSERT(rv == CKR_OK); // Not allowed to change a !ck8 parameter CK_BYTE id[] = "Another object ID"; attribs[3].type = CKA_OBJECT_ID; attribs[3].pValue = id; attribs[3].ulValueLen = sizeof(id); rv = C_CopyObject(hSession, hObject, &attribs[0], 4, &hObject1); CPPUNIT_ASSERT(rv == CKR_ATTRIBUTE_READ_ONLY); // Not allowed to downgrade privacy rv = C_DestroyObject(hSession, hObject); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectNormal(hSession, IN_SESSION, IS_PRIVATE, hObject); CPPUNIT_ASSERT(rv == CKR_OK); bToken = CK_FALSE; bPrivate = CK_FALSE; rv = C_CopyObject(hSession, hObject, &attribs[0], 3, &hObject1); CPPUNIT_ASSERT(rv == CKR_TEMPLATE_INCONSISTENT); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testDestroyObject() { // printf("\ntestDestroyObject\n"); // [PKCS#11 v2.3 p124] When logout is successful... // a. Any of the application's handles to private objects become invalid. // b. Even if a user is later logged back into the token those handles remain invalid. // c. All private session objects from sessions belonging to the application area destroyed. // [PKCS#11 v2.3 p126] // Only session objects can be created during read-only session. // Only public objects can be created unless the normal user is logged in. CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; CK_OBJECT_HANDLE hObjectSessionPublic; CK_OBJECT_HANDLE hObjectSessionPrivate; CK_OBJECT_HANDLE hObjectTokenPublic; CK_OBJECT_HANDLE hObjectTokenPrivate; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Try to destroy an invalid object using an invalid session rv = C_DestroyObject(hSessionRO,CK_INVALID_HANDLE); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); // Create a read-only session. rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Trying to destroy an invalid object in a read-only session rv = C_DestroyObject(hSessionRO,CK_INVALID_HANDLE); CPPUNIT_ASSERT(rv == CKR_OBJECT_HANDLE_INVALID); // Create a read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Trying to destroy an invalid object in a read-write session rv = C_DestroyObject(hSessionRO,CK_INVALID_HANDLE); CPPUNIT_ASSERT(rv == CKR_OBJECT_HANDLE_INVALID); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // Create all permutations of session/token, public/private objects rv = createDataObjectMinimal(hSessionRW, IN_SESSION, IS_PUBLIC, hObjectSessionPublic); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, IN_SESSION, IS_PRIVATE, hObjectSessionPrivate); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, ON_TOKEN, IS_PUBLIC, hObjectTokenPublic); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, ON_TOKEN, IS_PRIVATE, hObjectTokenPrivate); CPPUNIT_ASSERT(rv == CKR_OK); // On a read-only session we should not be able to destroy the public token object rv = C_DestroyObject(hSessionRO,hObjectTokenPublic); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); // On a read-only session we should not be able to destroy the private token object rv = C_DestroyObject(hSessionRO,hObjectTokenPrivate); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); // Logout with a different session than the one used for login should be fine. rv = C_Logout(hSessionRW); CPPUNIT_ASSERT(rv==CKR_OK); // Login USER into the sessions so we can destroy private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // We should be able to destroy the public session object from a read-only session. rv = C_DestroyObject(hSessionRO,hObjectSessionPublic); CPPUNIT_ASSERT(rv == CKR_OK); // All private session objects should have been destroyed when logging out. rv = C_DestroyObject(hSessionRW,hObjectSessionPrivate); CPPUNIT_ASSERT(rv == CKR_OBJECT_HANDLE_INVALID); // We should be able to destroy the public token object now. rv = C_DestroyObject(hSessionRW,hObjectTokenPublic); CPPUNIT_ASSERT(rv == CKR_OK); // All handles to private token objects should have been invalidated when logging out. rv = C_DestroyObject(hSessionRW,hObjectTokenPrivate); CPPUNIT_ASSERT(rv == CKR_OBJECT_HANDLE_INVALID); // Close session rv = C_CloseSession(hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Close session rv = C_CloseSession(hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testGetObjectSize() { CK_RV rv; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open a session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Get an object rv = createDataObjectMinimal(hSession, IN_SESSION, IS_PUBLIC, hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Get the object size CK_ULONG objectSize; rv = C_GetObjectSize(hSession, hObject, &objectSize); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(objectSize == CK_UNAVAILABLE_INFORMATION); // Close session rv = C_CloseSession(hSession); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testGetAttributeValue() { CK_RV rv; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; CK_OBJECT_HANDLE hObjectSessionPublic; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Try to destroy an invalid object using an invalid session rv = C_GetAttributeValue(hSessionRO,CK_INVALID_HANDLE,NULL,1); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); // Create all permutations of session/token, public/private objects rv = createDataObjectMinimal(hSessionRO, IN_SESSION, IS_PUBLIC, hObjectSessionPublic); CPPUNIT_ASSERT(rv == CKR_OK); CK_OBJECT_CLASS cClass = CKO_VENDOR_DEFINED; CK_ATTRIBUTE attribs[] = { { CKA_CLASS, &cClass, sizeof(cClass) } }; rv = C_GetAttributeValue (hSessionRO,hObjectSessionPublic,&attribs[0],1);//sizeof(attribs)/sizeof(CK_ATTRIBUTE)); CPPUNIT_ASSERT(rv == CKR_OK); // Close session rv = C_CloseSession(hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Close session rv = C_CloseSession(hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testSetAttributeValue() { // [PKCS#11 v2.3 pg. 61] // 1. If the supplied template specifies a value for an invalid attribute, then the attempt // should fail with the error code CKR_ATTRIBUTE_TYPE_INVALID. An attribute // is valid if it is either one of the attributes described in the Cryptoki specification or an // additional vendor-specific attribute supported by the library and token. // // 2. If the supplied template specifies an invalid value for a valid attribute, then the // attempt should fail with the error code CKR_ATTRIBUTE_VALUE_INVALID. // The valid values for Cryptoki attributes are described in the Cryptoki specification. // // 3. If the supplied template specifies a value for a read-only attribute, then the attempt // should fail with the error code CKR_ATTRIBUTE_READ_ONLY. Whether or not a // given Cryptoki attribute is read-only is explicitly stated in the Cryptoki specification; // however, a particular library and token may be even more restrictive than Cryptoki // specifies. In other words, an attribute which Cryptoki says is not read-only may // nonetheless be read-only under certain circumstances (i.e., in conjunction with some // combinations of other attributes) for a particular library and token. Whether or not a // given non-Cryptoki attribute is read-only is obviously outside the scope of Cryptoki. // // 4. N/A (Does not apply to C_SetAttributeValue) // // 5. If the attribute values in the supplied template, together with any default attribute // values and any attribute values contributed to the object by the object-creation // function itself, are inconsistent, then the attempt should fail with the error code // CKR_TEMPLATE_INCONSISTENT. A set of attribute values is inconsistent if not // all of its members can be satisfied simultaneously by the token, although each value // individually is valid in Cryptoki. One example of an inconsistent template would be // using a template which specifies two different values for the same attribute. Another // example would be trying to create a secret key object with an attribute which is // appropriate for various types of public keys or private keys, but not for secret keys. // A final example would be a template with an attribute that violates some token // specific requirement. Note that this final example of an inconsistent template is // token-dependent—on a different token, such a template might not be inconsistent. // // 6. If the supplied template specifies the same value for a particular attribute more than // once (or the template specifies the same value for a particular attribute that the object- // creation function itself contributes to the object), then the behavior of Cryptoki is not // completely specified. The attempt to create an object can either succeed—thereby // creating the same object that would have been created if the multiply-specified // attribute had only appeared once—or it can fail with error code // CKR_TEMPLATE_INCONSISTENT. Library developers are encouraged to make // their libraries behave as though the attribute had only appeared once in the template; // application developers are strongly encouraged never to put a particular attribute into // a particular template more than once. CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; CK_OBJECT_HANDLE hObjectSessionPublic; CK_OBJECT_HANDLE hObjectSessionPrivate; CK_OBJECT_HANDLE hObjectTokenPublic; CK_OBJECT_HANDLE hObjectTokenPrivate; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // Create all permutations of session/token, public/private objects rv = createDataObjectMinimal(hSessionRO, IN_SESSION, IS_PUBLIC, hObjectSessionPublic); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, IN_SESSION, IS_PRIVATE, hObjectSessionPrivate); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, ON_TOKEN, IS_PUBLIC, hObjectTokenPublic); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, ON_TOKEN, IS_PRIVATE, hObjectTokenPrivate); CPPUNIT_ASSERT(rv == CKR_OK); // Check that label can be modified on all combintations of session/token and public/private objects const char *pLabel = "Label modified via C_SetAttributeValue"; CK_ATTRIBUTE attribs[] = { { CKA_LABEL, (CK_UTF8CHAR_PTR)pLabel, strlen(pLabel) } }; rv = C_SetAttributeValue (hSessionRO,hObjectSessionPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetAttributeValue (hSessionRO,hObjectSessionPrivate,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetAttributeValue (hSessionRO,hObjectTokenPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); rv = C_SetAttributeValue (hSessionRW,hObjectTokenPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetAttributeValue (hSessionRO,hObjectTokenPrivate,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_SESSION_READ_ONLY); rv = C_SetAttributeValue (hSessionRW,hObjectTokenPrivate,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); attribs[0].pValue = NULL_PTR; rv = C_GetAttributeValue(hSessionRO,hObjectSessionPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == strlen(pLabel)); char pStoredLabel[64]; attribs[0].pValue = &pStoredLabel[0]; attribs[0].ulValueLen = 64; rv = C_GetAttributeValue(hSessionRO,hObjectSessionPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(attribs[0].ulValueLen == strlen(pLabel)); CPPUNIT_ASSERT(memcmp(pLabel,pStoredLabel,strlen(pLabel)) == 0); // Close session rv = C_CloseSession(hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Close session rv = C_CloseSession(hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testFindObjects() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; CK_OBJECT_HANDLE hObjectSessionPublic; CK_OBJECT_HANDLE hObjectSessionPrivate; CK_OBJECT_HANDLE hObjectTokenPublic; CK_OBJECT_HANDLE hObjectTokenPrivate; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // Create all permutations of session/token, public/private objects rv = createDataObjectMinimal(hSessionRO, IN_SESSION, IS_PUBLIC, hObjectSessionPublic); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, IN_SESSION, IS_PRIVATE, hObjectSessionPrivate); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, ON_TOKEN, IS_PUBLIC, hObjectTokenPublic); CPPUNIT_ASSERT(rv == CKR_OK); rv = createDataObjectMinimal(hSessionRW, ON_TOKEN, IS_PRIVATE, hObjectTokenPrivate); CPPUNIT_ASSERT(rv == CKR_OK); // Set labels for the objects const char *pLabel = "Label modified via C_SetAttributeValue"; CK_ATTRIBUTE attribs[] = { { CKA_LABEL, (CK_UTF8CHAR_PTR)pLabel, strlen(pLabel) } }; rv = C_SetAttributeValue (hSessionRO,hObjectSessionPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetAttributeValue (hSessionRO,hObjectSessionPrivate,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetAttributeValue (hSessionRW,hObjectTokenPublic,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_SetAttributeValue (hSessionRW,hObjectTokenPrivate,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); // Now find the objects while logged in should find them all. rv = C_FindObjectsInit(hSessionRO,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); CK_OBJECT_HANDLE hObjects[16]; CK_ULONG ulObjectCount = 0; rv = C_FindObjects(hSessionRO,&hObjects[0],16,&ulObjectCount); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(4 == ulObjectCount); rv = C_FindObjectsFinal(hSessionRO); rv = C_Logout(hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Now find the objects while no longer logged in should find only 2 rv = C_FindObjectsInit(hSessionRO,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_FindObjects(hSessionRO,&hObjects[0],16,&ulObjectCount); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(2 == ulObjectCount); rv = C_FindObjectsFinal(hSessionRO); // Close the session used to create the session objects, should also destroy the session objects. rv = C_CloseSession(hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Now find just the public token object as public session object should be gone now. rv = C_FindObjectsInit(hSessionRW,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_FindObjects(hSessionRW,&hObjects[0],16,&ulObjectCount); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(1 == ulObjectCount); rv = C_FindObjectsFinal(hSessionRW); // Login USER into the sessions so we can gain access to private objects rv = C_Login(hSessionRW,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); // Now find just the public token object as public session object should be gone now. rv = C_FindObjectsInit(hSessionRW,&attribs[0],1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_FindObjects(hSessionRW,&hObjects[0],16,&ulObjectCount); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(2 == ulObjectCount); rv = C_FindObjectsFinal(hSessionRW); } void ObjectTests::testGenerateKeys() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSessionRO; CK_SESSION_HANDLE hSessionRW; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Open read-only session on when the token is not initialized should fail rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-only session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSessionRO); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSessionRW); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSessionRO,CKU_USER,pin,pinLength); CPPUNIT_ASSERT(rv==CKR_OK); CK_OBJECT_HANDLE hPuk = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrk = CK_INVALID_HANDLE; // Generate all combinations of session/token public/private key pairs. rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,IN_SESSION,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,ON_TOKEN,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PUBLIC,ON_TOKEN,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,IN_SESSION,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,IN_SESSION,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,ON_TOKEN,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,IN_SESSION,IS_PRIVATE,ON_TOKEN,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,IN_SESSION,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,IN_SESSION,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,ON_TOKEN,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PUBLIC,ON_TOKEN,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,IN_SESSION,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,IN_SESSION,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,ON_TOKEN,IS_PUBLIC,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); rv = generateRsaKeyPair(hSessionRW,ON_TOKEN,IS_PRIVATE,ON_TOKEN,IS_PRIVATE,hPuk,hPrk); CPPUNIT_ASSERT(rv == CKR_OK); } void ObjectTests::testDefaultDataAttributes() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; // Minimal data object CK_OBJECT_CLASS objClass = CKO_DATA; CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &objClass, sizeof(objClass) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create minimal data object rv = C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE), &hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Check attributes in data object checkCommonObjectAttributes(hSession, hObject, objClass); checkCommonStorageObjectAttributes(hSession, hObject, CK_FALSE, CK_FALSE, CK_TRUE, NULL_PTR, 0, CK_TRUE); checkDataObjectAttributes(hSession, hObject, NULL_PTR, 0, NULL_PTR, 0, NULL_PTR, 0); } void ObjectTests::testDefaultX509CertAttributes() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; // Minimal X509 certificate object CK_OBJECT_CLASS objClass = CKO_CERTIFICATE; CK_CERTIFICATE_TYPE certificateType = CKC_X_509; CK_BYTE pSubject[] = "Test1"; CK_BYTE pValue[] = "Test2"; CK_DATE emptyDate; CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_CERTIFICATE_TYPE, &certificateType, sizeof(certificateType) }, { CKA_SUBJECT, pSubject, sizeof(pSubject)-1 }, { CKA_VALUE, pValue, sizeof(pValue)-1 } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create minimal X509 certificate rv = C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE), &hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Check attributes in X509 certificate object checkCommonObjectAttributes(hSession, hObject, objClass); checkCommonStorageObjectAttributes(hSession, hObject, CK_FALSE, CK_FALSE, CK_TRUE, NULL_PTR, 0, CK_TRUE); memset(&emptyDate, 0, sizeof(emptyDate)); checkCommonCertificateObjectAttributes(hSession, hObject, CKC_X_509, CK_FALSE, 0, NULL_PTR, 0, emptyDate, 0, emptyDate, 0); checkX509CertificateObjectAttributes(hSession, hObject, pSubject, sizeof(pSubject)-1, NULL_PTR, 0, NULL_PTR, 0, NULL_PTR, 0, pValue, sizeof(pValue)-1, NULL_PTR, 0, NULL_PTR, 0, NULL_PTR, 0, 0, CKM_SHA_1); } void ObjectTests::testDefaultRSAPubAttributes() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; // Minimal RSA public key object CK_OBJECT_CLASS objClass = CKO_PUBLIC_KEY; CK_KEY_TYPE objType = CKK_RSA; CK_BYTE pN[] = { 0xC6, 0x47, 0xDD, 0x74, 0x3B, 0xCB, 0xDC, 0x6F, 0xCE, 0xA7, 0xF0, 0x5F, 0x29, 0x4B, 0x27, 0x00, 0xCC, 0x92, 0xE9, 0x20, 0x8A, 0x2C, 0x87, 0x36, 0x47, 0x24, 0xB0, 0xD5, 0x7D, 0xB0, 0x92, 0x01, 0xA0, 0xA3, 0x55, 0x2E, 0x3F, 0xFE, 0xA7, 0x4C, 0x4B, 0x3F, 0x9D, 0x4E, 0xCB, 0x78, 0x12, 0xA9, 0x42, 0xAD, 0x51, 0x1F, 0x3B, 0xBD, 0x3D, 0x6A, 0xE5, 0x38, 0xB7, 0x45, 0x65, 0x50, 0x30, 0x35 }; CK_BYTE pE[] = { 0x01, 0x00, 0x01 }; CK_DATE emptyDate; CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_KEY_TYPE, &objType, sizeof(objType) }, { CKA_MODULUS, pN, sizeof(pN) }, { CKA_PUBLIC_EXPONENT, pE, sizeof(pE) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create minimal RSA public key object rv = C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE), &hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Check attributes in RSA public key object checkCommonObjectAttributes(hSession, hObject, objClass); checkCommonStorageObjectAttributes(hSession, hObject, CK_FALSE, CK_FALSE, CK_TRUE, NULL_PTR, 0, CK_TRUE); memset(&emptyDate, 0, sizeof(emptyDate)); checkCommonKeyAttributes(hSession, hObject, objType, NULL_PTR, 0, emptyDate, 0, emptyDate, 0, CK_FALSE, CK_FALSE, CK_UNAVAILABLE_INFORMATION, NULL_PTR, 0); checkCommonPublicKeyAttributes(hSession, hObject, NULL_PTR, 0, CK_TRUE, CK_TRUE, CK_TRUE, CK_TRUE, CK_FALSE, NULL_PTR, 0); checkCommonRSAPublicKeyAttributes(hSession, hObject, pN, sizeof(pN), 512, pE, sizeof(pE)); } void ObjectTests::testDefaultRSAPrivAttributes() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; // Minimal RSA private key object CK_OBJECT_CLASS objClass = CKO_PRIVATE_KEY; CK_KEY_TYPE objType = CKK_RSA; CK_BBOOL bTrue = CK_TRUE; CK_BBOOL bFalse = CK_FALSE; CK_BYTE pN[] = { 0xC6, 0x47, 0xDD, 0x74, 0x3B, 0xCB, 0xDC, 0x6F, 0xCE, 0xA7, 0xF0, 0x5F, 0x29, 0x4B, 0x27, 0x00, 0xCC, 0x92, 0xE9, 0x20, 0x8A, 0x2C, 0x87, 0x36, 0x47, 0x24, 0xB0, 0xD5, 0x7D, 0xB0, 0x92, 0x01, 0xA0, 0xA3, 0x55, 0x2E, 0x3F, 0xFE, 0xA7, 0x4C, 0x4B, 0x3F, 0x9D, 0x4E, 0xCB, 0x78, 0x12, 0xA9, 0x42, 0xAD, 0x51, 0x1F, 0x3B, 0xBD, 0x3D, 0x6A, 0xE5, 0x38, 0xB7, 0x45, 0x65, 0x50, 0x30, 0x35 }; CK_BYTE pD[] = { 0x6D, 0x94, 0x6B, 0xEB, 0xFF, 0xDC, 0x03, 0x80, 0x7B, 0x0A, 0x4F, 0x0A, 0x98, 0x6C, 0xA3, 0x2A, 0x8A, 0xE4, 0xAA, 0x18, 0x44, 0xA4, 0xA5, 0x39, 0x37, 0x0A, 0x2C, 0xFC, 0x5F, 0xD1, 0x44, 0x6E, 0xCE, 0x25, 0x9B, 0xE5, 0xD1, 0x51, 0xAF, 0xA8, 0x30, 0xD1, 0x4D, 0x3C, 0x60, 0x33, 0xB5, 0xED, 0x4C, 0x39, 0xDA, 0x68, 0x78, 0xF9, 0x6B, 0x4F, 0x47, 0x55, 0xB2, 0x02, 0x00, 0x7E, 0x9C, 0x05 }; CK_DATE emptyDate; // Make the key non-sensitive and extractable so that we can test it. CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_KEY_TYPE, &objType, sizeof(objType) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) }, { CKA_MODULUS, pN, sizeof(pN) }, { CKA_PRIVATE_EXPONENT, pD, sizeof(pD) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create minimal RSA public key object rv = C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE), &hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Check attributes in RSA public key object checkCommonObjectAttributes(hSession, hObject, objClass); checkCommonStorageObjectAttributes(hSession, hObject, CK_FALSE, CK_FALSE, CK_TRUE, NULL_PTR, 0, CK_TRUE); memset(&emptyDate, 0, sizeof(emptyDate)); checkCommonKeyAttributes(hSession, hObject, objType, NULL_PTR, 0, emptyDate, 0, emptyDate, 0, CK_FALSE, CK_FALSE, CK_UNAVAILABLE_INFORMATION, NULL_PTR, 0); checkCommonPrivateKeyAttributes(hSession, hObject, NULL_PTR, 0, CK_FALSE, CK_TRUE, CK_TRUE, CK_TRUE, CK_TRUE, CK_TRUE, CK_FALSE, CK_FALSE, CK_FALSE, NULL_PTR, 0, CK_FALSE); checkCommonRSAPrivateKeyAttributes(hSession, hObject, pN, sizeof(pN), NULL_PTR, 0, pD, sizeof(pD), NULL_PTR, 0, NULL_PTR, 0, NULL_PTR, 0, NULL_PTR, 0, NULL_PTR, 0); } void ObjectTests::testAlwaysNeverAttribute() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hPuk = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrk = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_BBOOL always; CK_BBOOL never; CK_ATTRIBUTE pukAttribs[] = { { CKA_MODULUS_BITS, &bits, sizeof(bits) } }; CK_ATTRIBUTE prkAttribs[] = { { CKA_SENSITIVE, &bTrue, sizeof(bTrue) }, { CKA_EXTRACTABLE, &bFalse, sizeof(bFalse) } }; CK_ATTRIBUTE getTemplate[] = { { CKA_ALWAYS_SENSITIVE, &always, sizeof(always) }, { CKA_NEVER_EXTRACTABLE, &never, sizeof(never) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create object rv = C_GenerateKeyPair(hSession, &mechanism, pukAttribs, 1, prkAttribs, 2, &hPuk, &hPrk); CPPUNIT_ASSERT(rv == CKR_OK); // Check value rv = C_GetAttributeValue(hSession, hPrk, getTemplate, 2); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(always == CK_TRUE); CPPUNIT_ASSERT(never == CK_TRUE); // Set value rv = C_SetAttributeValue(hSession, hPrk, prkAttribs, 2); CPPUNIT_ASSERT(rv == CKR_ATTRIBUTE_READ_ONLY); // Create object prkAttribs[0].pValue = &bFalse; prkAttribs[1].pValue = &bTrue; rv = C_GenerateKeyPair(hSession, &mechanism, pukAttribs, 1, prkAttribs, 2, &hPuk, &hPrk); CPPUNIT_ASSERT(rv == CKR_OK); // Check value rv = C_GetAttributeValue(hSession, hPrk, getTemplate, 2); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(always == CK_FALSE); CPPUNIT_ASSERT(never == CK_FALSE); } void ObjectTests::testSensitiveAttributes() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hPuk = CK_INVALID_HANDLE; CK_OBJECT_HANDLE hPrk = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0 }; CK_ULONG bits = 1536; CK_BBOOL bSensitive = CK_TRUE; CK_BBOOL bTrue = CK_TRUE; CK_ATTRIBUTE pukAttribs[] = { { CKA_MODULUS_BITS, &bits, sizeof(bits) } }; // Sensitive attributes cannot be revealed in plaintext even if wrapping is allowed CK_ATTRIBUTE prkAttribs[] = { { CKA_SENSITIVE, &bSensitive, sizeof(bSensitive) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) } }; CK_ATTRIBUTE getTemplate[] = { { CKA_PRIVATE_EXPONENT, NULL_PTR, 0 }, { CKA_PRIME_1, NULL_PTR, 0 }, { CKA_PRIME_2, NULL_PTR, 0 }, { CKA_EXPONENT_1, NULL_PTR, 0 }, { CKA_EXPONENT_2, NULL_PTR, 0 }, { CKA_COEFFICIENT, NULL_PTR, 0 } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create object rv = C_GenerateKeyPair(hSession, &mechanism, pukAttribs, 1, prkAttribs, 2, &hPuk, &hPrk); CPPUNIT_ASSERT(rv == CKR_OK); // Check value for (int i = 0; i < 6; i++) { rv = C_GetAttributeValue(hSession, hPrk, &getTemplate[i], 1); CPPUNIT_ASSERT(rv == CKR_ATTRIBUTE_SENSITIVE); } // Retry with non-sensitive object bSensitive = CK_FALSE; rv = C_GenerateKeyPair(hSession, &mechanism, pukAttribs, 1, prkAttribs, 2, &hPuk, &hPrk); CPPUNIT_ASSERT(rv == CKR_OK); // Check value for (int i = 0; i < 6; i++) { rv = C_GetAttributeValue(hSession, hPrk, &getTemplate[i], 1); CPPUNIT_ASSERT(rv == CKR_OK); } } void ObjectTests::testGetInvalidAttribute() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; // Minimal data object CK_OBJECT_CLASS objClass = CKO_DATA; CK_BBOOL bSign; CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &objClass, sizeof(objClass) } }; CK_ATTRIBUTE getTemplate[] = { { CKA_SIGN, &bSign, sizeof(bSign) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create minimal data object rv = C_CreateObject(hSession, objTemplate, 1, &hObject); CPPUNIT_ASSERT(rv == CKR_OK); // Check value rv = C_GetAttributeValue(hSession, hObject, getTemplate, 1); CPPUNIT_ASSERT(rv == CKR_ATTRIBUTE_TYPE_INVALID); } void ObjectTests::testArrayAttribute() { CK_RV rv; CK_UTF8CHAR pin[] = SLOT_0_USER1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_SESSION_HANDLE hSession; CK_OBJECT_HANDLE hObject = CK_INVALID_HANDLE; CK_BYTE pE[] = { 0x01, 0x00, 0x01 }; // Wrap template CK_KEY_TYPE wrapType = CKK_SHA256_HMAC;; CK_ATTRIBUTE wrapTemplate[] = { { CKA_KEY_TYPE, &wrapType, sizeof(wrapType) }, { CKA_PUBLIC_EXPONENT, pE, sizeof(pE) } }; // Minimal public key object CK_OBJECT_CLASS objClass = CKO_PUBLIC_KEY; CK_KEY_TYPE objType = CKK_RSA; CK_BYTE pN[] = { 0xC6, 0x47, 0xDD, 0x74, 0x3B, 0xCB, 0xDC, 0x6F, 0xCE, 0xA7, 0xF0, 0x5F, 0x29, 0x4B, 0x27, 0x00, 0xCC, 0x92, 0xE9, 0x20, 0x8A, 0x2C, 0x87, 0x36, 0x47, 0x24, 0xB0, 0xD5, 0x7D, 0xB0, 0x92, 0x01, 0xA0, 0xA3, 0x55, 0x2E, 0x3F, 0xFE, 0xA7, 0x4C, 0x4B, 0x3F, 0x9D, 0x4E, 0xCB, 0x78, 0x12, 0xA9, 0x42, 0xAD, 0x51, 0x1F, 0x3B, 0xBD, 0x3D, 0x6A, 0xE5, 0x38, 0xB7, 0x45, 0x65, 0x50, 0x30, 0x35 }; CK_ATTRIBUTE objTemplate[] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_KEY_TYPE, &objType, sizeof(objType) }, { CKA_MODULUS, pN, sizeof(pN) }, { CKA_PUBLIC_EXPONENT, pE, sizeof(pE) }, { CKA_WRAP_TEMPLATE, wrapTemplate, sizeof(wrapTemplate) } }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); // Initialize the library and start the test. rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); // Open read-write session rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION | CKF_RW_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Login USER into the sessions so we can create a private objects rv = C_Login(hSession, CKU_USER, pin, pinLength); CPPUNIT_ASSERT(rv == CKR_OK); // Create minimal RSA public key object rv = C_CreateObject(hSession, objTemplate, sizeof(objTemplate)/sizeof(CK_ATTRIBUTE), &hObject); CPPUNIT_ASSERT(rv == CKR_OK); CK_ATTRIBUTE wrapAttribs[] = { { 0, NULL_PTR, 0 }, { 0, NULL_PTR, 0 } }; CK_ATTRIBUTE wrapAttrib = { CKA_WRAP_TEMPLATE, NULL_PTR, 0 }; // Get number of elements rv = C_GetAttributeValue(hSession, hObject, &wrapAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(wrapAttrib.ulValueLen == 2 * sizeof(CK_ATTRIBUTE)); // Get element types and sizes wrapAttrib.pValue = wrapAttribs; rv = C_GetAttributeValue(hSession, hObject, &wrapAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(wrapAttrib.ulValueLen == 2 * sizeof(CK_ATTRIBUTE)); if (wrapAttribs[0].type == CKA_KEY_TYPE) { CPPUNIT_ASSERT(wrapAttribs[0].ulValueLen == sizeof(CK_KEY_TYPE)); CPPUNIT_ASSERT(wrapAttribs[1].type == CKA_PUBLIC_EXPONENT); CPPUNIT_ASSERT(wrapAttribs[1].ulValueLen == sizeof(pE)); } else { CPPUNIT_ASSERT(wrapAttribs[0].type == CKA_PUBLIC_EXPONENT); CPPUNIT_ASSERT(wrapAttribs[0].ulValueLen == sizeof(pE)); CPPUNIT_ASSERT(wrapAttribs[1].type == CKA_KEY_TYPE); CPPUNIT_ASSERT(wrapAttribs[1].ulValueLen == sizeof(CK_KEY_TYPE)); } // Get values wrapAttribs[0].pValue = (CK_VOID_PTR)malloc(wrapAttribs[0].ulValueLen); wrapAttribs[1].pValue = (CK_VOID_PTR)malloc(wrapAttribs[1].ulValueLen); rv = C_GetAttributeValue(hSession, hObject, &wrapAttrib, 1); CPPUNIT_ASSERT(rv == CKR_OK); if (wrapAttribs[0].type == CKA_KEY_TYPE) { CK_KEY_TYPE kt = *(CK_KEY_TYPE*) wrapAttribs[0].pValue; CPPUNIT_ASSERT(kt == CKK_SHA256_HMAC); CPPUNIT_ASSERT(memcmp(wrapAttribs[1].pValue, pE, sizeof(pE)) == 0); } else { CPPUNIT_ASSERT(memcmp(wrapAttribs[0].pValue, pE, sizeof(pE)) == 0); CK_KEY_TYPE kt = *(CK_KEY_TYPE*) wrapAttribs[1].pValue; CPPUNIT_ASSERT(kt == CKK_SHA256_HMAC); } free(wrapAttribs[0].pValue); free(wrapAttribs[1].pValue); } softhsm-2.0.0/src/lib/test/AsymEncryptDecryptTests.h0000664000175000017500000000471112533040716017444 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymEncryptDecryptTests.h Contains test cases for C_EncryptInit, C_Encrypt, C_DecryptInit, C_Decrypt using asymmetrical algorithms (i.e., RSA) *****************************************************************************/ #ifndef _SOFTHSM_V2_ASYMENCRYPTDECRYPTTESTS_H #define _SOFTHSM_V2_ASYMENCRYPTDECRYPTTESTS_H #include #include "cryptoki.h" class AsymEncryptDecryptTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(AsymEncryptDecryptTests); CPPUNIT_TEST(testRsaEncryptDecrypt); CPPUNIT_TEST_SUITE_END(); public: void testRsaEncryptDecrypt(); void setUp(); void tearDown(); protected: CK_RV generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk); void rsaEncryptDecrypt(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey); void rsaOAEPParams(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey); }; #endif // !_SOFTHSM_V2_ASYMENCRYPTDECRYPTTESTS_H softhsm-2.0.0/src/lib/test/RandomTests.h0000664000175000017500000000376412533040716015062 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RandomTests.h Contains test cases to C_SeedRandom and C_GenerateRandom *****************************************************************************/ #ifndef _SOFTHSM_V2_RANDOMTESTS_H #define _SOFTHSM_V2_RANDOMTESTS_H #include #include "cryptoki.h" class RandomTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RandomTests); CPPUNIT_TEST(testSeedRandom); CPPUNIT_TEST(testGenerateRandom); CPPUNIT_TEST_SUITE_END(); public: void testSeedRandom(); void testGenerateRandom(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_RANDOMTESTS_H softhsm-2.0.0/src/lib/test/testconfig.h0000664000175000017500000000356012533040716014756 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** testconfig.h Contains parameters for the test cases *****************************************************************************/ #ifndef _SOFTHSM_V2_TESTCONFIG_H #define _SOFTHSM_V2_TESTCONFIG_H // Slots #define SLOT_INVALID 9999 #define SLOT_INIT_TOKEN 0 #define SLOT_NO_INIT_TOKEN 1 // PIN #define SLOT_0_SO1_PIN "12345678" #define SLOT_0_SO2_PIN "123456789" #define SLOT_0_USER1_PIN "1234" #define SLOT_0_USER2_PIN "12345" #endif // !_SOFTHSM_V2_TESTCONFIG_H softhsm-2.0.0/src/lib/test/Makefile.in0000664000175000017500000010553512552216621014513 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = p11test$(EXEEXT) TESTS = p11test$(EXEEXT) subdir = src/lib/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(srcdir)/softhsm2.conf.in $(top_srcdir)/depcomp \ $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = softhsm2.conf CONFIG_CLEAN_VPATH_FILES = am__dirstamp = $(am__leading_dot)dirstamp am_p11test_OBJECTS = p11test.$(OBJEXT) \ SymmetricAlgorithmTests.$(OBJEXT) DigestTests.$(OBJEXT) \ InitTests.$(OBJEXT) InfoTests.$(OBJEXT) RandomTests.$(OBJEXT) \ SessionTests.$(OBJEXT) TokenTests.$(OBJEXT) \ UserTests.$(OBJEXT) ObjectTests.$(OBJEXT) \ DeriveTests.$(OBJEXT) SignVerifyTests.$(OBJEXT) \ AsymEncryptDecryptTests.$(OBJEXT) \ AsymWrapUnwrapTests.$(OBJEXT) ../common/osmutex.$(OBJEXT) p11test_OBJECTS = $(am_p11test_OBJECTS) p11test_DEPENDENCIES = ../libsofthsm2.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = p11test_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(p11test_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(p11test_SOURCES) DIST_SOURCES = $(p11test_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../common \ `cppunit-config --cflags` AUTOMAKE_OPTIONS = subdir-objects p11test_SOURCES = p11test.cpp \ SymmetricAlgorithmTests.cpp \ DigestTests.cpp \ InitTests.cpp \ InfoTests.cpp \ RandomTests.cpp \ SessionTests.cpp \ TokenTests.cpp \ UserTests.cpp \ ObjectTests.cpp \ DeriveTests.cpp \ SignVerifyTests.cpp \ AsymEncryptDecryptTests.cpp \ AsymWrapUnwrapTests.cpp \ ../common/osmutex.cpp p11test_LDADD = ../libsofthsm2.la p11test_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread -static EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/softhsm2.conf.win32 \ $(srcdir)/tokens/dummy.in all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): softhsm2.conf: $(top_builddir)/config.status $(srcdir)/softhsm2.conf.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list ../common/$(am__dirstamp): @$(MKDIR_P) ../common @: > ../common/$(am__dirstamp) ../common/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) ../common/$(DEPDIR) @: > ../common/$(DEPDIR)/$(am__dirstamp) ../common/osmutex.$(OBJEXT): ../common/$(am__dirstamp) \ ../common/$(DEPDIR)/$(am__dirstamp) p11test$(EXEEXT): $(p11test_OBJECTS) $(p11test_DEPENDENCIES) $(EXTRA_p11test_DEPENDENCIES) @rm -f p11test$(EXEEXT) $(AM_V_CXXLD)$(p11test_LINK) $(p11test_OBJECTS) $(p11test_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) -rm -f ../common/*.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@../common/$(DEPDIR)/osmutex.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/AsymEncryptDecryptTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/AsymWrapUnwrapTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DeriveTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DigestTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/InfoTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/InitTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ObjectTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RandomTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SignVerifyTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SymmetricAlgorithmTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/TokenTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/UserTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/p11test.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\ @am__fastdepCXX_TRUE@ $(CXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\ @am__fastdepCXX_TRUE@ $(LTCXXCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\ @am__fastdepCXX_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? p11test.log: p11test$(EXEEXT) @p='p11test$(EXEEXT)'; \ b='p11test'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) -rm -f ../common/$(DEPDIR)/$(am__dirstamp) -rm -f ../common/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ../common/$(DEPDIR) ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ../common/$(DEPDIR) ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/test/DigestTests.cpp0000664000175000017500000002456212533040716015413 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DigestTests.cpp Contains test cases to C_DigestInit, C_Digest, C_DigestUpdate, C_DigestFinal *****************************************************************************/ #include #include #include #include #include "DigestTests.h" #include "testconfig.h" CPPUNIT_TEST_SUITE_REGISTRATION(DigestTests); void DigestTests::setUp() { // printf("\nDigestTests\n"); #ifndef _WIN32 setenv("SOFTHSM2_CONF", "./softhsm2.conf", 1); #else setenv("SOFTHSM2_CONF", ".\\softhsm2.conf", 1); #endif CK_UTF8CHAR pin[] = SLOT_0_SO1_PIN; CK_ULONG pinLength = sizeof(pin) - 1; CK_UTF8CHAR label[32]; memset(label, ' ', 32); memcpy(label, "token1", strlen("token1")); // (Re)initialize the token CK_RV rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_InitToken(SLOT_INIT_TOKEN, pin, pinLength, label); CPPUNIT_ASSERT(rv == CKR_OK); C_Finalize(NULL_PTR); } void DigestTests::tearDown() { C_Finalize(NULL_PTR); } void DigestTests::testDigestInit() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_VENDOR_DEFINED, NULL_PTR, 0 }; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestInit(hSession, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_DigestInit(CK_INVALID_HANDLE, &mechanism); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_MECHANISM_INVALID); mechanism.mechanism = CKM_SHA512; rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_OPERATION_ACTIVE); } void DigestTests::testDigest() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_SHA512, NULL_PTR, 0 }; CK_ULONG digestLen; CK_BYTE_PTR digest; CK_BYTE data[] = {"Text to digest"}; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Digest(CK_INVALID_HANDLE, data, sizeof(data)-1, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_OPERATION_NOT_INITIALIZED); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Digest(hSession, NULL_PTR, sizeof(data)-1, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_OK); digest = (CK_BYTE_PTR)malloc(digestLen); digestLen = 0; rv = C_Digest(hSession, data, sizeof(data)-1, digest, &digestLen); CPPUNIT_ASSERT(rv == CKR_BUFFER_TOO_SMALL); rv = C_Digest(hSession, data, sizeof(data)-1, digest, &digestLen); CPPUNIT_ASSERT(rv == CKR_OK); free(digest); rv = C_Digest(hSession, data, sizeof(data)-1, digest, &digestLen); CPPUNIT_ASSERT(rv == CKR_OPERATION_NOT_INITIALIZED); } void DigestTests::testDigestUpdate() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_SHA512, NULL_PTR, 0 }; CK_BYTE data[] = {"Text to digest"}; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_DigestUpdate(hSession, data, sizeof(data)-1); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestUpdate(CK_INVALID_HANDLE, data, sizeof(data)-1); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_DigestUpdate(hSession, data, sizeof(data)-1); CPPUNIT_ASSERT(rv == CKR_OPERATION_NOT_INITIALIZED); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestUpdate(hSession, NULL_PTR, sizeof(data)-1); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_DigestUpdate(hSession, data, sizeof(data)-1); CPPUNIT_ASSERT(rv == CKR_OK); } void DigestTests::testDigestKey() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_SHA512, NULL_PTR, 0 }; CK_BYTE data[] = {"Text to digest"}; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_DigestKey(hSession, (CK_OBJECT_HANDLE)123UL); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); // Create the generic secret key to digest CK_BBOOL bFalse = CK_FALSE; CK_BBOOL bTrue = CK_TRUE; CK_OBJECT_CLASS secretClass = CKO_SECRET_KEY; CK_KEY_TYPE genKeyType = CKK_GENERIC_SECRET; CK_ATTRIBUTE attribs[] = { { CKA_CLASS, &secretClass, sizeof(secretClass) }, { CKA_KEY_TYPE, &genKeyType, sizeof(genKeyType) }, { CKA_TOKEN, &bFalse, sizeof(bFalse) }, { CKA_PRIVATE, &bFalse, sizeof(bFalse) }, { CKA_EXTRACTABLE, &bTrue, sizeof(bTrue) }, { CKA_SENSITIVE, &bFalse, sizeof(bFalse) }, { CKA_VALUE, data, sizeof(data) - 1 } }; CK_OBJECT_HANDLE hKey; hKey = CK_INVALID_HANDLE; rv = C_CreateObject(hSession, attribs, sizeof(attribs)/sizeof(CK_ATTRIBUTE), &hKey); CPPUNIT_ASSERT(rv == CKR_OK); CPPUNIT_ASSERT(hKey != CK_INVALID_HANDLE); rv = C_DigestKey(CK_INVALID_HANDLE, hKey); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_DigestKey(hSession, hKey); CPPUNIT_ASSERT(rv == CKR_OPERATION_NOT_INITIALIZED); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestKey(hSession, CK_INVALID_HANDLE); CPPUNIT_ASSERT(rv == CKR_KEY_HANDLE_INVALID); rv = C_DigestKey(hSession, hKey); CPPUNIT_ASSERT(rv == CKR_OK); } void DigestTests::testDigestFinal() { CK_RV rv; CK_SESSION_HANDLE hSession = CK_INVALID_HANDLE; CK_MECHANISM mechanism = { CKM_SHA512, NULL_PTR, 0 }; CK_BYTE data[] = {"Text to digest"}; CK_ULONG digestLen; CK_BYTE_PTR digest; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_DigestFinal(hSession, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_CRYPTOKI_NOT_INITIALIZED); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestFinal(CK_INVALID_HANDLE, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_SESSION_HANDLE_INVALID); rv = C_DigestFinal(hSession, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_OPERATION_NOT_INITIALIZED); rv = C_DigestInit(hSession, &mechanism); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestUpdate(hSession, data, sizeof(data)-1); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_DigestFinal(hSession, NULL_PTR, NULL_PTR); CPPUNIT_ASSERT(rv == CKR_ARGUMENTS_BAD); rv = C_DigestFinal(hSession, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_OK); digest = (CK_BYTE_PTR)malloc(digestLen); digestLen = 0; rv = C_DigestFinal(hSession, digest, &digestLen); CPPUNIT_ASSERT(rv == CKR_BUFFER_TOO_SMALL); rv = C_DigestFinal(hSession, digest, &digestLen); CPPUNIT_ASSERT(rv == CKR_OK); free(digest); rv = C_DigestFinal(hSession, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_OPERATION_NOT_INITIALIZED); } void DigestTests::testDigestAll() { CK_RV rv; CK_SESSION_HANDLE hSession; CK_MECHANISM mechanisms[] = { #ifndef WITH_FIPS { CKM_MD5, NULL_PTR, 0 }, #endif { CKM_SHA_1, NULL_PTR, 0 }, { CKM_SHA224, NULL_PTR, 0 }, { CKM_SHA256, NULL_PTR, 0 }, { CKM_SHA384, NULL_PTR, 0 }, { CKM_SHA512, NULL_PTR, 0 }, #ifdef WITH_GOST { CKM_GOSTR3411, NULL_PTR, 0 }, #endif }; CK_ULONG digestLen; CK_BYTE_PTR digest; CK_BYTE data[] = {"Text to digest"}; // Just make sure that we finalize any previous tests C_Finalize(NULL_PTR); rv = C_Initialize(NULL_PTR); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_OpenSession(SLOT_INIT_TOKEN, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &hSession); CPPUNIT_ASSERT(rv == CKR_OK); for (unsigned int i = 0; i < sizeof(mechanisms)/sizeof(CK_MECHANISM); i++) { rv = C_DigestInit(hSession, &mechanisms[i]); CPPUNIT_ASSERT(rv == CKR_OK); rv = C_Digest(hSession, data, sizeof(data)-1, NULL_PTR, &digestLen); CPPUNIT_ASSERT(rv == CKR_OK); digest = (CK_BYTE_PTR)malloc(digestLen); rv = C_Digest(hSession, data, sizeof(data)-1, digest, &digestLen); CPPUNIT_ASSERT(rv == CKR_OK); free(digest); } } softhsm-2.0.0/src/lib/test/softhsm2.conf.win320000664000175000017500000000015512533040716016012 00000000000000# SoftHSM v2 configuration file directories.tokendir = .\tokens objectstore.backend = file log.level = INFO softhsm-2.0.0/src/lib/test/p11test.cpp0000664000175000017500000000361612533040716014447 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** p11test.cpp The main test executor for tests on the PKCS#11 interface in SoftHSM v2 *****************************************************************************/ #include #include int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/test/TokenTests.h0000664000175000017500000000363012533040716014712 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** TokenTests.h Contains test cases to C_InitToken *****************************************************************************/ #ifndef _SOFTHSM_V2_TOKENTESTS_H #define _SOFTHSM_V2_TOKENTESTS_H #include #include "cryptoki.h" class TokenTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TokenTests); CPPUNIT_TEST(testInitToken); CPPUNIT_TEST_SUITE_END(); public: void testInitToken(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_TOKENTESTS_H softhsm-2.0.0/src/lib/test/AsymWrapUnwrapTests.h0000664000175000017500000000460312533040716016573 00000000000000/* * Copyright (c) 2014 Red Hat * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymWrapUnwrapTests.h Contains test cases for C_WrapKey and C_UnwrapKey using asymmetrical algorithms (RSA) *****************************************************************************/ #ifndef _SOFTHSM_V2_ASYMWRAPUNWRAPTESTS_H #define _SOFTHSM_V2_ASYMWRAPUNWRAPTESTS_H #include #include "cryptoki.h" class AsymWrapUnwrapTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(AsymWrapUnwrapTests); CPPUNIT_TEST(testRsaWrapUnwrap); CPPUNIT_TEST_SUITE_END(); public: void testRsaWrapUnwrap(); void setUp(); void tearDown(); protected: CK_RV generateAesKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE &hKey); CK_RV generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk); void rsaWrapUnwrap(CK_MECHANISM_TYPE mechanismType, CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hPublicKey, CK_OBJECT_HANDLE hPrivateKey); }; #endif // !_SOFTHSM_V2_ASYMWRAPUNWRAPTESTS_H softhsm-2.0.0/src/lib/test/InitTests.h0000664000175000017500000000422212533040716014533 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** InitTests.h Contains test cases to C_Initialize and C_Finalize *****************************************************************************/ #ifndef _SOFTHSM_V2_INITTESTS_H #define _SOFTHSM_V2_INITTESTS_H #include class InitTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(InitTests); CPPUNIT_TEST(testInit1); CPPUNIT_TEST(testInit2); CPPUNIT_TEST(testInit3); CPPUNIT_TEST(testInit4); CPPUNIT_TEST(testInit5); CPPUNIT_TEST(testInit6); CPPUNIT_TEST(testFinal); CPPUNIT_TEST_SUITE_END(); public: void testInit1(); void testInit2(); void testInit3(); void testInit4(); void testInit5(); void testInit6(); void testFinal(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_INITTESTS_H softhsm-2.0.0/src/lib/test/ObjectTests.h0000664000175000017500000001635212533040716015045 00000000000000/* * Copyright (c) 2012 SURFnet * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectTests.h Contains test cases to C_CreateObject, C_CopyObject, C_DestroyObject, C_GetAttributeValue, C_SetAttributeValue, C_FindObjectsInit, C_FindObjects, C_FindObjectsFinal, C_GenerateKeyPair *****************************************************************************/ #ifndef _SOFTHSM_V2_OBJECTTESTS_H #define _SOFTHSM_V2_OBJECTTESTS_H #include #include "cryptoki.h" class ObjectTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ObjectTests); CPPUNIT_TEST(testCreateObject); CPPUNIT_TEST(testCopyObject); CPPUNIT_TEST(testDestroyObject); CPPUNIT_TEST(testGetObjectSize); CPPUNIT_TEST(testGetAttributeValue); CPPUNIT_TEST(testSetAttributeValue); CPPUNIT_TEST(testFindObjects); CPPUNIT_TEST(testGenerateKeys); CPPUNIT_TEST(testDefaultDataAttributes); CPPUNIT_TEST(testDefaultX509CertAttributes); CPPUNIT_TEST(testDefaultRSAPubAttributes); CPPUNIT_TEST(testDefaultRSAPrivAttributes); CPPUNIT_TEST(testAlwaysNeverAttribute); CPPUNIT_TEST(testSensitiveAttributes); CPPUNIT_TEST(testGetInvalidAttribute); CPPUNIT_TEST(testArrayAttribute); CPPUNIT_TEST_SUITE_END(); public: void testCreateObject(); void testCopyObject(); void testDestroyObject(); void testGetObjectSize(); void testGetAttributeValue(); void testSetAttributeValue(); void testFindObjects(); void testGenerateKeys(); void testDefaultDataAttributes(); void testDefaultX509CertAttributes(); void testDefaultRSAPubAttributes(); void testDefaultRSAPrivAttributes(); void testAlwaysNeverAttribute(); void testSensitiveAttributes(); void testGetInvalidAttribute(); void testArrayAttribute(); void setUp(); void tearDown(); protected: void checkCommonObjectAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_OBJECT_CLASS objectClass ); void checkCommonStorageObjectAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_BBOOL bModifiable, CK_UTF8CHAR_PTR pLabel, CK_ULONG ulLabelLen, CK_BBOOL bCopyable ); void checkDataObjectAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_UTF8CHAR_PTR pApplication, CK_ULONG ulApplicationLen, CK_BYTE_PTR pObjectID, CK_ULONG ulObjectIdLen, CK_BYTE_PTR pValue, CK_ULONG ulValueLen ); void checkCommonCertificateObjectAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_CERTIFICATE_TYPE certType, CK_BBOOL bTrusted, CK_ULONG ulCertificateCategory, CK_BYTE_PTR pCheckValue, CK_ULONG ulCheckValueLen, CK_DATE startDate, CK_ULONG ulStartDateLen, CK_DATE endDate, CK_ULONG ulEndDateLen ); void checkX509CertificateObjectAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pSubject, CK_ULONG ulSubjectLen, CK_BYTE_PTR pId, CK_ULONG ulIdLen, CK_BYTE_PTR pIssuer, CK_ULONG ulIssuerLen, CK_BYTE_PTR pSerialNumber, CK_ULONG ulSerialNumberLen, CK_BYTE_PTR pValue, CK_ULONG ulValueLen, CK_BYTE_PTR pUrl, CK_ULONG ulUrlLen, CK_BYTE_PTR pHashOfSubjectPublicKey, CK_ULONG ulHashOfSubjectPublicKeyLen, CK_BYTE_PTR pHashOfIssuerPublicKey, CK_ULONG ulHashOfIssuerPublicKeyLen, CK_ULONG ulJavaMidpSecurityDomain, CK_MECHANISM_TYPE nameHashAlgorithm ); void checkCommonKeyAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_KEY_TYPE keyType, CK_BYTE_PTR pId, CK_ULONG ulIdLen, CK_DATE startDate, CK_ULONG ulStartDateLen, CK_DATE endDate, CK_ULONG ulEndDateLen, CK_BBOOL bDerive, CK_BBOOL bLocal, CK_MECHANISM_TYPE keyMechanismType, CK_MECHANISM_TYPE_PTR pAllowedMechanisms, CK_ULONG ulAllowedMechanismsLen /* len = count * sizeof(CK_MECHANISM_TYPE) */ ); void checkCommonPublicKeyAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pSubject, CK_ULONG ulSubjectLen, CK_BBOOL bEncrypt, CK_BBOOL bVerify, CK_BBOOL bVerifyRecover, CK_BBOOL bWrap, CK_BBOOL bTrusted, CK_ATTRIBUTE_PTR pWrapTemplate, CK_ULONG ulWrapTemplateLen /* len = count * sizeof(CK_ATTRIBUTE) */ ); void checkCommonPrivateKeyAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pSubject, CK_ULONG ulSubjectLen, CK_BBOOL bSensitive, CK_BBOOL bDecrypt, CK_BBOOL bSign, CK_BBOOL bSignRecover, CK_BBOOL bUnwrap, CK_BBOOL bExtractable, CK_BBOOL bAlwaysSensitive, CK_BBOOL bNeverExtractable, CK_BBOOL bWrapWithTrusted, CK_ATTRIBUTE_PTR pUnwrapTemplate, CK_ULONG ulUnwrapTemplateLen, /* len = count * sizeof(CK_ATTRIBUTE) */ CK_BBOOL bAlwaysAuthenticate ); void checkCommonRSAPublicKeyAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pModulus, CK_ULONG ulModulusLen, CK_ULONG ulModulusBits, CK_BYTE_PTR pPublicExponent, CK_ULONG ulPublicExponentLen ); void checkCommonRSAPrivateKeyAttributes ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_BYTE_PTR pModulus, CK_ULONG ulModulusLen, CK_BYTE_PTR pPublicExponent, CK_ULONG ulPublicExponentLen, CK_BYTE_PTR pPrivateExponent, CK_ULONG ulPrivateExponentLen, CK_BYTE_PTR pPrime1, CK_ULONG ulPrime1Len, CK_BYTE_PTR pPrime2, CK_ULONG ulPrime2Len, CK_BYTE_PTR pExponent1, CK_ULONG ulExponent1Len, CK_BYTE_PTR pExponent2, CK_ULONG ulExponent2Len, CK_BYTE_PTR pCoefficient, CK_ULONG ulCoefficientLen ); CK_RV createDataObjectMinimal(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hObject); CK_RV createDataObjectNormal(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hObject); CK_RV createCertificateObjectIncomplete(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hObject); CK_RV createCertificateObjectValue(CK_SESSION_HANDLE hSession, CK_BBOOL bToken, CK_BBOOL bPrivate, CK_OBJECT_HANDLE &hObject); CK_RV generateRsaKeyPair(CK_SESSION_HANDLE hSession, CK_BBOOL bTokenPuk, CK_BBOOL bPrivatePuk, CK_BBOOL bTokenPrk, CK_BBOOL bPrivatePrk, CK_OBJECT_HANDLE &hPuk, CK_OBJECT_HANDLE &hPrk); }; #endif // !_SOFTHSM_V2_OBJECTTESTS_H softhsm-2.0.0/src/lib/handle_mgr/0000775000175000017500000000000012552220147013634 500000000000000softhsm-2.0.0/src/lib/handle_mgr/Handle.h0000664000175000017500000000376012533040716015127 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Handle.h This class represents a single handle *****************************************************************************/ #ifndef _SOFTHSM_V2_HANDLE_H #define _SOFTHSM_V2_HANDLE_H #include "cryptoki.h" enum { CKH_INVALID, CKH_SESSION, CKH_OBJECT }; #define CK_HANDLE_KIND CK_ULONG class Handle { public: Handle(CK_HANDLE_KIND kind, CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession); Handle(CK_HANDLE_KIND kind, CK_SLOT_ID slotID); Handle(); CK_HANDLE_KIND kind; CK_SLOT_ID slotID; CK_SESSION_HANDLE hSession; CK_VOID_PTR object; bool isPrivate; }; #endif // !_SOFTHSM_V2_HANDLE_H softhsm-2.0.0/src/lib/handle_mgr/Makefile.am0000664000175000017500000000067212533040716015616 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../slot_mgr \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../object_store \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_handlemgr.la libsofthsm_handlemgr_la_SOURCES = HandleManager.cpp \ Handle.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/handle_mgr/HandleManager.cpp0000664000175000017500000001751412533040716016757 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HandleManager.cpp One of the most difficult problems to track down is when stale cryptoki handles for e.g. keys, objects and sessions get reused by a misbehaving application. Especialy when handles that became invalid have since been reused. A simple solution to this is to never reuse a handle once it has been issued and subsequently invalidated. The handle manager tracks issued handles along with what kind of object is presented by the handle and an actual pointer to the object in question. Issued handles are unique per application run. All session and object handles use the same handle manager and therefore there will never be e.g. a session with the same handle as an object. *****************************************************************************/ #include "HandleManager.h" #include "log.h" // Constructor HandleManager::HandleManager() { handlesMutex = MutexFactory::i()->getMutex(); handleCounter = 0; } // Destructor HandleManager::~HandleManager() { MutexFactory::i()->recycleMutex(handlesMutex); } CK_SESSION_HANDLE HandleManager::addSession(CK_SLOT_ID slotID, CK_VOID_PTR session) { MutexLocker lock(handlesMutex); Handle h( CKH_SESSION, slotID ); h.object = session; handles[++handleCounter] = h; return (CK_SESSION_HANDLE)handleCounter; } CK_VOID_PTR HandleManager::getSession(const CK_SESSION_HANDLE hSession) { MutexLocker lock(handlesMutex); std::map< CK_ULONG, Handle>::iterator it = handles.find(hSession); if (it == handles.end() || CKH_SESSION != it->second.kind) return NULL_PTR; return it->second.object; } CK_OBJECT_HANDLE HandleManager::addSessionObject(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession, bool isPrivate, CK_VOID_PTR object) { MutexLocker lock(handlesMutex); // Return existing handle when the object has already been registered. std::map< CK_VOID_PTR, CK_ULONG>::iterator oit = objects.find(object); if (oit != objects.end()) { std::map< CK_ULONG, Handle>::iterator hit = handles.find(oit->second); if (hit == handles.end() || CKH_OBJECT != hit->second.kind || slotID != hit->second.slotID) { objects.erase(oit); return CK_INVALID_HANDLE; } else return oit->second; } Handle h( CKH_OBJECT, slotID, hSession ); h.isPrivate = isPrivate; h.object = object; handles[++handleCounter] = h; objects[object] = handleCounter; return (CK_OBJECT_HANDLE)handleCounter; } CK_OBJECT_HANDLE HandleManager::addTokenObject(CK_SLOT_ID slotID, bool isPrivate, CK_VOID_PTR object) { MutexLocker lock(handlesMutex); // Return existing handle when the object has already been registered. std::map< CK_VOID_PTR, CK_ULONG>::iterator oit = objects.find(object); if (oit != objects.end()) { std::map< CK_ULONG, Handle>::iterator hit = handles.find(oit->second); if (hit == handles.end() || CKH_OBJECT != hit->second.kind || slotID != hit->second.slotID) { objects.erase(oit); return CK_INVALID_HANDLE; } else return oit->second; } // Token objects are not associated with a specific session. Handle h( CKH_OBJECT, slotID ); h.isPrivate = isPrivate; h.object = object; handles[++handleCounter] = h; objects[object] = handleCounter; return (CK_OBJECT_HANDLE)handleCounter; } CK_VOID_PTR HandleManager::getObject(const CK_OBJECT_HANDLE hObject) { MutexLocker lock(handlesMutex); std::map< CK_ULONG, Handle>::iterator it = handles.find(hObject); if (it == handles.end() || CKH_OBJECT != it->second.kind ) return NULL_PTR; return it->second.object; } CK_OBJECT_HANDLE HandleManager::getObjectHandle(CK_VOID_PTR object) { MutexLocker lock(handlesMutex); std::map< CK_VOID_PTR, CK_ULONG>::iterator it = objects.find(object); if (it == objects.end()) return CK_INVALID_HANDLE; return it->second; } void HandleManager::destroyObject(const CK_OBJECT_HANDLE hObject) { MutexLocker lock(handlesMutex); std::map< CK_ULONG, Handle>::iterator it = handles.find(hObject); if (it != handles.end() && CKH_OBJECT == it->second.kind) { objects.erase(it->second.object); handles.erase(it); } } void HandleManager::sessionClosed(const CK_SESSION_HANDLE hSession) { CK_SLOT_ID slotID; { MutexLocker lock(handlesMutex); std::map< CK_ULONG, Handle>::iterator it = handles.find(hSession); if (it == handles.end() || CKH_SESSION != it->second.kind) return; // Unable to find the specified session. slotID = it->second.slotID; // session closed, so we can erase information about it. handles.erase(it); // Erase all session object handles associated with the given session handle. CK_ULONG openSessionCount = 0; for (it = handles.begin(); it != handles.end(); ) { Handle &h = it->second; if (CKH_SESSION == h.kind && slotID == h.slotID) { ++openSessionCount; // another session is open for this slotID. } else { if (CKH_OBJECT == h.kind && hSession == h.hSession) { // A session object is present for the given session, so erase it. objects.erase(it->second.object); // Iterator post-incrementing (it++) will return a copy of the original it (which points to handle to be deleted). handles.erase(it++); continue; } } ++it; } // We are done when there are still sessions open. if (openSessionCount) return; } // No more sessions open for this token, so remove all object handles that are still valid for the given slotID. allSessionsClosed(slotID); } void HandleManager::allSessionsClosed(const CK_SLOT_ID slotID) { MutexLocker lock(handlesMutex); // Erase all "session", "session object" and "token object" handles for a given slot id. std::map< CK_ULONG, Handle>::iterator it; for (it = handles.begin(); it != handles.end(); ) { Handle &h = it->second; if (slotID == h.slotID) { if (CKH_OBJECT == it->second.kind) objects.erase(it->second.object); // Iterator post-incrementing (it++) will return a copy of the original it (which points to handle to be deleted). handles.erase(it++); continue; } ++it; } } void HandleManager::tokenLoggedOut(const CK_SLOT_ID slotID) { MutexLocker lock(handlesMutex); // Erase all private "token object" or "session object" handles for a given slot id. std::map< CK_ULONG, Handle>::iterator it; for (it = handles.begin(); it != handles.end(); ) { Handle &h = it->second; if (CKH_OBJECT == h.kind && slotID == h.slotID && h.isPrivate) { // A private object is present for the given slotID so we need to remove it. objects.erase(it->second.object); // Iterator post-incrementing (it++) will return a copy of the original it (which points to handle to be deleted). handles.erase(it++); continue; } ++it; } } softhsm-2.0.0/src/lib/handle_mgr/test/0000775000175000017500000000000012552220147014613 500000000000000softhsm-2.0.0/src/lib/handle_mgr/test/HandleManagerTests.cpp0000664000175000017500000001717112533040716020760 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HandleManagerTests.cpp Contains test cases to test the handle manager implementation *****************************************************************************/ #include #include #include #include "HandleManagerTests.h" CPPUNIT_TEST_SUITE_REGISTRATION(HandleManagerTests); void HandleManagerTests::setUp() { handleManager = new HandleManager(); } void HandleManagerTests::tearDown() { delete handleManager; } void HandleManagerTests::testHandleManager() { CPPUNIT_ASSERT(handleManager != NULL); CK_SLOT_ID slotID = 1234; // we need a unique value CK_SESSION_HANDLE hSession; CK_VOID_PTR session = &hSession; // we need a unique value CK_SESSION_HANDLE hSession2; CK_VOID_PTR session2 = &hSession2; // we need a unique value CK_OBJECT_HANDLE hObject; CK_VOID_PTR object = &hObject; // we need a unique value CK_OBJECT_HANDLE hObject2; CK_VOID_PTR object2 = &hObject2; // we need a unique value CK_OBJECT_HANDLE hObject3; CK_VOID_PTR object3 = &hObject3; // we need a unique value CK_OBJECT_HANDLE hObject4; CK_VOID_PTR object4 = &hObject4; // we need a unique value CK_OBJECT_HANDLE hObject5; CK_VOID_PTR object5 = &hObject5; // we need a unique value // Check session object management. hSession = handleManager->addSession(slotID, session); CPPUNIT_ASSERT(hSession != CK_INVALID_HANDLE); CPPUNIT_ASSERT(session == handleManager->getSession(hSession)); CPPUNIT_ASSERT_NO_THROW(handleManager->sessionClosed(123124)); handleManager->sessionClosed(hSession); CPPUNIT_ASSERT(NULL == handleManager->getSession(hSession)); // Add an object, hSession doesn't have to exists hObject = handleManager->addSessionObject(slotID, 4412412, true, object); CPPUNIT_ASSERT(hObject != CK_INVALID_HANDLE); CPPUNIT_ASSERT(object == handleManager->getObject(hObject)); handleManager->sessionClosed(4412412); // Object still exists as the hSession was invalid CPPUNIT_ASSERT(object == handleManager->getObject(hObject)); handleManager->allSessionsClosed(slotID); // Object is now gone as all sessions for the given slotID have been removed. CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject)); // Add an object and then destroy it. hObject = handleManager->addSessionObject(slotID, 4412412, true, object); CPPUNIT_ASSERT(hObject != CK_INVALID_HANDLE); handleManager->destroyObject(hObject); CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject)); hObject = handleManager->addTokenObject(slotID, false, object); CPPUNIT_ASSERT(hObject != CK_INVALID_HANDLE); handleManager->destroyObject(hObject); CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject)); // Create a valid session again hSession = handleManager->addSession(slotID, session); CPPUNIT_ASSERT(hSession != CK_INVALID_HANDLE); CPPUNIT_ASSERT(session == handleManager->getSession(hSession)); // Now some magic with a couple of objects // First add a public object hObject = handleManager->addTokenObject(slotID, false, object); CPPUNIT_ASSERT(hObject != CK_INVALID_HANDLE); CPPUNIT_ASSERT(object == handleManager->getObject(hObject)); // Now add a private object hObject2 = handleManager->addTokenObject(slotID, true, object2); CPPUNIT_ASSERT(hObject2 != CK_INVALID_HANDLE); CPPUNIT_ASSERT(object2 == handleManager->getObject(hObject2)); // Now add another private object hObject3 = handleManager->addTokenObject(slotID, true, object3); CPPUNIT_ASSERT(hObject3 != CK_INVALID_HANDLE); CPPUNIT_ASSERT(object3 == handleManager->getObject(hObject3)); // Adding the same object will return the same handle whether the object is marked private or public. CPPUNIT_ASSERT(hObject2 == handleManager->addTokenObject(slotID, true, object2)); // Because the private state of an object cannot be changed it won't be marked as public, it remains private CPPUNIT_ASSERT(hObject2 == handleManager->addTokenObject(slotID, false, object2)); // It is not allowed to migrate an object from one slot to another, so here we return an invalid handle. CPPUNIT_ASSERT(CK_INVALID_HANDLE == handleManager->addTokenObject(124121, false, object2)); // Now add another private session object hObject4 = handleManager->addSessionObject(slotID, hSession, true, object4); CPPUNIT_ASSERT(hObject4 != CK_INVALID_HANDLE); CPPUNIT_ASSERT(object4 == handleManager->getObject(hObject4)); // Now add another public session object hObject5 = handleManager->addSessionObject(slotID, hSession, false, object5); CPPUNIT_ASSERT(hObject5 != CK_INVALID_HANDLE); CPPUNIT_ASSERT(object5 == handleManager->getObject(hObject5)); // Logout, now private objects should be gone. handleManager->tokenLoggedOut(slotID); CPPUNIT_ASSERT(object == handleManager->getObject(hObject)); CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject2)); // should still be private and removed. CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject3)); CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject4)); CPPUNIT_ASSERT(object5 == handleManager->getObject(hObject5)); // Create another valid session for the slot hSession2 = handleManager->addSession(slotID, session2); CPPUNIT_ASSERT(hSession2 != CK_INVALID_HANDLE); CPPUNIT_ASSERT(session2 == handleManager->getSession(hSession2)); handleManager->sessionClosed(hSession); CPPUNIT_ASSERT(object == handleManager->getObject(hObject)); // token object should still be there. CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject5)); // session object should be gone. // Removing the last remaining session should kill the remaining handle. handleManager->sessionClosed(hSession2); CPPUNIT_ASSERT(NULL == handleManager->getObject(hObject)); // should be gone now. CPPUNIT_ASSERT(NULL == handleManager->getSession(hSession)); CPPUNIT_ASSERT(NULL == handleManager->getSession(hSession2)); // Create a valid session again hSession = handleManager->addSession(slotID, session); CPPUNIT_ASSERT(hSession != CK_INVALID_HANDLE); CPPUNIT_ASSERT(session == handleManager->getSession(hSession)); // Create another valid session for the slot hSession2 = handleManager->addSession(slotID, session2); CPPUNIT_ASSERT(hSession2 != CK_INVALID_HANDLE); CPPUNIT_ASSERT(session2 == handleManager->getSession(hSession2)); handleManager->allSessionsClosed(slotID); CPPUNIT_ASSERT(NULL == handleManager->getSession(hSession)); CPPUNIT_ASSERT(NULL == handleManager->getSession(hSession2)); } softhsm-2.0.0/src/lib/handle_mgr/test/Makefile.am0000664000175000017500000000123612533040716016572 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ -I$(srcdir)/../../data_mgr \ `cppunit-config --cflags` check_PROGRAMS = handlemgrtest handlemgrtest_SOURCES = handlemgrtest.cpp \ HandleManagerTests.cpp handlemgrtest_LDADD = ../../libsofthsm_convarch.la handlemgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` TESTS = handlemgrtest EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/handle_mgr/test/HandleManagerTests.h0000664000175000017500000000401112533040716020412 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HandleManagerTests.h Contains test cases to test the handle manager implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_HANDLEMANAGERTESTS_H #define _SOFTHSM_V2_HANDLEMANAGERTESTS_H #include #include "RNG.h" #include "HandleManager.h" class HandleManagerTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(HandleManagerTests); CPPUNIT_TEST(testHandleManager); CPPUNIT_TEST_SUITE_END(); public: void testHandleManager(); void setUp(); void tearDown(); private: HandleManager *handleManager; }; #endif // !_SOFTHSM_V2_HANDLEMANAGERTESTS_H softhsm-2.0.0/src/lib/handle_mgr/test/handlemgrtest.cpp0000664000175000017500000000362112533040716020103 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** handlemgrtest.cpp The main test executor for tests on the handle manager in SoftHSM v2 *****************************************************************************/ #include #include int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/handle_mgr/test/Makefile.in0000664000175000017500000010127712552216620016611 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = handlemgrtest$(EXEEXT) TESTS = handlemgrtest$(EXEEXT) subdir = src/lib/handle_mgr/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am_handlemgrtest_OBJECTS = handlemgrtest.$(OBJEXT) \ HandleManagerTests.$(OBJEXT) handlemgrtest_OBJECTS = $(am_handlemgrtest_OBJECTS) handlemgrtest_DEPENDENCIES = ../../libsofthsm_convarch.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = handlemgrtest_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(handlemgrtest_LDFLAGS) $(LDFLAGS) \ -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(handlemgrtest_SOURCES) DIST_SOURCES = $(handlemgrtest_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ -I$(srcdir)/../../data_mgr \ `cppunit-config --cflags` handlemgrtest_SOURCES = handlemgrtest.cpp \ HandleManagerTests.cpp handlemgrtest_LDADD = ../../libsofthsm_convarch.la handlemgrtest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/handle_mgr/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/handle_mgr/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list handlemgrtest$(EXEEXT): $(handlemgrtest_OBJECTS) $(handlemgrtest_DEPENDENCIES) $(EXTRA_handlemgrtest_DEPENDENCIES) @rm -f handlemgrtest$(EXEEXT) $(AM_V_CXXLD)$(handlemgrtest_LINK) $(handlemgrtest_OBJECTS) $(handlemgrtest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/HandleManagerTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/handlemgrtest.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? handlemgrtest.log: handlemgrtest$(EXEEXT) @p='handlemgrtest$(EXEEXT)'; \ b='handlemgrtest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/handle_mgr/Handle.cpp0000664000175000017500000000375712533040716015470 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Handle.h This class represents a single handle *****************************************************************************/ #include "Handle.h" // Constructor Handle::Handle(CK_HANDLE_KIND _kind, CK_SLOT_ID _slotID, CK_SESSION_HANDLE _hSession) : kind(_kind), slotID(_slotID), hSession(_hSession), object(NULL_PTR), isPrivate(false) { } Handle::Handle(CK_HANDLE_KIND _kind, CK_SLOT_ID _slotID) : kind(_kind), slotID(_slotID), hSession(CK_INVALID_HANDLE), object(NULL_PTR), isPrivate(false) { } Handle::Handle() : kind(CKH_INVALID), slotID(0), hSession(CK_INVALID_HANDLE), object(NULL_PTR), isPrivate(false) { } softhsm-2.0.0/src/lib/handle_mgr/Makefile.in0000664000175000017500000005615312552216620015634 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/lib/handle_mgr DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_handlemgr_la_LIBADD = am_libsofthsm_handlemgr_la_OBJECTS = HandleManager.lo Handle.lo libsofthsm_handlemgr_la_OBJECTS = \ $(am_libsofthsm_handlemgr_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_handlemgr_la_SOURCES) DIST_SOURCES = $(libsofthsm_handlemgr_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../slot_mgr \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../object_store \ -I$(srcdir)/../crypto \ -I$(srcdir)/../common \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_handlemgr.la libsofthsm_handlemgr_la_SOURCES = HandleManager.cpp \ Handle.cpp SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/handle_mgr/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/handle_mgr/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_handlemgr.la: $(libsofthsm_handlemgr_la_OBJECTS) $(libsofthsm_handlemgr_la_DEPENDENCIES) $(EXTRA_libsofthsm_handlemgr_la_DEPENDENCIES) $(AM_V_CXXLD)$(CXXLINK) $(libsofthsm_handlemgr_la_OBJECTS) $(libsofthsm_handlemgr_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Handle.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/HandleManager.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/handle_mgr/HandleManager.h0000664000175000017500000000757212533040716016427 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HandleManager.h Keeps track of the issued cryptoki handles within SoftHSM *****************************************************************************/ #ifndef _SOFTHSM_V2_HANDLEMANAGER_H #define _SOFTHSM_V2_HANDLEMANAGER_H #include "MutexFactory.h" #include "Handle.h" #include "cryptoki.h" #include #define CK_INTERNAL_SESSION_HANDLE CK_SESSION_HANDLE class HandleManager { public: HandleManager(); virtual ~HandleManager(); CK_SESSION_HANDLE addSession(CK_SLOT_ID slotID, CK_VOID_PTR session); CK_VOID_PTR getSession(const CK_SESSION_HANDLE hSession); // Add the session object and return a handle. For objects that have already been registered, check that the // slotID matches. The hSession may be different as the object may be added as part of a find objects operation. CK_OBJECT_HANDLE addSessionObject(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession, bool isPrivate, CK_VOID_PTR object); // Add the token object and return a handle. For objects that have already been registered, check that the // slotID mathces. CK_OBJECT_HANDLE addTokenObject(CK_SLOT_ID slotID, bool isPrivate, CK_VOID_PTR object); // Get the object pointer associated with the given object handle. CK_VOID_PTR getObject(const CK_OBJECT_HANDLE hObject); // Get the object handle for the object pointer that has been previously registered. // When the object is not found CK_INVALID_HANDLE is returned. CK_OBJECT_HANDLE getObjectHandle(CK_VOID_PTR object); // Remove the given object handle. void destroyObject(const CK_OBJECT_HANDLE hObject); // Remove the given session handle and all session object handles for the session. // The token object handles retrieved using the session will remain valid unless // this is the last session of a token being closed. In that case remove all token // object handles for the slot/token associated with the session. void sessionClosed(const CK_SESSION_HANDLE hSession); // Remove all session and object handles for the given slotID. // All handles for the given slotID will become invalid. void allSessionsClosed(const CK_SLOT_ID slotID); // Remove all handles to private objects for the given slotID. // All handles to public objects for the given slotID remain valid. void tokenLoggedOut(const CK_SLOT_ID slotID); private: Mutex* handlesMutex; std::map< CK_ULONG, Handle> handles; std::map< CK_VOID_PTR, CK_ULONG> objects; CK_ULONG handleCounter; }; #endif // !_SOFTHSM_V2_HANDLEMANAGER_H softhsm-2.0.0/src/lib/access.cpp0000664000175000017500000001043512533040716013425 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** access.cpp Implements the access rules. *****************************************************************************/ #include "access.h" #include #include // Checks if a read operation is allowed on a given object type. // // Type of session // Type of object R/O Public | R/W Public | R/O User | R/W User | R/W SO // ------------------------------------------------------------------------------ // Public session object OK | OK | OK | OK | OK // Private session object UNLI | UNLI | OK | OK | UNLI // Public token object OK | OK | OK | OK | OK // Private token object UNLI | UNLI | OK | OK | UNLI // // OK = CKR_OK // SRO = CKR_SESSION_READ_ONLY // UNLI = CKR_USER_NOT_LOGGED_IN // Can we do read operations? CK_RV haveRead(CK_STATE sessionState, CK_BBOOL /*isTokenObject*/, CK_BBOOL isPrivateObject) { switch (sessionState) { case CKS_RO_PUBLIC_SESSION: case CKS_RW_PUBLIC_SESSION: case CKS_RW_SO_FUNCTIONS: return isPrivateObject ? CKR_USER_NOT_LOGGED_IN : CKR_OK; case CKS_RO_USER_FUNCTIONS: case CKS_RW_USER_FUNCTIONS: return CKR_OK; } return CKR_GENERAL_ERROR; // internal error, switch should have covered every state } // Checks if a write operation is allowed on a given object type. // // Type of session // Type of object R/O Public | R/W Public | R/O User | R/W User | R/W SO // ------------------------------------------------------------------------------ // Public session object OK | OK | OK | OK | OK // Private session object UNLI | UNLI | OK | OK | UNLI // Public token object SRO | OK | SRO | OK | OK // Private token object SRO/UNLI | UNLI | SRO | OK | UNLI // // OK = CKR_OK // SRO = CKR_SESSION_READ_ONLY // UNLI = CKR_USER_NOT_LOGGED_IN // In the situation where both SRO and UNLI may be returned we favor SRO. // Can we do write operations? CK_RV haveWrite(CK_STATE sessionState, CK_BBOOL isTokenObject, CK_BBOOL isPrivateObject) { switch (sessionState) { case CKS_RO_PUBLIC_SESSION: if (isTokenObject) return CKR_SESSION_READ_ONLY; else return isPrivateObject ? CKR_USER_NOT_LOGGED_IN : CKR_OK; case CKS_RW_PUBLIC_SESSION: case CKS_RW_SO_FUNCTIONS: return isPrivateObject ? CKR_USER_NOT_LOGGED_IN : CKR_OK; case CKS_RO_USER_FUNCTIONS: return isTokenObject ? CKR_SESSION_READ_ONLY : CKR_OK; case CKS_RW_USER_FUNCTIONS: return CKR_OK; } return CKR_GENERAL_ERROR; // internal error, switch should have covered every state } softhsm-2.0.0/src/lib/P11Objects.h0000664000175000017500000001634412533040716013511 00000000000000/* * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** P11Objects.h This class respresent a PKCS#11 object *****************************************************************************/ #ifndef _SOFTHSM_V2_P11OBJECTS_H #define _SOFTHSM_V2_P11OBJECTS_H #include "OSObject.h" #include "P11Attributes.h" #include "Token.h" #include "cryptoki.h" #include class P11Object { public: // Destructor virtual ~P11Object(); protected: // Constructor P11Object(); // The object OSObject* osobject; // The attributes std::map attributes; public: // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; public: CK_RV loadTemplate(Token *token, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount); // Save template CK_RV saveTemplate(Token *token, bool isPrivate, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, int op); protected: bool isPrivate(); bool isCopyable(); bool isModifiable(); }; class P11DataObj : public P11Object { public: // Constructor P11DataObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11CertificateObj : public P11Object { protected: // Constructor P11CertificateObj(); // Add attributes virtual bool init(OSObject *inobject); bool initialized; }; class P11X509CertificateObj : public P11CertificateObj { public: // Constructor P11X509CertificateObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11OpenPGPPublicKeyObj : public P11CertificateObj { public: // Constructor P11OpenPGPPublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11KeyObj : public P11Object { protected: // Constructor P11KeyObj(); // Add attributes virtual bool init(OSObject *inobject); bool initialized; }; class P11PublicKeyObj : public P11KeyObj { protected: // Constructor P11PublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); bool initialized; }; class P11RSAPublicKeyObj : public P11PublicKeyObj { public: // Constructor P11RSAPublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DSAPublicKeyObj : public P11PublicKeyObj { public: // Constructor P11DSAPublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11ECPublicKeyObj : public P11PublicKeyObj { public: // Constructor P11ECPublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DHPublicKeyObj : public P11PublicKeyObj { public: // Constructor P11DHPublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11GOSTPublicKeyObj : public P11PublicKeyObj { public: // Constructor P11GOSTPublicKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11PrivateKeyObj : public P11KeyObj { protected: // Constructor P11PrivateKeyObj(); // Add attributes virtual bool init(OSObject *inobject); bool initialized; }; class P11RSAPrivateKeyObj : public P11PrivateKeyObj { public: // Constructor P11RSAPrivateKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DSAPrivateKeyObj : public P11PrivateKeyObj { public: // Constructor P11DSAPrivateKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11ECPrivateKeyObj : public P11PrivateKeyObj { public: // Constructor P11ECPrivateKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DHPrivateKeyObj : public P11PrivateKeyObj { public: // Constructor P11DHPrivateKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11GOSTPrivateKeyObj : public P11PrivateKeyObj { public: // Constructor P11GOSTPrivateKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11SecretKeyObj : public P11KeyObj { protected: // Constructor P11SecretKeyObj(); // Add attributes virtual bool init(OSObject *inobject); bool initialized; }; class P11GenericSecretKeyObj : public P11SecretKeyObj { public: // Constructor P11GenericSecretKeyObj(); // Add attributes virtual bool init(OSObject *inobject); // Better than multiply subclasses virtual bool setKeyType(CK_KEY_TYPE inKeytype); virtual CK_KEY_TYPE getKeyType(); protected: bool initialized; CK_KEY_TYPE keytype; }; class P11AESSecretKeyObj : public P11SecretKeyObj { public: // Constructor P11AESSecretKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DESSecretKeyObj : public P11SecretKeyObj { public: // Constructor P11DESSecretKeyObj(); // Add attributes virtual bool init(OSObject *inobject); // Better than multiply subclasses virtual bool setKeyType(CK_KEY_TYPE inKeytype); virtual CK_KEY_TYPE getKeyType(); protected: bool initialized; CK_KEY_TYPE keytype; }; class P11GOSTSecretKeyObj : public P11SecretKeyObj { public: // Constructor P11GOSTSecretKeyObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DomainObj : public P11Object { protected: // Constructor P11DomainObj(); // Add attributes virtual bool init(OSObject *inobject); bool initialized; }; class P11DSADomainObj : public P11DomainObj { public: // Constructor P11DSADomainObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; class P11DHDomainObj : public P11DomainObj { public: // Constructor P11DHDomainObj(); // Add attributes virtual bool init(OSObject *inobject); protected: bool initialized; }; #endif // !_SOFTHSM_V2_P11OBJECTS_H softhsm-2.0.0/src/lib/cryptoki_compat/0000775000175000017500000000000012552220146014742 500000000000000softhsm-2.0.0/src/lib/cryptoki_compat/pkcs11.h0000664000175000017500000015121212533040716016141 00000000000000/* pkcs11.h Copyright 2006, 2007 g10 Code GmbH Copyright 2006 Andreas Jellinghaus This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* Please submit changes back to the Scute project at http://www.scute.org/ (or send them to marcus@g10code.com), so that they can be picked up by other projects from there as well. */ /* This file is a modified implementation of the PKCS #11 standard by RSA Security Inc. It is mostly a drop-in replacement, with the following change: This header file does not require any macro definitions by the user (like CK_DEFINE_FUNCTION etc). In fact, it defines those macros for you (if useful, some are missing, let me know if you need more). There is an additional API available that does comply better to the GNU coding standard. It can be switched on by defining CRYPTOKI_GNU before including this header file. For this, the following changes are made to the specification: All structure types are changed to a "struct ck_foo" where CK_FOO is the type name in PKCS #11. All non-structure types are changed to ck_foo_t where CK_FOO is the lowercase version of the type name in PKCS #11. The basic types (CK_ULONG et al.) are removed without substitute. All members of structures are modified in the following way: Type indication prefixes are removed, and underscore characters are inserted before words. Then the result is lowercased. Note that function names are still in the original case, as they need for ABI compatibility. CK_FALSE, CK_TRUE and NULL_PTR are removed without substitute. Use . If CRYPTOKI_COMPAT is defined before including this header file, then none of the API changes above take place, and the API is the one defined by the PKCS #11 standard. */ #ifndef PKCS11_H #define PKCS11_H 1 #if defined(__cplusplus) extern "C" { #endif /* The version of cryptoki we implement. The revision is changed with each modification of this file. If you do not use the "official" version of this file, please consider deleting the revision macro (you may use a macro with a different name to keep track of your versions). */ #define CRYPTOKI_VERSION_MAJOR 2 #define CRYPTOKI_VERSION_MINOR 30 #define CRYPTOKI_VERSION_REVISION 0 #define CRYPTOKI_VERSION_AMENDMENT 0 /* Compatibility interface is default, unless CRYPTOKI_GNU is given. */ #ifndef CRYPTOKI_GNU #ifndef CRYPTOKI_COMPAT #define CRYPTOKI_COMPAT 1 #endif #endif /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) /* There is a matching pop below. */ #pragma pack(push, cryptoki, 1) #ifdef CRYPTOKI_EXPORTS #define CK_SPEC __declspec(dllexport) #else #define CK_SPEC __declspec(dllimport) #endif #else #if defined(CRYPTOKI_VISIBILITY) && defined(CRYPTOKI_EXPORTS) #define CK_SPEC __attribute__((visibility("default"))) #else #define CK_SPEC #endif #endif #ifdef CRYPTOKI_COMPAT /* If we are in compatibility mode, switch all exposed names to the PKCS #11 variant. There are corresponding #undefs below. */ #define ck_flags_t CK_FLAGS #define ck_version _CK_VERSION #define ck_info _CK_INFO #define cryptoki_version cryptokiVersion #define manufacturer_id manufacturerID #define library_description libraryDescription #define library_version libraryVersion #define ck_notification_t CK_NOTIFICATION #define ck_slot_id_t CK_SLOT_ID #define ck_slot_info _CK_SLOT_INFO #define slot_description slotDescription #define hardware_version hardwareVersion #define firmware_version firmwareVersion #define ck_token_info _CK_TOKEN_INFO #define serial_number serialNumber #define max_session_count ulMaxSessionCount #define session_count ulSessionCount #define max_rw_session_count ulMaxRwSessionCount #define rw_session_count ulRwSessionCount #define max_pin_len ulMaxPinLen #define min_pin_len ulMinPinLen #define total_public_memory ulTotalPublicMemory #define free_public_memory ulFreePublicMemory #define total_private_memory ulTotalPrivateMemory #define free_private_memory ulFreePrivateMemory #define utc_time utcTime #define ck_session_handle_t CK_SESSION_HANDLE #define ck_user_type_t CK_USER_TYPE #define ck_state_t CK_STATE #define ck_session_info _CK_SESSION_INFO #define slot_id slotID #define device_error ulDeviceError #define ck_object_handle_t CK_OBJECT_HANDLE #define ck_object_class_t CK_OBJECT_CLASS #define ck_hw_feature_type_t CK_HW_FEATURE_TYPE #define ck_key_type_t CK_KEY_TYPE #define ck_certificate_type_t CK_CERTIFICATE_TYPE #define ck_attribute_type_t CK_ATTRIBUTE_TYPE #define ck_attribute _CK_ATTRIBUTE #define value pValue #define value_len ulValueLen #define ck_date _CK_DATE #define ck_mechanism_type_t CK_MECHANISM_TYPE #define ck_mechanism _CK_MECHANISM #define parameter pParameter #define parameter_len ulParameterLen #define ck_mechanism_info _CK_MECHANISM_INFO #define min_key_size ulMinKeySize #define max_key_size ulMaxKeySize #define hash_alg hashAlg #define source_data pSourceData #define source_data_len ulSourceDataLen #define slen sLen #define ck_ec_kdf_type_t CK_EC_KDF_TYPE #define shared_data_len ulSharedDataLen #define shared_data pSharedData #define public_data_len ulPublicDataLen #define public_data pPublicData #define private_data_len ulPrivateDataLen #define private_data hPrivateData #define public_data_len2 ulPublicDataLen2 #define public_data2 pPublicData2 #define public_key publicKey #define ck_x9_42_dh_kdf_type_t CK_X9_42_DH_KDF_TYPE #define other_info_len ulOtherInfoLen #define other_info pOtherInfo #define data pData #define len ulLen #define ck_rv_t CK_RV #define ck_notify_t CK_NOTIFY #define ck_function_list _CK_FUNCTION_LIST #define ck_createmutex_t CK_CREATEMUTEX #define ck_destroymutex_t CK_DESTROYMUTEX #define ck_lockmutex_t CK_LOCKMUTEX #define ck_unlockmutex_t CK_UNLOCKMUTEX #define ck_c_initialize_args _CK_C_INITIALIZE_ARGS #define create_mutex CreateMutex #define destroy_mutex DestroyMutex #define lock_mutex LockMutex #define unlock_mutex UnlockMutex #define reserved pReserved #endif /* CRYPTOKI_COMPAT */ typedef unsigned long ck_flags_t; struct ck_version { unsigned char major; unsigned char minor; }; struct ck_info { struct ck_version cryptoki_version; unsigned char manufacturer_id[32]; ck_flags_t flags; unsigned char library_description[32]; struct ck_version library_version; }; typedef unsigned long ck_notification_t; #define CKN_SURRENDER (0) #define CKN_OTP_CHANGED (1) typedef unsigned long ck_slot_id_t; struct ck_slot_info { unsigned char slot_description[64]; unsigned char manufacturer_id[32]; ck_flags_t flags; struct ck_version hardware_version; struct ck_version firmware_version; }; #define CKF_TOKEN_PRESENT (1 << 0) #define CKF_REMOVABLE_DEVICE (1 << 1) #define CKF_HW_SLOT (1 << 2) #define CKF_ARRAY_ATTRIBUTE (1 << 30) struct ck_token_info { unsigned char label[32]; unsigned char manufacturer_id[32]; unsigned char model[16]; unsigned char serial_number[16]; ck_flags_t flags; unsigned long max_session_count; unsigned long session_count; unsigned long max_rw_session_count; unsigned long rw_session_count; unsigned long max_pin_len; unsigned long min_pin_len; unsigned long total_public_memory; unsigned long free_public_memory; unsigned long total_private_memory; unsigned long free_private_memory; struct ck_version hardware_version; struct ck_version firmware_version; unsigned char utc_time[16]; }; #define CKF_RNG (1 << 0) #define CKF_WRITE_PROTECTED (1 << 1) #define CKF_LOGIN_REQUIRED (1 << 2) #define CKF_USER_PIN_INITIALIZED (1 << 3) #define CKF_RESTORE_KEY_NOT_NEEDED (1 << 5) #define CKF_CLOCK_ON_TOKEN (1 << 6) #define CKF_PROTECTED_AUTHENTICATION_PATH (1 << 8) #define CKF_DUAL_CRYPTO_OPERATIONS (1 << 9) #define CKF_TOKEN_INITIALIZED (1 << 10) #define CKF_SECONDARY_AUTHENTICATION (1 << 11) #define CKF_USER_PIN_COUNT_LOW (1 << 16) #define CKF_USER_PIN_FINAL_TRY (1 << 17) #define CKF_USER_PIN_LOCKED (1 << 18) #define CKF_USER_PIN_TO_BE_CHANGED (1 << 19) #define CKF_SO_PIN_COUNT_LOW (1 << 20) #define CKF_SO_PIN_FINAL_TRY (1 << 21) #define CKF_SO_PIN_LOCKED (1 << 22) #define CKF_SO_PIN_TO_BE_CHANGED (1 << 23) #define CKF_ERROR_STATE (1 << 24) #define CK_UNAVAILABLE_INFORMATION ((unsigned long) -1) #define CK_EFFECTIVELY_INFINITE (0) typedef unsigned long ck_session_handle_t; #define CK_INVALID_HANDLE (0) typedef unsigned long ck_user_type_t; #define CKU_SO (0) #define CKU_USER (1) #define CKU_CONTEXT_SPECIFIC (2) typedef unsigned long ck_state_t; #define CKS_RO_PUBLIC_SESSION (0) #define CKS_RO_USER_FUNCTIONS (1) #define CKS_RW_PUBLIC_SESSION (2) #define CKS_RW_USER_FUNCTIONS (3) #define CKS_RW_SO_FUNCTIONS (4) struct ck_session_info { ck_slot_id_t slot_id; ck_state_t state; ck_flags_t flags; unsigned long device_error; }; #define CKF_RW_SESSION (1 << 1) #define CKF_SERIAL_SESSION (1 << 2) typedef unsigned long ck_object_handle_t; typedef unsigned long ck_object_class_t; #define CKO_DATA (0) #define CKO_CERTIFICATE (1) #define CKO_PUBLIC_KEY (2) #define CKO_PRIVATE_KEY (3) #define CKO_SECRET_KEY (4) #define CKO_HW_FEATURE (5) #define CKO_DOMAIN_PARAMETERS (6) #define CKO_MECHANISM (7) #define CKO_OTP_KEY (8) #define CKO_VENDOR_DEFINED ((unsigned long) (1ul << 31)) typedef unsigned long ck_hw_feature_type_t; #define CKH_MONOTONIC_COUNTER (1) #define CKH_CLOCK (2) #define CKH_USER_INTERFACE (3) #define CKH_VENDOR_DEFINED ((unsigned long) (1ul << 31)) typedef unsigned long ck_key_type_t; #define CKK_RSA (0) #define CKK_DSA (1) #define CKK_DH (2) #define CKK_ECDSA (3) #define CKK_EC (3) #define CKK_X9_42_DH (4) #define CKK_KEA (5) #define CKK_GENERIC_SECRET (0x10) #define CKK_RC2 (0x11) #define CKK_RC4 (0x12) #define CKK_DES (0x13) #define CKK_DES2 (0x14) #define CKK_DES3 (0x15) #define CKK_CAST (0x16) #define CKK_CAST3 (0x17) #define CKK_CAST5 (0x18) #define CKK_CAST128 (0x18) #define CKK_RC5 (0x19) #define CKK_IDEA (0x1a) #define CKK_SKIPJACK (0x1b) #define CKK_BATON (0x1c) #define CKK_JUNIPER (0x1d) #define CKK_CDMF (0x1e) #define CKK_AES (0x1f) #define CKK_BLOWFISH (0x20) #define CKK_TWOFISH (0x21) #define CKK_SECURID (0x22) #define CKK_HOTP (0x23) #define CKK_ACTI (0x24) #define CKK_CAMELLIA (0x25) #define CKK_ARIA (0x26) #define CKK_MD5_HMAC (0x27) #define CKK_SHA_1_HMAC (0x28) #define CKK_RIPEMD128_HMAC (0x29) #define CKK_RIPEMD160_HMAC (0x2A) #define CKK_SHA256_HMAC (0x2B) #define CKK_SHA384_HMAC (0x2C) #define CKK_SHA512_HMAC (0x2D) #define CKK_SHA224_HMAC (0x2E) #define CKK_SEED (0x2F) #define CKK_GOSTR3410 (0x30) #define CKK_GOSTR3411 (0x31) #define CKK_GOST28147 (0x32) #define CKK_VENDOR_DEFINED ((unsigned long) (1ul << 31)) typedef unsigned long ck_certificate_type_t; #define CKC_X_509 (0) #define CKC_X_509_ATTR_CERT (1) #define CKC_WTLS (2) #define CKC_VENDOR_DEFINED ((unsigned long) (1ul << 31)) #define CKC_OPENPGP (CKC_VENDOR_DEFINED|0x00504750) #define CK_OTP_FORMAT_DECIMAL (0) #define CK_OTP_FORMAT_HEXADECIMAL (1) #define CK_OTP_FORMAT_ALPHANUMERIC (2) #define CK_OTP_FORMAT_BINARY (3) #define CK_OTP_PARAM_IGNORED (0) #define CK_OTP_PARAM_OPTIONAL (1) #define CK_OTP_PARAM_MANDATORY (2) typedef unsigned long ck_attribute_type_t; #define CKA_CLASS (0) #define CKA_TOKEN (1) #define CKA_PRIVATE (2) #define CKA_LABEL (3) #define CKA_APPLICATION (0x10) #define CKA_VALUE (0x11) #define CKA_OBJECT_ID (0x12) #define CKA_CERTIFICATE_TYPE (0x80) #define CKA_ISSUER (0x81) #define CKA_SERIAL_NUMBER (0x82) #define CKA_AC_ISSUER (0x83) #define CKA_OWNER (0x84) #define CKA_ATTR_TYPES (0x85) #define CKA_TRUSTED (0x86) #define CKA_CERTIFICATE_CATEGORY (0x87) #define CKA_JAVA_MIDP_SECURITY_DOMAIN (0x88) #define CKA_URL (0x89) #define CKA_HASH_OF_SUBJECT_PUBLIC_KEY (0x8a) #define CKA_HASH_OF_ISSUER_PUBLIC_KEY (0x8b) #define CKA_NAME_HASH_ALGORITHM (0x8c) #define CKA_CHECK_VALUE (0x90) #define CKA_KEY_TYPE (0x100) #define CKA_SUBJECT (0x101) #define CKA_ID (0x102) #define CKA_SENSITIVE (0x103) #define CKA_ENCRYPT (0x104) #define CKA_DECRYPT (0x105) #define CKA_WRAP (0x106) #define CKA_UNWRAP (0x107) #define CKA_SIGN (0x108) #define CKA_SIGN_RECOVER (0x109) #define CKA_VERIFY (0x10a) #define CKA_VERIFY_RECOVER (0x10b) #define CKA_DERIVE (0x10c) #define CKA_START_DATE (0x110) #define CKA_END_DATE (0x111) #define CKA_MODULUS (0x120) #define CKA_MODULUS_BITS (0x121) #define CKA_PUBLIC_EXPONENT (0x122) #define CKA_PRIVATE_EXPONENT (0x123) #define CKA_PRIME_1 (0x124) #define CKA_PRIME_2 (0x125) #define CKA_EXPONENT_1 (0x126) #define CKA_EXPONENT_2 (0x127) #define CKA_COEFFICIENT (0x128) #define CKA_PRIME (0x130) #define CKA_SUBPRIME (0x131) #define CKA_BASE (0x132) #define CKA_PRIME_BITS (0x133) #define CKA_SUB_PRIME_BITS (0x134) #define CKA_SUBPRIME_BITS (0x134) #define CKA_VALUE_BITS (0x160) #define CKA_VALUE_LEN (0x161) #define CKA_EXTRACTABLE (0x162) #define CKA_LOCAL (0x163) #define CKA_NEVER_EXTRACTABLE (0x164) #define CKA_ALWAYS_SENSITIVE (0x165) #define CKA_KEY_GEN_MECHANISM (0x166) #define CKA_MODIFIABLE (0x170) #define CKA_COPYABLE (0x171) #define CKA_ECDSA_PARAMS (0x180) #define CKA_EC_PARAMS (0x180) #define CKA_EC_POINT (0x181) #define CKA_SECONDARY_AUTH (0x200) #define CKA_AUTH_PIN_FLAGS (0x201) #define CKA_ALWAYS_AUTHENTICATE (0x202) #define CKA_WRAP_WITH_TRUSTED (0x210) #define CKA_OTP_FORMAT (0x220) #define CKA_OTP_LENGTH (0x221) #define CKA_OTP_TIME_INTERVAL (0x222) #define CKA_OTP_USER_FRIENDLY_MODE (0x223) #define CKA_OTP_CHALLENGE_REQUIREMENT (0x224) #define CKA_OTP_TIME_REQUIREMENT (0x225) #define CKA_OTP_COUNTER_REQUIREMENT (0x226) #define CKA_OTP_PIN_REQUIREMENT (0x227) #define CKA_OTP_COUNTER (0x22E) #define CKA_OTP_TIME (0x22F) #define CKA_OTP_USER_IDENTIFIER (0x22A) #define CKA_OTP_SERVICE_IDENTIFIER (0x22B) #define CKA_OTP_SERVICE_LOGO (0x22C) #define CKA_OTP_SERVICE_LOGO_TYPE (0x22D) #define CKA_GOSTR3410_PARAMS (0x250) #define CKA_GOSTR3411_PARAMS (0x251) #define CKA_GOST28147_PARAMS (0x252) #define CKA_HW_FEATURE_TYPE (0x300) #define CKA_RESET_ON_INIT (0x301) #define CKA_HAS_RESET (0x302) #define CKA_PIXEL_X (0x400) #define CKA_PIXEL_Y (0x401) #define CKA_RESOLUTION (0x402) #define CKA_CHAR_ROWS (0x403) #define CKA_CHAR_COLUMNS (0x404) #define CKA_COLOR (0x405) #define CKA_BITS_PER_PIXEL (0x406) #define CKA_CHAR_SETS (0x480) #define CKA_ENCODING_METHODS (0x481) #define CKA_MIME_TYPES (0x482) #define CKA_MECHANISM_TYPE (0x500) #define CKA_REQUIRED_CMS_ATTRIBUTES (0x501) #define CKA_DEFAULT_CMS_ATTRIBUTES (0x502) #define CKA_SUPPORTED_CMS_ATTRIBUTES (0x503) #define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x211) #define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x212) #define CKA_DERIVE_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x213) #define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE | 0x600) #define CKA_VENDOR_DEFINED ((unsigned long) (1ul << 31)) struct ck_attribute { ck_attribute_type_t type; void *value; unsigned long value_len; }; struct ck_date { unsigned char year[4]; unsigned char month[2]; unsigned char day[2]; }; typedef unsigned long ck_mechanism_type_t; #define CKM_RSA_PKCS_KEY_PAIR_GEN (0) #define CKM_RSA_PKCS (1) #define CKM_RSA_9796 (2) #define CKM_RSA_X_509 (3) #define CKM_MD2_RSA_PKCS (4) #define CKM_MD5_RSA_PKCS (5) #define CKM_SHA1_RSA_PKCS (6) #define CKM_RIPEMD128_RSA_PKCS (7) #define CKM_RIPEMD160_RSA_PKCS (8) #define CKM_RSA_PKCS_OAEP (9) #define CKM_RSA_X9_31_KEY_PAIR_GEN (0xa) #define CKM_RSA_X9_31 (0xb) #define CKM_SHA1_RSA_X9_31 (0xc) #define CKM_RSA_PKCS_PSS (0xd) #define CKM_SHA1_RSA_PKCS_PSS (0xe) #define CKM_DSA_KEY_PAIR_GEN (0x10) #define CKM_DSA (0x11) #define CKM_DSA_SHA1 (0x12) #define CKM_DSA_SHA224 (0x13) #define CKM_DSA_SHA256 (0x14) #define CKM_DSA_SHA384 (0x15) #define CKM_DSA_SHA512 (0x16) #define CKM_DH_PKCS_KEY_PAIR_GEN (0x20) #define CKM_DH_PKCS_DERIVE (0x21) #define CKM_X9_42_DH_KEY_PAIR_GEN (0x30) #define CKM_X9_42_DH_DERIVE (0x31) #define CKM_X9_42_DH_HYBRID_DERIVE (0x32) #define CKM_X9_42_MQV_DERIVE (0x33) #define CKM_SHA256_RSA_PKCS (0x40) #define CKM_SHA384_RSA_PKCS (0x41) #define CKM_SHA512_RSA_PKCS (0x42) #define CKM_SHA256_RSA_PKCS_PSS (0x43) #define CKM_SHA384_RSA_PKCS_PSS (0x44) #define CKM_SHA512_RSA_PKCS_PSS (0x45) #define CKM_SHA224_RSA_PKCS (0x46) #define CKM_SHA224_RSA_PKCS_PSS (0x47) #define CKM_RC2_KEY_GEN (0x100) #define CKM_RC2_ECB (0x101) #define CKM_RC2_CBC (0x102) #define CKM_RC2_MAC (0x103) #define CKM_RC2_MAC_GENERAL (0x104) #define CKM_RC2_CBC_PAD (0x105) #define CKM_RC4_KEY_GEN (0x110) #define CKM_RC4 (0x111) #define CKM_DES_KEY_GEN (0x120) #define CKM_DES_ECB (0x121) #define CKM_DES_CBC (0x122) #define CKM_DES_MAC (0x123) #define CKM_DES_MAC_GENERAL (0x124) #define CKM_DES_CBC_PAD (0x125) #define CKM_DES2_KEY_GEN (0x130) #define CKM_DES3_KEY_GEN (0x131) #define CKM_DES3_ECB (0x132) #define CKM_DES3_CBC (0x133) #define CKM_DES3_MAC (0x134) #define CKM_DES3_MAC_GENERAL (0x135) #define CKM_DES3_CBC_PAD (0x136) #define CKM_DES3_CMAC_GENERAL (0x137) #define CKM_DES3_CMAC (0x138) #define CKM_CDMF_KEY_GEN (0x140) #define CKM_CDMF_ECB (0x141) #define CKM_CDMF_CBC (0x142) #define CKM_CDMF_MAC (0x143) #define CKM_CDMF_MAC_GENERAL (0x144) #define CKM_CDMF_CBC_PAD (0x145) #define CKM_DES_OFB64 (0x150) #define CKM_DES_OFB8 (0x151) #define CKM_DES_CFB64 (0x152) #define CKM_DES_CFB8 (0x153) #define CKM_MD2 (0x200) #define CKM_MD2_HMAC (0x201) #define CKM_MD2_HMAC_GENERAL (0x202) #define CKM_MD5 (0x210) #define CKM_MD5_HMAC (0x211) #define CKM_MD5_HMAC_GENERAL (0x212) #define CKM_SHA_1 (0x220) #define CKM_SHA_1_HMAC (0x221) #define CKM_SHA_1_HMAC_GENERAL (0x222) #define CKM_RIPEMD128 (0x230) #define CKM_RIPEMD128_HMAC (0x231) #define CKM_RIPEMD128_HMAC_GENERAL (0x232) #define CKM_RIPEMD160 (0x240) #define CKM_RIPEMD160_HMAC (0x241) #define CKM_RIPEMD160_HMAC_GENERAL (0x242) #define CKM_SHA256 (0x250) #define CKM_SHA256_HMAC (0x251) #define CKM_SHA256_HMAC_GENERAL (0x252) #define CKM_SHA224 (0x255) #define CKM_SHA224_HMAC (0x256) #define CKM_SHA224_HMAC_GENERAL (0x257) #define CKM_SHA384 (0x260) #define CKM_SHA384_HMAC (0x261) #define CKM_SHA384_HMAC_GENERAL (0x262) #define CKM_SHA512 (0x270) #define CKM_SHA512_HMAC (0x271) #define CKM_SHA512_HMAC_GENERAL (0x272) #define CKM_SECURID_KEY_GEN (0x280) #define CKM_SECURID (0x282) #define CKM_HOTP_KEY_GEN (0x290) #define CKM_HOTP (0x291) #define CKM_ACTI (0x2A0) #define CKM_ACTI_KEY_GEN (0x2A1) #define CKM_CAST_KEY_GEN (0x300) #define CKM_CAST_ECB (0x301) #define CKM_CAST_CBC (0x302) #define CKM_CAST_MAC (0x303) #define CKM_CAST_MAC_GENERAL (0x304) #define CKM_CAST_CBC_PAD (0x305) #define CKM_CAST3_KEY_GEN (0x310) #define CKM_CAST3_ECB (0x311) #define CKM_CAST3_CBC (0x312) #define CKM_CAST3_MAC (0x313) #define CKM_CAST3_MAC_GENERAL (0x314) #define CKM_CAST3_CBC_PAD (0x315) #define CKM_CAST5_KEY_GEN (0x320) #define CKM_CAST128_KEY_GEN (0x320) #define CKM_CAST5_ECB (0x321) #define CKM_CAST128_ECB (0x321) #define CKM_CAST5_CBC (0x322) #define CKM_CAST128_CBC (0x322) #define CKM_CAST5_MAC (0x323) #define CKM_CAST128_MAC (0x323) #define CKM_CAST5_MAC_GENERAL (0x324) #define CKM_CAST128_MAC_GENERAL (0x324) #define CKM_CAST5_CBC_PAD (0x325) #define CKM_CAST128_CBC_PAD (0x325) #define CKM_RC5_KEY_GEN (0x330) #define CKM_RC5_ECB (0x331) #define CKM_RC5_CBC (0x332) #define CKM_RC5_MAC (0x333) #define CKM_RC5_MAC_GENERAL (0x334) #define CKM_RC5_CBC_PAD (0x335) #define CKM_IDEA_KEY_GEN (0x340) #define CKM_IDEA_ECB (0x341) #define CKM_IDEA_CBC (0x342) #define CKM_IDEA_MAC (0x343) #define CKM_IDEA_MAC_GENERAL (0x344) #define CKM_IDEA_CBC_PAD (0x345) #define CKM_GENERIC_SECRET_KEY_GEN (0x350) #define CKM_CONCATENATE_BASE_AND_KEY (0x360) #define CKM_CONCATENATE_BASE_AND_DATA (0x362) #define CKM_CONCATENATE_DATA_AND_BASE (0x363) #define CKM_XOR_BASE_AND_DATA (0x364) #define CKM_EXTRACT_KEY_FROM_KEY (0x365) #define CKM_SSL3_PRE_MASTER_KEY_GEN (0x370) #define CKM_SSL3_MASTER_KEY_DERIVE (0x371) #define CKM_SSL3_KEY_AND_MAC_DERIVE (0x372) #define CKM_SSL3_MASTER_KEY_DERIVE_DH (0x373) #define CKM_TLS_PRE_MASTER_KEY_GEN (0x374) #define CKM_TLS_MASTER_KEY_DERIVE (0x375) #define CKM_TLS_KEY_AND_MAC_DERIVE (0x376) #define CKM_TLS_MASTER_KEY_DERIVE_DH (0x377) #define CKM_TLS_PRF (0x378) #define CKM_SSL3_MD5_MAC (0x380) #define CKM_SSL3_SHA1_MAC (0x381) #define CKM_MD5_KEY_DERIVATION (0x390) #define CKM_MD2_KEY_DERIVATION (0x391) #define CKM_SHA1_KEY_DERIVATION (0x392) #define CKM_SHA256_KEY_DERIVATION (0x393) #define CKM_SHA384_KEY_DERIVATION (0x394) #define CKM_SHA512_KEY_DERIVATION (0x395) #define CKM_SHA224_KEY_DERIVATION (0x396) #define CKM_PBE_MD2_DES_CBC (0x3a0) #define CKM_PBE_MD5_DES_CBC (0x3a1) #define CKM_PBE_MD5_CAST_CBC (0x3a2) #define CKM_PBE_MD5_CAST3_CBC (0x3a3) #define CKM_PBE_MD5_CAST5_CBC (0x3a4) #define CKM_PBE_MD5_CAST128_CBC (0x3a4) #define CKM_PBE_SHA1_CAST5_CBC (0x3a5) #define CKM_PBE_SHA1_CAST128_CBC (0x3a5) #define CKM_PBE_SHA1_RC4_128 (0x3a6) #define CKM_PBE_SHA1_RC4_40 (0x3a7) #define CKM_PBE_SHA1_DES3_EDE_CBC (0x3a8) #define CKM_PBE_SHA1_DES2_EDE_CBC (0x3a9) #define CKM_PBE_SHA1_RC2_128_CBC (0x3aa) #define CKM_PBE_SHA1_RC2_40_CBC (0x3ab) #define CKM_PKCS5_PBKD2 (0x3b0) #define CKM_PBA_SHA1_WITH_SHA1_HMAC (0x3c0) #define CKM_WTLS_PRE_MASTER_KEY_GEN (0x3d0) #define CKM_WTLS_MASTER_KEY_DERIVE (0x3d1) #define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC (0x3d2) #define CKM_WTLS_PRF (0x3d3) #define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE (0x3d4) #define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE (0x3d5) #define CKM_KEY_WRAP_LYNKS (0x400) #define CKM_KEY_WRAP_SET_OAEP (0x401) #define CKM_CMS_SIG (0x500) #define CKM_KIP_DERIVE (0x510) #define CKM_KIP_WRAP (0x511) #define CKM_KIP_MAC (0x512) #define CKM_CAMELLIA_KEY_GEN (0x550) #define CKM_CAMELLIA_ECB (0x551) #define CKM_CAMELLIA_CBC (0x552) #define CKM_CAMELLIA_MAC (0x553) #define CKM_CAMELLIA_MAC_GENERAL (0x554) #define CKM_CAMELLIA_CBC_PAD (0x555) #define CKM_CAMELLIA_ECB_ENCRYPT_DATA (0x556) #define CKM_CAMELLIA_CBC_ENCRYPT_DATA (0x557) #define CKM_CAMELLIA_CTR (0x558) #define CKM_ARIA_KEY_GEN (0x560) #define CKM_ARIA_ECB (0x561) #define CKM_ARIA_CBC (0x562) #define CKM_ARIA_MAC (0x563) #define CKM_ARIA_MAC_GENERAL (0x564) #define CKM_ARIA_CBC_PAD (0x565) #define CKM_ARIA_ECB_ENCRYPT_DATA (0x566) #define CKM_ARIA_CBC_ENCRYPT_DATA (0x567) #define CKM_SEED_KEY_GEN (0x650) #define CKM_SEED_ECB (0x651) #define CKM_SEED_CBC (0x652) #define CKM_SEED_MAC (0x653) #define CKM_SEED_MAC_GENERAL (0x654) #define CKM_SEED_CBC_PAD (0x655) #define CKM_SEED_ECB_ENCRYPT_DATA (0x656) #define CKM_SEED_CBC_ENCRYPT_DATA (0x657) #define CKM_SKIPJACK_KEY_GEN (0x1000) #define CKM_SKIPJACK_ECB64 (0x1001) #define CKM_SKIPJACK_CBC64 (0x1002) #define CKM_SKIPJACK_OFB64 (0x1003) #define CKM_SKIPJACK_CFB64 (0x1004) #define CKM_SKIPJACK_CFB32 (0x1005) #define CKM_SKIPJACK_CFB16 (0x1006) #define CKM_SKIPJACK_CFB8 (0x1007) #define CKM_SKIPJACK_WRAP (0x1008) #define CKM_SKIPJACK_PRIVATE_WRAP (0x1009) #define CKM_SKIPJACK_RELAYX (0x100a) #define CKM_KEA_KEY_PAIR_GEN (0x1010) #define CKM_KEA_KEY_DERIVE (0x1011) #define CKM_FORTEZZA_TIMESTAMP (0x1020) #define CKM_BATON_KEY_GEN (0x1030) #define CKM_BATON_ECB128 (0x1031) #define CKM_BATON_ECB96 (0x1032) #define CKM_BATON_CBC128 (0x1033) #define CKM_BATON_COUNTER (0x1034) #define CKM_BATON_SHUFFLE (0x1035) #define CKM_BATON_WRAP (0x1036) #define CKM_ECDSA_KEY_PAIR_GEN (0x1040) #define CKM_EC_KEY_PAIR_GEN (0x1040) #define CKM_ECDSA (0x1041) #define CKM_ECDSA_SHA1 (0x1042) #define CKM_ECDSA_SHA224 (0x1043) #define CKM_ECDSA_SHA256 (0x1044) #define CKM_ECDSA_SHA384 (0x1045) #define CKM_ECDSA_SHA512 (0x1046) #define CKM_ECDH1_DERIVE (0x1050) #define CKM_ECDH1_COFACTOR_DERIVE (0x1051) #define CKM_ECMQV_DERIVE (0x1052) #define CKM_JUNIPER_KEY_GEN (0x1060) #define CKM_JUNIPER_ECB128 (0x1061) #define CKM_JUNIPER_CBC128 (0x1062) #define CKM_JUNIPER_COUNTER (0x1063) #define CKM_JUNIPER_SHUFFLE (0x1064) #define CKM_JUNIPER_WRAP (0x1065) #define CKM_FASTHASH (0x1070) #define CKM_AES_KEY_GEN (0x1080) #define CKM_AES_ECB (0x1081) #define CKM_AES_CBC (0x1082) #define CKM_AES_MAC (0x1083) #define CKM_AES_MAC_GENERAL (0x1084) #define CKM_AES_CBC_PAD (0x1085) #define CKM_AES_CTR (0x1086) #define CKM_AES_GCM (0x1087) #define CKM_AES_CCM (0x1088) #define CKM_AES_CTS (0x1089) #define CKM_AES_CMAC (0x108a) #define CKM_AES_CMAC_GENERAL (0x108b) #define CKM_BLOWFISH_KEY_GEN (0x1090) #define CKM_BLOWFISH_CBC (0x1091) #define CKM_TWOFISH_KEY_GEN (0x1092) #define CKM_TWOFISH_CBC (0x1093) #define CKM_BLOWFISH_CBC_PAD (0x1094) #define CKM_TWOFISH_CBC_PAD (0x1095) #define CKM_DES_ECB_ENCRYPT_DATA (0x1100) #define CKM_DES_CBC_ENCRYPT_DATA (0x1101) #define CKM_DES3_ECB_ENCRYPT_DATA (0x1102) #define CKM_DES3_CBC_ENCRYPT_DATA (0x1103) #define CKM_AES_ECB_ENCRYPT_DATA (0x1104) #define CKM_AES_CBC_ENCRYPT_DATA (0x1105) #define CKM_GOSTR3410_KEY_PAIR_GEN (0x1200) #define CKM_GOSTR3410 (0x1201) #define CKM_GOSTR3410_WITH_GOSTR3411 (0x1202) #define CKM_GOSTR3410_KEY_WRAP (0x1203) #define CKM_GOSTR3410_DERIVE (0x1204) #define CKM_GOSTR3411 (0x1210) #define CKM_GOSTR3411_HMAC (0x1211) #define CKM_GOST28147_KEY_GEN (0x1220) #define CKM_GOST28147_ECB (0x1221) #define CKM_GOST28147 (0x1222) #define CKM_GOST28147_MAC (0x1223) #define CKM_GOST28147_KEY_WRAP (0x1224) #define CKM_DSA_PARAMETER_GEN (0x2000) #define CKM_DH_PKCS_PARAMETER_GEN (0x2001) #define CKM_X9_42_DH_PARAMETER_GEN (0x2002) #define CKM_AES_OFB (0x2104) #define CKM_AES_CFB64 (0x2105) #define CKM_AES_CFB8 (0x2106) #define CKM_AES_CFB128 (0x2107) #define CKM_AES_KEY_WRAP (0x2109) #define CKM_AES_KEY_WRAP_PAD (0x210a) #define CKM_RSA_PKCS_TPM_1_1 (0x4001) #define CKM_RSA_PKCS_OAEPTPM_1_1 (0x4002) #define CKM_VENDOR_DEFINED ((unsigned long) (1ul << 31)) struct ck_mechanism { ck_mechanism_type_t mechanism; void *parameter; unsigned long parameter_len; }; struct ck_mechanism_info { unsigned long min_key_size; unsigned long max_key_size; ck_flags_t flags; }; #define CKF_HW (1 << 0) #define CKF_ENCRYPT (1 << 8) #define CKF_DECRYPT (1 << 9) #define CKF_DIGEST (1 << 10) #define CKF_SIGN (1 << 11) #define CKF_SIGN_RECOVER (1 << 12) #define CKF_VERIFY (1 << 13) #define CKF_VERIFY_RECOVER (1 << 14) #define CKF_GENERATE (1 << 15) #define CKF_GENERATE_KEY_PAIR (1 << 16) #define CKF_WRAP (1 << 17) #define CKF_UNWRAP (1 << 18) #define CKF_DERIVE (1 << 19) #define CKF_EC_F_P (1 << 20) #define CKF_EC_F_2M (1 << 21) #define CKF_EC_ECPARAMETERS (1 << 22) #define CKF_EC_NAMEDCURVE (1 << 23) #define CKF_EC_UNCOMPRESS (1 << 24) #define CKF_EC_COMPRESS (1 << 25) #define CKF_EXTENSION ((unsigned long) (1ul << 31)) /* The following MGFs are defined */ #define CKG_MGF1_SHA1 (0x00000001) #define CKG_MGF1_SHA256 (0x00000002) #define CKG_MGF1_SHA384 (0x00000003) #define CKG_MGF1_SHA512 (0x00000004) #define CKG_MGF1_SHA224 (0x00000005) #define CKZ_DATA_SPECIFIED (0x00000001) struct ck_rsa_pkcs_oaep_params { ck_mechanism_type_t hash_alg; unsigned long mgf; unsigned long source; void *source_data; unsigned long source_data_len; }; struct ck_rsa_pkcs_pss_params { ck_mechanism_type_t hash_alg; unsigned long mgf; unsigned long slen; }; typedef unsigned long ck_ec_kdf_type_t; /* The following EC Key Derivation Functions are defined */ #define CKD_NULL (0x00000001) #define CKD_SHA1_KDF (0x00000002) struct ck_ecdh1_derive_params { ck_ec_kdf_type_t kdf; unsigned long shared_data_len; unsigned char *shared_data; unsigned long public_data_len; unsigned char *public_data; }; struct ck_ecdh2_derive_params { ck_ec_kdf_type_t kdf; unsigned long shared_data_len; unsigned char *shared_data; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; }; struct ck_ecmqv_derive_params { ck_ec_kdf_type_t kdf; unsigned long shared_data_len; unsigned char *shared_data; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; ck_object_handle_t public_key; }; typedef unsigned long ck_x9_42_dh_kdf_type_t; /* The following X9.42 DH key derivation functions are defined */ #define CKD_SHA1_KDF_ASN1 (0x00000003) #define CKD_SHA1_KDF_CONCATENATE (0x00000004) #define CKD_SHA224_KDF (0x00000005) #define CKD_SHA256_KDF (0x00000006) #define CKD_SHA384_KDF (0x00000007) #define CKD_SHA512_KDF (0x00000008) #define CKD_CPDIVERSIFY_KDF (0x00000009) struct ck_x9_42_dh1_derive_params { ck_x9_42_dh_kdf_type_t kdf; unsigned long other_info_len; unsigned char *other_info; unsigned long public_data_len; unsigned char *public_data; }; struct ck_x9_42_dh2_derive_params { ck_x9_42_dh_kdf_type_t kdf; unsigned long other_info_len; unsigned char *other_info; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; }; struct ck_x9_42_mqv_derive_params { ck_x9_42_dh_kdf_type_t kdf; unsigned long other_info_len; unsigned char *other_info; unsigned long public_data_len; unsigned char *public_data; unsigned long private_data_len; ck_object_handle_t private_data; unsigned long public_data_len2; unsigned char *public_data2; ck_object_handle_t public_key; }; struct ck_des_cbc_encrypt_data_params { unsigned char iv[8]; unsigned char *data; unsigned long length; }; struct ck_aes_cbc_encrypt_data_params { unsigned char iv[16]; unsigned char *data; unsigned long length; }; struct ck_key_derivation_string_data { unsigned char *data; unsigned long len; }; /* Flags for C_WaitForSlotEvent. */ #define CKF_DONT_BLOCK (1) typedef unsigned long ck_rv_t; typedef ck_rv_t (*ck_notify_t) (ck_session_handle_t session, ck_notification_t event, void *application); /* Forward reference. */ struct ck_function_list; #define _CK_DECLARE_FUNCTION(name, args) \ typedef ck_rv_t (*CK_ ## name) args; \ ck_rv_t CK_SPEC name args _CK_DECLARE_FUNCTION (C_Initialize, (void *init_args)); _CK_DECLARE_FUNCTION (C_Finalize, (void *reserved)); _CK_DECLARE_FUNCTION (C_GetInfo, (struct ck_info *info)); _CK_DECLARE_FUNCTION (C_GetFunctionList, (struct ck_function_list **function_list)); _CK_DECLARE_FUNCTION (C_GetSlotList, (unsigned char token_present, ck_slot_id_t *slot_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetSlotInfo, (ck_slot_id_t slot_id, struct ck_slot_info *info)); _CK_DECLARE_FUNCTION (C_GetTokenInfo, (ck_slot_id_t slot_id, struct ck_token_info *info)); _CK_DECLARE_FUNCTION (C_WaitForSlotEvent, (ck_flags_t flags, ck_slot_id_t *slot, void *reserved)); _CK_DECLARE_FUNCTION (C_GetMechanismList, (ck_slot_id_t slot_id, ck_mechanism_type_t *mechanism_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetMechanismInfo, (ck_slot_id_t slot_id, ck_mechanism_type_t type, struct ck_mechanism_info *info)); _CK_DECLARE_FUNCTION (C_InitToken, (ck_slot_id_t slot_id, unsigned char *pin, unsigned long pin_len, unsigned char *label)); _CK_DECLARE_FUNCTION (C_InitPIN, (ck_session_handle_t session, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_SetPIN, (ck_session_handle_t session, unsigned char *old_pin, unsigned long old_len, unsigned char *new_pin, unsigned long new_len)); _CK_DECLARE_FUNCTION (C_OpenSession, (ck_slot_id_t slot_id, ck_flags_t flags, void *application, ck_notify_t notify, ck_session_handle_t *session)); _CK_DECLARE_FUNCTION (C_CloseSession, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CloseAllSessions, (ck_slot_id_t slot_id)); _CK_DECLARE_FUNCTION (C_GetSessionInfo, (ck_session_handle_t session, struct ck_session_info *info)); _CK_DECLARE_FUNCTION (C_GetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long *operation_state_len)); _CK_DECLARE_FUNCTION (C_SetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long operation_state_len, ck_object_handle_t encryption_key, ck_object_handle_t authentiation_key)); _CK_DECLARE_FUNCTION (C_Login, (ck_session_handle_t session, ck_user_type_t user_type, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_Logout, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CreateObject, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *object)); _CK_DECLARE_FUNCTION (C_CopyObject, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *new_object)); _CK_DECLARE_FUNCTION (C_DestroyObject, (ck_session_handle_t session, ck_object_handle_t object)); _CK_DECLARE_FUNCTION (C_GetObjectSize, (ck_session_handle_t session, ck_object_handle_t object, unsigned long *size)); _CK_DECLARE_FUNCTION (C_GetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_SetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjectsInit, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjects, (ck_session_handle_t session, ck_object_handle_t *object, unsigned long max_object_count, unsigned long *object_count)); _CK_DECLARE_FUNCTION (C_FindObjectsFinal, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_EncryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Encrypt, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *encrypted_data, unsigned long *encrypted_data_len)); _CK_DECLARE_FUNCTION (C_EncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_EncryptFinal, (ck_session_handle_t session, unsigned char *last_encrypted_part, unsigned long *last_encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Decrypt, (ck_session_handle_t session, unsigned char *encrypted_data, unsigned long encrypted_data_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DecryptUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_DecryptFinal, (ck_session_handle_t session, unsigned char *last_part, unsigned long *last_part_len)); _CK_DECLARE_FUNCTION (C_DigestInit, (ck_session_handle_t session, struct ck_mechanism *mechanism)); _CK_DECLARE_FUNCTION (C_Digest, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_DigestUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_DigestKey, (ck_session_handle_t session, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_DigestFinal, (ck_session_handle_t session, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_SignInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Sign, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_SignFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_SignRecover, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_VerifyInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Verify, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_VerifyFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_VerifyRecover, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DigestEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptDigestUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_SignEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptVerifyUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_GenerateKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_GenerateKeyPair, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *public_key_template, unsigned long public_key_attribute_count, struct ck_attribute *private_key_template, unsigned long private_key_attribute_count, ck_object_handle_t *public_key, ck_object_handle_t *private_key)); _CK_DECLARE_FUNCTION (C_WrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t wrapping_key, ck_object_handle_t key, unsigned char *wrapped_key, unsigned long *wrapped_key_len)); _CK_DECLARE_FUNCTION (C_UnwrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t unwrapping_key, unsigned char *wrapped_key, unsigned long wrapped_key_len, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_DeriveKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t base_key, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_SeedRandom, (ck_session_handle_t session, unsigned char *seed, unsigned long seed_len)); _CK_DECLARE_FUNCTION (C_GenerateRandom, (ck_session_handle_t session, unsigned char *random_data, unsigned long random_len)); _CK_DECLARE_FUNCTION (C_GetFunctionStatus, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CancelFunction, (ck_session_handle_t session)); struct ck_function_list { struct ck_version version; CK_C_Initialize C_Initialize; CK_C_Finalize C_Finalize; CK_C_GetInfo C_GetInfo; CK_C_GetFunctionList C_GetFunctionList; CK_C_GetSlotList C_GetSlotList; CK_C_GetSlotInfo C_GetSlotInfo; CK_C_GetTokenInfo C_GetTokenInfo; CK_C_GetMechanismList C_GetMechanismList; CK_C_GetMechanismInfo C_GetMechanismInfo; CK_C_InitToken C_InitToken; CK_C_InitPIN C_InitPIN; CK_C_SetPIN C_SetPIN; CK_C_OpenSession C_OpenSession; CK_C_CloseSession C_CloseSession; CK_C_CloseAllSessions C_CloseAllSessions; CK_C_GetSessionInfo C_GetSessionInfo; CK_C_GetOperationState C_GetOperationState; CK_C_SetOperationState C_SetOperationState; CK_C_Login C_Login; CK_C_Logout C_Logout; CK_C_CreateObject C_CreateObject; CK_C_CopyObject C_CopyObject; CK_C_DestroyObject C_DestroyObject; CK_C_GetObjectSize C_GetObjectSize; CK_C_GetAttributeValue C_GetAttributeValue; CK_C_SetAttributeValue C_SetAttributeValue; CK_C_FindObjectsInit C_FindObjectsInit; CK_C_FindObjects C_FindObjects; CK_C_FindObjectsFinal C_FindObjectsFinal; CK_C_EncryptInit C_EncryptInit; CK_C_Encrypt C_Encrypt; CK_C_EncryptUpdate C_EncryptUpdate; CK_C_EncryptFinal C_EncryptFinal; CK_C_DecryptInit C_DecryptInit; CK_C_Decrypt C_Decrypt; CK_C_DecryptUpdate C_DecryptUpdate; CK_C_DecryptFinal C_DecryptFinal; CK_C_DigestInit C_DigestInit; CK_C_Digest C_Digest; CK_C_DigestUpdate C_DigestUpdate; CK_C_DigestKey C_DigestKey; CK_C_DigestFinal C_DigestFinal; CK_C_SignInit C_SignInit; CK_C_Sign C_Sign; CK_C_SignUpdate C_SignUpdate; CK_C_SignFinal C_SignFinal; CK_C_SignRecoverInit C_SignRecoverInit; CK_C_SignRecover C_SignRecover; CK_C_VerifyInit C_VerifyInit; CK_C_Verify C_Verify; CK_C_VerifyUpdate C_VerifyUpdate; CK_C_VerifyFinal C_VerifyFinal; CK_C_VerifyRecoverInit C_VerifyRecoverInit; CK_C_VerifyRecover C_VerifyRecover; CK_C_DigestEncryptUpdate C_DigestEncryptUpdate; CK_C_DecryptDigestUpdate C_DecryptDigestUpdate; CK_C_SignEncryptUpdate C_SignEncryptUpdate; CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate; CK_C_GenerateKey C_GenerateKey; CK_C_GenerateKeyPair C_GenerateKeyPair; CK_C_WrapKey C_WrapKey; CK_C_UnwrapKey C_UnwrapKey; CK_C_DeriveKey C_DeriveKey; CK_C_SeedRandom C_SeedRandom; CK_C_GenerateRandom C_GenerateRandom; CK_C_GetFunctionStatus C_GetFunctionStatus; CK_C_CancelFunction C_CancelFunction; CK_C_WaitForSlotEvent C_WaitForSlotEvent; }; typedef ck_rv_t (*ck_createmutex_t) (void **mutex); typedef ck_rv_t (*ck_destroymutex_t) (void *mutex); typedef ck_rv_t (*ck_lockmutex_t) (void *mutex); typedef ck_rv_t (*ck_unlockmutex_t) (void *mutex); struct ck_c_initialize_args { ck_createmutex_t create_mutex; ck_destroymutex_t destroy_mutex; ck_lockmutex_t lock_mutex; ck_unlockmutex_t unlock_mutex; ck_flags_t flags; void *reserved; }; #define CKF_LIBRARY_CANT_CREATE_OS_THREADS (1 << 0) #define CKF_OS_LOCKING_OK (1 << 1) #define CKR_OK (0) #define CKR_CANCEL (1) #define CKR_HOST_MEMORY (2) #define CKR_SLOT_ID_INVALID (3) #define CKR_GENERAL_ERROR (5) #define CKR_FUNCTION_FAILED (6) #define CKR_ARGUMENTS_BAD (7) #define CKR_NO_EVENT (8) #define CKR_NEED_TO_CREATE_THREADS (9) #define CKR_CANT_LOCK (0xa) #define CKR_ATTRIBUTE_READ_ONLY (0x10) #define CKR_ATTRIBUTE_SENSITIVE (0x11) #define CKR_ATTRIBUTE_TYPE_INVALID (0x12) #define CKR_ATTRIBUTE_VALUE_INVALID (0x13) #define CKR_COPY_PROHIBITED (0x1A) #define CKR_DATA_INVALID (0x20) #define CKR_DATA_LEN_RANGE (0x21) #define CKR_DEVICE_ERROR (0x30) #define CKR_DEVICE_MEMORY (0x31) #define CKR_DEVICE_REMOVED (0x32) #define CKR_ENCRYPTED_DATA_INVALID (0x40) #define CKR_ENCRYPTED_DATA_LEN_RANGE (0x41) #define CKR_FUNCTION_CANCELED (0x50) #define CKR_FUNCTION_NOT_PARALLEL (0x51) #define CKR_FUNCTION_NOT_SUPPORTED (0x54) #define CKR_KEY_HANDLE_INVALID (0x60) #define CKR_KEY_SIZE_RANGE (0x62) #define CKR_KEY_TYPE_INCONSISTENT (0x63) #define CKR_KEY_NOT_NEEDED (0x64) #define CKR_KEY_CHANGED (0x65) #define CKR_KEY_NEEDED (0x66) #define CKR_KEY_INDIGESTIBLE (0x67) #define CKR_KEY_FUNCTION_NOT_PERMITTED (0x68) #define CKR_KEY_NOT_WRAPPABLE (0x69) #define CKR_KEY_UNEXTRACTABLE (0x6a) #define CKR_MECHANISM_INVALID (0x70) #define CKR_MECHANISM_PARAM_INVALID (0x71) #define CKR_OBJECT_HANDLE_INVALID (0x82) #define CKR_OPERATION_ACTIVE (0x90) #define CKR_OPERATION_NOT_INITIALIZED (0x91) #define CKR_PIN_INCORRECT (0xa0) #define CKR_PIN_INVALID (0xa1) #define CKR_PIN_LEN_RANGE (0xa2) #define CKR_PIN_EXPIRED (0xa3) #define CKR_PIN_LOCKED (0xa4) #define CKR_SESSION_CLOSED (0xb0) #define CKR_SESSION_COUNT (0xb1) #define CKR_SESSION_HANDLE_INVALID (0xb3) #define CKR_SESSION_PARALLEL_NOT_SUPPORTED (0xb4) #define CKR_SESSION_READ_ONLY (0xb5) #define CKR_SESSION_EXISTS (0xb6) #define CKR_SESSION_READ_ONLY_EXISTS (0xb7) #define CKR_SESSION_READ_WRITE_SO_EXISTS (0xb8) #define CKR_SIGNATURE_INVALID (0xc0) #define CKR_SIGNATURE_LEN_RANGE (0xc1) #define CKR_TEMPLATE_INCOMPLETE (0xd0) #define CKR_TEMPLATE_INCONSISTENT (0xd1) #define CKR_TOKEN_NOT_PRESENT (0xe0) #define CKR_TOKEN_NOT_RECOGNIZED (0xe1) #define CKR_TOKEN_WRITE_PROTECTED (0xe2) #define CKR_UNWRAPPING_KEY_HANDLE_INVALID (0xf0) #define CKR_UNWRAPPING_KEY_SIZE_RANGE (0xf1) #define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT (0xf2) #define CKR_USER_ALREADY_LOGGED_IN (0x100) #define CKR_USER_NOT_LOGGED_IN (0x101) #define CKR_USER_PIN_NOT_INITIALIZED (0x102) #define CKR_USER_TYPE_INVALID (0x103) #define CKR_USER_ANOTHER_ALREADY_LOGGED_IN (0x104) #define CKR_USER_TOO_MANY_TYPES (0x105) #define CKR_WRAPPED_KEY_INVALID (0x110) #define CKR_WRAPPED_KEY_LEN_RANGE (0x112) #define CKR_WRAPPING_KEY_HANDLE_INVALID (0x113) #define CKR_WRAPPING_KEY_SIZE_RANGE (0x114) #define CKR_WRAPPING_KEY_TYPE_INCONSISTENT (0x115) #define CKR_RANDOM_SEED_NOT_SUPPORTED (0x120) #define CKR_RANDOM_NO_RNG (0x121) #define CKR_DOMAIN_PARAMS_INVALID (0x130) #define CKR_BUFFER_TOO_SMALL (0x150) #define CKR_SAVED_STATE_INVALID (0x160) #define CKR_INFORMATION_SENSITIVE (0x170) #define CKR_STATE_UNSAVEABLE (0x180) #define CKR_CRYPTOKI_NOT_INITIALIZED (0x190) #define CKR_CRYPTOKI_ALREADY_INITIALIZED (0x191) #define CKR_MUTEX_BAD (0x1a0) #define CKR_MUTEX_NOT_LOCKED (0x1a1) #define CKR_NEW_PIN_MODE (0x1b0) #define CKR_NEXT_OTP (0x1b1) #define CKR_EXCEEDED_MAX_ITERATIONS (0x1b5) #define CKR_FIPS_SELF_TEST_FAILED (0x1b6) #define CKR_LIBRARY_LOAD_FAILED (0x1b7) #define CKR_PIN_TOO_WEAK (0x1b8) #define CKR_PUBLIC_KEY_INVALID (0x1b9) #define CKR_FUNCTION_REJECTED (0x200) #define CKR_VENDOR_DEFINED ((unsigned long) (1ul << 31)) /* Compatibility layer. */ #ifdef CRYPTOKI_COMPAT #undef CK_DEFINE_FUNCTION #define CK_DEFINE_FUNCTION(retval, name) retval CK_SPEC name /* For NULL. */ #include typedef unsigned char CK_BYTE; typedef unsigned char CK_CHAR; typedef unsigned char CK_UTF8CHAR; typedef unsigned char CK_BBOOL; typedef unsigned long int CK_ULONG; typedef long int CK_LONG; typedef CK_BYTE *CK_BYTE_PTR; typedef CK_CHAR *CK_CHAR_PTR; typedef CK_UTF8CHAR *CK_UTF8CHAR_PTR; typedef CK_ULONG *CK_ULONG_PTR; typedef void *CK_VOID_PTR; typedef void **CK_VOID_PTR_PTR; #define CK_FALSE 0 #define CK_TRUE 1 #ifndef CK_DISABLE_TRUE_FALSE #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #endif typedef struct ck_version CK_VERSION; typedef struct ck_version *CK_VERSION_PTR; typedef struct ck_info CK_INFO; typedef struct ck_info *CK_INFO_PTR; typedef ck_slot_id_t *CK_SLOT_ID_PTR; typedef struct ck_slot_info CK_SLOT_INFO; typedef struct ck_slot_info *CK_SLOT_INFO_PTR; typedef struct ck_token_info CK_TOKEN_INFO; typedef struct ck_token_info *CK_TOKEN_INFO_PTR; typedef ck_session_handle_t *CK_SESSION_HANDLE_PTR; typedef struct ck_session_info CK_SESSION_INFO; typedef struct ck_session_info *CK_SESSION_INFO_PTR; typedef ck_object_handle_t *CK_OBJECT_HANDLE_PTR; typedef ck_object_class_t *CK_OBJECT_CLASS_PTR; typedef struct ck_attribute CK_ATTRIBUTE; typedef struct ck_attribute *CK_ATTRIBUTE_PTR; typedef struct ck_date CK_DATE; typedef struct ck_date *CK_DATE_PTR; typedef ck_mechanism_type_t *CK_MECHANISM_TYPE_PTR; typedef struct ck_mechanism CK_MECHANISM; typedef struct ck_mechanism *CK_MECHANISM_PTR; typedef struct ck_mechanism_info CK_MECHANISM_INFO; typedef struct ck_mechanism_info *CK_MECHANISM_INFO_PTR; typedef struct ck_rsa_pkcs_oaep_params CK_RSA_PKCS_OAEP_PARAMS; typedef struct ck_rsa_pkcs_oaep_params *CK_RSA_PKCS_OAEP_PARAMS_PTR; typedef struct ck_rsa_pkcs_pss_params CK_RSA_PKCS_PSS_PARAMS; typedef struct ck_rsa_pkcs_pss_params *CK_RSA_PKCS_PSS_PARAMS_PTR; typedef struct ck_ecdh1_derive_params CK_ECDH1_DERIVE_PARAMS; typedef struct ck_ecdh1_derive_params *CK_ECDH1_DERIVE_PARAMS_PTR; typedef struct ck_des_cbc_encrypt_data_params CK_DES_CBC_ENCRYPT_DATA_PARAMS; typedef struct ck_des_cbc_encrypt_data_params *CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct ck_aes_cbc_encrypt_data_params CK_AES_CBC_ENCRYPT_DATA_PARAMS; typedef struct ck_aes_cbc_encrypt_data_params *CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR; typedef struct ck_key_derivation_string_data CK_KEY_DERIVATION_STRING_DATA; typedef struct ck_key_derivation_string_data *CK_KEY_DERIVATION_STRING_DATA_PTR; typedef struct ck_function_list CK_FUNCTION_LIST; typedef struct ck_function_list *CK_FUNCTION_LIST_PTR; typedef struct ck_function_list **CK_FUNCTION_LIST_PTR_PTR; typedef struct ck_c_initialize_args CK_C_INITIALIZE_ARGS; typedef struct ck_c_initialize_args *CK_C_INITIALIZE_ARGS_PTR; #define NULL_PTR NULL /* Delete the helper macros defined at the top of the file. */ #undef ck_flags_t #undef ck_version #undef ck_info #undef cryptoki_version #undef manufacturer_id #undef library_description #undef library_version #undef ck_notification_t #undef ck_slot_id_t #undef ck_slot_info #undef slot_description #undef hardware_version #undef firmware_version #undef ck_token_info #undef serial_number #undef max_session_count #undef session_count #undef max_rw_session_count #undef rw_session_count #undef max_pin_len #undef min_pin_len #undef total_public_memory #undef free_public_memory #undef total_private_memory #undef free_private_memory #undef utc_time #undef ck_session_handle_t #undef ck_user_type_t #undef ck_state_t #undef ck_session_info #undef slot_id #undef device_error #undef ck_object_handle_t #undef ck_object_class_t #undef ck_hw_feature_type_t #undef ck_key_type_t #undef ck_certificate_type_t #undef ck_attribute_type_t #undef ck_attribute #undef value #undef value_len #undef ck_date #undef ck_mechanism_type_t #undef ck_mechanism #undef parameter #undef parameter_len #undef ck_mechanism_info #undef min_key_size #undef max_key_size #undef ck_rsa_pkcs_oaep_params #undef hash_alg #undef source_data #undef source_data_len #undef slen #undef ck_ec_kdf_type_t #undef shared_data_len #undef shared_data #undef public_data_len #undef public_data #undef private_data_len #undef private_data #undef public_data_len2 #undef public_data2 #undef public_key #undef ck_x9_42_dh_kdf_type_t #undef other_info_len #undef other_info #undef data #undef len #undef ck_rv_t #undef ck_notify_t #undef ck_function_list #undef ck_createmutex_t #undef ck_destroymutex_t #undef ck_lockmutex_t #undef ck_unlockmutex_t #undef ck_c_initialize_args #undef create_mutex #undef destroy_mutex #undef lock_mutex #undef unlock_mutex #undef reserved #endif /* CRYPTOKI_COMPAT */ /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) #pragma pack(pop, cryptoki) #endif #if defined(__cplusplus) } #endif #endif /* PKCS11_H */ softhsm-2.0.0/src/lib/cryptoki.h0000664000175000017500000000365112533040716013477 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** cryptoki.h This include file turns on export of functions by the SoftHSM v2 library by setting the #define symbol CRYPTOKI_EXPORTS before the main PKCS #11 header file is included. Include this header file in alle SoftHSM v2 code that links into a PKCS #11 library; currently that will only by softhsm.cpp *****************************************************************************/ #ifndef _SOFTHSM_V2_CRYPTOKI_H #define _SOFTHSM_V2_CRYPTOKI_H #define CRYPTOKI_EXPORTS #define CRYPTOKI_COMPAT #include "pkcs11.h" #endif // !_SOFTHSM_V2_CRYPTOKI_H softhsm-2.0.0/src/lib/Makefile.in0000664000175000017500000007101412552216620013525 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/lib DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__installdirs = "$(DESTDIR)$(libdir)" LTLIBRARIES = $(lib_LTLIBRARIES) $(noinst_LTLIBRARIES) libsofthsm2_la_DEPENDENCIES = common/libsofthsm_common.la \ crypto/libsofthsm_crypto.la data_mgr/libsofthsm_datamgr.la \ handle_mgr/libsofthsm_handlemgr.la \ object_store/libsofthsm_objectstore.la \ session_mgr/libsofthsm_sessionmgr.la \ slot_mgr/libsofthsm_slotmgr.la am_libsofthsm2_la_OBJECTS = access.lo main.lo P11Attributes.lo \ P11Objects.lo SoftHSM.lo libsofthsm2_la_OBJECTS = $(am_libsofthsm2_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libsofthsm2_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(AM_CXXFLAGS) $(CXXFLAGS) $(libsofthsm2_la_LDFLAGS) \ $(LDFLAGS) -o $@ libsofthsm_convarch_la_DEPENDENCIES = $(libsofthsm2_la_LIBADD) am_libsofthsm_convarch_la_OBJECTS = libsofthsm_convarch_la_OBJECTS = $(am_libsofthsm_convarch_la_OBJECTS) AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = SOURCES = $(libsofthsm2_la_SOURCES) $(libsofthsm_convarch_la_SOURCES) DIST_SOURCES = $(libsofthsm2_la_SOURCES) \ $(libsofthsm_convarch_la_SOURCES) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/cryptoki_compat \ -I$(srcdir)/common \ -I$(srcdir)/object_store \ -I$(srcdir)/slot_mgr \ -I$(srcdir)/session_mgr \ -I$(srcdir)/data_mgr \ -I$(srcdir)/handle_mgr \ -I$(srcdir)/crypto lib_LTLIBRARIES = libsofthsm2.la libsofthsm2_la_SOURCES = access.cpp \ main.cpp \ P11Attributes.cpp \ P11Objects.cpp \ SoftHSM.cpp libsofthsm2_la_LIBADD = common/libsofthsm_common.la \ crypto/libsofthsm_crypto.la \ data_mgr/libsofthsm_datamgr.la \ handle_mgr/libsofthsm_handlemgr.la \ object_store/libsofthsm_objectstore.la \ session_mgr/libsofthsm_sessionmgr.la \ slot_mgr/libsofthsm_slotmgr.la libsofthsm2_la_LDFLAGS = -version-info @VERSION_INFO@ \ -avoid-version -module # Create a convenience library from all the other convenience library; this is # necessary to resolve circular dependencies when statically linking the test # executables noinst_LTLIBRARIES = libsofthsm_convarch.la libsofthsm_convarch_la_SOURCES = libsofthsm_convarch_la_LIBADD = $(libsofthsm2_la_LIBADD) SUBDIRS = common \ crypto \ data_mgr \ object_store \ session_mgr \ slot_mgr \ handle_mgr \ test EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/cryptoki_compat/*.h \ $(srcdir)/win32/*.cc \ $(srcdir)/win32/*.cpp \ $(srcdir)/win32/*.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): install-libLTLIBRARIES: $(lib_LTLIBRARIES) @$(NORMAL_INSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ list2=; for p in $$list; do \ if test -f $$p; then \ list2="$$list2 $$p"; \ else :; fi; \ done; \ test -z "$$list2" || { \ echo " $(MKDIR_P) '$(DESTDIR)$(libdir)'"; \ $(MKDIR_P) "$(DESTDIR)$(libdir)" || exit 1; \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ } uninstall-libLTLIBRARIES: @$(NORMAL_UNINSTALL) @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ for p in $$list; do \ $(am__strip_dir) \ echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ done clean-libLTLIBRARIES: -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) @list='$(lib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm2.la: $(libsofthsm2_la_OBJECTS) $(libsofthsm2_la_DEPENDENCIES) $(EXTRA_libsofthsm2_la_DEPENDENCIES) $(AM_V_CXXLD)$(libsofthsm2_la_LINK) -rpath $(libdir) $(libsofthsm2_la_OBJECTS) $(libsofthsm2_la_LIBADD) $(LIBS) libsofthsm_convarch.la: $(libsofthsm_convarch_la_OBJECTS) $(libsofthsm_convarch_la_DEPENDENCIES) $(EXTRA_libsofthsm_convarch_la_DEPENDENCIES) $(AM_V_CCLD)$(LINK) $(libsofthsm_convarch_la_OBJECTS) $(libsofthsm_convarch_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/P11Attributes.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/P11Objects.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SoftHSM.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/access.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/main.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: for dir in "$(DESTDIR)$(libdir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libLTLIBRARIES clean-libtool \ clean-noinstLTLIBRARIES mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-libLTLIBRARIES install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: uninstall-libLTLIBRARIES .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libLTLIBRARIES \ clean-libtool clean-noinstLTLIBRARIES cscopelist-am ctags \ ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-libLTLIBRARIES install-man install-pdf \ install-pdf-am install-ps install-ps-am install-strip \ installcheck installcheck-am installdirs installdirs-am \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-libLTLIBRARIES # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/common/0000775000175000017500000000000012552220146013023 500000000000000softhsm-2.0.0/src/lib/common/softhsm2.conf.in0000664000175000017500000000022512533040716015765 00000000000000# SoftHSM v2 configuration file directories.tokendir = @softhsmtokendir@ objectstore.backend = file # ERROR, WARNING, INFO, DEBUG log.level = INFO softhsm-2.0.0/src/lib/common/Configuration.cpp0000664000175000017500000001052612533040716016264 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Configuration.cpp Loads the configuration and supports retrieval of configuration information *****************************************************************************/ #include #include #include "Configuration.h" #include "log.h" // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr Configuration::instance(nullptr); #else std::auto_ptr Configuration::instance(NULL); #endif // Add all valid configurations const struct config Configuration::valid_config[] = { { "directories.tokendir", CONFIG_TYPE_STRING }, { "objectstore.backend", CONFIG_TYPE_STRING }, { "log.level", CONFIG_TYPE_STRING }, { "", CONFIG_TYPE_UNSUPPORTED } }; // Return the one-and-only instance Configuration* Configuration::i() { if (instance.get() == NULL) { instance.reset(new Configuration()); } return instance.get(); } // Constructor Configuration::Configuration() { configLoader = NULL; } // Get the type of the configuration value int Configuration::getType(std::string key) { for (int i = 0; valid_config[i].key.compare("") != 0; i++) { if (valid_config[i].key.compare(key) == 0) { return valid_config[i].type; } } return CONFIG_TYPE_UNSUPPORTED; } // Retrieve a string based configuration value std::string Configuration::getString(std::string key, std::string ifEmpty /* = "" */) { if (stringConfiguration.find(key) != stringConfiguration.end()) { return stringConfiguration[key]; } else { return ifEmpty; } } // Retrieve an integer configuration value int Configuration::getInt(std::string key, int ifEmpty /* = 0 */) { if (integerConfiguration.find(key) != integerConfiguration.end()) { return integerConfiguration[key]; } else { return ifEmpty; } } // Retrieve a boolean configuration value bool Configuration::getBool(std::string key, bool ifEmpty /* = false */) { if (booleanConfiguration.find(key) != booleanConfiguration.end()) { return booleanConfiguration[key]; } else { return ifEmpty; } } // Set a string based configuration value void Configuration::setString(std::string key, std::string value) { stringConfiguration[key] = value; } // Set an integer based configuration value void Configuration::setInt(std::string key, int value) { integerConfiguration[key] = value; } // Set a boolean configuration value void Configuration::setBool(std::string key, bool value) { booleanConfiguration[key] = value; } // Reload the configuration bool Configuration::reload() { if (configLoader == NULL) { return false; } // Discard the current configuration stringConfiguration.clear(); integerConfiguration.clear(); booleanConfiguration.clear(); // Reload the configuration if (!configLoader->loadConfiguration()) { ERROR_MSG("Failed to load the SoftHSM configuration"); return false; } return true; } // Reload the configuration using the specified configuration loader bool Configuration::reload(ConfigLoader* inConfigLoader) { configLoader = inConfigLoader; return reload(); } softhsm-2.0.0/src/lib/common/MutexFactory.h0000664000175000017500000000634212533040716015555 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** MutexFactory.h This factory produces OS specific mutex objects *****************************************************************************/ #ifndef _SOFTHSM_V2_MUTEXFACTORY_H #define _SOFTHSM_V2_MUTEXFACTORY_H #include "config.h" #include "osmutex.h" #include "cryptoki.h" #include class Mutex { public: // Constructor Mutex(); // Destructor virtual ~Mutex(); // Lock the mutex bool lock(); // Unlock the mutex void unlock(); private: // The mutex handle CK_VOID_PTR handle; // Is the mutex valid? bool isValid; }; class MutexLocker { public: // Constructor MutexLocker(Mutex* inMutex); // Destructor virtual ~MutexLocker(); private: // The mutex to lock Mutex* mutex; }; class MutexFactory { public: // Return the one-and-only instance static MutexFactory* i(); // Destructor virtual ~MutexFactory(); // Get a mutex instance Mutex* getMutex(); // Recycle a mutex instance void recycleMutex(Mutex* mutex); // Set the function pointers void setCreateMutex(CK_CREATEMUTEX inCreateMutex); void setDestroyMutex(CK_DESTROYMUTEX inDestroyMutex); void setLockMutex(CK_LOCKMUTEX inLockMutex); void setUnlockMutex(CK_UNLOCKMUTEX inUnlockMutex); // Enable/disable mutex handling void enable(); void disable(); private: // Constructor MutexFactory(); // Mutex operations friend class Mutex; CK_RV CreateMutex(CK_VOID_PTR_PTR newMutex); CK_RV DestroyMutex(CK_VOID_PTR mutex); CK_RV LockMutex(CK_VOID_PTR mutex); CK_RV UnlockMutex(CK_VOID_PTR mutex); // The one-and-only instance #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif // The function pointers CK_CREATEMUTEX createMutex; CK_DESTROYMUTEX destroyMutex; CK_LOCKMUTEX lockMutex; CK_UNLOCKMUTEX unlockMutex; // Can we do mutex handling? bool enabled; }; #endif // !_SOFTHSM_V2_MUTEXFACTORY_H softhsm-2.0.0/src/lib/common/fatal.h0000664000175000017500000000357512533040716014217 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** fatal.h Implementens calls for handling fatal exceptions. When a fatal exception occurs, this code ensures that as much of the securely allocated memory as possible is wiped clean. *****************************************************************************/ #ifndef _SOFTHSM_V2_FATAL_H #define _SOFTHSM_V2_FATAL_H #include "config.h" #include "log.h" #if defined(__cplusplus) extern "C" { #endif // __cplusplus void FatalException(void); #if defined(__cplusplus) } #endif #endif // !_SOFTHSM_V2_FATAL_H softhsm-2.0.0/src/lib/common/Makefile.am0000664000175000017500000000162512533040716015005 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_common.la libsofthsm_common_la_SOURCES = Configuration.cpp \ fatal.cpp \ log.cpp \ osmutex.cpp \ SimpleConfigLoader.cpp \ MutexFactory.cpp man_MANS = softhsm2.conf.5 EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/softhsm2.conf.5.in install-data-hook: test -d ${DESTDIR}${sysconfdir} || \ ${INSTALL} -d ${DESTDIR}${sysconfdir} test -f ${DESTDIR}${sysconfdir}/softhsm2.conf || \ ${INSTALL_DATA} ${top_builddir}/src/lib/common/softhsm2.conf ${DESTDIR}${sysconfdir} ${INSTALL_DATA} ${top_builddir}/src/lib/common/softhsm2.conf ${DESTDIR}${sysconfdir}/softhsm2.conf.sample test -d ${DESTDIR}${softhsmtokendir} || \ ${INSTALL} -d -m 700 ${DESTDIR}${softhsmtokendir} softhsm-2.0.0/src/lib/common/osmutex.cpp0000664000175000017500000001213612533040716015160 00000000000000/* * Copyright (c) 2008-2010 .SE (The Internet Infrastructure Foundation). * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** osmutex.cpp Contains OS-specific implementations of intraprocess mutex functions. This implementation is based on SoftHSM v1 *****************************************************************************/ #include "config.h" #include "log.h" #include "osmutex.h" #ifdef HAVE_PTHREAD_H #include #include CK_RV OSCreateMutex(CK_VOID_PTR_PTR newMutex) { int rv; /* Allocate memory */ pthread_mutex_t* pthreadMutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)); if (pthreadMutex == NULL) { ERROR_MSG("Failed to allocate memory for a new mutex"); return CKR_HOST_MEMORY; } /* Initialise the mutex */ if ((rv = pthread_mutex_init(pthreadMutex, NULL)) != 0) { free(pthreadMutex); ERROR_MSG("Failed to initialise POSIX mutex (0x%08X)", rv); return CKR_GENERAL_ERROR; } *newMutex = pthreadMutex; return CKR_OK; } CK_RV OSDestroyMutex(CK_VOID_PTR mutex) { int rv; pthread_mutex_t* pthreadMutex = (pthread_mutex_t*) mutex; if (pthreadMutex == NULL) { ERROR_MSG("Cannot destroy NULL mutex"); return CKR_ARGUMENTS_BAD; } if ((rv = pthread_mutex_destroy(pthreadMutex)) != 0) { ERROR_MSG("Failed to destroy POSIX mutex (0x%08X)", rv); return CKR_GENERAL_ERROR; } free(pthreadMutex); return CKR_OK; } CK_RV OSLockMutex(CK_VOID_PTR mutex) { int rv; pthread_mutex_t* pthreadMutex = (pthread_mutex_t*) mutex; if (pthreadMutex == NULL) { ERROR_MSG("Cannot lock NULL mutex"); return CKR_ARGUMENTS_BAD; } if ((rv = pthread_mutex_lock(pthreadMutex)) != 0) { ERROR_MSG("Failed to lock POSIX mutex 0x%08X (0x%08X)", pthreadMutex, rv); return CKR_GENERAL_ERROR; } return CKR_OK; } CK_RV OSUnlockMutex(CK_VOID_PTR mutex) { int rv; pthread_mutex_t* pthreadMutex = (pthread_mutex_t*) mutex; if (pthreadMutex == NULL) { ERROR_MSG("Cannot unlock NULL mutex"); return CKR_ARGUMENTS_BAD; } if ((rv = pthread_mutex_unlock(pthreadMutex)) != 0) { ERROR_MSG("Failed to unlock POSIX mutex 0x%08X (0x%08X)", pthreadMutex, rv); return CKR_GENERAL_ERROR; } return CKR_OK; } #elif _WIN32 CK_RV OSCreateMutex(CK_VOID_PTR_PTR newMutex) { HANDLE hMutex; hMutex = CreateMutex(NULL, FALSE, NULL); if (hMutex == NULL) { DWORD rv = GetLastError(); ERROR_MSG("Failed to initialise WIN32 mutex (0x%08X)", rv); return CKR_GENERAL_ERROR; } *newMutex = hMutex; return CKR_OK; } CK_RV OSDestroyMutex(CK_VOID_PTR mutex) { HANDLE hMutex = (HANDLE) mutex; if (hMutex == NULL) { ERROR_MSG("Cannot destroy NULL mutex"); return CKR_ARGUMENTS_BAD; } if (CloseHandle(hMutex) == 0) { DWORD rv = GetLastError(); ERROR_MSG("Failed to destroy WIN32 mutex (0x%08X)", rv); return CKR_GENERAL_ERROR; } return CKR_OK; } CK_RV OSLockMutex(CK_VOID_PTR mutex) { DWORD rv; HANDLE hMutex = (HANDLE) mutex; if (hMutex == NULL) { ERROR_MSG("Cannot lock NULL mutex"); return CKR_ARGUMENTS_BAD; } rv = WaitForSingleObject(hMutex, INFINITE); if (rv != WAIT_OBJECT_0) { // WAIT_ABANDONED 0x00000080 // WAIT_OBJECT_0 0x00000000 // WAIT_TIMEOUT 0x00000102 // WAIT_FAILED 0xFFFFFFFF if (rv == WAIT_FAILED) rv = GetLastError(); ERROR_MSG("Failed to lock WIN32 mutex 0x%08X (0x%08X)", hMutex, rv); return CKR_GENERAL_ERROR; } return CKR_OK; } CK_RV OSUnlockMutex(CK_VOID_PTR mutex) { HANDLE hMutex = (HANDLE) mutex; if (hMutex == NULL) { ERROR_MSG("Cannot unlock NULL mutex"); return CKR_ARGUMENTS_BAD; } if (ReleaseMutex(hMutex) == 0) { DWORD rv = GetLastError(); ERROR_MSG("Failed to unlock WIN32 mutex 0x%08X (0x%08X)", hMutex, rv); return CKR_GENERAL_ERROR; } return CKR_OK; } #else #error "There are no mutex implementations for your operating system yet" #endif softhsm-2.0.0/src/lib/common/SimpleConfigLoader.cpp0000664000175000017500000001535012533040716017163 00000000000000/* * Copyright (c) 2010 .SE, The Internet Infrastructure Foundation * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SimpleConfigLoader.cpp Loads the configuration from the configuration file. *****************************************************************************/ #include #include #include #include #include #ifdef _WIN32 # include #else # include #endif #include "config.h" #if defined(HAVE_GETPWUID_R) # include # include #endif #include "SimpleConfigLoader.h" #include "log.h" #include "Configuration.h" // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr SimpleConfigLoader::instance(nullptr); #else std::auto_ptr SimpleConfigLoader::instance(NULL); #endif // Return the one-and-only instance SimpleConfigLoader* SimpleConfigLoader::i() { if (instance.get() == NULL) { instance.reset(new SimpleConfigLoader()); } return instance.get(); } // Constructor SimpleConfigLoader::SimpleConfigLoader() { } // Load the configuration bool SimpleConfigLoader::loadConfiguration() { char* configPath = getConfigPath(); FILE* fp = fopen(configPath,"r"); if (fp == NULL) { ERROR_MSG("Could not open the config file: %s", configPath); free(configPath); return false; } free(configPath); char fileBuf[1024]; // Format in config file // // = // # Line is ignored while (fgets(fileBuf, sizeof(fileBuf), fp) != NULL) { // End the string at the first comment or newline fileBuf[strcspn(fileBuf, "#\n\r")] = '\0'; // Get the first part of the line char* name = strtok(fileBuf, "="); if (name == NULL) { continue; } // Trim the name char* trimmedName = trimString(name); if (trimmedName == NULL) { continue; } // Get the second part of the line char* value = strtok(NULL, "="); if(value == NULL) { free(trimmedName); continue; } // Trim the value char* trimmedValue = trimString(value); if (trimmedValue == NULL) { free(trimmedName); continue; } // Save name,value std::string stringName(trimmedName); std::string stringValue(trimmedValue); free(trimmedName); free(trimmedValue); switch (Configuration::i()->getType(stringName)) { case CONFIG_TYPE_STRING: Configuration::i()->setString(stringName, stringValue); break; case CONFIG_TYPE_INT: Configuration::i()->setInt(stringName, atoi(stringValue.c_str())); break; case CONFIG_TYPE_BOOL: bool boolValue; if (string2bool(stringValue, &boolValue)) { Configuration::i()->setBool(stringName, boolValue); } else { WARNING_MSG("The value %s is not a boolean", stringValue.c_str()); } break; case CONFIG_TYPE_UNSUPPORTED: default: WARNING_MSG("The following configuration is not supported: %s = %s", stringName.c_str(), stringValue.c_str()); break; } } fclose(fp); return true; } // Get the boolean value from a string bool SimpleConfigLoader::string2bool(std::string stringValue, bool* boolValue) { // Convert to lowercase std::transform(stringValue.begin(), stringValue.end(), stringValue.begin(), tolower); if (stringValue.compare("true") == 0) { *boolValue = true; return true; } if (stringValue.compare("false") == 0) { *boolValue = false; return true; } return false; } #define CONFIG_FILE ".config/softhsm2/softhsm2.conf" /* Returns a user-specific path for configuration. */ static char *get_user_path(void) { #ifdef _WIN32 char path[512]; const char *home_drive = getenv("HOMEDRIVE"); const char *home_path = getenv("HOMEPATH"); if (home_drive && home_path) { snprintf(path, sizeof(path), "%s%s\\softhsm2.conf", home_drive, home_path); if (_access(path, 0) == 0) return strdup(path); } goto fail; #else char path[_POSIX_PATH_MAX]; const char *home_dir = getenv("HOME"); if (home_dir != NULL && home_dir[0] != 0) { snprintf(path, sizeof(path), "%s/" CONFIG_FILE, home_dir); if (access(path, R_OK) == 0) return strdup(path); else goto fail; } # if defined(HAVE_GETPWUID_R) if (home_dir == NULL || home_dir[0] == '\0') { struct passwd *pwd; struct passwd _pwd; int ret; char tmp[512]; ret = getpwuid_r(getuid(), &_pwd, tmp, sizeof(tmp), &pwd); if (ret == 0 && pwd != NULL) { snprintf(path, sizeof(path), "%s/" CONFIG_FILE, pwd->pw_dir); if (access(path, R_OK) == 0) return strdup(path); else goto fail; } } # endif #endif fail: return NULL; } char* SimpleConfigLoader::getConfigPath() { const char* configPath = getenv("SOFTHSM2_CONF"); char *tpath; if (configPath == NULL) { tpath = get_user_path(); if (tpath != NULL) { return tpath; } configPath = DEFAULT_SOFTHSM2_CONF; } return strdup(configPath); } char* SimpleConfigLoader::trimString(char* text) { if (text == NULL) { return NULL; } int startPos = 0; int endPos = strlen(text) - 1; // Find the first position without a space while (startPos <= endPos && isspace((int)*(text + startPos))) { startPos++; } // Find the last position without a space while (startPos <= endPos && isspace((int)*(text + endPos))) { endPos--; } // We must have a valid string int length = endPos - startPos + 1; if (length <= 0) { return NULL; } // Create the trimmed text char* trimmedText = (char*)malloc(length + 1); if (trimmedText == NULL) { return NULL; } trimmedText[length] = '\0'; memcpy(trimmedText, text + startPos, length); return trimmedText; } softhsm-2.0.0/src/lib/common/Configuration.h0000664000175000017500000000643112533040716015731 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Configuration.h Loads the configuration and supports retrieval of configuration information *****************************************************************************/ #ifndef _SOFTHSM_V2_CONFIGURATION_H #define _SOFTHSM_V2_CONFIGURATION_H #include "config.h" #include #include #include enum { CONFIG_TYPE_UNSUPPORTED, CONFIG_TYPE_STRING, CONFIG_TYPE_INT, CONFIG_TYPE_BOOL }; struct config { std::string key; int type; }; class ConfigLoader { public: virtual ~ConfigLoader() { } // Trigger loading of the configuration virtual bool loadConfiguration() = 0; }; class Configuration { public: static Configuration* i(); virtual ~Configuration() { } // Get the type of the configuration value int getType(std::string key); // Retrieve a string based configuration value std::string getString(std::string key, std::string ifEmpty = std::string("")); // Retrieve an integer configuration value int getInt(std::string key, int ifEmpty = 0); // Retrieve a boolean configuration value bool getBool(std::string key, bool ifEmpty = false); // Set a string based configuration value void setString(std::string key, std::string value); // Set an integer based configuration value void setInt(std::string key, int value); // Set a boolean configuration value void setBool(std::string key, bool value); // Reload the configuration bool reload(); // Reload the configuration using the specified configuration loader bool reload(ConfigLoader* inConfigLoader); private: Configuration(); #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif std::map stringConfiguration; std::map integerConfiguration; std::map booleanConfiguration; ConfigLoader* configLoader; static const struct config valid_config[]; }; #endif // !_SOFTHSM_V2_CONFIGURATION_H softhsm-2.0.0/src/lib/common/HandleFactory.h0000664000175000017500000000601412533040716015642 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HandleFactory.h This is a template class for handling handles ;-) *****************************************************************************/ #ifndef _SOFTHSM_V2_HANDLEFACTORY_H #define _SOFTHSM_V2_HANDLEFACTORY_H #include "config.h" #include "log.h" #include "MutexFactory.h" #include #include template class HandleFactory { public: // Constructor HandleFactory() { nextFree = (hType) 1; handleMutex = MutexFactory::i()->getMutex(); } // Destructor virtual ~HandleFactory() { MutexFactory::i()->recycleMutex(handleMutex); } // Get a new handle for the specified object hType getHandle(oType object) { MutexLocker lock(handleMutex); hType handle; if (!recycledHandles.empty()) { handle = recycledHandles.front(); recycledHandles.pop(); } else { handle = nextFree++; } handleMap[handle] = object; return handle; } // Check whether the specified handle is valid bool isValid(hType handle) { MutexLocker lock(handleMutex); return (handleMap.find(handle) != handleMap.end()); } // Return the object for the specified handle oType getObjectByHandle(hType handle) { MutexLocker lock(handleMutex); return handleMap[handle]; } // Discard the specified handle void deleteHandle(hType handle) { MutexLocker lock(handleMutex); handleMap.erase(handle); recycledHandles.push(handle); } private: // The handle map std::map handleMap; // The set of recycled handles std::queue recycledHandles; // The next free handle hType nextFree; // Cross-thread synchronisation Mutex* handleMutex; }; #endif // !_SOFTHSM_V2_HANDLEFACTORY_H softhsm-2.0.0/src/lib/common/MutexFactory.cpp0000664000175000017500000001101112533040716016075 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** MutexFactory.cpp This factory produces OS specific mutex objects *****************************************************************************/ #include "config.h" #include "MutexFactory.h" #include "osmutex.h" #include /***************************************************************************** Mutex implementation *****************************************************************************/ // Constructor Mutex::Mutex() { isValid = (MutexFactory::i()->CreateMutex(&handle) == CKR_OK); } // Destructor Mutex::~Mutex() { if (isValid) { MutexFactory::i()->DestroyMutex(handle); } } // Lock the mutex bool Mutex::lock() { return (isValid && (MutexFactory::i()->LockMutex(handle) == CKR_OK)); } // Unlock the mutex void Mutex::unlock() { if (isValid) { MutexFactory::i()->UnlockMutex(handle); } } /***************************************************************************** MutexLocker implementation *****************************************************************************/ // Constructor MutexLocker::MutexLocker(Mutex* inMutex) { mutex = inMutex; if (mutex != NULL) mutex->lock(); } // Destructor MutexLocker::~MutexLocker() { if (mutex != NULL) mutex->unlock(); } /***************************************************************************** MutexFactory implementation *****************************************************************************/ // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr MutexFactory::instance(nullptr); #else std::auto_ptr MutexFactory::instance(NULL); #endif // Constructor MutexFactory::MutexFactory() { createMutex = OSCreateMutex; destroyMutex = OSDestroyMutex; lockMutex = OSLockMutex; unlockMutex = OSUnlockMutex; enabled = true; } // Destructor MutexFactory::~MutexFactory() { } // Return the one-and-only instance MutexFactory* MutexFactory::i() { if (!instance.get()) { instance.reset(new MutexFactory()); } return instance.get(); } // Get a mutex instance Mutex* MutexFactory::getMutex() { return new Mutex(); } // Recycle a mutex instance void MutexFactory::recycleMutex(Mutex* mutex) { if (mutex != NULL) delete mutex; } // Set the function pointers void MutexFactory::setCreateMutex(CK_CREATEMUTEX inCreateMutex) { createMutex = inCreateMutex; } void MutexFactory::setDestroyMutex(CK_DESTROYMUTEX inDestroyMutex) { destroyMutex = inDestroyMutex; } void MutexFactory::setLockMutex(CK_LOCKMUTEX inLockMutex) { lockMutex = inLockMutex; } void MutexFactory::setUnlockMutex(CK_UNLOCKMUTEX inUnlockMutex) { unlockMutex = inUnlockMutex; } void MutexFactory::enable() { enabled = true; } void MutexFactory::disable() { enabled = false; } CK_RV MutexFactory::CreateMutex(CK_VOID_PTR_PTR newMutex) { if (!enabled) return CKR_OK; return (this->createMutex)(newMutex); } CK_RV MutexFactory::DestroyMutex(CK_VOID_PTR mutex) { if (!enabled) return CKR_OK; return (this->destroyMutex)(mutex); } CK_RV MutexFactory::LockMutex(CK_VOID_PTR mutex) { if (!enabled) return CKR_OK; return (this->lockMutex)(mutex); } CK_RV MutexFactory::UnlockMutex(CK_VOID_PTR mutex) { if (!enabled) return CKR_OK; return (this->unlockMutex)(mutex); } softhsm-2.0.0/src/lib/common/fatal.cpp0000664000175000017500000000406312533040716014543 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** fatal.cpp Implementens calls for handling fatal exceptions. When a fatal exception occurs, this code ensures that as much of the securely allocated memory as possible is wiped clean. *****************************************************************************/ #include "config.h" #include "log.h" #include "fatal.h" #include "SecureMemoryRegistry.h" #include "pkcs11.h" void FatalException(void) { try { DEBUG_MSG("Fatal exception handler called"); } catch (...) { } // Wipe as much of the securely allocated memory as possible SecureMemoryRegistry::i()->wipe(); try { ERROR_MSG("A fatal exception occurred; exiting..."); } catch (...) { } exit(CKR_GENERAL_ERROR); } softhsm-2.0.0/src/lib/common/Serialisable.h0000664000175000017500000000354012533040716015517 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Serialisable.h Interface description for serialisable classes *****************************************************************************/ #ifndef _SOFTHSM_V2_SERIALISABLE_H #define _SOFTHSM_V2_SERIALISABLE_H #include "config.h" #include "ByteString.h" class ByteString; class Serialisable { public: // Serialise the data content of a class virtual ByteString serialise() const = 0; // Default destructor virtual ~Serialisable() { } }; #endif // !_SOFTHSM_V2_SERIALISABLE_H softhsm-2.0.0/src/lib/common/osmutex.h0000664000175000017500000000371112533040716014624 00000000000000/* * Copyright (c) 2008-2010 .SE (The Internet Infrastructure Foundation). * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** osmutex.h Contains OS-specific implementations of intraprocess mutex functions. This implementation is based on SoftHSM v1 *****************************************************************************/ #ifndef _SOFTHSM_V2_OSMUTEX_H #define _SOFTHSM_V2_OSMUTEX_H #include "config.h" #include "cryptoki.h" CK_RV OSCreateMutex(CK_VOID_PTR_PTR newMutex); CK_RV OSDestroyMutex(CK_VOID_PTR mutex); CK_RV OSLockMutex(CK_VOID_PTR mutex); CK_RV OSUnlockMutex(CK_VOID_PTR mutex); #endif /* !_SOFTHSM_V2_OSMUTEX_H */ softhsm-2.0.0/src/lib/common/Makefile.in0000664000175000017500000005616212552216620015024 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src/lib/common DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(srcdir)/softhsm2.conf.in $(srcdir)/softhsm2.conf.5.in \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = softhsm2.conf softhsm2.conf.5 CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_common_la_LIBADD = am_libsofthsm_common_la_OBJECTS = Configuration.lo fatal.lo log.lo \ osmutex.lo SimpleConfigLoader.lo MutexFactory.lo libsofthsm_common_la_OBJECTS = $(am_libsofthsm_common_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_common_la_SOURCES) DIST_SOURCES = $(libsofthsm_common_la_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } man5dir = $(mandir)/man5 am__installdirs = "$(DESTDIR)$(man5dir)" NROFF = nroff MANS = $(man_MANS) am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/.. noinst_LTLIBRARIES = libsofthsm_common.la libsofthsm_common_la_SOURCES = Configuration.cpp \ fatal.cpp \ log.cpp \ osmutex.cpp \ SimpleConfigLoader.cpp \ MutexFactory.cpp man_MANS = softhsm2.conf.5 EXTRA_DIST = $(srcdir)/*.h \ $(srcdir)/softhsm2.conf.5.in all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/common/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/common/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): softhsm2.conf: $(top_builddir)/config.status $(srcdir)/softhsm2.conf.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ softhsm2.conf.5: $(top_builddir)/config.status $(srcdir)/softhsm2.conf.5.in cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_common.la: $(libsofthsm_common_la_OBJECTS) $(libsofthsm_common_la_DEPENDENCIES) $(EXTRA_libsofthsm_common_la_DEPENDENCIES) $(AM_V_CXXLD)$(CXXLINK) $(libsofthsm_common_la_OBJECTS) $(libsofthsm_common_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Configuration.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/MutexFactory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SimpleConfigLoader.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/fatal.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/log.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/osmutex.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs install-man5: $(man_MANS) @$(NORMAL_INSTALL) @list1=''; \ list2='$(man_MANS)'; \ test -n "$(man5dir)" \ && test -n "`echo $$list1$$list2`" \ || exit 0; \ echo " $(MKDIR_P) '$(DESTDIR)$(man5dir)'"; \ $(MKDIR_P) "$(DESTDIR)$(man5dir)" || exit 1; \ { for i in $$list1; do echo "$$i"; done; \ if test -n "$$list2"; then \ for i in $$list2; do echo "$$i"; done \ | sed -n '/\.5[a-z]*$$/p'; \ fi; \ } | while read p; do \ if test -f $$p; then d=; else d="$(srcdir)/"; fi; \ echo "$$d$$p"; echo "$$p"; \ done | \ sed -e 'n;s,.*/,,;p;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,' | \ sed 'N;N;s,\n, ,g' | { \ list=; while read file base inst; do \ if test "$$base" = "$$inst"; then list="$$list $$file"; else \ echo " $(INSTALL_DATA) '$$file' '$(DESTDIR)$(man5dir)/$$inst'"; \ $(INSTALL_DATA) "$$file" "$(DESTDIR)$(man5dir)/$$inst" || exit $$?; \ fi; \ done; \ for i in $$list; do echo "$$i"; done | $(am__base_list) | \ while read files; do \ test -z "$$files" || { \ echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(man5dir)'"; \ $(INSTALL_DATA) $$files "$(DESTDIR)$(man5dir)" || exit $$?; }; \ done; } uninstall-man5: @$(NORMAL_UNINSTALL) @list=''; test -n "$(man5dir)" || exit 0; \ files=`{ for i in $$list; do echo "$$i"; done; \ l2='$(man_MANS)'; for i in $$l2; do echo "$$i"; done | \ sed -n '/\.5[a-z]*$$/p'; \ } | sed -e 's,.*/,,;h;s,.*\.,,;s,^[^5][0-9a-z]*$$,5,;x' \ -e 's,\.[0-9a-z]*$$,,;$(transform);G;s,\n,.,'`; \ dir='$(DESTDIR)$(man5dir)'; $(am__uninstall_files_from_dir) ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am check: check-am all-am: Makefile $(LTLIBRARIES) $(MANS) installdirs: for dir in "$(DESTDIR)$(man5dir)"; do \ test -z "$$dir" || $(MKDIR_P) "$$dir"; \ done install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-man @$(NORMAL_INSTALL) $(MAKE) $(AM_MAKEFLAGS) install-data-hook install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-man5 install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: uninstall-man uninstall-man: uninstall-man5 .MAKE: install-am install-data-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-am clean clean-generic \ clean-libtool clean-noinstLTLIBRARIES cscopelist-am ctags \ ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-data-hook install-dvi install-dvi-am \ install-exec install-exec-am install-html install-html-am \ install-info install-info-am install-man install-man5 \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ maintainer-clean maintainer-clean-generic mostlyclean \ mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ uninstall-man uninstall-man5 install-data-hook: test -d ${DESTDIR}${sysconfdir} || \ ${INSTALL} -d ${DESTDIR}${sysconfdir} test -f ${DESTDIR}${sysconfdir}/softhsm2.conf || \ ${INSTALL_DATA} ${top_builddir}/src/lib/common/softhsm2.conf ${DESTDIR}${sysconfdir} ${INSTALL_DATA} ${top_builddir}/src/lib/common/softhsm2.conf ${DESTDIR}${sysconfdir}/softhsm2.conf.sample test -d ${DESTDIR}${softhsmtokendir} || \ ${INSTALL} -d -m 700 ${DESTDIR}${softhsmtokendir} # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/common/log.cpp0000664000175000017500000000624512533040716014241 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** log.cpp Implements logging functions. This file is based on the concepts from SoftHSM v1 but extends the logging functions with support for a variable argument list as defined in stdarg (3). *****************************************************************************/ #include "config.h" #include #include #include #include #include #include "log.h" int softLogLevel = LOG_DEBUG; bool setLogLevel(const std::string &loglevel) { if (loglevel == "ERROR") { softLogLevel = LOG_ERR; } else if (loglevel == "WARNING") { softLogLevel = LOG_WARNING; } else if (loglevel == "INFO") { softLogLevel = LOG_INFO; } else if (loglevel == "DEBUG") { softLogLevel = LOG_DEBUG; } else { ERROR_MSG("Unknown value (%s) for log.level in configuration", loglevel.c_str()); return false; } return true; } void softHSMLog(const int loglevel, const char* functionName, const char* fileName, const int lineNo, const char* format, ...) { if (loglevel > softLogLevel) return; std::stringstream prepend; #ifdef SOFTHSM_LOG_FILE_AND_LINE prepend << fileName << "(" << lineNo << ")"; #ifndef SOFTHSM_LOG_FUNCTION_NAME (void) functionName; prepend << ":"; #endif // !SOFTHSM_LOG_FUNCTION_NAME prepend << " "; #endif // SOFTHSM_LOG_FILE_AND_LINE #ifdef SOFTHSM_LOG_FUNCTION_NAME prepend << functionName << ": "; #endif // SOFTHSM_LOG_FUNCTION_NAME // Print the format to a log message std::vector logMessage; va_list args; logMessage.resize(4096); va_start(args, format); vsnprintf(&logMessage[0], 4096, format, args); va_end(args); // And log it syslog(loglevel, "%s%s", prepend.str().c_str(), &logMessage[0]); #ifdef DEBUG_LOG_STDERR fprintf(stderr, "%s%s\n", prepend.str().c_str(), &logMessage[0]); fflush(stderr); #endif // DEBUG_LOG_STDERR } softhsm-2.0.0/src/lib/common/log.h0000664000175000017500000000633112533040716013702 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** log.h Implements logging functions. This file is based on the concepts from SoftHSM v1 but extends the logging functions with support for a variable argument list as defined in stdarg (3). *****************************************************************************/ #ifndef _SOFTHSM_V2_LOG_H #define _SOFTHSM_V2_LOG_H #include "config.h" #include #include /* Unset this define if you don't want to log the source file name and line number */ #define SOFTHSM_LOG_FILE_AND_LINE /* Set this define to log the function name */ /* #define SOFTHSM_LOG_FUNCTION_NAME */ /* Define this symbol (either here or in the build setup) to log to stderr */ /* #define DEBUG_LOG_STDERR */ /* Logging errors */ #ifndef _WIN32 #define ERROR_MSG(...) softHSMLog(LOG_ERR, __func__, __FILE__, __LINE__, __VA_ARGS__); #else #define ERROR_MSG(...) softHSMLog(LOG_ERR, __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__); #endif /* Logging warnings */ #ifndef _WIN32 #define WARNING_MSG(...) softHSMLog(LOG_WARNING, __func__, __FILE__, __LINE__, __VA_ARGS__); #else #define WARNING_MSG(...) softHSMLog(LOG_WARNING, __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__); #endif /* Logging information */ #ifndef _WIN32 #define INFO_MSG(...) softHSMLog(LOG_INFO, __func__, __FILE__, __LINE__, __VA_ARGS__); #else #define INFO_MSG(...) softHSMLog(LOG_INFO, __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__); #endif /* Logging debug information */ #ifndef _WIN32 #define DEBUG_MSG(...) softHSMLog(LOG_DEBUG, __func__, __FILE__, __LINE__, __VA_ARGS__); #else #define DEBUG_MSG(...) softHSMLog(LOG_DEBUG, __FUNCTION__, __FILE__, __LINE__, __VA_ARGS__); #endif /* Function definitions */ bool setLogLevel(const std::string &loglevel); void softHSMLog(const int loglevel, const char* functionName, const char* fileName, const int lineNo, const char* format, ...); #endif /* !_SOFTHSM_V2_LOG_H */ softhsm-2.0.0/src/lib/common/softhsm2.conf.5.in0000664000175000017500000000370612533040716016137 00000000000000.TH softhsm2.conf 5 "30 October 2014" "SoftHSM" .SH NAME softhsm2.conf \- SoftHSM configuration file .SH SYNOPSIS .B softhsm2.conf .SH DESCRIPTION This is the configuration file for SoftHSM. It can be found on a default location, but can also be relocated by using the environment variable. Any configuration must be done according to the file format found in this document. .SH FILE FORMAT Each configuration option is a pair of name and value separated by a equality sign. The configuration option must be located on a single line. .LP .RS .nf = .fi .RE .LP It is also possible to add comments in the file by using the hash sign. Anything after the hash sign will be ignored. .LP .RS .nf # A comment .RE .LP Any empty lines or lines that does not have the correct format will be ignored. .SH DIRECTORIES.TOKENDIR The location where SoftHSM can store the tokens. .LP .RS .nf directories.tokendir = @softhsmtokendir@ .fi .RE .LP .SH OBJECTSTORE.BACKEND The backend to use by SoftHSM to store token objects. Either "file" or "db" is supported. In order to use the "db" backend, the SoftHSM build needs to be configured with "configure --with-objectstore-backend-db" .LP .RS .nf objectstore.backend = file .fi .RE .LP .SH LOG.LEVEL The log level which can be set to ERROR, WARNING, INFO or DEBUG. .LP .RS .nf log.level = INFO .fi .RE .LP .SH ENVIRONMENT .TP SOFTHSM2_CONF When defined, the value will be used as path to the configuration file. .SH FILES .TP .I ~/.config/softhsm2/softhsm2.conf default user-specific location of the SoftHSM configuration file; if it exists it will override the system wide configuration .TP .I @default_softhsm2_conf@ default system-wide location of the SoftHSM configuration file .TP .I @default_softhsm2_conf@.sample an example of a SoftHSM configuration file .SH AUTHOR Written by Rickard Bellgrim, Francis Dupont, René Post, and Roland van Rijswijk. .SH "SEE ALSO" .IR softhsm2-keyconv (1), .IR softhsm2-migrate (1), .IR softhsm2-util (1) softhsm-2.0.0/src/lib/common/SimpleConfigLoader.h0000664000175000017500000000427512533040716016634 00000000000000/* * Copyright (c) 2010 .SE, The Internet Infrastructure Foundation * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SimpleConfigLoader.h Loads the configuration from the configuration file. *****************************************************************************/ #ifndef _SOFTHSM_V2_SIMPLECONFIGLOADER_H #define _SOFTHSM_V2_SIMPLECONFIGLOADER_H #include #include "config.h" #include "Configuration.h" class SimpleConfigLoader : public ConfigLoader { public: static SimpleConfigLoader* i(); virtual ~SimpleConfigLoader() { } virtual bool loadConfiguration(); private: SimpleConfigLoader(); char* getConfigPath(); char* trimString(char* text); bool string2bool(std::string stringValue, bool* boolValue); #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif }; #endif // !_SOFTHSM_V2_SIMPLECONFIGLOADER_H softhsm-2.0.0/src/lib/SoftHSM.cpp0000664000175000017500000106454012533040736013460 00000000000000/* * Copyright (c) 2010 SURFnet bv * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SoftHSM.cpp The implementation of the SoftHSM's main class *****************************************************************************/ #include "config.h" #include "log.h" #include "access.h" #include "Configuration.h" #include "SimpleConfigLoader.h" #include "MutexFactory.h" #include "SecureMemoryRegistry.h" #include "CryptoFactory.h" #include "AsymmetricAlgorithm.h" #include "SymmetricAlgorithm.h" #include "AESKey.h" #include "DESKey.h" #include "RNG.h" #include "RSAParameters.h" #include "RSAPublicKey.h" #include "RSAPrivateKey.h" #include "DSAParameters.h" #include "DSAPublicKey.h" #include "DSAPrivateKey.h" #include "ECPublicKey.h" #include "ECPrivateKey.h" #include "ECParameters.h" #include "DHParameters.h" #include "DHPublicKey.h" #include "DHPrivateKey.h" #include "GOSTPublicKey.h" #include "GOSTPrivateKey.h" #include "cryptoki.h" #include "SoftHSM.h" #include "osmutex.h" #include "SessionManager.h" #include "SessionObjectStore.h" #include "HandleManager.h" #include "P11Objects.h" #include "odd.h" #include static CK_RV newP11Object(CK_OBJECT_CLASS objClass, CK_KEY_TYPE keyType, CK_CERTIFICATE_TYPE certType, P11Object **p11object) { switch(objClass) { case CKO_DATA: *p11object = new P11DataObj(); break; case CKO_CERTIFICATE: if (certType == CKC_X_509) *p11object = new P11X509CertificateObj(); else if (certType == CKC_OPENPGP) *p11object = new P11OpenPGPPublicKeyObj(); else return CKR_ATTRIBUTE_VALUE_INVALID; break; case CKO_PUBLIC_KEY: if (keyType == CKK_RSA) *p11object = new P11RSAPublicKeyObj(); else if (keyType == CKK_DSA) *p11object = new P11DSAPublicKeyObj(); else if (keyType == CKK_EC) *p11object = new P11ECPublicKeyObj(); else if (keyType == CKK_DH) *p11object = new P11DHPublicKeyObj(); else if (keyType == CKK_GOSTR3410) *p11object = new P11GOSTPublicKeyObj(); else return CKR_ATTRIBUTE_VALUE_INVALID; break; case CKO_PRIVATE_KEY: // we need to know the type too if (keyType == CKK_RSA) *p11object = new P11RSAPrivateKeyObj(); else if (keyType == CKK_DSA) *p11object = new P11DSAPrivateKeyObj(); else if (keyType == CKK_EC) *p11object = new P11ECPrivateKeyObj(); else if (keyType == CKK_DH) *p11object = new P11DHPrivateKeyObj(); else if (keyType == CKK_GOSTR3410) *p11object = new P11GOSTPrivateKeyObj(); else return CKR_ATTRIBUTE_VALUE_INVALID; break; case CKO_SECRET_KEY: if ((keyType == CKK_GENERIC_SECRET) || (keyType == CKK_MD5_HMAC) || (keyType == CKK_SHA_1_HMAC) || (keyType == CKK_SHA224_HMAC) || (keyType == CKK_SHA256_HMAC) || (keyType == CKK_SHA384_HMAC) || (keyType == CKK_SHA512_HMAC)) { P11GenericSecretKeyObj* key = new P11GenericSecretKeyObj(); *p11object = key; key->setKeyType(keyType); } else if (keyType == CKK_AES) { *p11object = new P11AESSecretKeyObj(); } else if ((keyType == CKK_DES) || (keyType == CKK_DES2) || (keyType == CKK_DES3)) { P11DESSecretKeyObj* key = new P11DESSecretKeyObj(); *p11object = key; key->setKeyType(keyType); } else if (keyType == CKK_GOST28147) { *p11object = new P11GOSTSecretKeyObj(); } else return CKR_ATTRIBUTE_VALUE_INVALID; break; case CKO_DOMAIN_PARAMETERS: if (keyType == CKK_DSA) *p11object = new P11DSADomainObj(); else if (keyType == CKK_DH) *p11object = new P11DHDomainObj(); else return CKR_ATTRIBUTE_VALUE_INVALID; break; default: return CKR_ATTRIBUTE_VALUE_INVALID; // invalid value for a valid argument } return CKR_OK; } static CK_RV extractObjectInformation(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_CLASS &objClass, CK_KEY_TYPE &keyType, CK_CERTIFICATE_TYPE &certType, CK_BBOOL &isOnToken, CK_BBOOL &isPrivate, bool bImplicit) { bool bHasClass = false; bool bHasKeyType = false; bool bHasCertType = false; // Extract object information for (CK_ULONG i = 0; i < ulCount; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: if (pTemplate[i].ulValueLen == sizeof(CK_OBJECT_CLASS)) { objClass = *(CK_OBJECT_CLASS_PTR)pTemplate[i].pValue; bHasClass = true; } break; case CKA_KEY_TYPE: if (pTemplate[i].ulValueLen == sizeof(CK_KEY_TYPE)) { keyType = *(CK_KEY_TYPE*)pTemplate[i].pValue; bHasKeyType = true; } break; case CKA_CERTIFICATE_TYPE: if (pTemplate[i].ulValueLen == sizeof(CK_CERTIFICATE_TYPE)) { certType = *(CK_CERTIFICATE_TYPE*)pTemplate[i].pValue; bHasCertType = true; } break; case CKA_TOKEN: if (pTemplate[i].ulValueLen == sizeof(CK_BBOOL)) { isOnToken = *(CK_BBOOL*)pTemplate[i].pValue; } break; case CKA_PRIVATE: if (pTemplate[i].ulValueLen == sizeof(CK_BBOOL)) { isPrivate = *(CK_BBOOL*)pTemplate[i].pValue; } break; default: break; } } if (bImplicit) { return CKR_OK; } if (!bHasClass) { return CKR_TEMPLATE_INCOMPLETE; } bool bKeyTypeRequired = (objClass == CKO_PUBLIC_KEY || objClass == CKO_PRIVATE_KEY || objClass == CKO_SECRET_KEY); if (bKeyTypeRequired && !bHasKeyType) { return CKR_TEMPLATE_INCOMPLETE; } bool bCertTypeRequired = (objClass == CKO_CERTIFICATE); if (bCertTypeRequired && !bHasCertType) { return CKR_TEMPLATE_INCOMPLETE; } return CKR_OK; } static CK_RV newP11Object(OSObject *object, P11Object **p11object) { CK_OBJECT_CLASS objClass = object->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED); CK_KEY_TYPE keyType = CKK_RSA; CK_CERTIFICATE_TYPE certType = CKC_X_509; if (object->attributeExists(CKA_KEY_TYPE)) keyType = object->getUnsignedLongValue(CKA_KEY_TYPE, CKK_RSA); if (object->attributeExists(CKA_CERTIFICATE_TYPE)) certType = object->getUnsignedLongValue(CKA_CERTIFICATE_TYPE, CKC_X_509); CK_RV rv = newP11Object(objClass,keyType,certType,p11object); if (rv != CKR_OK) return rv; if (!(*p11object)->init(object)) return CKR_GENERAL_ERROR; // something went wrong that shouldn't have. return CKR_OK; } #ifdef notyet static CK_ATTRIBUTE bsAttribute(CK_ATTRIBUTE_TYPE type, const ByteString &value) { CK_ATTRIBUTE attr = {type, (CK_VOID_PTR)value.const_byte_str(), value.size() }; return attr; } #endif static void libcleanup() { SoftHSM::i()->C_Finalize(NULL); } /***************************************************************************** Implementation of SoftHSM class specific functions *****************************************************************************/ // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr SoftHSM::instance(nullptr); #else std::auto_ptr SoftHSM::instance(NULL); #endif // Return the one-and-only instance SoftHSM* SoftHSM::i() { if (!instance.get()) { instance.reset(new SoftHSM()); } return instance.get(); } void SoftHSM::reset() { if (instance.get()) instance.reset(); } // Constructor SoftHSM::SoftHSM() { isInitialised = false; sessionObjectStore = NULL; objectStore = NULL; slotManager = NULL; sessionManager = NULL; handleManager = NULL; } // Destructor SoftHSM::~SoftHSM() { if (handleManager != NULL) delete handleManager; if (sessionManager != NULL) delete sessionManager; if (slotManager != NULL) delete slotManager; if (objectStore != NULL) delete objectStore; if (sessionObjectStore != NULL) delete sessionObjectStore; } /***************************************************************************** Implementation of PKCS #11 functions *****************************************************************************/ // PKCS #11 initialisation function CK_RV SoftHSM::C_Initialize(CK_VOID_PTR pInitArgs) { CK_C_INITIALIZE_ARGS_PTR args; // Check if PKCS #11 is already initialised if (isInitialised) { return CKR_CRYPTOKI_ALREADY_INITIALIZED; } // Do we have any arguments? if (pInitArgs != NULL_PTR) { args = (CK_C_INITIALIZE_ARGS_PTR)pInitArgs; // Must be set to NULL_PTR in this version of PKCS#11 if (args->pReserved != NULL_PTR) { DEBUG_MSG("pReserved must be set to NULL_PTR"); return CKR_ARGUMENTS_BAD; } // Can we spawn our own threads? // if (args->flags & CKF_LIBRARY_CANT_CREATE_OS_THREADS) // { // DEBUG_MSG("Cannot create threads if CKF_LIBRARY_CANT_CREATE_OS_THREADS is set"); // return CKR_NEED_TO_CREATE_THREADS; // } // Are we not supplied with mutex functions? if ( args->CreateMutex == NULL_PTR && args->DestroyMutex == NULL_PTR && args->LockMutex == NULL_PTR && args->UnlockMutex == NULL_PTR ) { // Can we use our own mutex functions? if (args->flags & CKF_OS_LOCKING_OK) { // Use our own mutex functions. MutexFactory::i()->setCreateMutex(OSCreateMutex); MutexFactory::i()->setDestroyMutex(OSDestroyMutex); MutexFactory::i()->setLockMutex(OSLockMutex); MutexFactory::i()->setUnlockMutex(OSUnlockMutex); MutexFactory::i()->enable(); } else { // The external application is not using threading MutexFactory::i()->disable(); } } else { // We must have all mutex functions if ( args->CreateMutex == NULL_PTR || args->DestroyMutex == NULL_PTR || args->LockMutex == NULL_PTR || args->UnlockMutex == NULL_PTR ) { DEBUG_MSG("Not all mutex functions are supplied"); return CKR_ARGUMENTS_BAD; } // We could use our own mutex functions if the flag is set, // but we use the external functions in both cases. // Load the external mutex functions MutexFactory::i()->setCreateMutex(args->CreateMutex); MutexFactory::i()->setDestroyMutex(args->DestroyMutex); MutexFactory::i()->setLockMutex(args->LockMutex); MutexFactory::i()->setUnlockMutex(args->UnlockMutex); MutexFactory::i()->enable(); } } else { // No concurrent access by multiple threads MutexFactory::i()->disable(); } // Initiate SecureMemoryRegistry if (SecureMemoryRegistry::i() == NULL) { return CKR_GENERAL_ERROR; } // Build the CryptoFactory if (CryptoFactory::i() == NULL) { return CKR_GENERAL_ERROR; } #ifdef WITH_FIPS // Check the FIPS status if (!CryptoFactory::i()->getFipsSelfTestStatus()) { return CKR_FIPS_SELF_TEST_FAILED; } #endif // (Re)load the configuration if (!Configuration::i()->reload(SimpleConfigLoader::i())) { return CKR_GENERAL_ERROR; } // Configure the log level if (!setLogLevel(Configuration::i()->getString("log.level", DEFAULT_LOG_LEVEL))) { return CKR_GENERAL_ERROR; } // Configure object store storage backend used by all tokens. if (!ObjectStoreToken::selectBackend(Configuration::i()->getString("objectstore.backend", DEFAULT_OBJECTSTORE_BACKEND))) { return CKR_GENERAL_ERROR; } sessionObjectStore = new SessionObjectStore(); // Load the object store objectStore = new ObjectStore(Configuration::i()->getString("directories.tokendir", DEFAULT_TOKENDIR)); if (!objectStore->isValid()) { ERROR_MSG("Could not load the object store"); delete objectStore; objectStore = NULL; delete sessionObjectStore; sessionObjectStore = NULL; return CKR_GENERAL_ERROR; } // Load the slot manager slotManager = new SlotManager(objectStore); // Load the session manager sessionManager = new SessionManager(); // Load the handle manager handleManager = new HandleManager(); // Set the state to initialised isInitialised = true; // Hook cleanup on dlclose() or exit() atexit(libcleanup); return CKR_OK; } // PKCS #11 finalisation function CK_RV SoftHSM::C_Finalize(CK_VOID_PTR pReserved) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Must be set to NULL_PTR in this version of PKCS#11 if (pReserved != NULL_PTR) return CKR_ARGUMENTS_BAD; if (handleManager != NULL) delete handleManager; handleManager = NULL; if (sessionManager != NULL) delete sessionManager; sessionManager = NULL; if (slotManager != NULL) delete slotManager; slotManager = NULL; if (objectStore != NULL) delete objectStore; objectStore = NULL; if (sessionObjectStore != NULL) delete sessionObjectStore; sessionObjectStore = NULL; CryptoFactory::reset(); SecureMemoryRegistry::reset(); // TODO: What should we finalize? isInitialised = false; SoftHSM::reset(); return CKR_OK; } // Return information about the PKCS #11 module CK_RV SoftHSM::C_GetInfo(CK_INFO_PTR pInfo) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pInfo == NULL_PTR) return CKR_ARGUMENTS_BAD; pInfo->cryptokiVersion.major = CRYPTOKI_VERSION_MAJOR; pInfo->cryptokiVersion.minor = CRYPTOKI_VERSION_MINOR; memset(pInfo->manufacturerID, ' ', 32); memcpy(pInfo->manufacturerID, "SoftHSM", 7); pInfo->flags = 0; memset(pInfo->libraryDescription, ' ', 32); #ifdef WITH_FIPS memcpy(pInfo->libraryDescription, "Implementation of PKCS11+FIPS", 29); #else memcpy(pInfo->libraryDescription, "Implementation of PKCS11", 24); #endif pInfo->libraryVersion.major = VERSION_MAJOR; pInfo->libraryVersion.minor = VERSION_MINOR; return CKR_OK; } // Return a list of available slots CK_RV SoftHSM::C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; return slotManager->getSlotList(tokenPresent, pSlotList, pulCount); } // Return information about a slot CK_RV SoftHSM::C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; Slot* slot = slotManager->getSlot(slotID); if (slot == NULL) { return CKR_SLOT_ID_INVALID; } return slot->getSlotInfo(pInfo); } // Return information about a token in a slot CK_RV SoftHSM::C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; Slot* slot = slotManager->getSlot(slotID); if (slot == NULL) { return CKR_SLOT_ID_INVALID; } Token* token = slot->getToken(); if (token == NULL) { return CKR_TOKEN_NOT_PRESENT; } return token->getTokenInfo(pInfo); } // Return the list of supported mechanisms for a given slot CK_RV SoftHSM::C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount) { // A list with the supported mechanisms CK_ULONG nrSupportedMechanisms = 58; #ifdef WITH_ECC nrSupportedMechanisms += 3; #endif #ifdef WITH_FIPS nrSupportedMechanisms -= 9; #endif #ifdef WITH_GOST nrSupportedMechanisms += 5; #endif #ifdef HAVE_AES_KEY_WRAP_PAD nrSupportedMechanisms += 1; #endif CK_MECHANISM_TYPE supportedMechanisms[] = { #ifndef WITH_FIPS CKM_MD5, #endif CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, CKM_SHA512, #ifndef WITH_FIPS CKM_MD5_HMAC, #endif CKM_SHA_1_HMAC, CKM_SHA224_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_PKCS, CKM_RSA_X_509, #ifndef WITH_FIPS CKM_MD5_RSA_PKCS, #endif CKM_SHA1_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_SHA224_RSA_PKCS, CKM_SHA256_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_SHA1_RSA_PKCS_PSS, CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, CKM_SHA512_RSA_PKCS_PSS, #ifndef WITH_FIPS CKM_DES_KEY_GEN, #endif CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, #ifndef WITH_FIPS CKM_DES_ECB, CKM_DES_CBC, CKM_DES_CBC_PAD, CKM_DES_ECB_ENCRYPT_DATA, CKM_DES_CBC_ENCRYPT_DATA, #endif CKM_DES3_ECB, CKM_DES3_CBC, CKM_DES3_CBC_PAD, CKM_DES3_ECB_ENCRYPT_DATA, CKM_DES3_CBC_ENCRYPT_DATA, CKM_AES_KEY_GEN, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, CKM_AES_KEY_WRAP, #ifdef HAVE_AES_KEY_WRAP_PAD CKM_AES_KEY_WRAP_PAD, #endif CKM_AES_ECB_ENCRYPT_DATA, CKM_AES_CBC_ENCRYPT_DATA, CKM_DSA_PARAMETER_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA, CKM_DSA_SHA1, CKM_DSA_SHA224, CKM_DSA_SHA256, CKM_DSA_SHA384, CKM_DSA_SHA512, CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKM_DH_PKCS_DERIVE, #ifdef WITH_ECC CKM_EC_KEY_PAIR_GEN, CKM_ECDSA, CKM_ECDH1_DERIVE, #endif #ifdef WITH_GOST CKM_GOSTR3411, CKM_GOSTR3411_HMAC, CKM_GOSTR3410_KEY_PAIR_GEN, CKM_GOSTR3410, CKM_GOSTR3410_WITH_GOSTR3411 #endif }; if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pulCount == NULL_PTR) return CKR_ARGUMENTS_BAD; Slot* slot = slotManager->getSlot(slotID); if (slot == NULL) { return CKR_SLOT_ID_INVALID; } if (pMechanismList == NULL_PTR) { *pulCount = nrSupportedMechanisms; return CKR_OK; } if (*pulCount < nrSupportedMechanisms) { *pulCount = nrSupportedMechanisms; return CKR_BUFFER_TOO_SMALL; } *pulCount = nrSupportedMechanisms; for (CK_ULONG i = 0; i < nrSupportedMechanisms; i ++) { pMechanismList[i] = supportedMechanisms[i]; } return CKR_OK; } // Return more information about a mechanism for a given slot CK_RV SoftHSM::C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo) { unsigned long rsaMinSize, rsaMaxSize; unsigned long dsaMinSize, dsaMaxSize; unsigned long dhMinSize, dhMaxSize; #ifdef WITH_ECC unsigned long ecdsaMinSize, ecdsaMaxSize; unsigned long ecdhMinSize, ecdhMaxSize; #endif if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pInfo == NULL_PTR) return CKR_ARGUMENTS_BAD; Slot* slot = slotManager->getSlot(slotID); if (slot == NULL) { return CKR_SLOT_ID_INVALID; } AsymmetricAlgorithm* rsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (rsa != NULL) { rsaMinSize = rsa->getMinKeySize(); rsaMaxSize = rsa->getMaxKeySize(); } else { return CKR_GENERAL_ERROR; } CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); AsymmetricAlgorithm* dsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); if (dsa != NULL) { dsaMinSize = dsa->getMinKeySize(); // Limitation in PKCS#11 if (dsaMinSize < 512) { dsaMinSize = 512; } dsaMaxSize = dsa->getMaxKeySize(); // Limitation in PKCS#11 if (dsaMaxSize > 1024) { dsaMaxSize = 1024; } } else { return CKR_GENERAL_ERROR; } CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); AsymmetricAlgorithm* dh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DH); if (dh != NULL) { dhMinSize = dh->getMinKeySize(); dhMaxSize = dh->getMaxKeySize(); } else { return CKR_GENERAL_ERROR; } CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); #ifdef WITH_ECC AsymmetricAlgorithm* ecdsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDSA); if (ecdsa != NULL) { ecdsaMinSize = ecdsa->getMinKeySize(); ecdsaMaxSize = ecdsa->getMaxKeySize(); } else { return CKR_GENERAL_ERROR; } CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdsa); AsymmetricAlgorithm* ecdh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDH); if (ecdh != NULL) { ecdhMinSize = ecdh->getMinKeySize(); ecdhMaxSize = ecdh->getMaxKeySize(); } else { return CKR_GENERAL_ERROR; } CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); #endif switch (type) { #ifndef WITH_FIPS case CKM_MD5: #endif case CKM_SHA_1: case CKM_SHA224: case CKM_SHA256: case CKM_SHA384: case CKM_SHA512: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_DIGEST; break; #ifndef WITH_FIPS case CKM_MD5_HMAC: #endif case CKM_SHA_1_HMAC: case CKM_SHA224_HMAC: case CKM_SHA256_HMAC: case CKM_SHA384_HMAC: case CKM_SHA512_HMAC: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_SIGN | CKF_VERIFY; break; case CKM_RSA_PKCS_KEY_PAIR_GEN: pInfo->ulMinKeySize = rsaMinSize; pInfo->ulMaxKeySize = rsaMaxSize; pInfo->flags = CKF_GENERATE_KEY_PAIR; break; case CKM_RSA_PKCS: pInfo->ulMinKeySize = rsaMinSize; pInfo->ulMaxKeySize = rsaMaxSize; pInfo->flags = CKF_SIGN | CKF_VERIFY | CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP; break; case CKM_RSA_X_509: pInfo->ulMinKeySize = rsaMinSize; pInfo->ulMaxKeySize = rsaMaxSize; pInfo->flags = CKF_SIGN | CKF_VERIFY | CKF_ENCRYPT | CKF_DECRYPT; break; #ifndef WITH_FIPS case CKM_MD5_RSA_PKCS: #endif case CKM_SHA1_RSA_PKCS: case CKM_SHA224_RSA_PKCS: case CKM_SHA256_RSA_PKCS: case CKM_SHA384_RSA_PKCS: case CKM_SHA512_RSA_PKCS: case CKM_SHA1_RSA_PKCS_PSS: case CKM_SHA224_RSA_PKCS_PSS: case CKM_SHA256_RSA_PKCS_PSS: case CKM_SHA384_RSA_PKCS_PSS: case CKM_SHA512_RSA_PKCS_PSS: pInfo->ulMinKeySize = rsaMinSize; pInfo->ulMaxKeySize = rsaMaxSize; pInfo->flags = CKF_SIGN | CKF_VERIFY; break; case CKM_RSA_PKCS_OAEP: pInfo->ulMinKeySize = rsaMinSize; pInfo->ulMaxKeySize = rsaMaxSize; pInfo->flags = CKF_ENCRYPT | CKF_DECRYPT | CKF_WRAP | CKF_UNWRAP; break; #ifndef WITH_FIPS case CKM_DES_KEY_GEN: #endif case CKM_DES2_KEY_GEN: case CKM_DES3_KEY_GEN: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_GENERATE; break; #ifndef WITH_FIPS case CKM_DES_ECB: case CKM_DES_CBC: case CKM_DES_CBC_PAD: #endif case CKM_DES3_ECB: case CKM_DES3_CBC: case CKM_DES3_CBC_PAD: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_ENCRYPT | CKF_DECRYPT; break; case CKM_AES_KEY_GEN: pInfo->ulMinKeySize = 16; pInfo->ulMaxKeySize = 32; pInfo->flags = CKF_GENERATE; break; case CKM_AES_ECB: case CKM_AES_CBC: case CKM_AES_CBC_PAD: pInfo->ulMinKeySize = 16; pInfo->ulMaxKeySize = 32; pInfo->flags = CKF_ENCRYPT | CKF_DECRYPT; break; case CKM_AES_KEY_WRAP: pInfo->ulMinKeySize = 16; pInfo->ulMaxKeySize = 0x80000000; pInfo->flags = CKF_WRAP | CKF_UNWRAP; break; #ifdef HAVE_AES_KEY_WRAP_PAD case CKM_AES_KEY_WRAP_PAD: pInfo->ulMinKeySize = 1; pInfo->ulMaxKeySize = 0x80000000; pInfo->flags = CKF_WRAP | CKF_UNWRAP; break; #endif #ifndef WITH_FIPS case CKM_DES_ECB_ENCRYPT_DATA: case CKM_DES_CBC_ENCRYPT_DATA: #endif case CKM_DES3_ECB_ENCRYPT_DATA: case CKM_DES3_CBC_ENCRYPT_DATA: case CKM_AES_ECB_ENCRYPT_DATA: case CKM_AES_CBC_ENCRYPT_DATA: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_DERIVE; break; case CKM_DSA_PARAMETER_GEN: pInfo->ulMinKeySize = dsaMinSize; pInfo->ulMaxKeySize = dsaMaxSize; pInfo->flags = CKF_GENERATE; break; case CKM_DSA_KEY_PAIR_GEN: pInfo->ulMinKeySize = dsaMinSize; pInfo->ulMaxKeySize = dsaMaxSize; pInfo->flags = CKF_GENERATE_KEY_PAIR; break; case CKM_DSA: case CKM_DSA_SHA1: case CKM_DSA_SHA224: case CKM_DSA_SHA256: case CKM_DSA_SHA384: case CKM_DSA_SHA512: pInfo->ulMinKeySize = dsaMinSize; pInfo->ulMaxKeySize = dsaMaxSize; pInfo->flags = CKF_SIGN | CKF_VERIFY; break; case CKM_DH_PKCS_KEY_PAIR_GEN: pInfo->ulMinKeySize = dhMinSize; pInfo->ulMaxKeySize = dhMaxSize; pInfo->flags = CKF_GENERATE_KEY_PAIR; break; case CKM_DH_PKCS_PARAMETER_GEN: pInfo->ulMinKeySize = dhMinSize; pInfo->ulMaxKeySize = dhMaxSize; pInfo->flags = CKF_GENERATE; break; case CKM_DH_PKCS_DERIVE: pInfo->ulMinKeySize = dhMinSize; pInfo->ulMaxKeySize = dhMaxSize; pInfo->flags = CKF_DERIVE; break; #ifdef WITH_ECC case CKM_EC_KEY_PAIR_GEN: pInfo->ulMinKeySize = ecdsaMinSize; pInfo->ulMaxKeySize = ecdsaMaxSize; #define CKF_EC_COMMOM (CKF_EC_F_P | CKF_EC_NAMEDCURVE | CKF_EC_UNCOMPRESS) pInfo->flags = CKF_GENERATE_KEY_PAIR | CKF_EC_COMMOM; break; case CKM_ECDSA: pInfo->ulMinKeySize = ecdsaMinSize; pInfo->ulMaxKeySize = ecdsaMaxSize; pInfo->flags = CKF_SIGN | CKF_VERIFY | CKF_EC_COMMOM; break; case CKM_ECDH1_DERIVE: pInfo->ulMinKeySize = ecdhMinSize; pInfo->ulMaxKeySize = ecdhMaxSize; pInfo->flags = CKF_DERIVE; break; #endif #ifdef WITH_GOST case CKM_GOSTR3411: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_DIGEST; break; case CKM_GOSTR3411_HMAC: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_SIGN | CKF_VERIFY; break; case CKM_GOSTR3410_KEY_PAIR_GEN: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_GENERATE_KEY_PAIR; break; case CKM_GOSTR3410: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_SIGN | CKF_VERIFY; break; case CKM_GOSTR3410_WITH_GOSTR3411: // Key size is not in use pInfo->ulMinKeySize = 0; pInfo->ulMaxKeySize = 0; pInfo->flags = CKF_SIGN | CKF_VERIFY; break; #endif default: DEBUG_MSG("The selected mechanism is not supported"); return CKR_MECHANISM_INVALID; break; } return CKR_OK; } // Initialise the token in the specified slot CK_RV SoftHSM::C_InitToken(CK_SLOT_ID slotID, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen, CK_UTF8CHAR_PTR pLabel) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; Slot* slot = slotManager->getSlot(slotID); if (slot == NULL) { return CKR_SLOT_ID_INVALID; } // Check if any session is open with this token. if (sessionManager->haveSession(slotID)) { return CKR_SESSION_EXISTS; } // Check the PIN if (pPin == NULL_PTR) return CKR_ARGUMENTS_BAD; if (ulPinLen < MIN_PIN_LEN || ulPinLen > MAX_PIN_LEN) return CKR_PIN_INCORRECT; ByteString soPIN(pPin, ulPinLen); return slot->initToken(soPIN, pLabel); } // Initialise the user PIN CK_RV SoftHSM::C_InitPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // The SO must be logged in if (session->getState() != CKS_RW_SO_FUNCTIONS) return CKR_USER_NOT_LOGGED_IN; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the PIN if (pPin == NULL_PTR) return CKR_ARGUMENTS_BAD; if (ulPinLen < MIN_PIN_LEN || ulPinLen > MAX_PIN_LEN) return CKR_PIN_LEN_RANGE; ByteString userPIN(pPin, ulPinLen); return token->initUserPIN(userPIN); } // Change the PIN CK_RV SoftHSM::C_SetPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pOldPin, CK_ULONG ulOldLen, CK_UTF8CHAR_PTR pNewPin, CK_ULONG ulNewLen) { CK_RV rv = CKR_OK; if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check the new PINs if (pOldPin == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pNewPin == NULL_PTR) return CKR_ARGUMENTS_BAD; if (ulNewLen < MIN_PIN_LEN || ulNewLen > MAX_PIN_LEN) return CKR_PIN_LEN_RANGE; ByteString oldPIN(pOldPin, ulOldLen); ByteString newPIN(pNewPin, ulNewLen); // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; switch (session->getState()) { case CKS_RW_PUBLIC_SESSION: case CKS_RW_USER_FUNCTIONS: rv = token->setUserPIN(oldPIN, newPIN); break; case CKS_RW_SO_FUNCTIONS: rv = token->setSOPIN(oldPIN, newPIN); break; default: return CKR_SESSION_READ_ONLY; } return rv; } // Open a new session to the specified slot CK_RV SoftHSM::C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY notify, CK_SESSION_HANDLE_PTR phSession) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; Slot* slot = slotManager->getSlot(slotID); CK_RV rv = sessionManager->openSession(slot, flags, pApplication, notify, phSession); if (rv != CKR_OK) return rv; // Get a pointer to the session object and store it in the handle manager. Session* session = sessionManager->getSession(*phSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; *phSession = handleManager->addSession(slotID,session); return CKR_OK; } // Close the given session CK_RV SoftHSM::C_CloseSession(CK_SESSION_HANDLE hSession) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Tell the handle manager the session has been closed. handleManager->sessionClosed(hSession); // Tell the session object store that the session has closed. sessionObjectStore->sessionClosed(hSession); // Tell the session manager the session has been closed. return sessionManager->closeSession(session->getHandle()); } // Close all open sessions CK_RV SoftHSM::C_CloseAllSessions(CK_SLOT_ID slotID) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the slot Slot* slot = slotManager->getSlot(slotID); if (slot == NULL) return CKR_SLOT_ID_INVALID; // Get the token Token* token = slot->getToken(); if (token == NULL) return CKR_TOKEN_NOT_PRESENT; // Tell the handle manager all sessions were closed for the given slotID. // The handle manager should then remove all session and object handles for this slot. handleManager->allSessionsClosed(slotID); // Tell the session object store that all sessions were closed for the given slotID. // The session object store should then remove all session objects for this slot. sessionObjectStore->allSessionsClosed(slotID); // Finally tell the session manager tho close all sessions for the given slot. // This will also trigger a logout on the associated token to occur. return sessionManager->closeAllSessions(slot); } // Retrieve information about the specified session CK_RV SoftHSM::C_GetSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return session->getInfo(pInfo); } // Determine the state of a running operation in a session CK_RV SoftHSM::C_GetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pOperationState*/, CK_ULONG_PTR /*pulOperationStateLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Set the operation sate in a session CK_RV SoftHSM::C_SetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pOperationState*/, CK_ULONG /*ulOperationStateLen*/, CK_OBJECT_HANDLE /*hEncryptionKey*/, CK_OBJECT_HANDLE /*hAuthenticationKey*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Login on the token in the specified session CK_RV SoftHSM::C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen) { CK_RV rv = CKR_OK; if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the PIN if (pPin == NULL_PTR) return CKR_ARGUMENTS_BAD; ByteString pin(pPin, ulPinLen); // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; switch (userType) { case CKU_SO: // There cannot exist a R/O session on this slot if (sessionManager->haveROSession(session->getSlot()->getSlotID())) return CKR_SESSION_READ_ONLY_EXISTS; // Login rv = token->loginSO(pin); break; case CKU_USER: // Login rv = token->loginUser(pin); break; case CKU_CONTEXT_SPECIFIC: // TODO: When do we want to use this user type? return CKR_OPERATION_NOT_INITIALIZED; break; default: return CKR_USER_TYPE_INVALID; } return rv; } // Log out of the token in the specified session CK_RV SoftHSM::C_Logout(CK_SESSION_HANDLE hSession) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Logout token->logout(); // [PKCS#11 v2.3 p124] When logout is successful... // a. Any of the application's handles to private objects become invalid. // b. Even if a user is later logged back into the token those handles remain invalid. // c. All private session objects from sessions belonging to the application area destroyed. // Have the handle manager remove all handles pointing to private objects for this slot. CK_SLOT_ID slotID = session->getSlot()->getSlotID(); handleManager->tokenLoggedOut(slotID); sessionObjectStore->tokenLoggedOut(slotID); return CKR_OK; } // Create a new object on the token in the specified session using the given attribute template CK_RV SoftHSM::C_CreateObject(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject) { return this->CreateObject(hSession,pTemplate,ulCount,phObject,OBJECT_OP_CREATE); } // Create a copy of the object with the specified handle CK_RV SoftHSM::C_CopyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phNewObject) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pTemplate == NULL_PTR) return CKR_ARGUMENTS_BAD; if (phNewObject == NULL_PTR) return CKR_ARGUMENTS_BAD; *phNewObject = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the slot Slot* slot = session->getSlot(); if (slot == NULL_PTR) return CKR_GENERAL_ERROR; // Get the token Token* token = session->getToken(); if (token == NULL_PTR) return CKR_GENERAL_ERROR; // Check the object handle. OSObject *object = (OSObject *)handleManager->getObject(hObject); if (object == NULL_PTR || !object->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL wasOnToken = object->getBooleanValue(CKA_TOKEN, false); CK_BBOOL wasPrivate = object->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), wasOnToken, wasPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if the object is copyable CK_BBOOL isCopyable = object->getBooleanValue(CKA_COPYABLE, true); if (!isCopyable) return CKR_COPY_PROHIBITED; // Extract critical information from the template CK_BBOOL isOnToken = wasOnToken; CK_BBOOL isPrivate = wasPrivate; for (CK_ULONG i = 0; i < ulCount; i++) { if ((pTemplate[i].type == CKA_TOKEN) && (pTemplate[i].ulValueLen == sizeof(CK_BBOOL))) { isOnToken = *(CK_BBOOL*)pTemplate[i].pValue; continue; } if ((pTemplate[i].type == CKA_PRIVATE) && (pTemplate[i].ulValueLen == sizeof(CK_BBOOL))) { isPrivate = *(CK_BBOOL*)pTemplate[i].pValue; continue; } } // Check privacy does not downgrade if (wasPrivate && !isPrivate) return CKR_TEMPLATE_INCONSISTENT; // Check write user credentials rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Create the object in session or on the token OSObject *newobject = NULL_PTR; if (isOnToken) { newobject = (OSObject*) token->createObject(); } else { newobject = sessionObjectStore->createObject(slot->getSlotID(), hSession, isPrivate != CK_FALSE); } if (newobject == NULL) return CKR_GENERAL_ERROR; // Copy attributes from object class (CKA_CLASS=0 so the first) if (!newobject->startTransaction()) { newobject->destroyObject(); return CKR_FUNCTION_FAILED; } CK_ATTRIBUTE_TYPE attrType = CKA_CLASS; do { if (!object->attributeExists(attrType)) { rv = CKR_FUNCTION_FAILED; break; } OSAttribute attr = object->getAttribute(attrType); // Upgrade privacy has to encrypt byte strings if (!wasPrivate && isPrivate && attr.isByteStringAttribute() && attr.getByteStringValue().size() != 0) { ByteString value; if (!token->encrypt(attr.getByteStringValue(), value) || !newobject->setAttribute(attrType, value)) { rv = CKR_FUNCTION_FAILED; break; } } else { if (!newobject->setAttribute(attrType, attr)) { rv = CKR_FUNCTION_FAILED; break; } } attrType = object->nextAttributeType(attrType); } while (attrType != CKA_CLASS); if (rv != CKR_OK) { newobject->abortTransaction(); } else if (!newobject->commitTransaction()) { rv = CKR_FUNCTION_FAILED; } if (rv != CKR_OK) { newobject->destroyObject(); return rv; } // Get the new P11 object P11Object* newp11object = NULL; rv = newP11Object(newobject,&newp11object); if (rv != CKR_OK) { newobject->destroyObject(); return rv; } // Apply the template rv = newp11object->saveTemplate(token, isPrivate != CK_FALSE, pTemplate, ulCount, OBJECT_OP_COPY); delete newp11object; if (rv != CKR_OK) { newobject->destroyObject(); return rv; } // Set handle if (isOnToken) { *phNewObject = handleManager->addTokenObject(slot->getSlotID(), isPrivate != CK_FALSE, newobject); } else { *phNewObject = handleManager->addSessionObject(slot->getSlotID(), hSession, isPrivate != CK_FALSE, newobject); } return CKR_OK; } // Destroy the specified object CK_RV SoftHSM::C_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL_PTR) return CKR_GENERAL_ERROR; // Check the object handle. OSObject *object = (OSObject *)handleManager->getObject(hObject); if (object == NULL_PTR || !object->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = object->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = object->getBooleanValue(CKA_PRIVATE, true); // Check user credentials CK_RV rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Tell the handleManager to forget about the object. handleManager->destroyObject(hObject); // Destroy the object if (!object->destroyObject()) return CKR_FUNCTION_FAILED; return CKR_OK; } // Determine the size of the specified object CK_RV SoftHSM::C_GetObjectSize(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pulSize == NULL) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL_PTR) return CKR_GENERAL_ERROR; // Check the object handle. OSObject *object = (OSObject *)handleManager->getObject(hObject); if (object == NULL_PTR || !object->isValid()) return CKR_OBJECT_HANDLE_INVALID; *pulSize = CK_UNAVAILABLE_INFORMATION; return CKR_OK; } // Retrieve the specified attributes for the given object CK_RV SoftHSM::C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pTemplate == NULL) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the object handle. OSObject *object = (OSObject *)handleManager->getObject(hObject); if (object == NULL_PTR || !object->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = object->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = object->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); // CKR_USER_NOT_LOGGED_IN is not a valid return code for this function, // so we use CKR_GENERAL_ERROR. return CKR_GENERAL_ERROR; } // Wrap a P11Object around the OSObject so we can access the attributes in the // context of the object in which it is defined. P11Object* p11object = NULL; rv = newP11Object(object,&p11object); if (rv != CKR_OK) return rv; // Ask the P11Object to fill the template with attribute values. rv = p11object->loadTemplate(token, pTemplate,ulCount); delete p11object; return rv; } // Change or set the value of the specified attributes on the specified object CK_RV SoftHSM::C_SetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pTemplate == NULL) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the object handle. OSObject *object = (OSObject *)handleManager->getObject(hObject); if (object == NULL_PTR || !object->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = object->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = object->getBooleanValue(CKA_PRIVATE, true); // Check user credentials CK_RV rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Wrap a P11Object around the OSObject so we can access the attributes in the // context of the object in which it is defined. P11Object* p11object = NULL; rv = newP11Object(object,&p11object); if (rv != CKR_OK) return rv; // Ask the P11Object to save the template with attribute values. rv = p11object->saveTemplate(token, isPrivate != CK_FALSE, pTemplate,ulCount,OBJECT_OP_SET); delete p11object; return rv; } // Initialise object search in the specified session using the specified attribute template as search parameters CK_RV SoftHSM::C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the slot Slot* slot = session->getSlot(); if (slot == NULL_PTR) return CKR_GENERAL_ERROR; // Determine whether we have a public session or not. bool isPublicSession; switch (session->getState()) { case CKS_RO_USER_FUNCTIONS: case CKS_RW_USER_FUNCTIONS: case CKS_RW_SO_FUNCTIONS: isPublicSession = false; break; default: isPublicSession = true; } // Get the token Token* token = session->getToken(); if (token == NULL_PTR) return CKR_GENERAL_ERROR; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; session->setOpType(SESSION_OP_FIND); FindOperation *findOp = FindOperation::create(); // Check if we are out of memory if (findOp == NULL_PTR) return CKR_HOST_MEMORY; std::set allObjects; token->getObjects(allObjects); sessionObjectStore->getObjects(slot->getSlotID(),allObjects); std::set handles; std::set::iterator it; for (it=allObjects.begin(); it != allObjects.end(); ++it) { // Determine if the object has CKA_PRIVATE set to CK_TRUE bool isPrivateObject = (*it)->getBooleanValue(CKA_PRIVATE, true); // If the object is private, and we are in a public session then skip it ! if (isPublicSession && isPrivateObject) continue; // skip object // Perform the actual attribute matching. bool bAttrMatch = true; // We let an empty template match everything. for (CK_ULONG i=0; iattributeExists(pTemplate[i].type)) break; OSAttribute attr = (*it)->getAttribute(pTemplate[i].type); if (attr.isBooleanAttribute()) { if (sizeof(CK_BBOOL) != pTemplate[i].ulValueLen) break; bool bTemplateValue = (*(CK_BBOOL*)pTemplate[i].pValue == CK_TRUE); if (attr.getBooleanValue() != bTemplateValue) break; } else { if (attr.isUnsignedLongAttribute()) { if (sizeof(CK_ULONG) != pTemplate[i].ulValueLen) break; CK_ULONG ulTemplateValue = *(CK_ULONG_PTR)pTemplate[i].pValue; if (attr.getUnsignedLongValue() != ulTemplateValue) break; } else { if (attr.isByteStringAttribute()) { ByteString bsAttrValue; if (isPrivateObject && attr.getByteStringValue().size() != 0) { if (!token->decrypt(attr.getByteStringValue(), bsAttrValue)) { delete findOp; return CKR_GENERAL_ERROR; } } else bsAttrValue = attr.getByteStringValue(); if (bsAttrValue.size() != pTemplate[i].ulValueLen) break; if (pTemplate[i].ulValueLen != 0) { ByteString bsTemplateValue((const unsigned char*)pTemplate[i].pValue, pTemplate[i].ulValueLen); if (bsAttrValue != bsTemplateValue) break; } } else break; } } // The attribute matched ! bAttrMatch = true; } if (bAttrMatch) { CK_SLOT_ID slotID = slot->getSlotID(); bool isOnToken = (*it)->getBooleanValue(CKA_TOKEN, false); bool isPrivate = (*it)->getBooleanValue(CKA_PRIVATE, true); // Create an object handle for every returned object. CK_OBJECT_HANDLE hObject; if (isOnToken) hObject = handleManager->addTokenObject(slotID,isPrivate,*it); else hObject = handleManager->addSessionObject(slotID,hSession,isPrivate,*it); if (hObject == CK_INVALID_HANDLE) { delete findOp; return CKR_GENERAL_ERROR; } handles.insert(hObject); } } // Storing the object handles for the find will protect the library // whenever a stale object handle is used to access the library. findOp->setHandles(handles); session->setFindOp(findOp); return CKR_OK; } // Continue the search for objects in the specified session CK_RV SoftHSM::C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (phObject == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pulObjectCount == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_FIND) return CKR_OPERATION_NOT_INITIALIZED; // return the object handles that have been added to the find operation. FindOperation *findOp = session->getFindOp(); if (findOp == NULL) return CKR_GENERAL_ERROR; // Ask the find operation to retrieve the object handles *pulObjectCount = findOp->retrieveHandles(phObject,ulMaxObjectCount); // Erase the object handles from the find operation. findOp->eraseHandles(0,*pulObjectCount); return CKR_OK; } // Finish searching for objects CK_RV SoftHSM::C_FindObjectsFinal(CK_SESSION_HANDLE hSession) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_FIND) return CKR_OPERATION_NOT_INITIALIZED; session->resetOp(); return CKR_OK; } // Encrypt*/Decrypt*() is for Symmetrical ciphers too static bool isSymMechanism(CK_MECHANISM_PTR pMechanism) { if (pMechanism == NULL_PTR) return false; switch(pMechanism->mechanism) { case CKM_DES_ECB: case CKM_DES_CBC: case CKM_DES_CBC_PAD: case CKM_DES3_ECB: case CKM_DES3_CBC: case CKM_DES3_CBC_PAD: case CKM_AES_ECB: case CKM_AES_CBC: case CKM_AES_CBC_PAD: return true; default: return false; } } // SymAlgorithm version of C_EncryptInit CK_RV SoftHSM::SymEncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for encryption if (!key->getBooleanValue(CKA_ENCRYPT, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the symmetric algorithm matching the mechanism SymAlgo::Type algo = SymAlgo::Unknown; SymMode::Type mode = SymMode::Unknown; bool padding = false; ByteString iv; size_t bb = 8; switch(pMechanism->mechanism) { #ifndef WITH_FIPS case CKM_DES_ECB: algo = SymAlgo::DES; mode = SymMode::ECB; bb = 7; break; case CKM_DES_CBC: algo = SymAlgo::DES; mode = SymMode::CBC; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; case CKM_DES_CBC_PAD: algo = SymAlgo::DES; mode = SymMode::CBC; padding = true; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; #endif case CKM_DES3_ECB: algo = SymAlgo::DES3; mode = SymMode::ECB; bb = 7; break; case CKM_DES3_CBC: algo = SymAlgo::DES3; mode = SymMode::CBC; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; case CKM_DES3_CBC_PAD: algo = SymAlgo::DES3; mode = SymMode::CBC; padding = true; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; case CKM_AES_ECB: algo = SymAlgo::AES; mode = SymMode::ECB; break; case CKM_AES_CBC: algo = SymAlgo::AES; mode = SymMode::CBC; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); break; case CKM_AES_CBC_PAD: algo = SymAlgo::AES; mode = SymMode::CBC; padding = true; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); break; default: return CKR_MECHANISM_INVALID; } SymmetricAlgorithm* cipher = CryptoFactory::i()->getSymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* secretkey = new SymmetricKey(); if (secretkey == NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } if (getSymmetricKey(secretkey, token, key) != CKR_OK) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } // adjust key bit length secretkey->setBitLen(secretkey->getKeyBits().size() * bb); // Initialize encryption if (!cipher->encryptInit(secretkey, mode, iv, padding)) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_ENCRYPT); session->setSymmetricCryptoOp(cipher); session->setAllowMultiPartOp(true); session->setAllowSinglePartOp(true); session->setSymmetricKey(secretkey); return CKR_OK; } // AsymAlgorithm version of C_EncryptInit CK_RV SoftHSM::AsymEncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for encryption if (!key->getBooleanValue(CKA_ENCRYPT, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the asymmetric algorithm matching the mechanism AsymMech::Type mechanism; bool isRSA = false; switch(pMechanism->mechanism) { case CKM_RSA_PKCS: mechanism = AsymMech::RSA_PKCS; isRSA = true; break; case CKM_RSA_X_509: mechanism = AsymMech::RSA; isRSA = true; break; case CKM_RSA_PKCS_OAEP: rv = MechParamCheckRSAPKCSOAEP(pMechanism); if (rv != CKR_OK) return rv; mechanism = AsymMech::RSA_PKCS_OAEP; isRSA = true; break; default: return CKR_MECHANISM_INVALID; } AsymmetricAlgorithm* asymCrypto = NULL; PublicKey* publicKey = NULL; if (isRSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; publicKey = asymCrypto->newPublicKey(); if (publicKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getRSAPublicKey((RSAPublicKey*)publicKey, token, key) != CKR_OK) { asymCrypto->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } else { return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_ENCRYPT); session->setAsymmetricCryptoOp(asymCrypto); session->setMechanism(mechanism); session->setAllowMultiPartOp(false); session->setAllowSinglePartOp(true); session->setPublicKey(publicKey); return CKR_OK; } // Initialise encryption using the specified object and mechanism CK_RV SoftHSM::C_EncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (isSymMechanism(pMechanism)) return SymEncryptInit(hSession, pMechanism, hKey); else return AsymEncryptInit(hSession, pMechanism, hKey); } // SymAlgorithm version of C_Encrypt static CK_RV SymEncrypt(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { SymmetricAlgorithm* cipher = session->getSymmetricCryptoOp(); if (cipher == NULL || !session->getAllowSinglePartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Check data size SymMode::Type mode = cipher->getCipherMode(); CK_ULONG remainder = ulDataLen % cipher->getBlockSize(); if ((mode == SymMode::ECB || mode == SymMode::CBC) && cipher->getPaddingMode() == false && remainder != 0) { session->resetOp(); return CKR_DATA_LEN_RANGE; } // Round up to block size CK_ULONG maxSize = ulDataLen; if (remainder != 0) { maxSize = ulDataLen + cipher->getBlockSize() - remainder; } else if (cipher->getPaddingMode() == true) { maxSize = ulDataLen + cipher->getBlockSize(); } if (pEncryptedData == NULL_PTR) { *pulEncryptedDataLen = maxSize; return CKR_OK; } // Check buffer size if (*pulEncryptedDataLen < maxSize) { *pulEncryptedDataLen = maxSize; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data(pData, ulDataLen); ByteString encryptedData; // Encrypt the data if (!cipher->encryptUpdate(data, encryptedData)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Finalize encryption ByteString encryptedFinal; if (!cipher->encryptFinal(encryptedFinal)) { session->resetOp(); return CKR_GENERAL_ERROR; } encryptedData += encryptedFinal; encryptedData.resize(maxSize); memcpy(pEncryptedData, encryptedData.byte_str(), encryptedData.size()); *pulEncryptedDataLen = encryptedData.size(); session->resetOp(); return CKR_OK; } // AsymAlgorithm version of C_Encrypt static CK_RV AsymEncrypt(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); AsymMech::Type mechanism = session->getMechanism(); PublicKey* publicKey = session->getPublicKey(); if (asymCrypto == NULL || !session->getAllowSinglePartOp() || publicKey == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the encrypted data CK_ULONG size = publicKey->getOutputLength(); if (pEncryptedData == NULL_PTR) { *pulEncryptedDataLen = size; return CKR_OK; } // Check buffer size if (*pulEncryptedDataLen < size) { *pulEncryptedDataLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data; ByteString encryptedData; // PKCS #11 Mechanisms v2.30: Cryptoki Draft 7 page 32 // We must allow input length <= k and therfore need to prepend the data with zeroes. if (mechanism == AsymMech::RSA) { data.wipe(size-ulDataLen); } data += ByteString(pData, ulDataLen); // Encrypt the data if (!asymCrypto->encrypt(publicKey,data,encryptedData,mechanism)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (encryptedData.size() != size) { ERROR_MSG("The size of the encrypted data differs from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pEncryptedData, encryptedData.byte_str(), size); *pulEncryptedDataLen = size; session->resetOp(); return CKR_OK; } // Perform a single operation encryption operation in the specified session CK_RV SoftHSM::C_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pData == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pulEncryptedDataLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_ENCRYPT) return CKR_OPERATION_NOT_INITIALIZED; if (session->getSymmetricCryptoOp() != NULL) return SymEncrypt(session, pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); else return AsymEncrypt(session, pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); } // SymAlgorithm version of C_EncryptUpdate static CK_RV SymEncryptUpdate(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { SymmetricAlgorithm* cipher = session->getSymmetricCryptoOp(); if (cipher == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Check data size SymMode::Type mode = cipher->getCipherMode(); CK_ULONG remainder = ulDataLen % cipher->getBlockSize(); if ((mode == SymMode::ECB || mode == SymMode::CBC) && cipher->getPaddingMode() == false && remainder != 0) { session->resetOp(); return CKR_DATA_LEN_RANGE; } // Round down/up to block size CK_ULONG maxSize = ulDataLen - remainder; if (remainder + cipher->getBufferSize() > cipher->getBlockSize()) { maxSize += cipher->getBlockSize(); } if (pEncryptedData == NULL_PTR) { *pulEncryptedDataLen = maxSize; return CKR_OK; } // Check buffer size if (*pulEncryptedDataLen < maxSize) { *pulEncryptedDataLen = maxSize; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data(pData, ulDataLen); ByteString encryptedData; // Encrypt the data if (!cipher->encryptUpdate(data, encryptedData)) { session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pEncryptedData, encryptedData.byte_str(), encryptedData.size()); *pulEncryptedDataLen = encryptedData.size(); return CKR_OK; } // Feed data to the running encryption operation in a session CK_RV SoftHSM::C_EncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pData == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pulEncryptedDataLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_ENCRYPT) return CKR_OPERATION_NOT_INITIALIZED; if (session->getSymmetricCryptoOp() != NULL) return SymEncryptUpdate(session, pData, ulDataLen, pEncryptedData, pulEncryptedDataLen); else return CKR_FUNCTION_NOT_SUPPORTED; } // SymAlgorithm version of C_EncryptFinal static CK_RV SymEncryptFinal(Session* session, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { SymmetricAlgorithm* cipher = session->getSymmetricCryptoOp(); if (cipher == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the encrypted data CK_ULONG size = 0; if (cipher->getPaddingMode() == true) { size = cipher->getBlockSize(); } if (pEncryptedData == NULL_PTR) { *pulEncryptedDataLen = size; return CKR_OK; } // Check buffer size if (*pulEncryptedDataLen < size) { *pulEncryptedDataLen = size; return CKR_BUFFER_TOO_SMALL; } // Finalize encryption ByteString encryptedFinal; if (!cipher->encryptFinal(encryptedFinal)) { session->resetOp(); return CKR_GENERAL_ERROR; } if (encryptedFinal.size() != 0) { memcpy(pEncryptedData, encryptedFinal.byte_str(), encryptedFinal.size()); } *pulEncryptedDataLen = encryptedFinal.size(); session->resetOp(); return CKR_OK; } // Finalise the encryption operation CK_RV SoftHSM::C_EncryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_ENCRYPT) return CKR_OPERATION_NOT_INITIALIZED; if (session->getSymmetricCryptoOp() != NULL) return SymEncryptFinal(session, pEncryptedData, pulEncryptedDataLen); else return CKR_FUNCTION_NOT_SUPPORTED; } // SymAlgorithm version of C_DecryptInit CK_RV SoftHSM::SymDecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for decryption if (!key->getBooleanValue(CKA_DECRYPT, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the symmetric algorithm matching the mechanism SymAlgo::Type algo = SymAlgo::Unknown; SymMode::Type mode = SymMode::Unknown; bool padding = false; ByteString iv; size_t bb = 8; switch(pMechanism->mechanism) { #ifndef WITH_FIPS case CKM_DES_ECB: algo = SymAlgo::DES; mode = SymMode::ECB; bb = 7; break; case CKM_DES_CBC: algo = SymAlgo::DES; mode = SymMode::CBC; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; case CKM_DES_CBC_PAD: algo = SymAlgo::DES; mode = SymMode::CBC; padding = true; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; #endif case CKM_DES3_ECB: algo = SymAlgo::DES3; mode = SymMode::ECB; bb = 7; break; case CKM_DES3_CBC: algo = SymAlgo::DES3; mode = SymMode::CBC; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; case CKM_DES3_CBC_PAD: algo = SymAlgo::DES3; mode = SymMode::CBC; padding = true; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); bb = 7; break; case CKM_AES_ECB: algo = SymAlgo::AES; mode = SymMode::ECB; break; case CKM_AES_CBC: algo = SymAlgo::AES; mode = SymMode::CBC; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); break; case CKM_AES_CBC_PAD: algo = SymAlgo::AES; mode = SymMode::CBC; padding = true; if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen == 0) { DEBUG_MSG("CBC mode requires an init vector"); return CKR_ARGUMENTS_BAD; } iv.resize(pMechanism->ulParameterLen); memcpy(&iv[0], pMechanism->pParameter, pMechanism->ulParameterLen); break; default: return CKR_MECHANISM_INVALID; } SymmetricAlgorithm* cipher = CryptoFactory::i()->getSymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* secretkey = new SymmetricKey(); if (secretkey == NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } if (getSymmetricKey(secretkey, token, key) != CKR_OK) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } // adjust key bit length secretkey->setBitLen(secretkey->getKeyBits().size() * bb); // Initialize decryption if (!cipher->decryptInit(secretkey, mode, iv, padding)) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_DECRYPT); session->setSymmetricCryptoOp(cipher); session->setAllowMultiPartOp(true); session->setAllowSinglePartOp(true); session->setSymmetricKey(secretkey); return CKR_OK; } // AsymAlgorithm version of C_DecryptInit CK_RV SoftHSM::AsymDecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for decryption if (!key->getBooleanValue(CKA_DECRYPT, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the asymmetric algorithm matching the mechanism AsymMech::Type mechanism = AsymMech::Unknown; bool isRSA = false; switch(pMechanism->mechanism) { case CKM_RSA_PKCS: mechanism = AsymMech::RSA_PKCS; isRSA = true; break; case CKM_RSA_X_509: mechanism = AsymMech::RSA; isRSA = true; break; case CKM_RSA_PKCS_OAEP: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_OAEP_PARAMS)) { DEBUG_MSG("pParameter must be of type CK_RSA_PKCS_OAEP_PARAMS"); return CKR_ARGUMENTS_BAD; } if (CK_RSA_PKCS_OAEP_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA_1) { DEBUG_MSG("hashAlg must be CKM_SHA_1"); return CKR_ARGUMENTS_BAD; } if (CK_RSA_PKCS_OAEP_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA1) { DEBUG_MSG("mgf must be CKG_MGF1_SHA1"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_PKCS_OAEP; isRSA = true; break; default: return CKR_MECHANISM_INVALID; } AsymmetricAlgorithm* asymCrypto = NULL; PrivateKey* privateKey = NULL; if (isRSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; privateKey = asymCrypto->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getRSAPrivateKey((RSAPrivateKey*)privateKey, token, key) != CKR_OK) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } else { return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_DECRYPT); session->setAsymmetricCryptoOp(asymCrypto); session->setMechanism(mechanism); session->setAllowMultiPartOp(false); session->setAllowSinglePartOp(true); session->setPrivateKey(privateKey); return CKR_OK; } // Initialise decryption using the specified object CK_RV SoftHSM::C_DecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (isSymMechanism(pMechanism)) return SymDecryptInit(hSession, pMechanism, hKey); else return AsymDecryptInit(hSession, pMechanism, hKey); } // SymAlgorithm version of C_Decrypt static CK_RV SymDecrypt(Session* session, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { SymmetricAlgorithm* cipher = session->getSymmetricCryptoOp(); if (cipher == NULL || !session->getAllowSinglePartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Check encrypted size if (ulEncryptedDataLen % cipher->getBlockSize() != 0) { session->resetOp(); return CKR_ENCRYPTED_DATA_LEN_RANGE; } if (pData == NULL_PTR) { *pulDataLen = ulEncryptedDataLen; return CKR_OK; } // Check buffer size if (*pulDataLen < ulEncryptedDataLen) { *pulDataLen = ulEncryptedDataLen; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString encryptedData(pEncryptedData, ulEncryptedDataLen); ByteString data; // Decrypt the data if (!cipher->decryptUpdate(encryptedData,data)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Finalize decryption ByteString dataFinal; if (!cipher->decryptFinal(dataFinal)) { session->resetOp(); return CKR_GENERAL_ERROR; } data += dataFinal; if (data.size() > ulEncryptedDataLen) { data.resize(ulEncryptedDataLen); } memcpy(pData, data.byte_str(), data.size()); *pulDataLen = data.size(); session->resetOp(); return CKR_OK; } // AsymAlgorithm version of C_Decrypt static CK_RV AsymDecrypt(Session* session, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); AsymMech::Type mechanism = session->getMechanism(); PrivateKey* privateKey = session->getPrivateKey(); if (asymCrypto == NULL || !session->getAllowSinglePartOp() || privateKey == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the data CK_ULONG size = privateKey->getOutputLength(); if (pData == NULL_PTR) { *pulDataLen = size; return CKR_OK; } // Check buffer size if (*pulDataLen < size) { *pulDataLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString encryptedData(pEncryptedData, ulEncryptedDataLen); ByteString data; // Decrypt the data if (!asymCrypto->decrypt(privateKey,encryptedData,data,mechanism)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (data.size() > size) { ERROR_MSG("The size of the decrypted data exceeds the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pData, data.byte_str(), data.size()); *pulDataLen = data.size(); session->resetOp(); return CKR_OK; } // Perform a single operation decryption in the given session CK_RV SoftHSM::C_Decrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pEncryptedData == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pulDataLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DECRYPT) return CKR_OPERATION_NOT_INITIALIZED; if (session->getSymmetricCryptoOp() != NULL) return SymDecrypt(session, pEncryptedData, ulEncryptedDataLen, pData, pulDataLen); else return AsymDecrypt(session, pEncryptedData, ulEncryptedDataLen, pData, pulDataLen); } // SymAlgorithm version of C_DecryptUpdate static CK_RV SymDecryptUpdate(Session* session, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { SymmetricAlgorithm* cipher = session->getSymmetricCryptoOp(); if (cipher == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Check data size SymMode::Type mode = cipher->getCipherMode(); CK_ULONG remainder = ulEncryptedDataLen % cipher->getBlockSize(); if ((mode == SymMode::ECB || mode == SymMode::CBC) && cipher->getPaddingMode() == false && remainder != 0) { session->resetOp(); return CKR_DATA_LEN_RANGE; } // Round down/up to block size CK_ULONG maxSize = ulEncryptedDataLen - remainder; if (remainder + cipher->getBufferSize() > cipher->getBlockSize()) { maxSize += cipher->getBlockSize(); } if (pData == NULL_PTR) { *pDataLen = maxSize; return CKR_OK; } // Check buffer size if (*pDataLen < maxSize) { *pDataLen = maxSize; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data(pEncryptedData, ulEncryptedDataLen); ByteString decryptedData; // Encrypt the data if (!cipher->decryptUpdate(data, decryptedData)) { session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pData, decryptedData.byte_str(), decryptedData.size()); *pDataLen = decryptedData.size(); return CKR_OK; } // Feed data to the running decryption operation in a session CK_RV SoftHSM::C_DecryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pEncryptedData == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pDataLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DECRYPT) return CKR_OPERATION_NOT_INITIALIZED; if (session->getSymmetricCryptoOp() != NULL) return SymDecryptUpdate(session, pEncryptedData, ulEncryptedDataLen, pData, pDataLen); else return CKR_FUNCTION_NOT_SUPPORTED; } static CK_RV SymDecryptFinal(Session* session, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen) { SymmetricAlgorithm* cipher = session->getSymmetricCryptoOp(); if (cipher == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the encrypted data CK_ULONG size = 0; if (cipher->getPaddingMode() == true) { size = cipher->getBlockSize(); } if (pEncryptedData == NULL_PTR) { *pulEncryptedDataLen = size; return CKR_OK; } // Check buffer size if (*pulEncryptedDataLen < size) { *pulEncryptedDataLen = size; return CKR_BUFFER_TOO_SMALL; } // Finalize encryption ByteString encryptedFinal; if (!cipher->decryptFinal(encryptedFinal)) { session->resetOp(); return CKR_GENERAL_ERROR; } if (encryptedFinal.size() != 0) { memcpy(pEncryptedData, encryptedFinal.byte_str(), encryptedFinal.size()); } *pulEncryptedDataLen = encryptedFinal.size(); session->resetOp(); return CKR_OK; } // Finalise the decryption operation CK_RV SoftHSM::C_DecryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DECRYPT) return CKR_OPERATION_NOT_INITIALIZED; if (session->getSymmetricCryptoOp() != NULL) return SymDecryptFinal(session, pData, pDataLen); else return CKR_FUNCTION_NOT_SUPPORTED; } // Initialise digesting using the specified mechanism in the specified session CK_RV SoftHSM::C_DigestInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the mechanism HashAlgo::Type algo = HashAlgo::Unknown; switch(pMechanism->mechanism) { #ifndef WITH_FIPS case CKM_MD5: algo = HashAlgo::MD5; break; #endif case CKM_SHA_1: algo = HashAlgo::SHA1; break; case CKM_SHA224: algo = HashAlgo::SHA224; break; case CKM_SHA256: algo = HashAlgo::SHA256; break; case CKM_SHA384: algo = HashAlgo::SHA384; break; case CKM_SHA512: algo = HashAlgo::SHA512; break; #ifdef WITH_GOST case CKM_GOSTR3411: algo = HashAlgo::GOST; break; #endif default: return CKR_MECHANISM_INVALID; } HashAlgorithm* hash = CryptoFactory::i()->getHashAlgorithm(algo); if (hash == NULL) return CKR_MECHANISM_INVALID; // Initialize hashing if (hash->hashInit() == false) { CryptoFactory::i()->recycleHashAlgorithm(hash); return CKR_GENERAL_ERROR; } session->setOpType(SESSION_OP_DIGEST); session->setDigestOp(hash); return CKR_OK; } // Digest the specified data in a one-pass operation and return the resulting digest CK_RV SoftHSM::C_Digest(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pulDigestLen == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pData == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DIGEST) return CKR_OPERATION_NOT_INITIALIZED; // Return size CK_ULONG size = session->getDigestOp()->getHashSize(); if (pDigest == NULL_PTR) { *pulDigestLen = size; return CKR_OK; } // Check buffer size if (*pulDigestLen < size) { *pulDigestLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data(pData, ulDataLen); // Digest the data if (session->getDigestOp()->hashUpdate(data) == false) { session->resetOp(); return CKR_GENERAL_ERROR; } // Get the digest ByteString digest; if (session->getDigestOp()->hashFinal(digest) == false) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (digest.size() != size) { ERROR_MSG("The size of the digest differ from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pDigest, digest.byte_str(), size); *pulDigestLen = size; session->resetOp(); return CKR_OK; } // Update a running digest operation CK_RV SoftHSM::C_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pPart == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DIGEST) return CKR_OPERATION_NOT_INITIALIZED; // Get the data ByteString data(pPart, ulPartLen); // Digest the data if (session->getDigestOp()->hashUpdate(data) == false) { session->resetOp(); return CKR_GENERAL_ERROR; } return CKR_OK; } // Update a running digest operation by digesting a secret key with the specified handle CK_RV SoftHSM::C_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DIGEST) return CKR_OPERATION_NOT_INITIALIZED; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hObject); if (key == NULL_PTR || !key->isValid()) return CKR_KEY_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); // CKR_USER_NOT_LOGGED_IN is not a valid return code for this function, // so we use CKR_GENERAL_ERROR. return CKR_GENERAL_ERROR; } // Parano... if (!key->getBooleanValue(CKA_EXTRACTABLE, false)) return CKR_KEY_INDIGESTIBLE; if (key->getBooleanValue(CKA_SENSITIVE, false)) return CKR_KEY_INDIGESTIBLE; // Get value if (!key->attributeExists(CKA_VALUE)) return CKR_KEY_INDIGESTIBLE; ByteString keybits; if (isPrivate) { if (!token->decrypt(key->getByteStringValue(CKA_VALUE), keybits)) return CKR_GENERAL_ERROR; } else { keybits = key->getByteStringValue(CKA_VALUE); } // Digest the value if (session->getDigestOp()->hashUpdate(keybits) == false) { session->resetOp(); return CKR_GENERAL_ERROR; } return CKR_OK; } // Finalise the digest operation in the specified session and return the digest CK_RV SoftHSM::C_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pulDigestLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_DIGEST) return CKR_OPERATION_NOT_INITIALIZED; // Return size CK_ULONG size = session->getDigestOp()->getHashSize(); if (pDigest == NULL_PTR) { *pulDigestLen = size; return CKR_OK; } // Check buffer size if (*pulDigestLen < size) { *pulDigestLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the digest ByteString digest; if (session->getDigestOp()->hashFinal(digest) == false) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (digest.size() != size) { ERROR_MSG("The size of the digest differ from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pDigest, digest.byte_str(), size); *pulDigestLen = size; session->resetOp(); return CKR_OK; } // Sign*/Verify*() is for MACs too static bool isMacMechanism(CK_MECHANISM_PTR pMechanism) { if (pMechanism == NULL_PTR) return false; switch(pMechanism->mechanism) { case CKM_MD5_HMAC: case CKM_SHA_1_HMAC: case CKM_SHA224_HMAC: case CKM_SHA256_HMAC: case CKM_SHA384_HMAC: case CKM_SHA512_HMAC: #ifdef WITH_GOST case CKM_GOSTR3411_HMAC: #endif return true; default: return false; } } // MacAlgorithm version of C_SignInit CK_RV SoftHSM::MacSignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for signing if (!key->getBooleanValue(CKA_SIGN, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the MAC algorithm matching the mechanism MacAlgo::Type algo = MacAlgo::Unknown; switch(pMechanism->mechanism) { #ifndef WITH_FIPS case CKM_MD5_HMAC: algo = MacAlgo::HMAC_MD5; break; #endif case CKM_SHA_1_HMAC: algo = MacAlgo::HMAC_SHA1; break; case CKM_SHA224_HMAC: algo = MacAlgo::HMAC_SHA224; break; case CKM_SHA256_HMAC: algo = MacAlgo::HMAC_SHA256; break; case CKM_SHA384_HMAC: algo = MacAlgo::HMAC_SHA384; break; case CKM_SHA512_HMAC: algo = MacAlgo::HMAC_SHA512; break; #ifdef WITH_GOST case CKM_GOSTR3411_HMAC: algo = MacAlgo::HMAC_GOST; break; #endif default: return CKR_MECHANISM_INVALID; } MacAlgorithm* mac = CryptoFactory::i()->getMacAlgorithm(algo); if (mac == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* privkey = new SymmetricKey(); if (privkey == NULL) { CryptoFactory::i()->recycleMacAlgorithm(mac); return CKR_HOST_MEMORY; } if (getSymmetricKey(privkey, token, key) != CKR_OK) { mac->recycleKey(privkey); CryptoFactory::i()->recycleMacAlgorithm(mac); return CKR_GENERAL_ERROR; } // Initialize signing if (!mac->signInit(privkey)) { mac->recycleKey(privkey); CryptoFactory::i()->recycleMacAlgorithm(mac); return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_SIGN); session->setMacOp(mac); session->setAllowMultiPartOp(true); session->setAllowSinglePartOp(true); session->setSymmetricKey(privkey); return CKR_OK; } // AsymmetricAlgorithm version of C_SignInit CK_RV SoftHSM::AsymSignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for signing if (!key->getBooleanValue(CKA_SIGN, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the asymmetric algorithm matching the mechanism AsymMech::Type mechanism = AsymMech::Unknown; void* param = NULL; size_t paramLen = 0; RSA_PKCS_PSS_PARAMS pssParam; bool bAllowMultiPartOp; bool isRSA = false; bool isDSA = false; bool isECDSA = false; switch(pMechanism->mechanism) { case CKM_RSA_PKCS: mechanism = AsymMech::RSA_PKCS; bAllowMultiPartOp = false; isRSA = true; break; case CKM_RSA_X_509: mechanism = AsymMech::RSA; bAllowMultiPartOp = false; isRSA = true; break; #ifndef WITH_FIPS case CKM_MD5_RSA_PKCS: mechanism = AsymMech::RSA_MD5_PKCS; bAllowMultiPartOp = true; isRSA = true; break; #endif case CKM_SHA1_RSA_PKCS: mechanism = AsymMech::RSA_SHA1_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA224_RSA_PKCS: mechanism = AsymMech::RSA_SHA224_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA256_RSA_PKCS: mechanism = AsymMech::RSA_SHA256_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA384_RSA_PKCS: mechanism = AsymMech::RSA_SHA384_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA512_RSA_PKCS: mechanism = AsymMech::RSA_SHA512_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA1_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA_1 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA1) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA1_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA1; pssParam.mgf = AsymRSAMGF::MGF1_SHA1; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA224_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA224 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA224) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA224_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA224; pssParam.mgf = AsymRSAMGF::MGF1_SHA224; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA256_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA256 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA256) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA256_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA256; pssParam.mgf = AsymRSAMGF::MGF1_SHA256; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA384_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA384 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA384) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA384_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA384; pssParam.mgf = AsymRSAMGF::MGF1_SHA384; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA512_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA512 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA512) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA512_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA512; pssParam.mgf = AsymRSAMGF::MGF1_SHA512; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_DSA: mechanism = AsymMech::DSA; bAllowMultiPartOp = false; isDSA = true; break; case CKM_DSA_SHA1: mechanism = AsymMech::DSA_SHA1; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA224: mechanism = AsymMech::DSA_SHA224; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA256: mechanism = AsymMech::DSA_SHA256; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA384: mechanism = AsymMech::DSA_SHA384; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA512: mechanism = AsymMech::DSA_SHA512; bAllowMultiPartOp = true; isDSA = true; break; #ifdef WITH_ECC case CKM_ECDSA: mechanism = AsymMech::ECDSA; bAllowMultiPartOp = false; isECDSA = true; break; #endif #ifdef WITH_GOST case CKM_GOSTR3410: mechanism = AsymMech::GOST; bAllowMultiPartOp = false; break; case CKM_GOSTR3410_WITH_GOSTR3411: mechanism = AsymMech::GOST_GOST; bAllowMultiPartOp = true; break; #endif default: return CKR_MECHANISM_INVALID; } AsymmetricAlgorithm* asymCrypto = NULL; PrivateKey* privateKey = NULL; if (isRSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; privateKey = asymCrypto->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getRSAPrivateKey((RSAPrivateKey*)privateKey, token, key) != CKR_OK) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } else if (isDSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; privateKey = asymCrypto->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getDSAPrivateKey((DSAPrivateKey*)privateKey, token, key) != CKR_OK) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } #ifdef WITH_ECC else if (isECDSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; privateKey = asymCrypto->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getECPrivateKey((ECPrivateKey*)privateKey, token, key) != CKR_OK) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } #endif else { #ifdef WITH_GOST asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::GOST); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; privateKey = asymCrypto->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getGOSTPrivateKey((GOSTPrivateKey*)privateKey, token, key) != CKR_OK) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } #else return CKR_MECHANISM_INVALID; #endif } // Initialize signing if (bAllowMultiPartOp && !asymCrypto->signInit(privateKey,mechanism,param,paramLen)) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_SIGN); session->setAsymmetricCryptoOp(asymCrypto); session->setMechanism(mechanism); session->setParameters(param, paramLen); session->setAllowMultiPartOp(bAllowMultiPartOp); session->setAllowSinglePartOp(true); session->setPrivateKey(privateKey); return CKR_OK; } // Initialise a signing operation using the specified key and mechanism CK_RV SoftHSM::C_SignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (isMacMechanism(pMechanism)) return MacSignInit(hSession, pMechanism, hKey); else return AsymSignInit(hSession, pMechanism, hKey); } // MacAlgorithm version of C_Sign static CK_RV MacSign(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { MacAlgorithm* mac = session->getMacOp(); if (mac == NULL || !session->getAllowSinglePartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = mac->getMacSize(); if (pSignature == NULL_PTR) { *pulSignatureLen = size; return CKR_OK; } // Check buffer size if (*pulSignatureLen < size) { *pulSignatureLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data(pData, ulDataLen); // Sign the data if (!mac->signUpdate(data)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Get the signature ByteString signature; if (!mac->signFinal(signature)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (signature.size() != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pSignature, signature.byte_str(), size); *pulSignatureLen = size; session->resetOp(); return CKR_OK; } // AsymmetricAlgorithm version of C_Sign static CK_RV AsymSign(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); AsymMech::Type mechanism = session->getMechanism(); PrivateKey* privateKey = session->getPrivateKey(); size_t paramLen; void* param = session->getParameters(paramLen); if (asymCrypto == NULL || !session->getAllowSinglePartOp() || privateKey == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = privateKey->getOutputLength(); if (pSignature == NULL_PTR) { *pulSignatureLen = size; return CKR_OK; } // Check buffer size if (*pulSignatureLen < size) { *pulSignatureLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the data ByteString data; // PKCS #11 Mechanisms v2.30: Cryptoki Draft 7 page 32 // We must allow input length <= k and therfore need to prepend the data with zeroes. if (mechanism == AsymMech::RSA) { data.wipe(size-ulDataLen); } data += ByteString(pData, ulDataLen); ByteString signature; // Sign the data if (session->getAllowMultiPartOp()) { if (!asymCrypto->signUpdate(data) || !asymCrypto->signFinal(signature)) { session->resetOp(); return CKR_GENERAL_ERROR; } } else if (!asymCrypto->sign(privateKey,data,signature,mechanism,param,paramLen)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (signature.size() != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pSignature, signature.byte_str(), size); *pulSignatureLen = size; session->resetOp(); return CKR_OK; } // Sign the data in a single pass operation CK_RV SoftHSM::C_Sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pData == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pulSignatureLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_SIGN) return CKR_OPERATION_NOT_INITIALIZED; if (session->getMacOp() != NULL) return MacSign(session, pData, ulDataLen, pSignature, pulSignatureLen); else return AsymSign(session, pData, ulDataLen, pSignature, pulSignatureLen); } // MacAlgorithm version of C_SignUpdate static CK_RV MacSignUpdate(Session* session, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { MacAlgorithm* mac = session->getMacOp(); if (mac == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Get the part ByteString part(pPart, ulPartLen); // Sign the data if (!mac->signUpdate(part)) { session->resetOp(); return CKR_GENERAL_ERROR; } session->setAllowSinglePartOp(false); return CKR_OK; } // AsymmetricAlgorithm version of C_SignUpdate static CK_RV AsymSignUpdate(Session* session, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); if (asymCrypto == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Get the part ByteString part(pPart, ulPartLen); // Sign the data if (!asymCrypto->signUpdate(part)) { session->resetOp(); return CKR_GENERAL_ERROR; } session->setAllowSinglePartOp(false); return CKR_OK; } // Update a running signing operation with additional data CK_RV SoftHSM::C_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pPart == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_SIGN) return CKR_OPERATION_NOT_INITIALIZED; if (session->getMacOp() != NULL) return MacSignUpdate(session, pPart, ulPartLen); else return AsymSignUpdate(session, pPart, ulPartLen); } // MacAlgorithm version of C_SignFinal static CK_RV MacSignFinal(Session* session, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { MacAlgorithm* mac = session->getMacOp(); if (mac == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = mac->getMacSize(); if (pSignature == NULL_PTR) { *pulSignatureLen = size; return CKR_OK; } // Check buffer size if (*pulSignatureLen < size) { *pulSignatureLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the signature ByteString signature; if (!mac->signFinal(signature)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (signature.size() != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pSignature, signature.byte_str(), size); *pulSignatureLen = size; session->resetOp(); return CKR_OK; } // AsymmetricAlgorithm version of C_SignFinal static CK_RV AsymSignFinal(Session* session, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); PrivateKey* privateKey = session->getPrivateKey(); if (asymCrypto == NULL || privateKey == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = privateKey->getOutputLength(); if (pSignature == NULL_PTR) { *pulSignatureLen = size; return CKR_OK; } // Check buffer size if (*pulSignatureLen < size) { *pulSignatureLen = size; return CKR_BUFFER_TOO_SMALL; } // Get the signature ByteString signature; if (!asymCrypto->signFinal(signature)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Check size if (signature.size() != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_GENERAL_ERROR; } memcpy(pSignature, signature.byte_str(), size); *pulSignatureLen = size; session->resetOp(); return CKR_OK; } // Finalise a running signing operation and return the signature CK_RV SoftHSM::C_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pulSignatureLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_SIGN || !session->getAllowMultiPartOp()) return CKR_OPERATION_NOT_INITIALIZED; if (session->getMacOp() != NULL) return MacSignFinal(session, pSignature, pulSignatureLen); else return AsymSignFinal(session, pSignature, pulSignatureLen); } // Initialise a signing operation that allows recovery of the signed data CK_RV SoftHSM::C_SignRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR /*pMechanism*/, CK_OBJECT_HANDLE /*hKey*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; return CKR_FUNCTION_NOT_SUPPORTED; } // Perform a single part signing operation that allows recovery of the signed data CK_RV SoftHSM::C_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pData*/, CK_ULONG /*ulDataLen*/, CK_BYTE_PTR /*pSignature*/, CK_ULONG_PTR /*pulSignatureLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // MacAlgorithm version of C_VerifyInit CK_RV SoftHSM::MacVerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for verifying if (!key->getBooleanValue(CKA_VERIFY, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the MAC algorithm matching the mechanism MacAlgo::Type algo = MacAlgo::Unknown; switch(pMechanism->mechanism) { #ifndef WITH_FIPS case CKM_MD5_HMAC: algo = MacAlgo::HMAC_MD5; break; #endif case CKM_SHA_1_HMAC: algo = MacAlgo::HMAC_SHA1; break; case CKM_SHA224_HMAC: algo = MacAlgo::HMAC_SHA224; break; case CKM_SHA256_HMAC: algo = MacAlgo::HMAC_SHA256; break; case CKM_SHA384_HMAC: algo = MacAlgo::HMAC_SHA384; break; case CKM_SHA512_HMAC: algo = MacAlgo::HMAC_SHA512; break; #ifdef WITH_GOST case CKM_GOSTR3411_HMAC: algo = MacAlgo::HMAC_GOST; break; #endif default: return CKR_MECHANISM_INVALID; } MacAlgorithm* mac = CryptoFactory::i()->getMacAlgorithm(algo); if (mac == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* pubkey = new SymmetricKey(); if (pubkey == NULL) { CryptoFactory::i()->recycleMacAlgorithm(mac); return CKR_HOST_MEMORY; } if (getSymmetricKey(pubkey, token, key) != CKR_OK) { mac->recycleKey(pubkey); CryptoFactory::i()->recycleMacAlgorithm(mac); return CKR_GENERAL_ERROR; } // Initialize verifying if (!mac->verifyInit(pubkey)) { mac->recycleKey(pubkey); CryptoFactory::i()->recycleMacAlgorithm(mac); return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_VERIFY); session->setMacOp(mac); session->setAllowMultiPartOp(true); session->setAllowSinglePartOp(true); session->setSymmetricKey(pubkey); return CKR_OK; } // AsymmetricAlgorithm version of C_VerifyInit CK_RV SoftHSM::AsymVerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check read user credentials CK_RV rv = haveRead(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for verifying if (!key->getBooleanValue(CKA_VERIFY, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Get the asymmetric algorithm matching the mechanism AsymMech::Type mechanism = AsymMech::Unknown; void* param = NULL; size_t paramLen = 0; RSA_PKCS_PSS_PARAMS pssParam; bool bAllowMultiPartOp; bool isRSA = false; bool isDSA = false; bool isECDSA = false; switch(pMechanism->mechanism) { case CKM_RSA_PKCS: mechanism = AsymMech::RSA_PKCS; bAllowMultiPartOp = false; isRSA = true; break; case CKM_RSA_X_509: mechanism = AsymMech::RSA; bAllowMultiPartOp = false; isRSA = true; break; #ifndef WITH_FIPS case CKM_MD5_RSA_PKCS: mechanism = AsymMech::RSA_MD5_PKCS; bAllowMultiPartOp = true; isRSA = true; break; #endif case CKM_SHA1_RSA_PKCS: mechanism = AsymMech::RSA_SHA1_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA224_RSA_PKCS: mechanism = AsymMech::RSA_SHA224_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA256_RSA_PKCS: mechanism = AsymMech::RSA_SHA256_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA384_RSA_PKCS: mechanism = AsymMech::RSA_SHA384_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA512_RSA_PKCS: mechanism = AsymMech::RSA_SHA512_PKCS; bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA1_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA_1 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA1) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA1_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA1; pssParam.mgf = AsymRSAMGF::MGF1_SHA1; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA224_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA224 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA224) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA224_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA224; pssParam.mgf = AsymRSAMGF::MGF1_SHA224; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA256_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA256 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA256) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA256_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA256; pssParam.mgf = AsymRSAMGF::MGF1_SHA256; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA384_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA384 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA384) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA384_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA384; pssParam.mgf = AsymRSAMGF::MGF1_SHA384; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_SHA512_RSA_PKCS_PSS: if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_PSS_PARAMS) || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->hashAlg != CKM_SHA512 || CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->mgf != CKG_MGF1_SHA512) { ERROR_MSG("Invalid parameters"); return CKR_ARGUMENTS_BAD; } mechanism = AsymMech::RSA_SHA512_PKCS_PSS; pssParam.hashAlg = HashAlgo::SHA512; pssParam.mgf = AsymRSAMGF::MGF1_SHA512; pssParam.sLen = CK_RSA_PKCS_PSS_PARAMS_PTR(pMechanism->pParameter)->sLen; param = &pssParam; paramLen = sizeof(pssParam); bAllowMultiPartOp = true; isRSA = true; break; case CKM_DSA: mechanism = AsymMech::DSA; bAllowMultiPartOp = false; isDSA = true; break; case CKM_DSA_SHA1: mechanism = AsymMech::DSA_SHA1; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA224: mechanism = AsymMech::DSA_SHA224; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA256: mechanism = AsymMech::DSA_SHA256; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA384: mechanism = AsymMech::DSA_SHA384; bAllowMultiPartOp = true; isDSA = true; break; case CKM_DSA_SHA512: mechanism = AsymMech::DSA_SHA512; bAllowMultiPartOp = true; isDSA = true; break; #ifdef WITH_ECC case CKM_ECDSA: mechanism = AsymMech::ECDSA; bAllowMultiPartOp = false; isECDSA = true; break; #endif #ifdef WITH_GOST case CKM_GOSTR3410: mechanism = AsymMech::GOST; bAllowMultiPartOp = false; break; case CKM_GOSTR3410_WITH_GOSTR3411: mechanism = AsymMech::GOST_GOST; bAllowMultiPartOp = true; break; #endif default: return CKR_MECHANISM_INVALID; } AsymmetricAlgorithm* asymCrypto = NULL; PublicKey* publicKey = NULL; if (isRSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; publicKey = asymCrypto->newPublicKey(); if (publicKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getRSAPublicKey((RSAPublicKey*)publicKey, token, key) != CKR_OK) { asymCrypto->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } else if (isDSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; publicKey = asymCrypto->newPublicKey(); if (publicKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getDSAPublicKey((DSAPublicKey*)publicKey, token, key) != CKR_OK) { asymCrypto->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } #ifdef WITH_ECC else if (isECDSA) { asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDSA); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; publicKey = asymCrypto->newPublicKey(); if (publicKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getECPublicKey((ECPublicKey*)publicKey, token, key) != CKR_OK) { asymCrypto->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } } #endif else { #ifdef WITH_GOST asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::GOST); if (asymCrypto == NULL) return CKR_MECHANISM_INVALID; publicKey = asymCrypto->newPublicKey(); if (publicKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } if (getGOSTPublicKey((GOSTPublicKey*)publicKey, token, key) != CKR_OK) { asymCrypto->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } #else return CKR_MECHANISM_INVALID; #endif } // Initialize verifying if (bAllowMultiPartOp && !asymCrypto->verifyInit(publicKey,mechanism,param,paramLen)) { asymCrypto->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_MECHANISM_INVALID; } session->setOpType(SESSION_OP_VERIFY); session->setAsymmetricCryptoOp(asymCrypto); session->setMechanism(mechanism); session->setParameters(param, paramLen); session->setAllowMultiPartOp(bAllowMultiPartOp); session->setAllowSinglePartOp(true); session->setPublicKey(publicKey); return CKR_OK; } // Initialise a verification operation using the specified key and mechanism CK_RV SoftHSM::C_VerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { if (isMacMechanism(pMechanism)) return MacVerifyInit(hSession, pMechanism, hKey); else return AsymVerifyInit(hSession, pMechanism, hKey); } // MacAlgorithm version of C_Verify static CK_RV MacVerify(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { MacAlgorithm* mac = session->getMacOp(); if (mac == NULL || !session->getAllowSinglePartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = mac->getMacSize(); // Check buffer size if (ulSignatureLen != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_SIGNATURE_LEN_RANGE; } // Get the data ByteString data(pData, ulDataLen); // Verify the data if (!mac->verifyUpdate(data)) { session->resetOp(); return CKR_GENERAL_ERROR; } // Get the signature ByteString signature(pSignature, ulSignatureLen); // Verify the signature if (!mac->verifyFinal(signature)) { session->resetOp(); return CKR_SIGNATURE_INVALID; } session->resetOp(); return CKR_OK; } // AsymmetricAlgorithm version of C_Verify static CK_RV AsymVerify(Session* session, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); AsymMech::Type mechanism = session->getMechanism(); PublicKey* publicKey = session->getPublicKey(); size_t paramLen; void* param = session->getParameters(paramLen); if (asymCrypto == NULL || !session->getAllowSinglePartOp() || publicKey == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = publicKey->getOutputLength(); // Check buffer size if (ulSignatureLen != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_SIGNATURE_LEN_RANGE; } // Get the data ByteString data; // PKCS #11 Mechanisms v2.30: Cryptoki Draft 7 page 32 // We must allow input length <= k and therfore need to prepend the data with zeroes. if (mechanism == AsymMech::RSA) { data.wipe(size-ulDataLen); } data += ByteString(pData, ulDataLen); ByteString signature(pSignature, ulSignatureLen); // Verify the data if (session->getAllowMultiPartOp()) { if (!asymCrypto->verifyUpdate(data) || !asymCrypto->verifyFinal(signature)) { session->resetOp(); return CKR_SIGNATURE_INVALID; } } else if (!asymCrypto->verify(publicKey,data,signature,mechanism,param,paramLen)) { session->resetOp(); return CKR_SIGNATURE_INVALID; } session->resetOp(); return CKR_OK; } // Perform a single pass verification operation CK_RV SoftHSM::C_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pData == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pSignature == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_VERIFY) return CKR_OPERATION_NOT_INITIALIZED; if (session->getMacOp() != NULL) return MacVerify(session, pData, ulDataLen, pSignature, ulSignatureLen); else return AsymVerify(session, pData, ulDataLen, pSignature, ulSignatureLen); } // MacAlgorithm version of C_VerifyUpdate static CK_RV MacVerifyUpdate(Session* session, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { MacAlgorithm* mac = session->getMacOp(); if (mac == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Get the part ByteString part(pPart, ulPartLen); // Verify the data if (!mac->verifyUpdate(part)) { // verifyUpdate can't fail for a logical reason, so we assume total breakdown. session->resetOp(); return CKR_GENERAL_ERROR; } session->setAllowSinglePartOp(false); return CKR_OK; } // AsymmetricAlgorithm version of C_VerifyUpdate static CK_RV AsymVerifyUpdate(Session* session, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); if (asymCrypto == NULL || !session->getAllowMultiPartOp()) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Get the part ByteString part(pPart, ulPartLen); // Verify the data if (!asymCrypto->verifyUpdate(part)) { // verifyUpdate can't fail for a logical reason, so we assume total breakdown. session->resetOp(); return CKR_GENERAL_ERROR; } session->setAllowSinglePartOp(false); return CKR_OK; } // Update a running verification operation with additional data CK_RV SoftHSM::C_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pPart == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_VERIFY) return CKR_OPERATION_NOT_INITIALIZED; if (session->getMacOp() != NULL) return MacVerifyUpdate(session, pPart, ulPartLen); else return AsymVerifyUpdate(session, pPart, ulPartLen); } // MacAlgorithm version of C_SignFinal static CK_RV MacVerifyFinal(Session* session, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { MacAlgorithm* mac = session->getMacOp(); if (mac == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = mac->getMacSize(); // Check buffer size if (ulSignatureLen != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_SIGNATURE_LEN_RANGE; } // Get the signature ByteString signature(pSignature, ulSignatureLen); // Verify the data if (!mac->verifyFinal(signature)) { session->resetOp(); return CKR_SIGNATURE_INVALID; } session->resetOp(); return CKR_OK; } // AsymmetricAlgorithm version of C_VerifyFinal static CK_RV AsymVerifyFinal(Session* session, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { AsymmetricAlgorithm* asymCrypto = session->getAsymmetricCryptoOp(); PublicKey* publicKey = session->getPublicKey(); if (asymCrypto == NULL || publicKey == NULL) { session->resetOp(); return CKR_OPERATION_NOT_INITIALIZED; } // Size of the signature CK_ULONG size = publicKey->getOutputLength(); // Check buffer size if (ulSignatureLen != size) { ERROR_MSG("The size of the signature differs from the size of the mechanism"); session->resetOp(); return CKR_SIGNATURE_LEN_RANGE; } // Get the data ByteString signature(pSignature, ulSignatureLen); // Verify the data if (!asymCrypto->verifyFinal(signature)) { session->resetOp(); return CKR_SIGNATURE_INVALID; } session->resetOp(); return CKR_OK; } // Finalise the verification operation and check the signature CK_RV SoftHSM::C_VerifyFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pSignature == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we are doing the correct operation if (session->getOpType() != SESSION_OP_VERIFY || !session->getAllowMultiPartOp()) return CKR_OPERATION_NOT_INITIALIZED; if (session->getMacOp() != NULL) return MacVerifyFinal(session, pSignature, ulSignatureLen); else return AsymVerifyFinal(session, pSignature, ulSignatureLen); } // Initialise a verification operation the allows recovery of the signed data from the signature CK_RV SoftHSM::C_VerifyRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR /*pMechanism*/, CK_OBJECT_HANDLE /*hKey*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check if we have another operation if (session->getOpType() != SESSION_OP_NONE) return CKR_OPERATION_ACTIVE; return CKR_FUNCTION_NOT_SUPPORTED; } // Perform a single part verification operation and recover the signed data CK_RV SoftHSM::C_VerifyRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pSignature*/, CK_ULONG /*ulSignatureLen*/, CK_BYTE_PTR /*pData*/, CK_ULONG_PTR /*pulDataLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Update a running multi-part encryption and digesting operation CK_RV SoftHSM::C_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pPart*/, CK_ULONG /*ulPartLen*/, CK_BYTE_PTR /*pEncryptedPart*/, CK_ULONG_PTR /*pulEncryptedPartLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Update a running multi-part decryption and digesting operation CK_RV SoftHSM::C_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pPart*/, CK_ULONG /*ulPartLen*/, CK_BYTE_PTR /*pDecryptedPart*/, CK_ULONG_PTR /*pulDecryptedPartLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Update a running multi-part signing and encryption operation CK_RV SoftHSM::C_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pPart*/, CK_ULONG /*ulPartLen*/, CK_BYTE_PTR /*pEncryptedPart*/, CK_ULONG_PTR /*pulEncryptedPartLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Update a running multi-part decryption and verification operation CK_RV SoftHSM::C_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR /*pEncryptedPart*/, CK_ULONG /*ulEncryptedPartLen*/, CK_BYTE_PTR /*pPart*/, CK_ULONG_PTR /*pulPartLen*/) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_SUPPORTED; } // Generate a secret key or a domain parameter set using the specified mechanism CK_RV SoftHSM::C_GenerateKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; if (phKey == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check the mechanism, only accept DSA and DH parameters // and symmetric ciphers CK_OBJECT_CLASS objClass; CK_KEY_TYPE keyType; switch (pMechanism->mechanism) { case CKM_DSA_PARAMETER_GEN: objClass = CKO_DOMAIN_PARAMETERS; keyType = CKK_DSA; break; case CKM_DH_PKCS_PARAMETER_GEN: objClass = CKO_DOMAIN_PARAMETERS; keyType = CKK_DH; break; #ifndef WITH_FIPS case CKM_DES_KEY_GEN: objClass = CKO_SECRET_KEY; keyType = CKK_DES; break; #endif case CKM_DES2_KEY_GEN: objClass = CKO_SECRET_KEY; keyType = CKK_DES2; break; case CKM_DES3_KEY_GEN: objClass = CKO_SECRET_KEY; keyType = CKK_DES3; break; case CKM_AES_KEY_GEN: objClass = CKO_SECRET_KEY; keyType = CKK_AES; break; default: return CKR_MECHANISM_INVALID; } // Extract information from the template that is needed to create the object. CK_BBOOL isOnToken = CK_FALSE; CK_BBOOL isPrivate = CK_TRUE; CK_CERTIFICATE_TYPE dummy; bool isImplicit = true; extractObjectInformation(pTemplate, ulCount, objClass, keyType, dummy, isOnToken, isPrivate, isImplicit); // Report errors and/or unexpected usage. if (objClass != CKO_SECRET_KEY && objClass != CKO_DOMAIN_PARAMETERS) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DSA_PARAMETER_GEN && (objClass != CKO_DOMAIN_PARAMETERS || keyType != CKK_DSA)) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DH_PKCS_PARAMETER_GEN && (objClass != CKO_DOMAIN_PARAMETERS || keyType != CKK_DH)) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES_KEY_GEN && (objClass != CKO_SECRET_KEY || keyType != CKK_DES)) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES2_KEY_GEN && (objClass != CKO_SECRET_KEY || keyType != CKK_DES2)) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES3_KEY_GEN && (objClass != CKO_SECRET_KEY || keyType != CKK_DES3)) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_KEY_GEN && (objClass != CKO_SECRET_KEY || keyType != CKK_AES)) return CKR_TEMPLATE_INCONSISTENT; // Check authorization CK_RV rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Generate DSA domain parameters if (pMechanism->mechanism == CKM_DSA_PARAMETER_GEN) { return this->generateDSAParameters(hSession, pTemplate, ulCount, phKey, isOnToken, isPrivate); } // Generate DH domain parameters if (pMechanism->mechanism == CKM_DH_PKCS_PARAMETER_GEN) { return this->generateDHParameters(hSession, pTemplate, ulCount, phKey, isOnToken, isPrivate); } // Generate DES secret key if (pMechanism->mechanism == CKM_DES_KEY_GEN) { return this->generateDES(hSession, pTemplate, ulCount, phKey, isOnToken, isPrivate); } // Generate DES2 secret key if (pMechanism->mechanism == CKM_DES2_KEY_GEN) { return this->generateDES2(hSession, pTemplate, ulCount, phKey, isOnToken, isPrivate); } // Generate DES3 secret key if (pMechanism->mechanism == CKM_DES3_KEY_GEN) { return this->generateDES3(hSession, pTemplate, ulCount, phKey, isOnToken, isPrivate); } // Generate AES secret key if (pMechanism->mechanism == CKM_AES_KEY_GEN) { return this->generateAES(hSession, pTemplate, ulCount, phKey, isOnToken, isPrivate); } return CKR_GENERAL_ERROR; } // Generate a key-pair using the specified mechanism CK_RV SoftHSM::C_GenerateKeyPair ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey ) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; if (phPublicKey == NULL_PTR) return CKR_ARGUMENTS_BAD; if (phPrivateKey == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check the mechanism, only accept RSA, DSA, EC and DH key pair generation. CK_KEY_TYPE keyType; switch (pMechanism->mechanism) { case CKM_RSA_PKCS_KEY_PAIR_GEN: keyType = CKK_RSA; break; case CKM_DSA_KEY_PAIR_GEN: keyType = CKK_DSA; break; case CKM_DH_PKCS_KEY_PAIR_GEN: keyType = CKK_DH; break; #ifdef WITH_ECC case CKM_EC_KEY_PAIR_GEN: keyType = CKK_EC; break; #endif #ifdef WITH_GOST case CKM_GOSTR3410_KEY_PAIR_GEN: keyType = CKK_GOSTR3410; break; #endif default: return CKR_MECHANISM_INVALID; } CK_CERTIFICATE_TYPE dummy; // Extract information from the public key template that is needed to create the object. CK_OBJECT_CLASS publicKeyClass = CKO_PUBLIC_KEY; CK_BBOOL ispublicKeyToken = CK_FALSE; CK_BBOOL ispublicKeyPrivate = CK_TRUE; bool isPublicKeyImplicit = true; extractObjectInformation(pPublicKeyTemplate, ulPublicKeyAttributeCount, publicKeyClass, keyType, dummy, ispublicKeyToken, ispublicKeyPrivate, isPublicKeyImplicit); // Report errors caused by accidental template mix-ups in the application using this cryptoki lib. if (publicKeyClass != CKO_PUBLIC_KEY) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_RSA_PKCS_KEY_PAIR_GEN && keyType != CKK_RSA) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DSA_KEY_PAIR_GEN && keyType != CKK_DSA) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_EC_KEY_PAIR_GEN && keyType != CKK_EC) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DH_PKCS_KEY_PAIR_GEN && keyType != CKK_DH) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_GOSTR3410_KEY_PAIR_GEN && keyType != CKK_GOSTR3410) return CKR_TEMPLATE_INCONSISTENT; // Extract information from the private key template that is needed to create the object. CK_OBJECT_CLASS privateKeyClass = CKO_PRIVATE_KEY; CK_BBOOL isprivateKeyToken = CK_FALSE; CK_BBOOL isprivateKeyPrivate = CK_TRUE; bool isPrivateKeyImplicit = true; extractObjectInformation(pPrivateKeyTemplate, ulPrivateKeyAttributeCount, privateKeyClass, keyType, dummy, isprivateKeyToken, isprivateKeyPrivate, isPrivateKeyImplicit); // Report errors caused by accidental template mix-ups in the application using this cryptoki lib. if (privateKeyClass != CKO_PRIVATE_KEY) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_RSA_PKCS_KEY_PAIR_GEN && keyType != CKK_RSA) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DSA_KEY_PAIR_GEN && keyType != CKK_DSA) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_EC_KEY_PAIR_GEN && keyType != CKK_EC) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_DH_PKCS_KEY_PAIR_GEN && keyType != CKK_DH) return CKR_TEMPLATE_INCONSISTENT; if (pMechanism->mechanism == CKM_GOSTR3410_KEY_PAIR_GEN && keyType != CKK_GOSTR3410) return CKR_TEMPLATE_INCONSISTENT; // Check user credentials CK_RV rv = haveWrite(session->getState(), ispublicKeyToken || isprivateKeyToken, ispublicKeyPrivate || isprivateKeyPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Generate RSA keys if (pMechanism->mechanism == CKM_RSA_PKCS_KEY_PAIR_GEN) { return this->generateRSA(hSession, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, phPublicKey, phPrivateKey, ispublicKeyToken, ispublicKeyPrivate, isprivateKeyToken, isprivateKeyPrivate); } // Generate DSA keys if (pMechanism->mechanism == CKM_DSA_KEY_PAIR_GEN) { return this->generateDSA(hSession, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, phPublicKey, phPrivateKey, ispublicKeyToken, ispublicKeyPrivate, isprivateKeyToken, isprivateKeyPrivate); } // Generate EC keys if (pMechanism->mechanism == CKM_EC_KEY_PAIR_GEN) { return this->generateEC(hSession, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, phPublicKey, phPrivateKey, ispublicKeyToken, ispublicKeyPrivate, isprivateKeyToken, isprivateKeyPrivate); } // Generate DH keys if (pMechanism->mechanism == CKM_DH_PKCS_KEY_PAIR_GEN) { return this->generateDH(hSession, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, phPublicKey, phPrivateKey, ispublicKeyToken, ispublicKeyPrivate, isprivateKeyToken, isprivateKeyPrivate); } // Generate GOST keys if (pMechanism->mechanism == CKM_GOSTR3410_KEY_PAIR_GEN) { return this->generateGOST(hSession, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, phPublicKey, phPrivateKey, ispublicKeyToken, ispublicKeyPrivate, isprivateKeyToken, isprivateKeyPrivate); } return CKR_GENERAL_ERROR; } // Internal: Wrap blob using symmetric key CK_RV SoftHSM::WrapKeySym ( CK_MECHANISM_PTR pMechanism, Token* token, OSObject* wrapKey, ByteString& keydata, ByteString& wrapped ) { // Get the symmetric algorithm matching the mechanism SymAlgo::Type algo = SymAlgo::Unknown; SymWrap::Type mode = SymWrap::Unknown; size_t bb = 8; #ifdef HAVE_AES_KEY_WRAP CK_ULONG wrappedlen = keydata.size(); #endif switch(pMechanism->mechanism) { #ifdef HAVE_AES_KEY_WRAP case CKM_AES_KEY_WRAP: if ((wrappedlen < 16) || ((wrappedlen % 8) != 0)) return CKR_KEY_SIZE_RANGE; algo = SymAlgo::AES; mode = SymWrap::AES_KEYWRAP; break; #endif #ifdef HAVE_AES_KEY_WRAP_PAD case CKM_AES_KEY_WRAP_PAD: algo = SymAlgo::AES; mode = SymWrap::AES_KEYWRAP_PAD; break; #endif default: return CKR_MECHANISM_INVALID; } SymmetricAlgorithm* cipher = CryptoFactory::i()->getSymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* wrappingkey = new SymmetricKey(); if (wrappingkey == NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } if (getSymmetricKey(wrappingkey, token, wrapKey) != CKR_OK) { cipher->recycleKey(wrappingkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } // adjust key bit length wrappingkey->setBitLen(wrappingkey->getKeyBits().size() * bb); // Wrap the key if (!cipher->wrapKey(wrappingkey, mode, keydata, wrapped)) { cipher->recycleKey(wrappingkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } cipher->recycleKey(wrappingkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_OK; } // Internal: Wrap blob using asymmetric key CK_RV SoftHSM::WrapKeyAsym ( CK_MECHANISM_PTR pMechanism, Token* token, OSObject* wrapKey, ByteString& keydata, ByteString& wrapped ) { const size_t bb = 8; AsymAlgo::Type algo = AsymAlgo::Unknown; AsymMech::Type mech = AsymMech::Unknown; CK_ULONG modulus_length; switch(pMechanism->mechanism) { case CKM_RSA_PKCS: case CKM_RSA_PKCS_OAEP: algo = AsymAlgo::RSA; if (!wrapKey->attributeExists(CKA_MODULUS_BITS)) return CKR_GENERAL_ERROR; modulus_length = wrapKey->getUnsignedLongValue(CKA_MODULUS_BITS, 0); // adjust key bit length modulus_length /= bb; break; default: return CKR_MECHANISM_INVALID; } switch(pMechanism->mechanism) { case CKM_RSA_PKCS: mech = AsymMech::RSA_PKCS; // RFC 3447 section 7.2.1 if (keydata.size() > modulus_length - 11) return CKR_KEY_SIZE_RANGE; break; case CKM_RSA_PKCS_OAEP: mech = AsymMech::RSA_PKCS_OAEP; // SHA-1 is the only supported option // PKCS#11 2.40 draft 2 section 2.1.8: input length <= k-2-2hashLen if (keydata.size() > modulus_length - 2 - 2 * 160 / 8) return CKR_KEY_SIZE_RANGE; break; default: return CKR_MECHANISM_INVALID; } AsymmetricAlgorithm* cipher = CryptoFactory::i()->getAsymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; PublicKey* publicKey = cipher->newPublicKey(); if (publicKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } switch(pMechanism->mechanism) { case CKM_RSA_PKCS: case CKM_RSA_PKCS_OAEP: if (getRSAPublicKey((RSAPublicKey*)publicKey, token, wrapKey) != CKR_OK) { cipher->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } break; default: return CKR_MECHANISM_INVALID; } // Wrap the key if (!cipher->wrapKey(publicKey, keydata, wrapped, mech)) { cipher->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } cipher->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return CKR_OK; } // Wrap the specified key using the specified wrapping key and mechanism CK_RV SoftHSM::C_WrapKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, CK_ULONG_PTR pulWrappedKeyLen ) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pulWrappedKeyLen == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; CK_RV rv; // Check the mechanism, only accept advanced AES key wrapping and RSA switch(pMechanism->mechanism) { #ifdef HAVE_AES_KEY_WRAP case CKM_AES_KEY_WRAP: #endif #ifdef HAVE_AES_KEY_WRAP_PAD case CKM_AES_KEY_WRAP_PAD: #endif case CKM_RSA_PKCS: // Does not handle optional init vector if (pMechanism->pParameter != NULL_PTR || pMechanism->ulParameterLen != 0) return CKR_ARGUMENTS_BAD; break; case CKM_RSA_PKCS_OAEP: rv = MechParamCheckRSAPKCSOAEP(pMechanism); if (rv != CKR_OK) return rv; break; default: return CKR_MECHANISM_INVALID; } // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the wrapping key handle. OSObject *wrapKey = (OSObject *)handleManager->getObject(hWrappingKey); if (wrapKey == NULL_PTR || !wrapKey->isValid()) return CKR_WRAPPING_KEY_HANDLE_INVALID; CK_BBOOL isWrapKeyOnToken = wrapKey->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isWrapKeyPrivate = wrapKey->getBooleanValue(CKA_PRIVATE, true); // Check user credentials for the wrapping key rv = haveRead(session->getState(), isWrapKeyOnToken, isWrapKeyPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check wrapping key class and type if ((pMechanism->mechanism == CKM_AES_KEY_WRAP || pMechanism->mechanism == CKM_AES_KEY_WRAP_PAD) && wrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_SECRET_KEY) return CKR_WRAPPING_KEY_TYPE_INCONSISTENT; if ((pMechanism->mechanism == CKM_RSA_PKCS || pMechanism->mechanism == CKM_RSA_PKCS_OAEP) && wrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_PUBLIC_KEY) return CKR_WRAPPING_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_KEY_WRAP && wrapKey->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_AES) return CKR_WRAPPING_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_KEY_WRAP_PAD && wrapKey->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_AES) return CKR_WRAPPING_KEY_TYPE_INCONSISTENT; if ((pMechanism->mechanism == CKM_RSA_PKCS || pMechanism->mechanism == CKM_RSA_PKCS_OAEP) && wrapKey->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_RSA) return CKR_WRAPPING_KEY_TYPE_INCONSISTENT; // Check if the wrapping key can be used for wrapping if (wrapKey->getBooleanValue(CKA_WRAP, false) == false) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Check the to be wrapped key handle. OSObject *key = (OSObject *)handleManager->getObject(hKey); if (key == NULL_PTR || !key->isValid()) return CKR_KEY_HANDLE_INVALID; CK_BBOOL isKeyOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check user credentials for the to be wrapped key rv = haveRead(session->getState(), isKeyOnToken, isKeyPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if the to be wrapped key can be wrapped if (key->getBooleanValue(CKA_EXTRACTABLE, false) == false) return CKR_KEY_UNEXTRACTABLE; if (key->getBooleanValue(CKA_WRAP_WITH_TRUSTED, false) && wrapKey->getBooleanValue(CKA_TRUSTED, false) == false) return CKR_KEY_NOT_WRAPPABLE; // Check the class CK_OBJECT_CLASS keyClass = key->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED); if (keyClass != CKO_SECRET_KEY && keyClass != CKO_PRIVATE_KEY) return CKR_KEY_NOT_WRAPPABLE; // CKM_RSA_PKCS and CKM_RSA_PKCS_OAEP can be used only on SECRET keys: PKCS#11 2.40 draft 2 section 2.1.6 PKCS #1 v1.5 RSA & section 2.1.8 PKCS #1 RSA OAEP if ((pMechanism->mechanism == CKM_RSA_PKCS || pMechanism->mechanism == CKM_RSA_PKCS_OAEP) && keyClass != CKO_SECRET_KEY) return CKR_KEY_NOT_WRAPPABLE; // Verify the wrap template attribute if (wrapKey->attributeExists(CKA_WRAP_TEMPLATE)) { OSAttribute attr = wrapKey->getAttribute(CKA_WRAP_TEMPLATE); if (attr.isArrayAttribute()) { typedef std::map array_type; const array_type& array = attr.getArrayValue(); for (array_type::const_iterator it = array.begin(); it != array.end(); ++it) { if (!key->attributeExists(it->first)) { return CKR_KEY_NOT_WRAPPABLE; } OSAttribute keyAttr = key->getAttribute(it->first); ByteString v1, v2; if (!keyAttr.peekValue(v1) || !it->second.peekValue(v2) || (v1 != v2)) { return CKR_KEY_NOT_WRAPPABLE; } } } } // Get the key data to encrypt ByteString keydata; if (keyClass == CKO_SECRET_KEY) { if (isKeyPrivate) { bool bOK = token->decrypt(key->getByteStringValue(CKA_VALUE), keydata); if (!bOK) return CKR_GENERAL_ERROR; } else { keydata = key->getByteStringValue(CKA_VALUE); } } else { CK_KEY_TYPE keyType = key->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED); AsymAlgo::Type alg = AsymAlgo::Unknown; switch (keyType) { case CKK_RSA: alg = AsymAlgo::RSA; break; case CKK_DSA: alg = AsymAlgo::DSA; break; case CKK_DH: alg = AsymAlgo::DH; break; #ifdef WITH_ECC case CKK_EC: // can be ecdh too but it doesn't matter alg = AsymAlgo::ECDSA; break; #endif default: return CKR_KEY_NOT_WRAPPABLE; } AsymmetricAlgorithm* asymCrypto = NULL; PrivateKey* privateKey = NULL; asymCrypto = CryptoFactory::i()->getAsymmetricAlgorithm(alg); if (asymCrypto == NULL) return CKR_GENERAL_ERROR; privateKey = asymCrypto->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_HOST_MEMORY; } switch (keyType) { case CKK_RSA: rv = getRSAPrivateKey((RSAPrivateKey*)privateKey, token, key); break; case CKK_DSA: rv = getDSAPrivateKey((DSAPrivateKey*)privateKey, token, key); break; case CKK_DH: rv = getDHPrivateKey((DHPrivateKey*)privateKey, token, key); break; #ifdef WITH_ECC case CKK_EC: rv = getECPrivateKey((ECPrivateKey*)privateKey, token, key); break; #endif } if (rv != CKR_OK) { asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); return CKR_GENERAL_ERROR; } keydata = privateKey->PKCS8Encode(); asymCrypto->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(asymCrypto); } if (keydata.size() == 0) return CKR_KEY_NOT_WRAPPABLE; keyClass = wrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED); ByteString wrapped; if (keyClass == CKO_SECRET_KEY) rv = SoftHSM::WrapKeySym(pMechanism, token, wrapKey, keydata, wrapped); else rv = SoftHSM::WrapKeyAsym(pMechanism, token, wrapKey, keydata, wrapped); if (rv != CKR_OK) return rv; if (pWrappedKey != NULL) { if (*pulWrappedKeyLen >= wrapped.size()) memcpy(pWrappedKey, wrapped.byte_str(), wrapped.size()); else rv = CKR_BUFFER_TOO_SMALL; } *pulWrappedKeyLen = wrapped.size(); return rv; } // Internal: Unwrap blob using symmetric key CK_RV SoftHSM::UnwrapKeySym ( CK_MECHANISM_PTR pMechanism, ByteString& wrapped, Token* token, OSObject* unwrapKey, ByteString& keydata ) { // Get the symmetric algorithm matching the mechanism SymAlgo::Type algo = SymAlgo::Unknown; SymWrap::Type mode = SymWrap::Unknown; size_t bb = 8; switch(pMechanism->mechanism) { #ifdef HAVE_AES_KEY_WRAP case CKM_AES_KEY_WRAP: algo = SymAlgo::AES; mode = SymWrap::AES_KEYWRAP; break; #endif #ifdef HAVE_AES_KEY_WRAP_PAD case CKM_AES_KEY_WRAP_PAD: algo = SymAlgo::AES; mode = SymWrap::AES_KEYWRAP_PAD; break; #endif default: return CKR_MECHANISM_INVALID; } SymmetricAlgorithm* cipher = CryptoFactory::i()->getSymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* unwrappingkey = new SymmetricKey(); if (unwrappingkey == NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } if (getSymmetricKey(unwrappingkey, token, unwrapKey) != CKR_OK) { cipher->recycleKey(unwrappingkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } // adjust key bit length unwrappingkey->setBitLen(unwrappingkey->getKeyBits().size() * bb); // Unwrap the key CK_RV rv = CKR_OK; if (!cipher->unwrapKey(unwrappingkey, mode, wrapped, keydata)) rv = CKR_GENERAL_ERROR; cipher->recycleKey(unwrappingkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return rv; } // Internal: Unwrap blob using asymmetric key CK_RV SoftHSM::UnwrapKeyAsym ( CK_MECHANISM_PTR pMechanism, ByteString& wrapped, Token* token, OSObject* unwrapKey, ByteString& keydata ) { // Get the symmetric algorithm matching the mechanism AsymAlgo::Type algo = AsymAlgo::Unknown; AsymMech::Type mode = AsymMech::Unknown; switch(pMechanism->mechanism) { case CKM_RSA_PKCS: algo = AsymAlgo::RSA; mode = AsymMech::RSA_PKCS; break; case CKM_RSA_PKCS_OAEP: algo = AsymAlgo::RSA; mode = AsymMech::RSA_PKCS_OAEP; break; default: return CKR_MECHANISM_INVALID; } AsymmetricAlgorithm* cipher = CryptoFactory::i()->getAsymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; PrivateKey* unwrappingkey = cipher->newPrivateKey(); if (unwrappingkey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } switch(pMechanism->mechanism) { case CKM_RSA_PKCS: case CKM_RSA_PKCS_OAEP: if (getRSAPrivateKey((RSAPrivateKey*)unwrappingkey, token, unwrapKey) != CKR_OK) { cipher->recyclePrivateKey(unwrappingkey); CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } break; default: return CKR_MECHANISM_INVALID; } // Unwrap the key CK_RV rv = CKR_OK; if (!cipher->unwrapKey(unwrappingkey, wrapped, keydata, mode)) rv = CKR_GENERAL_ERROR; cipher->recyclePrivateKey(unwrappingkey); CryptoFactory::i()->recycleAsymmetricAlgorithm(cipher); return rv; } // Unwrap the specified key using the specified unwrapping key CK_RV SoftHSM::C_UnwrapKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR hKey ) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pWrappedKey == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pTemplate == NULL_PTR) return CKR_ARGUMENTS_BAD; if (hKey == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; CK_RV rv; // Check the mechanism switch(pMechanism->mechanism) { #ifdef HAVE_AES_KEY_WRAP case CKM_AES_KEY_WRAP: if ((ulWrappedKeyLen < 24) || ((ulWrappedKeyLen % 8) != 0)) return CKR_WRAPPED_KEY_LEN_RANGE; // Does not handle optional init vector if (pMechanism->pParameter != NULL_PTR || pMechanism->ulParameterLen != 0) return CKR_ARGUMENTS_BAD; break; #endif #ifdef HAVE_AES_KEY_WRAP_PAD case CKM_AES_KEY_WRAP_PAD: if ((ulWrappedKeyLen < 16) || ((ulWrappedKeyLen % 8) != 0)) return CKR_WRAPPED_KEY_LEN_RANGE; // Does not handle optional init vector if (pMechanism->pParameter != NULL_PTR || pMechanism->ulParameterLen != 0) return CKR_ARGUMENTS_BAD; break; #endif case CKM_RSA_PKCS: // Input length checks needs to be done later when unwrapping key is known break; case CKM_RSA_PKCS_OAEP: rv = MechParamCheckRSAPKCSOAEP(pMechanism); if (rv != CKR_OK) return rv; break; default: return CKR_MECHANISM_INVALID; } // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the unwrapping key handle. OSObject *unwrapKey = (OSObject *)handleManager->getObject(hUnwrappingKey); if (unwrapKey == NULL_PTR || !unwrapKey->isValid()) return CKR_UNWRAPPING_KEY_HANDLE_INVALID; CK_BBOOL isUnwrapKeyOnToken = unwrapKey->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isUnwrapKeyPrivate = unwrapKey->getBooleanValue(CKA_PRIVATE, true); // Check user credentials rv = haveRead(session->getState(), isUnwrapKeyOnToken, isUnwrapKeyPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check unwrapping key class and type if ((pMechanism->mechanism == CKM_AES_KEY_WRAP || pMechanism->mechanism == CKM_AES_KEY_WRAP_PAD) && unwrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_SECRET_KEY) return CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_KEY_WRAP && unwrapKey->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_AES) return CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_KEY_WRAP_PAD && unwrapKey->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_AES) return CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; if ((pMechanism->mechanism == CKM_RSA_PKCS || pMechanism->mechanism == CKM_RSA_PKCS_OAEP) && unwrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_PRIVATE_KEY) return CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; if ((pMechanism->mechanism == CKM_RSA_PKCS || pMechanism->mechanism == CKM_RSA_PKCS_OAEP) && unwrapKey->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_RSA) return CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; // Check if the unwrapping key can be used for unwrapping if (unwrapKey->getBooleanValue(CKA_UNWRAP, false) == false) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Extract information from the template that is needed to create the object. CK_OBJECT_CLASS objClass; CK_KEY_TYPE keyType; CK_BBOOL isOnToken = CK_FALSE; CK_BBOOL isPrivate = CK_TRUE; CK_CERTIFICATE_TYPE dummy; bool isImplicit = false; rv = extractObjectInformation(pTemplate, ulCount, objClass, keyType, dummy, isOnToken, isPrivate, isImplicit); if (rv != CKR_OK) { ERROR_MSG("Mandatory attribute not present in template"); return rv; } // Report errors and/or unexpected usage. if (objClass != CKO_SECRET_KEY && objClass != CKO_PRIVATE_KEY) return CKR_TEMPLATE_INCONSISTENT; // Key type will be handled at object creation // Check authorization rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Build unwrapped key template const CK_ULONG maxAttribs = 32; CK_ATTRIBUTE secretAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) } }; CK_ULONG secretAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - secretAttribsCount)) return CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i = 0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: secretAttribs[secretAttribsCount++] = pTemplate[i]; } } // Apply the unwrap template if (unwrapKey->attributeExists(CKA_UNWRAP_TEMPLATE)) { OSAttribute unwrapAttr = unwrapKey->getAttribute(CKA_UNWRAP_TEMPLATE); if (unwrapAttr.isArrayAttribute()) { typedef std::map array_type; const array_type& array = unwrapAttr.getArrayValue(); for (array_type::const_iterator it = array.begin(); it != array.end(); ++it) { CK_ATTRIBUTE* attr = NULL; for (CK_ULONG i = 0; i < secretAttribsCount; ++i) { if (it->first == secretAttribs[i].type) { if (attr != NULL) { return CKR_TEMPLATE_INCONSISTENT; } attr = &secretAttribs[i]; ByteString value; it->second.peekValue(value); if (attr->ulValueLen != value.size()) { return CKR_TEMPLATE_INCONSISTENT; } if (memcmp(attr->pValue, value.const_byte_str(), value.size()) != 0) { return CKR_TEMPLATE_INCONSISTENT; } } } if (attr == NULL) { return CKR_TEMPLATE_INCONSISTENT; } } } } *hKey = CK_INVALID_HANDLE; // Unwrap the key ByteString wrapped(pWrappedKey, ulWrappedKeyLen); ByteString keydata; if (unwrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) == CKO_SECRET_KEY) rv = UnwrapKeySym(pMechanism, wrapped, token, unwrapKey, keydata); else if (unwrapKey->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) == CKO_PRIVATE_KEY) rv = UnwrapKeyAsym(pMechanism, wrapped, token, unwrapKey, keydata); else rv = CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT; if (rv != CKR_OK) return rv; // Create the secret object using C_CreateObject rv = this->CreateObject(hSession, secretAttribs, secretAttribsCount, hKey, OBJECT_OP_UNWRAP); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*hKey); if (osobject == NULL_PTR || !osobject->isValid()) rv = CKR_FUNCTION_FAILED; if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL, false); // Common Secret Key Attributes bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, false); // Secret Attributes if (objClass == CKO_SECRET_KEY) { ByteString value; if (isPrivate) token->encrypt(keydata, value); else value = keydata; bOK = bOK && osobject->setAttribute(CKA_VALUE, value); } else if (keyType == CKK_RSA) { bOK = bOK && setRSAPrivateKey(osobject, keydata, token, isPrivate != CK_FALSE); } else if (keyType == CKK_DSA) { bOK = bOK && setDSAPrivateKey(osobject, keydata, token, isPrivate != CK_FALSE); } else if (keyType == CKK_DH) { bOK = bOK && setDHPrivateKey(osobject, keydata, token, isPrivate != CK_FALSE); } else if (keyType == CKK_EC) { bOK = bOK && setECPrivateKey(osobject, keydata, token, isPrivate != CK_FALSE); } else bOK = false; if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Remove secret that may have been created already when the function fails. if (rv != CKR_OK) { if (*hKey != CK_INVALID_HANDLE) { OSObject* obj = (OSObject*)handleManager->getObject(*hKey); handleManager->destroyObject(*hKey); if (obj) obj->destroyObject(); *hKey = CK_INVALID_HANDLE; } } return rv; } // Derive a key from the specified base key CK_RV SoftHSM::C_DeriveKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey ) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; if (pTemplate == NULL_PTR) return CKR_ARGUMENTS_BAD; if (phKey == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Check the mechanism, only accept DH and ECDH derive switch (pMechanism->mechanism) { case CKM_DH_PKCS_DERIVE: #ifdef WITH_ECC case CKM_ECDH1_DERIVE: #endif #ifndef WITH_FIPS case CKM_DES_ECB_ENCRYPT_DATA: case CKM_DES_CBC_ENCRYPT_DATA: #endif case CKM_DES3_ECB_ENCRYPT_DATA: case CKM_DES3_CBC_ENCRYPT_DATA: case CKM_AES_ECB_ENCRYPT_DATA: case CKM_AES_CBC_ENCRYPT_DATA: break; default: ERROR_MSG("Invalid mechanism"); return CKR_MECHANISM_INVALID; } // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Check the key handle. OSObject *key = (OSObject *)handleManager->getObject(hBaseKey); if (key == NULL_PTR || !key->isValid()) return CKR_OBJECT_HANDLE_INVALID; CK_BBOOL isKeyOnToken = key->getBooleanValue(CKA_TOKEN, false); CK_BBOOL isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, true); // Check user credentials CK_RV rv = haveRead(session->getState(), isKeyOnToken, isKeyPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); return rv; } // Check if key can be used for derive if (!key->getBooleanValue(CKA_DERIVE, false)) return CKR_KEY_FUNCTION_NOT_PERMITTED; // Extract information from the template that is needed to create the object. CK_OBJECT_CLASS objClass; CK_KEY_TYPE keyType; CK_BBOOL isOnToken = CK_FALSE; CK_BBOOL isPrivate = CK_TRUE; CK_CERTIFICATE_TYPE dummy; bool isImplicit = false; rv = extractObjectInformation(pTemplate, ulCount, objClass, keyType, dummy, isOnToken, isPrivate, isImplicit); if (rv != CKR_OK) { ERROR_MSG("Mandatory attribute not present in template"); return rv; } // Report errors and/or unexpected usage. if (objClass != CKO_SECRET_KEY) return CKR_TEMPLATE_INCONSISTENT; if (keyType != CKK_GENERIC_SECRET && keyType != CKK_DES && keyType != CKK_DES2 && keyType != CKK_DES3 && keyType != CKK_AES) return CKR_TEMPLATE_INCONSISTENT; // Check authorization rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } // Derive DH secret if (pMechanism->mechanism == CKM_DH_PKCS_DERIVE) { // Check key class and type if (key->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_PRIVATE_KEY) return CKR_KEY_TYPE_INCONSISTENT; if (key->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DH) return CKR_KEY_TYPE_INCONSISTENT; return this->deriveDH(hSession, pMechanism, hBaseKey, pTemplate, ulCount, phKey, keyType, isOnToken, isPrivate); } #ifdef WITH_ECC // Derive ECDH secret if (pMechanism->mechanism == CKM_ECDH1_DERIVE) { // Check key class and type if (key->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_PRIVATE_KEY) return CKR_KEY_TYPE_INCONSISTENT; if (key->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_EC) return CKR_KEY_TYPE_INCONSISTENT; return this->deriveECDH(hSession, pMechanism, hBaseKey, pTemplate, ulCount, phKey, keyType, isOnToken, isPrivate); } #endif // Derive symmetric secret if (pMechanism->mechanism == CKM_DES_ECB_ENCRYPT_DATA || pMechanism->mechanism == CKM_DES_CBC_ENCRYPT_DATA || pMechanism->mechanism == CKM_DES3_ECB_ENCRYPT_DATA || pMechanism->mechanism == CKM_DES3_CBC_ENCRYPT_DATA || pMechanism->mechanism == CKM_AES_ECB_ENCRYPT_DATA || pMechanism->mechanism == CKM_AES_CBC_ENCRYPT_DATA) { // Check key class and type CK_KEY_TYPE baseKeyType = key->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED); if (key->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_SECRET_KEY) return CKR_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES_ECB_ENCRYPT_DATA && baseKeyType != CKK_DES) return CKR_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES_CBC_ENCRYPT_DATA && baseKeyType != CKK_DES) return CKR_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES3_ECB_ENCRYPT_DATA && baseKeyType != CKK_DES2 && baseKeyType != CKK_DES3) return CKR_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_DES3_CBC_ENCRYPT_DATA && baseKeyType != CKK_DES2 && baseKeyType != CKK_DES3) return CKR_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_ECB_ENCRYPT_DATA && baseKeyType != CKK_AES) return CKR_KEY_TYPE_INCONSISTENT; if (pMechanism->mechanism == CKM_AES_CBC_ENCRYPT_DATA && baseKeyType != CKK_AES) return CKR_KEY_TYPE_INCONSISTENT; return this->deriveSymmetric(hSession, pMechanism, hBaseKey, pTemplate, ulCount, phKey, keyType, isOnToken, isPrivate); } return CKR_MECHANISM_INVALID; } // Seed the random number generator with new data CK_RV SoftHSM::C_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, CK_ULONG ulSeedLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pSeed == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the RNG RNG* rng = CryptoFactory::i()->getRNG(); if (rng == NULL) return CKR_GENERAL_ERROR; // Seed the RNG ByteString seed(pSeed, ulSeedLen); rng->seed(seed); return CKR_OK; } // Generate the specified amount of random data CK_RV SoftHSM::C_GenerateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pRandomData == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the RNG RNG* rng = CryptoFactory::i()->getRNG(); if (rng == NULL) return CKR_GENERAL_ERROR; // Generate random data ByteString randomData; if (!rng->generateRandom(randomData, ulRandomLen)) return CKR_GENERAL_ERROR; // Return random data memcpy(pRandomData, randomData.byte_str(), ulRandomLen); return CKR_OK; } // Legacy function CK_RV SoftHSM::C_GetFunctionStatus(CK_SESSION_HANDLE hSession) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_PARALLEL; } // Legacy function CK_RV SoftHSM::C_CancelFunction(CK_SESSION_HANDLE hSession) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; return CKR_FUNCTION_NOT_PARALLEL; } // Wait or poll for a slot event on the specified slot CK_RV SoftHSM::C_WaitForSlotEvent(CK_FLAGS /*flags*/, CK_SLOT_ID_PTR /*pSlot*/, CK_VOID_PTR /*pReserved*/) { return CKR_FUNCTION_NOT_SUPPORTED; } // Generate an AES secret key CK_RV SoftHSM::generateAES (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired parameter information size_t keyLen = 0; for (CK_ULONG i = 0; i < ulCount; i++) { switch (pTemplate[i].type) { case CKA_VALUE_LEN: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_VALUE_LEN does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } keyLen = *(CK_ULONG*)pTemplate[i].pValue; break; default: break; } } // CKA_VALUE_LEN must be specified if (keyLen == 0) { INFO_MSG("Missing CKA_VALUE_LEN in pTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // keyLen must be 16, 24 or 32 if ((keyLen != 16) && (keyLen != 24) && (keyLen != 32)) { INFO_MSG("bad AES key length"); return CKR_ATTRIBUTE_VALUE_INVALID; } // Generate the secret key AESKey* key = new AESKey(keyLen * 8); SymmetricAlgorithm* aes = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::AES); if (aes == NULL) { ERROR_MSG("Could not get SymmetricAlgorithm"); delete key; return CKR_GENERAL_ERROR; } RNG* rng = CryptoFactory::i()->getRNG(); if (rng == NULL) { ERROR_MSG("Could not get RNG"); aes->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(aes); return CKR_GENERAL_ERROR; } if (!aes->generateKey(*key, rng)) { ERROR_MSG("Could not generate AES secret key"); aes->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(aes); return CKR_GENERAL_ERROR; } CK_RV rv = CKR_OK; // Create the secret key object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_AES; CK_ATTRIBUTE keyAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG keyAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - keyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: keyAttribs[keyAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, keyAttribs, keyAttribsCount, phKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_AES_KEY_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Secret Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // AES Secret Key Attributes ByteString value; if (isPrivate) token->encrypt(key->getKeyBits(), value); else value = key->getKeyBits(); bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up aes->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(aes); // Remove the key that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* oskey = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (oskey) oskey->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DES secret key CK_RV SoftHSM::generateDES (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Generate the secret key DESKey* key = new DESKey(56); SymmetricAlgorithm* des = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::DES); if (des == NULL) { ERROR_MSG("Could not get SymmetricAlgorithm"); delete key; return CKR_GENERAL_ERROR; } RNG* rng = CryptoFactory::i()->getRNG(); if (rng == NULL) { ERROR_MSG("Could not get RNG"); des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); return CKR_GENERAL_ERROR; } if (!des->generateKey(*key, rng)) { ERROR_MSG("Could not generate DES secret key"); des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); return CKR_GENERAL_ERROR; } CK_RV rv = CKR_OK; // Create the secret key object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_DES; CK_ATTRIBUTE keyAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG keyAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - keyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: keyAttribs[keyAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, keyAttribs, keyAttribsCount, phKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DES_KEY_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Secret Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // DES Secret Key Attributes ByteString value; if (isPrivate) token->encrypt(key->getKeyBits(), value); else value = key->getKeyBits(); bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); // Remove the key that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* oskey = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (oskey) oskey->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DES2 secret key CK_RV SoftHSM::generateDES2 (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Generate the secret key DESKey* key = new DESKey(112); SymmetricAlgorithm* des = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::DES3); if (des == NULL) { ERROR_MSG("Could not get SymmetricAlgorith"); delete key; return CKR_GENERAL_ERROR; } RNG* rng = CryptoFactory::i()->getRNG(); if (rng == NULL) { ERROR_MSG("Could not get RNG"); des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); return CKR_GENERAL_ERROR; } if (!des->generateKey(*key, rng)) { ERROR_MSG("Could not generate DES secret key"); des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); return CKR_GENERAL_ERROR; } CK_RV rv = CKR_OK; // Create the secret key object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_DES2; CK_ATTRIBUTE keyAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG keyAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - keyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: keyAttribs[keyAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, keyAttribs, keyAttribsCount, phKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DES2_KEY_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Secret Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // DES Secret Key Attributes ByteString value; if (isPrivate) token->encrypt(key->getKeyBits(), value); else value = key->getKeyBits(); bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); // Remove the key that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* oskey = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (oskey) oskey->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DES3 secret key CK_RV SoftHSM::generateDES3 (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Generate the secret key DESKey* key = new DESKey(168); SymmetricAlgorithm* des = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::DES3); if (des == NULL) { ERROR_MSG("Could not get SymmetricAlgorithm"); delete key; return CKR_GENERAL_ERROR; } RNG* rng = CryptoFactory::i()->getRNG(); if (rng == NULL) { ERROR_MSG("Could not get RNG"); des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); return CKR_GENERAL_ERROR; } if (!des->generateKey(*key, rng)) { ERROR_MSG("Could not generate DES secret key"); des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); return CKR_GENERAL_ERROR; } CK_RV rv = CKR_OK; // Create the secret key object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_DES3; CK_ATTRIBUTE keyAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG keyAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - keyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: keyAttribs[keyAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, keyAttribs, keyAttribsCount, phKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DES3_KEY_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Secret Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // DES Secret Key Attributes ByteString value; if (isPrivate) token->encrypt(key->getKeyBits(), value); else value = key->getKeyBits(); bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up des->recycleKey(key); CryptoFactory::i()->recycleSymmetricAlgorithm(des); // Remove the key that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* oskey = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (oskey) oskey->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Generate an RSA key pair CK_RV SoftHSM::generateRSA (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate ) { *phPublicKey = CK_INVALID_HANDLE; *phPrivateKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired key information: bitlen and public exponent size_t bitLen = 0; ByteString exponent("010001"); for (CK_ULONG i = 0; i < ulPublicKeyAttributeCount; i++) { switch (pPublicKeyTemplate[i].type) { case CKA_MODULUS_BITS: if (pPublicKeyTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_MODULUS_BITS does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } bitLen = *(CK_ULONG*)pPublicKeyTemplate[i].pValue; break; case CKA_PUBLIC_EXPONENT: exponent = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; default: break; } } // CKA_MODULUS_BITS must be specified to be able to generate a key pair. if (bitLen == 0) { INFO_MSG("Missing CKA_MODULUS_BITS in pPublicKeyTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // Set the parameters RSAParameters p; p.setE(exponent); p.setBitLength(bitLen); // Generate key pair AsymmetricKeyPair* kp = NULL; AsymmetricAlgorithm* rsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (rsa == NULL) return CKR_GENERAL_ERROR; if (!rsa->generateKeyPair(&kp, &p)) { ERROR_MSG("Could not generate key pair"); CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); return CKR_GENERAL_ERROR; } RSAPublicKey* pub = (RSAPublicKey*) kp->getPublicKey(); RSAPrivateKey* priv = (RSAPrivateKey*) kp->getPrivateKey(); CK_RV rv = CKR_OK; // Create a public key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS publicKeyClass = CKO_PUBLIC_KEY; CK_KEY_TYPE publicKeyType = CKK_RSA; CK_ATTRIBUTE publicKeyAttribs[maxAttribs] = { { CKA_CLASS, &publicKeyClass, sizeof(publicKeyClass) }, { CKA_TOKEN, &isPublicKeyOnToken, sizeof(isPublicKeyOnToken) }, { CKA_PRIVATE, &isPublicKeyPrivate, sizeof(isPublicKeyPrivate) }, { CKA_KEY_TYPE, &publicKeyType, sizeof(publicKeyType) }, }; CK_ULONG publicKeyAttribsCount = 4; // Add the additional if (ulPublicKeyAttributeCount > (maxAttribs - publicKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPublicKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPublicKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: case CKA_PUBLIC_EXPONENT: continue; default: publicKeyAttribs[publicKeyAttribsCount++] = pPublicKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,publicKeyAttribs,publicKeyAttribsCount,phPublicKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPublicKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_RSA_PKCS_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // RSA Public Key Attributes ByteString modulus; ByteString publicExponent; if (isPublicKeyPrivate) { token->encrypt(pub->getN(), modulus); token->encrypt(pub->getE(), publicExponent); } else { modulus = pub->getN(); publicExponent = pub->getE(); } bOK = bOK && osobject->setAttribute(CKA_MODULUS, modulus); bOK = bOK && osobject->setAttribute(CKA_PUBLIC_EXPONENT, publicExponent); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Create a private key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS privateKeyClass = CKO_PRIVATE_KEY; CK_KEY_TYPE privateKeyType = CKK_RSA; CK_ATTRIBUTE privateKeyAttribs[maxAttribs] = { { CKA_CLASS, &privateKeyClass, sizeof(privateKeyClass) }, { CKA_TOKEN, &isPrivateKeyOnToken, sizeof(isPrivateKeyOnToken) }, { CKA_PRIVATE, &isPrivateKeyPrivate, sizeof(isPrivateKeyPrivate) }, { CKA_KEY_TYPE, &privateKeyType, sizeof(privateKeyType) }, }; CK_ULONG privateKeyAttribsCount = 4; if (ulPrivateKeyAttributeCount > (maxAttribs - privateKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPrivateKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPrivateKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: privateKeyAttribs[privateKeyAttribsCount++] = pPrivateKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,privateKeyAttribs,privateKeyAttribsCount,phPrivateKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPrivateKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_RSA_PKCS_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Private Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // RSA Private Key Attributes ByteString modulus; ByteString publicExponent; ByteString privateExponent; ByteString prime1; ByteString prime2; ByteString exponent1; ByteString exponent2; ByteString coefficient; if (isPrivateKeyPrivate) { token->encrypt(priv->getN(), modulus); token->encrypt(priv->getE(), publicExponent); token->encrypt(priv->getD(), privateExponent); token->encrypt(priv->getP(), prime1); token->encrypt(priv->getQ(), prime2); token->encrypt(priv->getDP1(), exponent1); token->encrypt(priv->getDQ1(), exponent2); token->encrypt(priv->getPQ(), coefficient); } else { modulus = priv->getN(); publicExponent = priv->getE(); privateExponent = priv->getD(); prime1 = priv->getP(); prime2 = priv->getQ(); exponent1 = priv->getDP1(); exponent2 = priv->getDQ1(); coefficient = priv->getPQ(); } bOK = bOK && osobject->setAttribute(CKA_MODULUS, modulus); bOK = bOK && osobject->setAttribute(CKA_PUBLIC_EXPONENT, publicExponent); bOK = bOK && osobject->setAttribute(CKA_PRIVATE_EXPONENT, privateExponent); bOK = bOK && osobject->setAttribute(CKA_PRIME_1, prime1); bOK = bOK && osobject->setAttribute(CKA_PRIME_2, prime2); bOK = bOK && osobject->setAttribute(CKA_EXPONENT_1,exponent1); bOK = bOK && osobject->setAttribute(CKA_EXPONENT_2, exponent2); bOK = bOK && osobject->setAttribute(CKA_COEFFICIENT, coefficient); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Clean up rsa->recycleKeyPair(kp); CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); // Remove keys that may have been created already when the function fails. if (rv != CKR_OK) { if (*phPrivateKey != CK_INVALID_HANDLE) { OSObject* ospriv = (OSObject*)handleManager->getObject(*phPrivateKey); handleManager->destroyObject(*phPrivateKey); if (ospriv) ospriv->destroyObject(); *phPrivateKey = CK_INVALID_HANDLE; } if (*phPublicKey != CK_INVALID_HANDLE) { OSObject* ospub = (OSObject*)handleManager->getObject(*phPublicKey); handleManager->destroyObject(*phPublicKey); if (ospub) ospub->destroyObject(); *phPublicKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DSA key pair CK_RV SoftHSM::generateDSA (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate) { *phPublicKey = CK_INVALID_HANDLE; *phPrivateKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired key information ByteString prime; ByteString subprime; ByteString generator; for (CK_ULONG i = 0; i < ulPublicKeyAttributeCount; i++) { switch (pPublicKeyTemplate[i].type) { case CKA_PRIME: prime = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; case CKA_SUBPRIME: subprime = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; case CKA_BASE: generator = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; default: break; } } // The parameters must be specified to be able to generate a key pair. if (prime.size() == 0 || subprime.size() == 0 || generator.size() == 0) { INFO_MSG("Missing parameter(s) in pPublicKeyTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // Set the parameters DSAParameters p; p.setP(prime); p.setQ(subprime); p.setG(generator); // Generate key pair AsymmetricKeyPair* kp = NULL; AsymmetricAlgorithm* dsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); if (dsa == NULL) return CKR_GENERAL_ERROR; if (!dsa->generateKeyPair(&kp, &p)) { ERROR_MSG("Could not generate key pair"); CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); return CKR_GENERAL_ERROR; } DSAPublicKey* pub = (DSAPublicKey*) kp->getPublicKey(); DSAPrivateKey* priv = (DSAPrivateKey*) kp->getPrivateKey(); CK_RV rv = CKR_OK; // Create a public key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS publicKeyClass = CKO_PUBLIC_KEY; CK_KEY_TYPE publicKeyType = CKK_DSA; CK_ATTRIBUTE publicKeyAttribs[maxAttribs] = { { CKA_CLASS, &publicKeyClass, sizeof(publicKeyClass) }, { CKA_TOKEN, &isPublicKeyOnToken, sizeof(isPublicKeyOnToken) }, { CKA_PRIVATE, &isPublicKeyPrivate, sizeof(isPublicKeyPrivate) }, { CKA_KEY_TYPE, &publicKeyType, sizeof(publicKeyType) }, }; CK_ULONG publicKeyAttribsCount = 4; // Add the additional if (ulPublicKeyAttributeCount > (maxAttribs - publicKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPublicKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPublicKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: publicKeyAttribs[publicKeyAttribsCount++] = pPublicKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,publicKeyAttribs,publicKeyAttribsCount,phPublicKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPublicKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DSA_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // DSA Public Key Attributes ByteString value; if (isPublicKeyPrivate) { token->encrypt(pub->getY(), value); } else { value = pub->getY(); } bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Create a private key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS privateKeyClass = CKO_PRIVATE_KEY; CK_KEY_TYPE privateKeyType = CKK_DSA; CK_ATTRIBUTE privateKeyAttribs[maxAttribs] = { { CKA_CLASS, &privateKeyClass, sizeof(privateKeyClass) }, { CKA_TOKEN, &isPrivateKeyOnToken, sizeof(isPrivateKeyOnToken) }, { CKA_PRIVATE, &isPrivateKeyPrivate, sizeof(isPrivateKeyPrivate) }, { CKA_KEY_TYPE, &privateKeyType, sizeof(privateKeyType) }, }; CK_ULONG privateKeyAttribsCount = 4; if (ulPrivateKeyAttributeCount > (maxAttribs - privateKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPrivateKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPrivateKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: privateKeyAttribs[privateKeyAttribsCount++] = pPrivateKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,privateKeyAttribs,privateKeyAttribsCount,phPrivateKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPrivateKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DSA_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Private Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // DSA Private Key Attributes ByteString bPrime; ByteString bSubprime; ByteString bGenerator; ByteString bValue; if (isPrivateKeyPrivate) { token->encrypt(priv->getP(), bPrime); token->encrypt(priv->getQ(), bSubprime); token->encrypt(priv->getG(), bGenerator); token->encrypt(priv->getX(), bValue); } else { bPrime = priv->getP(); bSubprime = priv->getQ(); bGenerator = priv->getG(); bValue = priv->getX(); } bOK = bOK && osobject->setAttribute(CKA_PRIME, bPrime); bOK = bOK && osobject->setAttribute(CKA_SUBPRIME, bSubprime); bOK = bOK && osobject->setAttribute(CKA_BASE, bGenerator); bOK = bOK && osobject->setAttribute(CKA_VALUE, bValue); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Clean up dsa->recycleKeyPair(kp); CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); // Remove keys that may have been created already when the function fails. if (rv != CKR_OK) { if (*phPrivateKey != CK_INVALID_HANDLE) { OSObject* ospriv = (OSObject*)handleManager->getObject(*phPrivateKey); handleManager->destroyObject(*phPrivateKey); if (ospriv) ospriv->destroyObject(); *phPrivateKey = CK_INVALID_HANDLE; } if (*phPublicKey != CK_INVALID_HANDLE) { OSObject* ospub = (OSObject*)handleManager->getObject(*phPublicKey); handleManager->destroyObject(*phPublicKey); if (ospub) ospub->destroyObject(); *phPublicKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DSA domain parameter set CK_RV SoftHSM::generateDSAParameters (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired parameter information size_t bitLen = 0; size_t qLen = 0; for (CK_ULONG i = 0; i < ulCount; i++) { switch (pTemplate[i].type) { case CKA_PRIME_BITS: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_PRIME_BITS does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } bitLen = *(CK_ULONG*)pTemplate[i].pValue; break; case CKA_SUBPRIME_BITS: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_SUBPRIME_BITS does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } qLen = *(CK_ULONG*)pTemplate[i].pValue; break; default: break; } } // CKA_PRIME_BITS must be specified if (bitLen == 0) { INFO_MSG("Missing CKA_PRIME_BITS in pTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // No real choice for CKA_SUBPRIME_BITS if ((qLen != 0) && (((bitLen >= 2048) && (qLen != 256)) || ((bitLen < 2048) && (qLen != 160)))) INFO_MSG("CKA_SUBPRIME_BITS is ignored"); // Generate domain parameters AsymmetricParameters* p = NULL; AsymmetricAlgorithm* dsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); if (dsa == NULL) return CKR_GENERAL_ERROR; if (!dsa->generateParameters(&p, (void *)bitLen)) { ERROR_MSG("Could not generate parameters"); CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); return CKR_GENERAL_ERROR; } DSAParameters* params = (DSAParameters*) p; CK_RV rv = CKR_OK; // Create the domain parameter object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_DOMAIN_PARAMETERS; CK_KEY_TYPE keyType = CKK_DSA; CK_ATTRIBUTE paramsAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG paramsAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - paramsAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: paramsAttribs[paramsAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, paramsAttribs, paramsAttribsCount, phKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DSA_PARAMETER_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // DSA Domain Parameters Attributes ByteString prime; ByteString subprime; ByteString generator; if (isPrivate) { token->encrypt(params->getP(), prime); token->encrypt(params->getQ(), subprime); token->encrypt(params->getG(), generator); } else { prime = params->getP(); subprime = params->getQ(); generator = params->getG(); } bOK = bOK && osobject->setAttribute(CKA_PRIME, prime); bOK = bOK && osobject->setAttribute(CKA_SUBPRIME, subprime); bOK = bOK && osobject->setAttribute(CKA_BASE, generator); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up dsa->recycleParameters(p); CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); // Remove parameters that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* osparams = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (osparams) osparams->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Generate an EC key pair CK_RV SoftHSM::generateEC (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate) { *phPublicKey = CK_INVALID_HANDLE; *phPrivateKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired key information ByteString params; for (CK_ULONG i = 0; i < ulPublicKeyAttributeCount; i++) { switch (pPublicKeyTemplate[i].type) { case CKA_EC_PARAMS: params = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; default: break; } } // The parameters must be specified to be able to generate a key pair. if (params.size() == 0) { INFO_MSG("Missing parameter(s) in pPublicKeyTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // Set the parameters ECParameters p; p.setEC(params); // Generate key pair AsymmetricKeyPair* kp = NULL; AsymmetricAlgorithm* ec = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDSA); if (ec == NULL) return CKR_GENERAL_ERROR; if (!ec->generateKeyPair(&kp, &p)) { ERROR_MSG("Could not generate key pair"); CryptoFactory::i()->recycleAsymmetricAlgorithm(ec); return CKR_GENERAL_ERROR; } ECPublicKey* pub = (ECPublicKey*) kp->getPublicKey(); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CK_RV rv = CKR_OK; // Create a public key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS publicKeyClass = CKO_PUBLIC_KEY; CK_KEY_TYPE publicKeyType = CKK_EC; CK_ATTRIBUTE publicKeyAttribs[maxAttribs] = { { CKA_CLASS, &publicKeyClass, sizeof(publicKeyClass) }, { CKA_TOKEN, &isPublicKeyOnToken, sizeof(isPublicKeyOnToken) }, { CKA_PRIVATE, &isPublicKeyPrivate, sizeof(isPublicKeyPrivate) }, { CKA_KEY_TYPE, &publicKeyType, sizeof(publicKeyType) }, }; CK_ULONG publicKeyAttribsCount = 4; // Add the additional if (ulPublicKeyAttributeCount > (maxAttribs - publicKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPublicKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPublicKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: publicKeyAttribs[publicKeyAttribsCount++] = pPublicKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,publicKeyAttribs,publicKeyAttribsCount,phPublicKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPublicKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_EC_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // EC Public Key Attributes ByteString point; if (isPublicKeyPrivate) { token->encrypt(pub->getQ(), point); } else { point = pub->getQ(); } bOK = bOK && osobject->setAttribute(CKA_EC_POINT, point); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Create a private key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS privateKeyClass = CKO_PRIVATE_KEY; CK_KEY_TYPE privateKeyType = CKK_EC; CK_ATTRIBUTE privateKeyAttribs[maxAttribs] = { { CKA_CLASS, &privateKeyClass, sizeof(privateKeyClass) }, { CKA_TOKEN, &isPrivateKeyOnToken, sizeof(isPrivateKeyOnToken) }, { CKA_PRIVATE, &isPrivateKeyPrivate, sizeof(isPrivateKeyPrivate) }, { CKA_KEY_TYPE, &privateKeyType, sizeof(privateKeyType) }, }; CK_ULONG privateKeyAttribsCount = 4; if (ulPrivateKeyAttributeCount > (maxAttribs - privateKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPrivateKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPrivateKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: privateKeyAttribs[privateKeyAttribsCount++] = pPrivateKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,privateKeyAttribs,privateKeyAttribsCount,phPrivateKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPrivateKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_EC_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Private Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // EC Private Key Attributes ByteString group; ByteString value; if (isPrivateKeyPrivate) { token->encrypt(priv->getEC(), group); token->encrypt(priv->getD(), value); } else { group = priv->getEC(); value = priv->getD(); } bOK = bOK && osobject->setAttribute(CKA_EC_PARAMS, group); bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Clean up ec->recycleKeyPair(kp); CryptoFactory::i()->recycleAsymmetricAlgorithm(ec); // Remove keys that may have been created already when the function fails. if (rv != CKR_OK) { if (*phPrivateKey != CK_INVALID_HANDLE) { OSObject* ospriv = (OSObject*)handleManager->getObject(*phPrivateKey); handleManager->destroyObject(*phPrivateKey); if (ospriv) ospriv->destroyObject(); *phPrivateKey = CK_INVALID_HANDLE; } if (*phPublicKey != CK_INVALID_HANDLE) { OSObject* ospub = (OSObject*)handleManager->getObject(*phPublicKey); handleManager->destroyObject(*phPublicKey); if (ospub) ospub->destroyObject(); *phPublicKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DH key pair CK_RV SoftHSM::generateDH (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate) { *phPublicKey = CK_INVALID_HANDLE; *phPrivateKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired key information ByteString prime; ByteString generator; for (CK_ULONG i = 0; i < ulPublicKeyAttributeCount; i++) { switch (pPublicKeyTemplate[i].type) { case CKA_PRIME: prime = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; case CKA_BASE: generator = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; default: break; } } // The parameters must be specified to be able to generate a key pair. if (prime.size() == 0 || generator.size() == 0) { INFO_MSG("Missing parameter(s) in pPublicKeyTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // Extract optional bit length size_t bitLen = 0; for (CK_ULONG i = 0; i < ulPrivateKeyAttributeCount; i++) { switch (pPrivateKeyTemplate[i].type) { case CKA_VALUE_BITS: bitLen = *(CK_ULONG*)pPrivateKeyTemplate[i].pValue; break; default: break; } } // Set the parameters DHParameters p; p.setP(prime); p.setG(generator); p.setXBitLength(bitLen); // Generate key pair AsymmetricKeyPair* kp = NULL; AsymmetricAlgorithm* dh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DH); if (dh == NULL) return CKR_GENERAL_ERROR; if (!dh->generateKeyPair(&kp, &p)) { ERROR_MSG("Could not generate key pair"); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return CKR_GENERAL_ERROR; } DHPublicKey* pub = (DHPublicKey*) kp->getPublicKey(); DHPrivateKey* priv = (DHPrivateKey*) kp->getPrivateKey(); CK_RV rv = CKR_OK; // Create a public key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS publicKeyClass = CKO_PUBLIC_KEY; CK_KEY_TYPE publicKeyType = CKK_DH; CK_ATTRIBUTE publicKeyAttribs[maxAttribs] = { { CKA_CLASS, &publicKeyClass, sizeof(publicKeyClass) }, { CKA_TOKEN, &isPublicKeyOnToken, sizeof(isPublicKeyOnToken) }, { CKA_PRIVATE, &isPublicKeyPrivate, sizeof(isPublicKeyPrivate) }, { CKA_KEY_TYPE, &publicKeyType, sizeof(publicKeyType) }, }; CK_ULONG publicKeyAttribsCount = 4; // Add the additional if (ulPublicKeyAttributeCount > (maxAttribs - publicKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPublicKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPublicKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: publicKeyAttribs[publicKeyAttribsCount++] = pPublicKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,publicKeyAttribs,publicKeyAttribsCount,phPublicKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPublicKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DH_PKCS_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // DH Public Key Attributes ByteString value; if (isPublicKeyPrivate) { token->encrypt(pub->getY(), value); } else { value = pub->getY(); } bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Create a private key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS privateKeyClass = CKO_PRIVATE_KEY; CK_KEY_TYPE privateKeyType = CKK_DH; CK_ATTRIBUTE privateKeyAttribs[maxAttribs] = { { CKA_CLASS, &privateKeyClass, sizeof(privateKeyClass) }, { CKA_TOKEN, &isPrivateKeyOnToken, sizeof(isPrivateKeyOnToken) }, { CKA_PRIVATE, &isPrivateKeyPrivate, sizeof(isPrivateKeyPrivate) }, { CKA_KEY_TYPE, &privateKeyType, sizeof(privateKeyType) }, }; CK_ULONG privateKeyAttribsCount = 4; if (ulPrivateKeyAttributeCount > (maxAttribs - privateKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPrivateKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPrivateKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: privateKeyAttribs[privateKeyAttribsCount++] = pPrivateKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,privateKeyAttribs,privateKeyAttribsCount,phPrivateKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPrivateKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DH_PKCS_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Private Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // DH Private Key Attributes ByteString bPrime; ByteString bGenerator; ByteString bValue; if (isPrivateKeyPrivate) { token->encrypt(priv->getP(), bPrime); token->encrypt(priv->getG(), bGenerator); token->encrypt(priv->getX(), bValue); } else { bPrime = priv->getP(); bGenerator = priv->getG(); bValue = priv->getX(); } bOK = bOK && osobject->setAttribute(CKA_PRIME, bPrime); bOK = bOK && osobject->setAttribute(CKA_BASE, bGenerator); bOK = bOK && osobject->setAttribute(CKA_VALUE, bValue); if (bitLen == 0) { bOK = bOK && osobject->setAttribute(CKA_VALUE_BITS, (unsigned long)priv->getX().bits()); } if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Clean up dh->recycleKeyPair(kp); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); // Remove keys that may have been created already when the function fails. if (rv != CKR_OK) { if (*phPrivateKey != CK_INVALID_HANDLE) { OSObject* ospriv = (OSObject*)handleManager->getObject(*phPrivateKey); handleManager->destroyObject(*phPrivateKey); if (ospriv) ospriv->destroyObject(); *phPrivateKey = CK_INVALID_HANDLE; } if (*phPublicKey != CK_INVALID_HANDLE) { OSObject* ospub = (OSObject*)handleManager->getObject(*phPublicKey); handleManager->destroyObject(*phPublicKey); if (ospub) ospub->destroyObject(); *phPublicKey = CK_INVALID_HANDLE; } } return rv; } // Generate a DH domain parameter set CK_RV SoftHSM::generateDHParameters (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired parameter information size_t bitLen = 0; for (CK_ULONG i = 0; i < ulCount; i++) { switch (pTemplate[i].type) { case CKA_PRIME_BITS: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_PRIME_BITS does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } bitLen = *(CK_ULONG*)pTemplate[i].pValue; break; default: break; } } // CKA_PRIME_BITS must be specified if (bitLen == 0) { INFO_MSG("Missing CKA_PRIME_BITS in pTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // Generate domain parameters AsymmetricParameters* p = NULL; AsymmetricAlgorithm* dh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DH); if (dh == NULL) return CKR_GENERAL_ERROR; if (!dh->generateParameters(&p, (void *)bitLen)) { ERROR_MSG("Could not generate parameters"); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return CKR_GENERAL_ERROR; } DHParameters* params = (DHParameters*) p; CK_RV rv = CKR_OK; // Create the domain parameter object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_DOMAIN_PARAMETERS; CK_KEY_TYPE keyType = CKK_DH; CK_ATTRIBUTE paramsAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG paramsAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - paramsAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: paramsAttribs[paramsAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, paramsAttribs, paramsAttribsCount, phKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_DH_PKCS_PARAMETER_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // DH Domain Parameters Attributes ByteString prime; ByteString generator; if (isPrivate) { token->encrypt(params->getP(), prime); token->encrypt(params->getG(), generator); } else { prime = params->getP(); generator = params->getG(); } bOK = bOK && osobject->setAttribute(CKA_PRIME, prime); bOK = bOK && osobject->setAttribute(CKA_BASE, generator); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up dh->recycleParameters(p); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); // Remove parameters that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* osparams = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (osparams) osparams->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Generate a GOST key pair CK_RV SoftHSM::generateGOST (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate) { *phPublicKey = CK_INVALID_HANDLE; *phPrivateKey = CK_INVALID_HANDLE; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired key information ByteString param_3410; ByteString param_3411; ByteString param_28147; for (CK_ULONG i = 0; i < ulPublicKeyAttributeCount; i++) { switch (pPublicKeyTemplate[i].type) { case CKA_GOSTR3410_PARAMS: param_3410 = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; case CKA_GOSTR3411_PARAMS: param_3411 = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; case CKA_GOST28147_PARAMS: param_28147 = ByteString((unsigned char*)pPublicKeyTemplate[i].pValue, pPublicKeyTemplate[i].ulValueLen); break; default: break; } } // The parameters must be specified to be able to generate a key pair. if (param_3410.size() == 0 || param_3411.size() == 0) { INFO_MSG("Missing parameter(s) in pPublicKeyTemplate"); return CKR_TEMPLATE_INCOMPLETE; } // Set the parameters ECParameters p; p.setEC(param_3410); // Generate key pair AsymmetricKeyPair* kp = NULL; AsymmetricAlgorithm* gost = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::GOST); if (gost == NULL) return CKR_GENERAL_ERROR; if (!gost->generateKeyPair(&kp, &p)) { ERROR_MSG("Could not generate key pair"); CryptoFactory::i()->recycleAsymmetricAlgorithm(gost); return CKR_GENERAL_ERROR; } GOSTPublicKey* pub = (GOSTPublicKey*) kp->getPublicKey(); GOSTPrivateKey* priv = (GOSTPrivateKey*) kp->getPrivateKey(); CK_RV rv = CKR_OK; // Create a public key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS publicKeyClass = CKO_PUBLIC_KEY; CK_KEY_TYPE publicKeyType = CKK_GOSTR3410; CK_ATTRIBUTE publicKeyAttribs[maxAttribs] = { { CKA_CLASS, &publicKeyClass, sizeof(publicKeyClass) }, { CKA_TOKEN, &isPublicKeyOnToken, sizeof(isPublicKeyOnToken) }, { CKA_PRIVATE, &isPublicKeyPrivate, sizeof(isPublicKeyPrivate) }, { CKA_KEY_TYPE, &publicKeyType, sizeof(publicKeyType) }, }; CK_ULONG publicKeyAttribsCount = 4; // Add the additional if (ulPublicKeyAttributeCount > (maxAttribs - publicKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPublicKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPublicKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: publicKeyAttribs[publicKeyAttribsCount++] = pPublicKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,publicKeyAttribs,publicKeyAttribsCount,phPublicKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPublicKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_EC_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // EC Public Key Attributes ByteString point; if (isPublicKeyPrivate) { token->encrypt(pub->getQ(), point); } else { point = pub->getQ(); } bOK = bOK && osobject->setAttribute(CKA_VALUE, point); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Create a private key using C_CreateObject if (rv == CKR_OK) { const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS privateKeyClass = CKO_PRIVATE_KEY; CK_KEY_TYPE privateKeyType = CKK_GOSTR3410; CK_ATTRIBUTE privateKeyAttribs[maxAttribs] = { { CKA_CLASS, &privateKeyClass, sizeof(privateKeyClass) }, { CKA_TOKEN, &isPrivateKeyOnToken, sizeof(isPrivateKeyOnToken) }, { CKA_PRIVATE, &isPrivateKeyPrivate, sizeof(isPrivateKeyPrivate) }, { CKA_KEY_TYPE, &privateKeyType, sizeof(privateKeyType) }, }; CK_ULONG privateKeyAttribsCount = 4; if (ulPrivateKeyAttributeCount > (maxAttribs - privateKeyAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulPrivateKeyAttributeCount && rv == CKR_OK; ++i) { switch (pPrivateKeyTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: privateKeyAttribs[privateKeyAttribsCount++] = pPrivateKeyTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession,privateKeyAttribs,privateKeyAttribsCount,phPrivateKey,OBJECT_OP_GENERATE); // Store the attributes that are being supplied by the key generation to the object if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phPrivateKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Key Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,true); CK_ULONG ulKeyGenMechanism = (CK_ULONG)CKM_EC_KEY_PAIR_GEN; bOK = bOK && osobject->setAttribute(CKA_KEY_GEN_MECHANISM,ulKeyGenMechanism); // Common Private Key Attributes bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE, bNeverExtractable); // GOST Private Key Attributes ByteString value; ByteString param_a; ByteString param_b; ByteString param_c; if (isPrivateKeyPrivate) { token->encrypt(priv->getD(), value); token->encrypt(priv->getEC(), param_a); token->encrypt(param_3411, param_b); token->encrypt(param_28147, param_c); } else { value = priv->getD(); param_a = priv->getEC(); param_b = param_3411; param_c = param_28147; } bOK = bOK && osobject->setAttribute(CKA_VALUE, value); bOK = bOK && osobject->setAttribute(CKA_GOSTR3410_PARAMS, param_a); bOK = bOK && osobject->setAttribute(CKA_GOSTR3411_PARAMS, param_b); bOK = bOK && osobject->setAttribute(CKA_GOST28147_PARAMS, param_c); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } } // Clean up gost->recycleKeyPair(kp); CryptoFactory::i()->recycleAsymmetricAlgorithm(gost); // Remove keys that may have been created already when the function fails. if (rv != CKR_OK) { if (*phPrivateKey != CK_INVALID_HANDLE) { OSObject* ospriv = (OSObject*)handleManager->getObject(*phPrivateKey); handleManager->destroyObject(*phPrivateKey); if (ospriv) ospriv->destroyObject(); *phPrivateKey = CK_INVALID_HANDLE; } if (*phPublicKey != CK_INVALID_HANDLE) { OSObject* ospub = (OSObject*)handleManager->getObject(*phPublicKey); handleManager->destroyObject(*phPublicKey); if (ospub) ospub->destroyObject(); *phPublicKey = CK_INVALID_HANDLE; } } return rv; } // Derive a DH secret CK_RV SoftHSM::deriveDH (CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_KEY_TYPE keyType, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; if (pMechanism->pParameter == NULL_PTR) return CKR_MECHANISM_PARAM_INVALID; if (pMechanism->ulParameterLen == 0) return CKR_MECHANISM_PARAM_INVALID; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired parameter information size_t byteLen = 0; for (CK_ULONG i = 0; i < ulCount; i++) { switch (pTemplate[i].type) { case CKA_VALUE: INFO_MSG("CKA_VALUE must not be included"); return CKR_TEMPLATE_INCONSISTENT; case CKA_VALUE_LEN: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_VALUE_LEN does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } byteLen = *(CK_ULONG*)pTemplate[i].pValue; break; default: break; } } // Check the length switch (keyType) { case CKK_GENERIC_SECRET: if (byteLen == 0) { INFO_MSG("CKA_VALUE_LEN must be set"); return CKR_TEMPLATE_INCONSISTENT; } break; #ifndef WITH_FIPS case CKK_DES: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 8; break; #endif case CKK_DES2: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 16; break; case CKK_DES3: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 24; break; case CKK_AES: if (byteLen != 16 && byteLen != 24 && byteLen != 32) { INFO_MSG("CKA_VALUE_LEN must be 16, 24 or 32"); return CKR_TEMPLATE_INCOMPLETE; } break; default: return CKR_TEMPLATE_INCONSISTENT; } // Get the base key handle OSObject *baseKey = (OSObject *)handleManager->getObject(hBaseKey); if (baseKey == NULL || !baseKey->isValid()) return CKR_KEY_HANDLE_INVALID; // Get the DH algorithm handler AsymmetricAlgorithm* dh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DH); if (dh == NULL) return CKR_MECHANISM_INVALID; // Get the keys PrivateKey* privateKey = dh->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return CKR_HOST_MEMORY; } if (getDHPrivateKey((DHPrivateKey*)privateKey, token, baseKey) != CKR_OK) { dh->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return CKR_GENERAL_ERROR; } ByteString mechParameters; mechParameters.resize(pMechanism->ulParameterLen); memcpy(&mechParameters[0], pMechanism->pParameter, pMechanism->ulParameterLen); PublicKey* publicKey = dh->newPublicKey(); if (publicKey == NULL) { dh->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return CKR_HOST_MEMORY; } if (getDHPublicKey((DHPublicKey*)publicKey, (DHPrivateKey*)privateKey, mechParameters) != CKR_OK) { dh->recyclePrivateKey(privateKey); dh->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return CKR_GENERAL_ERROR; } // Derive the secret SymmetricKey* secret = NULL; CK_RV rv = CKR_OK; if (!dh->deriveKey(&secret, publicKey, privateKey)) rv = CKR_GENERAL_ERROR; dh->recyclePrivateKey(privateKey); dh->recyclePublicKey(publicKey); // Create the secret object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_ATTRIBUTE secretAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG secretAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - secretAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: secretAttribs[secretAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, secretAttribs, secretAttribsCount, phKey, OBJECT_OP_DERIVE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,false); // Common Secret Key Attributes if (baseKey->getBooleanValue(CKA_ALWAYS_SENSITIVE, false)) { bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); } else { bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,false); } if (baseKey->getBooleanValue(CKA_NEVER_EXTRACTABLE, true)) { bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE,bNeverExtractable); } else { bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE,false); } // Secret Attributes ByteString secretValue = secret->getKeyBits(); // Truncate value when requested if (byteLen > secretValue.size()) { INFO_MSG("The derived secret is too short"); bOK = false; } if (bOK && byteLen != 0) secretValue.resize(byteLen); // Fix the odd parity for DES if (keyType == CKK_DES || keyType == CKK_DES2 || keyType == CKK_DES3) { for (size_t i = 0; i < secretValue.size(); i++) { secretValue[i] = odd_parity[secretValue[i]]; } } ByteString value; if (isPrivate) { token->encrypt(secretValue, value); } else { value = secretValue; } bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up dh->recycleSymmetricKey(secret); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); // Remove secret that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* ossecret = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (ossecret) ossecret->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } // Derive an ECDH secret CK_RV SoftHSM::deriveECDH (CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_KEY_TYPE keyType, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { #ifdef WITH_ECC *phKey = CK_INVALID_HANDLE; if ((pMechanism->pParameter == NULL_PTR) || (pMechanism->ulParameterLen != sizeof(CK_ECDH1_DERIVE_PARAMS))) { DEBUG_MSG("pParameter must be of type CK_ECDH1_DERIVE_PARAMS"); return CKR_MECHANISM_PARAM_INVALID; } if (CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->kdf != CKD_NULL) { DEBUG_MSG("kdf must be CKD_NULL"); return CKR_MECHANISM_PARAM_INVALID; } if ((CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->ulSharedDataLen != 0) || (CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->pSharedData != NULL_PTR)) { DEBUG_MSG("there must be no shared data"); return CKR_MECHANISM_PARAM_INVALID; } if ((CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->ulPublicDataLen == 0) || (CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->pPublicData == NULL_PTR)) { DEBUG_MSG("there must be a public data"); return CKR_MECHANISM_PARAM_INVALID; } // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired parameter information size_t byteLen = 0; for (CK_ULONG i = 0; i < ulCount; i++) { switch (pTemplate[i].type) { case CKA_VALUE: INFO_MSG("CKA_VALUE must not be included"); return CKR_TEMPLATE_INCONSISTENT; case CKA_VALUE_LEN: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_VALUE_LEN does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } byteLen = *(CK_ULONG*)pTemplate[i].pValue; break; default: break; } } // Check the length switch (keyType) { case CKK_GENERIC_SECRET: if (byteLen == 0) { INFO_MSG("CKA_VALUE_LEN must be set"); return CKR_TEMPLATE_INCONSISTENT; } break; #ifndef WITH_FIPS case CKK_DES: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 8; break; #endif case CKK_DES2: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 16; break; case CKK_DES3: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 24; break; case CKK_AES: if (byteLen != 16 && byteLen != 24 && byteLen != 32) { INFO_MSG("CKA_VALUE_LEN must be 16, 24 or 32"); return CKR_TEMPLATE_INCOMPLETE; } break; default: return CKR_TEMPLATE_INCONSISTENT; } // Get the base key handle OSObject *baseKey = (OSObject *)handleManager->getObject(hBaseKey); if (baseKey == NULL || !baseKey->isValid()) return CKR_KEY_HANDLE_INVALID; // Get the ECDH algorithm handler AsymmetricAlgorithm* ecdh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDH); if (ecdh == NULL) return CKR_MECHANISM_INVALID; // Get the keys PrivateKey* privateKey = ecdh->newPrivateKey(); if (privateKey == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); return CKR_HOST_MEMORY; } if (getECPrivateKey((ECPrivateKey*)privateKey, token, baseKey) != CKR_OK) { ecdh->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); return CKR_GENERAL_ERROR; } ByteString publicData; publicData.resize(CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->ulPublicDataLen); memcpy(&publicData[0], CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->pPublicData, CK_ECDH1_DERIVE_PARAMS_PTR(pMechanism->pParameter)->ulPublicDataLen); PublicKey* publicKey = ecdh->newPublicKey(); if (publicKey == NULL) { ecdh->recyclePrivateKey(privateKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); return CKR_HOST_MEMORY; } if (getECDHPublicKey((ECPublicKey*)publicKey, (ECPrivateKey*)privateKey, publicData) != CKR_OK) { ecdh->recyclePrivateKey(privateKey); ecdh->recyclePublicKey(publicKey); CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); return CKR_GENERAL_ERROR; } // Derive the secret SymmetricKey* secret = NULL; CK_RV rv = CKR_OK; if (!ecdh->deriveKey(&secret, publicKey, privateKey)) rv = CKR_GENERAL_ERROR; ecdh->recyclePrivateKey(privateKey); ecdh->recyclePublicKey(publicKey); // Create the secret object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_ATTRIBUTE secretAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG secretAttribsCount = 4; // Add the additional if (ulCount > (maxAttribs - secretAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: secretAttribs[secretAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, secretAttribs, secretAttribsCount, phKey, OBJECT_OP_DERIVE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,false); // Common Secret Key Attributes if (baseKey->getBooleanValue(CKA_ALWAYS_SENSITIVE, false)) { bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); } else { bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,false); } if (baseKey->getBooleanValue(CKA_NEVER_EXTRACTABLE, true)) { bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE,bNeverExtractable); } else { bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE,false); } // Secret Attributes ByteString secretValue = secret->getKeyBits(); // Truncate value when requested if (byteLen > secretValue.size()) { INFO_MSG("The derived secret is too short"); bOK = false; } if (bOK && byteLen != 0) secretValue.resize(byteLen); // Fix the odd parity for DES if (keyType == CKK_DES || keyType == CKK_DES2 || keyType == CKK_DES3) { for (size_t i = 0; i < secretValue.size(); i++) { secretValue[i] = odd_parity[secretValue[i]]; } } ByteString value; if (isPrivate) { token->encrypt(secretValue, value); } else { value = secretValue; } bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Clean up ecdh->recycleSymmetricKey(secret); CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); // Remove secret that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* ossecret = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (ossecret) ossecret->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; #else return CKR_MECHANISM_INVALID; #endif } // Derive an symmetric secret CK_RV SoftHSM::deriveSymmetric (CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_KEY_TYPE keyType, CK_BBOOL isOnToken, CK_BBOOL isPrivate) { *phKey = CK_INVALID_HANDLE; if (pMechanism->pParameter == NULL_PTR) { DEBUG_MSG("pParameter must be supplied"); return CKR_MECHANISM_PARAM_INVALID; } ByteString data; if ((pMechanism->mechanism == CKM_DES_ECB_ENCRYPT_DATA || pMechanism->mechanism == CKM_DES3_ECB_ENCRYPT_DATA) && pMechanism->ulParameterLen == sizeof(CK_KEY_DERIVATION_STRING_DATA)) { CK_BYTE_PTR pData = CK_KEY_DERIVATION_STRING_DATA_PTR(pMechanism->pParameter)->pData; CK_ULONG ulLen = CK_KEY_DERIVATION_STRING_DATA_PTR(pMechanism->pParameter)->ulLen; if (ulLen == 0 || pData == NULL_PTR) { DEBUG_MSG("There must be data in the parameter"); return CKR_MECHANISM_PARAM_INVALID; } if (ulLen % 8 != 0) { DEBUG_MSG("The data must be a multiple of 8 bytes long"); return CKR_MECHANISM_PARAM_INVALID; } data.resize(ulLen); memcpy(&data[0], pData, ulLen); } else if ((pMechanism->mechanism == CKM_DES_CBC_ENCRYPT_DATA || pMechanism->mechanism == CKM_DES3_CBC_ENCRYPT_DATA) && pMechanism->ulParameterLen == sizeof(CK_DES_CBC_ENCRYPT_DATA_PARAMS)) { CK_BYTE_PTR pData = CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->pData; CK_ULONG length = CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->length; if (length == 0 || pData == NULL_PTR) { DEBUG_MSG("There must be data in the parameter"); return CKR_MECHANISM_PARAM_INVALID; } if (length % 8 != 0) { DEBUG_MSG("The data must be a multiple of 8 bytes long"); return CKR_MECHANISM_PARAM_INVALID; } data.resize(length); memcpy(&data[0], pData, length); } else if (pMechanism->mechanism == CKM_AES_ECB_ENCRYPT_DATA && pMechanism->ulParameterLen == sizeof(CK_KEY_DERIVATION_STRING_DATA)) { CK_BYTE_PTR pData = CK_KEY_DERIVATION_STRING_DATA_PTR(pMechanism->pParameter)->pData; CK_ULONG ulLen = CK_KEY_DERIVATION_STRING_DATA_PTR(pMechanism->pParameter)->ulLen; if (ulLen == 0 || pData == NULL_PTR) { DEBUG_MSG("There must be data in the parameter"); return CKR_MECHANISM_PARAM_INVALID; } if (ulLen % 16 != 0) { DEBUG_MSG("The data must be a multiple of 16 bytes long"); return CKR_MECHANISM_PARAM_INVALID; } data.resize(ulLen); memcpy(&data[0], pData, ulLen); } else if ((pMechanism->mechanism == CKM_AES_CBC_ENCRYPT_DATA) && pMechanism->ulParameterLen == sizeof(CK_AES_CBC_ENCRYPT_DATA_PARAMS)) { CK_BYTE_PTR pData = CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->pData; CK_ULONG length = CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->length; if (length == 0 || pData == NULL_PTR) { DEBUG_MSG("There must be data in the parameter"); return CKR_MECHANISM_PARAM_INVALID; } if (length % 16 != 0) { DEBUG_MSG("The data must be a multiple of 16 bytes long"); return CKR_MECHANISM_PARAM_INVALID; } data.resize(length); memcpy(&data[0], pData, length); } else { DEBUG_MSG("pParameter is invalid"); return CKR_MECHANISM_PARAM_INVALID; } // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the token Token* token = session->getToken(); if (token == NULL) return CKR_GENERAL_ERROR; // Extract desired parameter information size_t byteLen = 0; for (CK_ULONG i = 0; i < ulCount; i++) { switch (pTemplate[i].type) { case CKA_VALUE: INFO_MSG("CKA_VALUE must not be included"); return CKR_TEMPLATE_INCONSISTENT; case CKA_VALUE_LEN: if (pTemplate[i].ulValueLen != sizeof(CK_ULONG)) { INFO_MSG("CKA_VALUE_LEN does not have the size of CK_ULONG"); return CKR_TEMPLATE_INCOMPLETE; } byteLen = *(CK_ULONG*)pTemplate[i].pValue; break; default: break; } } // Check the length switch (keyType) { case CKK_GENERIC_SECRET: if (byteLen == 0) { INFO_MSG("CKA_VALUE_LEN must be set"); return CKR_TEMPLATE_INCONSISTENT; } break; #ifndef WITH_FIPS case CKK_DES: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 8; break; #endif case CKK_DES2: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 16; break; case CKK_DES3: if (byteLen != 0) { INFO_MSG("CKA_VALUE_LEN must not be set"); return CKR_TEMPLATE_INCONSISTENT; } byteLen = 24; break; case CKK_AES: if (byteLen != 16 && byteLen != 24 && byteLen != 32) { INFO_MSG("CKA_VALUE_LEN must be 16, 24 or 32"); return CKR_TEMPLATE_INCOMPLETE; } break; default: return CKR_TEMPLATE_INCONSISTENT; } // Get the symmetric algorithm matching the mechanism SymAlgo::Type algo = SymAlgo::Unknown; SymMode::Type mode = SymMode::Unknown; bool padding = false; ByteString iv; size_t bb = 8; switch(pMechanism->mechanism) { #ifndef WITH_FIPS case CKM_DES_ECB_ENCRYPT_DATA: algo = SymAlgo::DES; mode = SymMode::ECB; bb = 7; break; case CKM_DES_CBC_ENCRYPT_DATA: algo = SymAlgo::DES; mode = SymMode::CBC; bb = 7; iv.resize(8); memcpy(&iv[0], &(CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->iv[0]), 8); break; #endif case CKM_DES3_ECB_ENCRYPT_DATA: algo = SymAlgo::DES3; mode = SymMode::ECB; bb = 7; break; case CKM_DES3_CBC_ENCRYPT_DATA: algo = SymAlgo::DES3; mode = SymMode::CBC; bb = 7; iv.resize(8); memcpy(&iv[0], &(CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->iv[0]), 8); break; case CKM_AES_ECB_ENCRYPT_DATA: algo = SymAlgo::AES; mode = SymMode::ECB; break; case CKM_AES_CBC_ENCRYPT_DATA: algo = SymAlgo::AES; mode = SymMode::CBC; iv.resize(16); memcpy(&iv[0], &(CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR(pMechanism->pParameter)->iv[0]), 16); break; default: return CKR_MECHANISM_INVALID; } // Check the key handle OSObject *baseKey = (OSObject *)handleManager->getObject(hBaseKey); if (baseKey == NULL_PTR || !baseKey->isValid()) return CKR_OBJECT_HANDLE_INVALID; SymmetricAlgorithm* cipher = CryptoFactory::i()->getSymmetricAlgorithm(algo); if (cipher == NULL) return CKR_MECHANISM_INVALID; SymmetricKey* secretkey = new SymmetricKey(); if (secretkey == NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_HOST_MEMORY; } if (getSymmetricKey(secretkey, token, baseKey) != CKR_OK) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } // adjust key bit length secretkey->setBitLen(secretkey->getKeyBits().size() * bb); // Initialize encryption if (!cipher->encryptInit(secretkey, mode, iv, padding)) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_MECHANISM_INVALID; } // Get the data ByteString secretValue; // Encrypt the data if (!cipher->encryptUpdate(data, secretValue)) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } // Finalize encryption ByteString encryptedFinal; if (!cipher->encryptFinal(encryptedFinal)) { cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); return CKR_GENERAL_ERROR; } cipher->recycleKey(secretkey); CryptoFactory::i()->recycleSymmetricAlgorithm(cipher); secretValue += encryptedFinal; // Create the secret object using C_CreateObject const CK_ULONG maxAttribs = 32; CK_OBJECT_CLASS objClass = CKO_SECRET_KEY; CK_ATTRIBUTE secretAttribs[maxAttribs] = { { CKA_CLASS, &objClass, sizeof(objClass) }, { CKA_TOKEN, &isOnToken, sizeof(isOnToken) }, { CKA_PRIVATE, &isPrivate, sizeof(isPrivate) }, { CKA_KEY_TYPE, &keyType, sizeof(keyType) }, }; CK_ULONG secretAttribsCount = 4; // Add the additional CK_RV rv = CKR_OK; if (ulCount > (maxAttribs - secretAttribsCount)) rv = CKR_TEMPLATE_INCONSISTENT; for (CK_ULONG i=0; i < ulCount && rv == CKR_OK; ++i) { switch (pTemplate[i].type) { case CKA_CLASS: case CKA_TOKEN: case CKA_PRIVATE: case CKA_KEY_TYPE: continue; default: secretAttribs[secretAttribsCount++] = pTemplate[i]; } } if (rv == CKR_OK) rv = this->CreateObject(hSession, secretAttribs, secretAttribsCount, phKey, OBJECT_OP_DERIVE); // Store the attributes that are being supplied if (rv == CKR_OK) { OSObject* osobject = (OSObject*)handleManager->getObject(*phKey); if (osobject == NULL_PTR || !osobject->isValid()) { rv = CKR_FUNCTION_FAILED; } else if (osobject->startTransaction()) { bool bOK = true; // Common Attributes bOK = bOK && osobject->setAttribute(CKA_LOCAL,false); // Common Secret Key Attributes if (baseKey->getBooleanValue(CKA_ALWAYS_SENSITIVE, false)) { bool bAlwaysSensitive = osobject->getBooleanValue(CKA_SENSITIVE, false); bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,bAlwaysSensitive); } else { bOK = bOK && osobject->setAttribute(CKA_ALWAYS_SENSITIVE,false); } if (baseKey->getBooleanValue(CKA_NEVER_EXTRACTABLE, true)) { bool bNeverExtractable = osobject->getBooleanValue(CKA_EXTRACTABLE, false) == false; bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE,bNeverExtractable); } else { bOK = bOK && osobject->setAttribute(CKA_NEVER_EXTRACTABLE,false); } // Truncate value when requested if (byteLen > secretValue.size()) { INFO_MSG("The derived secret is too short"); bOK = false; } if (bOK && byteLen != 0) secretValue.resize(byteLen); // Fix the odd parity for DES if (keyType == CKK_DES || keyType == CKK_DES2 || keyType == CKK_DES3) { for (size_t i = 0; i < secretValue.size(); i++) { secretValue[i] = odd_parity[secretValue[i]]; } } ByteString value; if (isPrivate) { token->encrypt(secretValue, value); } else { value = secretValue; } bOK = bOK && osobject->setAttribute(CKA_VALUE, value); if (bOK) bOK = osobject->commitTransaction(); else osobject->abortTransaction(); if (!bOK) rv = CKR_FUNCTION_FAILED; } else rv = CKR_FUNCTION_FAILED; } // Remove secret that may have been created already when the function fails. if (rv != CKR_OK) { if (*phKey != CK_INVALID_HANDLE) { OSObject* ossecret = (OSObject*)handleManager->getObject(*phKey); handleManager->destroyObject(*phKey); if (ossecret) ossecret->destroyObject(); *phKey = CK_INVALID_HANDLE; } } return rv; } CK_RV SoftHSM::CreateObject(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject, int op) { if (!isInitialised) return CKR_CRYPTOKI_NOT_INITIALIZED; if (pTemplate == NULL_PTR) return CKR_ARGUMENTS_BAD; if (phObject == NULL_PTR) return CKR_ARGUMENTS_BAD; // Get the session Session* session = (Session*)handleManager->getSession(hSession); if (session == NULL) return CKR_SESSION_HANDLE_INVALID; // Get the slot Slot* slot = session->getSlot(); if (slot == NULL_PTR) return CKR_GENERAL_ERROR; // Get the token Token* token = session->getToken(); if (token == NULL_PTR) return CKR_GENERAL_ERROR; // Extract information from the template that is needed to create the object. CK_OBJECT_CLASS objClass = CKO_DATA; CK_KEY_TYPE keyType = CKK_RSA; CK_CERTIFICATE_TYPE certType = CKC_X_509; CK_BBOOL isOnToken = CK_FALSE; CK_BBOOL isPrivate = CK_TRUE; bool isImplicit = false; CK_RV rv = extractObjectInformation(pTemplate,ulCount,objClass,keyType,certType, isOnToken, isPrivate, isImplicit); if (rv != CKR_OK) { ERROR_MSG("Mandatory attribute not present in template"); return rv; } // Check user credentials rv = haveWrite(session->getState(), isOnToken, isPrivate); if (rv != CKR_OK) { if (rv == CKR_USER_NOT_LOGGED_IN) INFO_MSG("User is not authorized"); if (rv == CKR_SESSION_READ_ONLY) INFO_MSG("Session is read-only"); return rv; } P11Object* p11object = NULL; rv = newP11Object(objClass,keyType,certType,&p11object); if (rv != CKR_OK) return rv; // Create the object in session or on the token OSObject *object = NULL_PTR; if (isOnToken) { object = (OSObject*) token->createObject(); } else { object = sessionObjectStore->createObject(slot->getSlotID(), hSession, isPrivate != CK_FALSE); } if (object == NULL || !p11object->init(object)) { delete p11object; return CKR_GENERAL_ERROR; } rv = p11object->saveTemplate(token, isPrivate != CK_FALSE, pTemplate,ulCount,op); delete p11object; if (rv != CKR_OK) return rv; if (isOnToken) { *phObject = handleManager->addTokenObject(slot->getSlotID(), isPrivate != CK_FALSE, object); } else { *phObject = handleManager->addSessionObject(slot->getSlotID(), hSession, isPrivate != CK_FALSE, object); } return CKR_OK; } CK_RV SoftHSM::getRSAPrivateKey(RSAPrivateKey* privateKey, Token* token, OSObject* key) { if (privateKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // RSA Private Key Attributes ByteString modulus; ByteString publicExponent; ByteString privateExponent; ByteString prime1; ByteString prime2; ByteString exponent1; ByteString exponent2; ByteString coefficient; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_MODULUS), modulus); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PUBLIC_EXPONENT), publicExponent); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PRIVATE_EXPONENT), privateExponent); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PRIME_1), prime1); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PRIME_2), prime2); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_EXPONENT_1), exponent1); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_EXPONENT_2), exponent2); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_COEFFICIENT), coefficient); if (!bOK) return CKR_GENERAL_ERROR; } else { modulus = key->getByteStringValue(CKA_MODULUS); publicExponent = key->getByteStringValue(CKA_PUBLIC_EXPONENT); privateExponent = key->getByteStringValue(CKA_PRIVATE_EXPONENT); prime1 = key->getByteStringValue(CKA_PRIME_1); prime2 = key->getByteStringValue(CKA_PRIME_2); exponent1 = key->getByteStringValue(CKA_EXPONENT_1); exponent2 = key->getByteStringValue(CKA_EXPONENT_2); coefficient = key->getByteStringValue(CKA_COEFFICIENT); } privateKey->setN(modulus); privateKey->setE(publicExponent); privateKey->setD(privateExponent); privateKey->setP(prime1); privateKey->setQ(prime2); privateKey->setDP1(exponent1); privateKey->setDQ1(exponent2); privateKey->setPQ(coefficient); return CKR_OK; } CK_RV SoftHSM::getRSAPublicKey(RSAPublicKey* publicKey, Token* token, OSObject* key) { if (publicKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // RSA Public Key Attributes ByteString modulus; ByteString publicExponent; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_MODULUS), modulus); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PUBLIC_EXPONENT), publicExponent); if (!bOK) return CKR_GENERAL_ERROR; } else { modulus = key->getByteStringValue(CKA_MODULUS); publicExponent = key->getByteStringValue(CKA_PUBLIC_EXPONENT); } publicKey->setN(modulus); publicKey->setE(publicExponent); return CKR_OK; } CK_RV SoftHSM::getDSAPrivateKey(DSAPrivateKey* privateKey, Token* token, OSObject* key) { if (privateKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // DSA Private Key Attributes ByteString prime; ByteString subprime; ByteString generator; ByteString value; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PRIME), prime); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_SUBPRIME), subprime); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_BASE), generator); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_VALUE), value); if (!bOK) return CKR_GENERAL_ERROR; } else { prime = key->getByteStringValue(CKA_PRIME); subprime = key->getByteStringValue(CKA_SUBPRIME); generator = key->getByteStringValue(CKA_BASE); value = key->getByteStringValue(CKA_VALUE); } privateKey->setP(prime); privateKey->setQ(subprime); privateKey->setG(generator); privateKey->setX(value); return CKR_OK; } CK_RV SoftHSM::getDSAPublicKey(DSAPublicKey* publicKey, Token* token, OSObject* key) { if (publicKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // DSA Public Key Attributes ByteString prime; ByteString subprime; ByteString generator; ByteString value; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PRIME), prime); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_SUBPRIME), subprime); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_BASE), generator); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_VALUE), value); if (!bOK) return CKR_GENERAL_ERROR; } else { prime = key->getByteStringValue(CKA_PRIME); subprime = key->getByteStringValue(CKA_SUBPRIME); generator = key->getByteStringValue(CKA_BASE); value = key->getByteStringValue(CKA_VALUE); } publicKey->setP(prime); publicKey->setQ(subprime); publicKey->setG(generator); publicKey->setY(value); return CKR_OK; } CK_RV SoftHSM::getECPrivateKey(ECPrivateKey* privateKey, Token* token, OSObject* key) { if (privateKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // EC Private Key Attributes ByteString group; ByteString value; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_EC_PARAMS), group); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_VALUE), value); if (!bOK) return CKR_GENERAL_ERROR; } else { group = key->getByteStringValue(CKA_EC_PARAMS); value = key->getByteStringValue(CKA_VALUE); } privateKey->setEC(group); privateKey->setD(value); return CKR_OK; } CK_RV SoftHSM::getECPublicKey(ECPublicKey* publicKey, Token* token, OSObject* key) { if (publicKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // EC Public Key Attributes ByteString group; ByteString point; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_EC_PARAMS), group); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_EC_POINT), point); if (!bOK) return CKR_GENERAL_ERROR; } else { group = key->getByteStringValue(CKA_EC_PARAMS); point = key->getByteStringValue(CKA_EC_POINT); } publicKey->setEC(group); publicKey->setQ(point); return CKR_OK; } CK_RV SoftHSM::getDHPrivateKey(DHPrivateKey* privateKey, Token* token, OSObject* key) { if (privateKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // DH Private Key Attributes ByteString prime; ByteString generator; ByteString value; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_PRIME), prime); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_BASE), generator); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_VALUE), value); if (!bOK) return CKR_GENERAL_ERROR; } else { prime = key->getByteStringValue(CKA_PRIME); generator = key->getByteStringValue(CKA_BASE); value = key->getByteStringValue(CKA_VALUE); } privateKey->setP(prime); privateKey->setG(generator); privateKey->setX(value); return CKR_OK; } CK_RV SoftHSM::getDHPublicKey(DHPublicKey* publicKey, DHPrivateKey* privateKey, ByteString& pubParams) { if (publicKey == NULL) return CKR_ARGUMENTS_BAD; if (privateKey == NULL) return CKR_ARGUMENTS_BAD; // Copy Domain Parameters from Private Key publicKey->setP(privateKey->getP()); publicKey->setG(privateKey->getG()); // Set value publicKey->setY(pubParams); return CKR_OK; } CK_RV SoftHSM::getECDHPublicKey(ECPublicKey* publicKey, ECPrivateKey* privateKey, ByteString& pubData) { if (publicKey == NULL) return CKR_ARGUMENTS_BAD; if (privateKey == NULL) return CKR_ARGUMENTS_BAD; // Copy Domain Parameters from Private Key publicKey->setEC(privateKey->getEC()); // Set value publicKey->setQ(pubData); return CKR_OK; } CK_RV SoftHSM::getGOSTPrivateKey(GOSTPrivateKey* privateKey, Token* token, OSObject* key) { if (privateKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // GOST Private Key Attributes ByteString value; ByteString param; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_VALUE), value); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_GOSTR3410_PARAMS), param); if (!bOK) return CKR_GENERAL_ERROR; } else { value = key->getByteStringValue(CKA_VALUE); param = key->getByteStringValue(CKA_GOSTR3410_PARAMS); } privateKey->setD(value); privateKey->setEC(param); return CKR_OK; } CK_RV SoftHSM::getGOSTPublicKey(GOSTPublicKey* publicKey, Token* token, OSObject* key) { if (publicKey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); // GOST Public Key Attributes ByteString point; ByteString param; if (isKeyPrivate) { bool bOK = true; bOK = bOK && token->decrypt(key->getByteStringValue(CKA_VALUE), point); bOK = bOK && token->decrypt(key->getByteStringValue(CKA_GOSTR3410_PARAMS), param); if (!bOK) return CKR_GENERAL_ERROR; } else { point = key->getByteStringValue(CKA_VALUE); param = key->getByteStringValue(CKA_GOSTR3410_PARAMS); } publicKey->setQ(point); publicKey->setEC(param); return CKR_OK; } CK_RV SoftHSM::getSymmetricKey(SymmetricKey* skey, Token* token, OSObject* key) { if (skey == NULL) return CKR_ARGUMENTS_BAD; if (token == NULL) return CKR_ARGUMENTS_BAD; if (key == NULL) return CKR_ARGUMENTS_BAD; // Get the CKA_PRIVATE attribute, when the attribute is not present use default false bool isKeyPrivate = key->getBooleanValue(CKA_PRIVATE, false); ByteString keybits; if (isKeyPrivate) { if (!token->decrypt(key->getByteStringValue(CKA_VALUE), keybits)) return CKR_GENERAL_ERROR; } else { keybits = key->getByteStringValue(CKA_VALUE); } skey->setKeyBits(keybits); return CKR_OK; } bool SoftHSM::setRSAPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate) { AsymmetricAlgorithm* rsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); if (rsa == NULL) return false; PrivateKey* priv = rsa->newPrivateKey(); if (priv == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); return false; } if (!priv->PKCS8Decode(ber)) { rsa->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); return false; } // RSA Private Key Attributes ByteString modulus; ByteString publicExponent; ByteString privateExponent; ByteString prime1; ByteString prime2; ByteString exponent1; ByteString exponent2; ByteString coefficient; if (isPrivate) { token->encrypt(((RSAPrivateKey*)priv)->getN(), modulus); token->encrypt(((RSAPrivateKey*)priv)->getE(), publicExponent); token->encrypt(((RSAPrivateKey*)priv)->getD(), privateExponent); token->encrypt(((RSAPrivateKey*)priv)->getP(), prime1); token->encrypt(((RSAPrivateKey*)priv)->getQ(), prime2); token->encrypt(((RSAPrivateKey*)priv)->getDP1(), exponent1); token->encrypt(((RSAPrivateKey*)priv)->getDQ1(), exponent2); token->encrypt(((RSAPrivateKey*)priv)->getPQ(), coefficient); } else { modulus = ((RSAPrivateKey*)priv)->getN(); publicExponent = ((RSAPrivateKey*)priv)->getE(); privateExponent = ((RSAPrivateKey*)priv)->getD(); prime1 = ((RSAPrivateKey*)priv)->getP(); prime2 = ((RSAPrivateKey*)priv)->getQ(); exponent1 = ((RSAPrivateKey*)priv)->getDP1(); exponent2 = ((RSAPrivateKey*)priv)->getDQ1(); coefficient = ((RSAPrivateKey*)priv)->getPQ(); } bool bOK = true; bOK = bOK && key->setAttribute(CKA_MODULUS, modulus); bOK = bOK && key->setAttribute(CKA_PUBLIC_EXPONENT, publicExponent); bOK = bOK && key->setAttribute(CKA_PRIVATE_EXPONENT, privateExponent); bOK = bOK && key->setAttribute(CKA_PRIME_1, prime1); bOK = bOK && key->setAttribute(CKA_PRIME_2, prime2); bOK = bOK && key->setAttribute(CKA_EXPONENT_1,exponent1); bOK = bOK && key->setAttribute(CKA_EXPONENT_2, exponent2); bOK = bOK && key->setAttribute(CKA_COEFFICIENT, coefficient); rsa->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); return bOK; } bool SoftHSM::setDSAPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate) { AsymmetricAlgorithm* dsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); if (dsa == NULL) return false; PrivateKey* priv = dsa->newPrivateKey(); if (priv == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); return false; } if (!priv->PKCS8Decode(ber)) { dsa->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); return false; } // DSA Private Key Attributes ByteString prime; ByteString subprime; ByteString generator; ByteString value; if (isPrivate) { token->encrypt(((DSAPrivateKey*)priv)->getP(), prime); token->encrypt(((DSAPrivateKey*)priv)->getQ(), subprime); token->encrypt(((DSAPrivateKey*)priv)->getG(), generator); token->encrypt(((DSAPrivateKey*)priv)->getX(), value); } else { prime = ((DSAPrivateKey*)priv)->getP(); subprime = ((DSAPrivateKey*)priv)->getQ(); generator = ((DSAPrivateKey*)priv)->getG(); value = ((DSAPrivateKey*)priv)->getX(); } bool bOK = true; bOK = bOK && key->setAttribute(CKA_PRIME, prime); bOK = bOK && key->setAttribute(CKA_SUBPRIME, subprime); bOK = bOK && key->setAttribute(CKA_BASE, generator); bOK = bOK && key->setAttribute(CKA_VALUE, value); dsa->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); return bOK; } bool SoftHSM::setDHPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate) { AsymmetricAlgorithm* dh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DH); if (dh == NULL) return false; PrivateKey* priv = dh->newPrivateKey(); if (priv == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return false; } if (!priv->PKCS8Decode(ber)) { dh->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return false; } // DH Private Key Attributes ByteString prime; ByteString generator; ByteString value; if (isPrivate) { token->encrypt(((DHPrivateKey*)priv)->getP(), prime); token->encrypt(((DHPrivateKey*)priv)->getG(), generator); token->encrypt(((DHPrivateKey*)priv)->getX(), value); } else { prime = ((DHPrivateKey*)priv)->getP(); generator = ((DHPrivateKey*)priv)->getG(); value = ((DHPrivateKey*)priv)->getX(); } bool bOK = true; bOK = bOK && key->setAttribute(CKA_PRIME, prime); bOK = bOK && key->setAttribute(CKA_BASE, generator); bOK = bOK && key->setAttribute(CKA_VALUE, value); dh->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); return bOK; } bool SoftHSM::setECPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate) { AsymmetricAlgorithm* ecc = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDSA); if (ecc == NULL) return false; PrivateKey* priv = ecc->newPrivateKey(); if (priv == NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(ecc); return false; } if (!priv->PKCS8Decode(ber)) { ecc->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(ecc); return false; } // EC Private Key Attributes ByteString group; ByteString value; if (isPrivate) { token->encrypt(((ECPrivateKey*)priv)->getEC(), group); token->encrypt(((ECPrivateKey*)priv)->getD(), value); } else { group = ((ECPrivateKey*)priv)->getEC(); value = ((ECPrivateKey*)priv)->getD(); } bool bOK = true; bOK = bOK && key->setAttribute(CKA_EC_PARAMS, group); bOK = bOK && key->setAttribute(CKA_VALUE, value); ecc->recyclePrivateKey(priv); CryptoFactory::i()->recycleAsymmetricAlgorithm(ecc); return bOK; } CK_RV SoftHSM::MechParamCheckRSAPKCSOAEP(CK_MECHANISM_PTR pMechanism) { // This is a programming error if (pMechanism->mechanism != CKM_RSA_PKCS_OAEP) { ERROR_MSG("MechParamCheckRSAPKCSOAEP called on wrong mechanism"); return CKR_GENERAL_ERROR; } if (pMechanism->pParameter == NULL_PTR || pMechanism->ulParameterLen != sizeof(CK_RSA_PKCS_OAEP_PARAMS)) { ERROR_MSG("pParameter must be of type CK_RSA_PKCS_OAEP_PARAMS"); return CKR_ARGUMENTS_BAD; } CK_RSA_PKCS_OAEP_PARAMS_PTR params = (CK_RSA_PKCS_OAEP_PARAMS_PTR)pMechanism->pParameter; if (params->hashAlg != CKM_SHA_1) { ERROR_MSG("hashAlg must be CKM_SHA_1"); return CKR_ARGUMENTS_BAD; } if (params->mgf != CKG_MGF1_SHA1) { ERROR_MSG("mgf must be CKG_MGF1_SHA1"); return CKR_ARGUMENTS_BAD; } if (params->source != CKZ_DATA_SPECIFIED) { ERROR_MSG("source must be CKZ_DATA_SPECIFIED"); return CKR_ARGUMENTS_BAD; } if (params->pSourceData != NULL) { ERROR_MSG("pSourceData must be NULL"); return CKR_ARGUMENTS_BAD; } if (params->ulSourceDataLen != 0) { ERROR_MSG("ulSourceDataLen must be 0"); return CKR_ARGUMENTS_BAD; } return CKR_OK; } softhsm-2.0.0/src/lib/win32/0000775000175000017500000000000012552220146012475 500000000000000softhsm-2.0.0/src/lib/win32/syslog.cpp0000664000175000017500000000241012533040716014440 00000000000000#include #include #include #include #include #include #ifdef _WIN32 static HANDLE hEventLog = NULL; /* * Close the Handle to the application Event Log */ void closelog() { DeregisterEventSource(hEventLog); } /* * Initialize event logging */ void openlog(const char *ident, int logopt, int facility) { /* Get a handle to the Application event log */ hEventLog = RegisterEventSourceA(NULL, ident); } /* * Log to the NT Event Log */ void syslog(int priority, const char *message, ...) { va_list ap; char buf[1024]; LPCSTR str[1]; str[0] = buf; va_start(ap, message); vsprintf(buf, message, ap); va_end(ap); /* Make sure that the channel is open to write the event */ if (hEventLog == NULL) { openlog("SoftHSM", 0, 0); } if (hEventLog != NULL) { switch (priority) { case LOG_INFO: case LOG_NOTICE: case LOG_DEBUG: ReportEventA(hEventLog, EVENTLOG_INFORMATION_TYPE, 0, 0x40000003, NULL, 1, 0, str, NULL); break; case LOG_WARNING: ReportEventA(hEventLog, EVENTLOG_WARNING_TYPE, 0, 0x80000002, NULL, 1, 0, str, NULL); break; default: ReportEventA(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0xc0000001, NULL, 1, 0, str, NULL); break; } } } #endif softhsm-2.0.0/src/lib/win32/dllmain.cc0000664000175000017500000000061312533040716014346 00000000000000#include __declspec(dllexport) BOOL WINAPI DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpvReserved) { hModule = hModule; lpvReserved = lpvReserved; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: default: break; } return (TRUE); } softhsm-2.0.0/src/lib/win32/syslog.h0000664000175000017500000000216112533040716014110 00000000000000#ifndef _SYSLOG_H #define _SYSLOG_H #include /* priorities */ #define LOG_EMERG 0 /* system is unusable */ #define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_CRIT 2 /* critical conditions */ #define LOG_ERR 3 /* error conditions */ #define LOG_WARNING 4 /* warning conditions */ #define LOG_NOTICE 5 /* normal but signification condition */ #define LOG_INFO 6 /* informational */ #define LOG_DEBUG 7 /* debug-level messages */ /* NT event log does not support facility level */ #define LOG_KERN 0 #define LOG_USER 0 #define LOG_MAIL 0 #define LOG_DAEMON 0 #define LOG_AUTH 0 #define LOG_SYSLOG 0 #define LOG_LPR 0 #define LOG_LOCAL0 0 #define LOG_LOCAL1 0 #define LOG_LOCAL2 0 #define LOG_LOCAL3 0 #define LOG_LOCAL4 0 #define LOG_LOCAL5 0 #define LOG_LOCAL6 0 #define LOG_LOCAL7 0 /* Constant definitions for openlog() */ #define LOG_PID 1 #define LOG_CONS 2 void closelog(void); void openlog(const char *ident, int logopt, int facility); void syslog(int priority, const char *message, ...); #endif softhsm-2.0.0/src/lib/win32/setenv.cpp0000664000175000017500000000042012533040716014423 00000000000000#include #include #include #ifdef _WIN32 int setenv(const char *name, const char *value, int overwrite) { std::string vv = name; vv += "="; vv += value; if (overwrite != 1) return false; return _putenv(vv.c_str()) == 0; } #endif softhsm-2.0.0/src/lib/SoftHSM.h0000664000175000017500000004170412533040716013117 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SoftHSM.h This is the main class of the SoftHSM; it has the PKCS #11 interface and dispatches all calls to the relevant components of the SoftHSM. The SoftHSM class is a singleton implementation. *****************************************************************************/ #include "config.h" #include "log.h" #include "cryptoki.h" #include "SessionObjectStore.h" #include "ObjectStore.h" #include "SessionManager.h" #include "SlotManager.h" #include "HandleManager.h" #include "RSAPublicKey.h" #include "RSAPrivateKey.h" #include "DSAPublicKey.h" #include "DSAPrivateKey.h" #include "ECPublicKey.h" #include "ECPrivateKey.h" #include "DHPublicKey.h" #include "DHPrivateKey.h" #include "GOSTPublicKey.h" #include "GOSTPrivateKey.h" #include class SoftHSM { public: // Return the one-and-only instance static SoftHSM* i(); // This will destroy the one-and-only instance. static void reset(); // Destructor virtual ~SoftHSM(); // PKCS #11 functions CK_RV C_Initialize(CK_VOID_PTR pInitArgs); CK_RV C_Finalize(CK_VOID_PTR pReserved); CK_RV C_GetInfo(CK_INFO_PTR pInfo); CK_RV C_GetSlotList(CK_BBOOL tokenPresent, CK_SLOT_ID_PTR pSlotList, CK_ULONG_PTR pulCount); CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo); CK_RV C_GetTokenInfo(CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo); CK_RV C_GetMechanismList(CK_SLOT_ID slotID, CK_MECHANISM_TYPE_PTR pMechanismList, CK_ULONG_PTR pulCount); CK_RV C_GetMechanismInfo(CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo); CK_RV C_InitToken(CK_SLOT_ID slotID, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen, CK_UTF8CHAR_PTR pLabel); CK_RV C_InitPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen); CK_RV C_SetPIN(CK_SESSION_HANDLE hSession, CK_UTF8CHAR_PTR pOldPin, CK_ULONG ulOldLen, CK_UTF8CHAR_PTR pNewPin, CK_ULONG ulNewLen); CK_RV C_OpenSession(CK_SLOT_ID slotID, CK_FLAGS flags, CK_VOID_PTR pApplication, CK_NOTIFY notify, CK_SESSION_HANDLE_PTR phSession); CK_RV C_CloseSession(CK_SESSION_HANDLE hSession); CK_RV C_CloseAllSessions(CK_SLOT_ID slotID); CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo); CK_RV C_GetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pOperationState, CK_ULONG_PTR pulOperationStateLen); CK_RV C_SetOperationState(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pOperationState, CK_ULONG ulOperationStateLen, CK_OBJECT_HANDLE hEncryptionKey, CK_OBJECT_HANDLE hAuthenticationKey); CK_RV C_Login(CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen); CK_RV C_Logout(CK_SESSION_HANDLE hSession); CK_RV C_CreateObject(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject); CK_RV C_CopyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phNewObject); CK_RV C_DestroyObject(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject); CK_RV C_GetObjectSize(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG_PTR pulSize); CK_RV C_GetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount); CK_RV C_SetAttributeValue(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount); CK_RV C_FindObjectsInit(CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount); CK_RV C_FindObjects(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount); CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession); CK_RV C_EncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Encrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen); CK_RV C_EncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen); CK_RV C_EncryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG_PTR pulEncryptedDataLen); CK_RV C_DecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Decrypt(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen); CK_RV C_DecryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen); CK_RV C_DecryptFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG_PTR pDataLen); CK_RV C_DigestInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism); CK_RV C_Digest(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen); CK_RV C_DigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen); CK_RV C_DigestKey(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject); CK_RV C_DigestFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen); CK_RV C_SignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Sign(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen); CK_RV C_SignUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen); CK_RV C_SignFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen); CK_RV C_SignRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_SignRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen); CK_RV C_VerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Verify(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen); CK_RV C_VerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen); CK_RV C_VerifyFinal(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen); CK_RV C_VerifyRecoverInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_VerifyRecover(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSignature, CK_ULONG ulSignatureLen, CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen); CK_RV C_DigestEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen); CK_RV C_DecryptDigestUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pDecryptedPart, CK_ULONG_PTR pulDecryptedPartLen); CK_RV C_SignEncryptUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen, CK_BYTE_PTR pEncryptedPart, CK_ULONG_PTR pulEncryptedPartLen); CK_RV C_DecryptVerifyUpdate(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pEncryptedPart, CK_ULONG ulEncryptedPartLen, CK_BYTE_PTR pPart, CK_ULONG_PTR pulPartLen); CK_RV C_GenerateKey(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey); CK_RV C_GenerateKeyPair ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey ); CK_RV C_WrapKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, CK_BYTE_PTR pWrappedKey, CK_ULONG_PTR pulWrappedKeyLen ); CK_RV C_UnwrapKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, CK_BYTE_PTR pWrappedKey, CK_ULONG ulWrappedKeyLen, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR hKey ); CK_RV C_DeriveKey ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey ); CK_RV C_SeedRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pSeed, CK_ULONG ulSeedLen); CK_RV C_GenerateRandom(CK_SESSION_HANDLE hSession, CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen); CK_RV C_GetFunctionStatus(CK_SESSION_HANDLE hSession); CK_RV C_CancelFunction(CK_SESSION_HANDLE hSession); CK_RV C_WaitForSlotEvent(CK_FLAGS flags, CK_SLOT_ID_PTR pSlot, CK_VOID_PTR pReserved); private: // Constructor SoftHSM(); // The one-and-only instance #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif // Is the SoftHSM PKCS #11 library initialised? bool isInitialised; SessionObjectStore* sessionObjectStore; ObjectStore* objectStore; SlotManager* slotManager; SessionManager* sessionManager; HandleManager* handleManager; // Encrypt/Decrypt variants CK_RV SymEncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV AsymEncryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV SymDecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV AsymDecryptInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); // Sign/Verify variants CK_RV MacSignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV AsymSignInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV MacVerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); CK_RV AsymVerifyInit(CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey); // Key generation CK_RV generateDES ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV generateDES2 ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV generateDES3 ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV generateAES ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV generateRSA (CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate ); CK_RV generateDSA ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate ); CK_RV generateDSAParameters ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV generateEC ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate ); CK_RV generateDH ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate ); CK_RV generateDHParameters ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV generateGOST ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR phPublicKey, CK_OBJECT_HANDLE_PTR phPrivateKey, CK_BBOOL isPublicKeyOnToken, CK_BBOOL isPublicKeyPrivate, CK_BBOOL isPrivateKeyOnToken, CK_BBOOL isPrivateKeyPrivate ); CK_RV deriveDH ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_KEY_TYPE keyType, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV deriveECDH ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_KEY_TYPE keyType, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV deriveSymmetric ( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hBaseKey, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phKey, CK_KEY_TYPE keyType, CK_BBOOL isOnToken, CK_BBOOL isPrivate ); CK_RV CreateObject ( CK_SESSION_HANDLE hSession, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR phObject, int op ); CK_RV getRSAPrivateKey(RSAPrivateKey* privateKey, Token* token, OSObject* key); CK_RV getRSAPublicKey(RSAPublicKey* publicKey, Token* token, OSObject* key); CK_RV getDSAPrivateKey(DSAPrivateKey* privateKey, Token* token, OSObject* key); CK_RV getDSAPublicKey(DSAPublicKey* publicKey, Token* token, OSObject* key); CK_RV getECPrivateKey(ECPrivateKey* privateKey, Token* token, OSObject* key); CK_RV getECPublicKey(ECPublicKey* publicKey, Token* token, OSObject* key); CK_RV getDHPrivateKey(DHPrivateKey* privateKey, Token* token, OSObject* key); CK_RV getDHPublicKey(DHPublicKey* publicKey, DHPrivateKey* privateKey, ByteString& pubParams); CK_RV getECDHPublicKey(ECPublicKey* publicKey, ECPrivateKey* privateKey, ByteString& pubData); CK_RV getGOSTPrivateKey(GOSTPrivateKey* privateKey, Token* token, OSObject* key); CK_RV getGOSTPublicKey(GOSTPublicKey* publicKey, Token* token, OSObject* key); CK_RV getSymmetricKey(SymmetricKey* skey, Token* token, OSObject* key); bool setRSAPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate); bool setDSAPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate); bool setDHPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate); bool setECPrivateKey(OSObject* key, ByteString ber, Token* token, bool isPrivate); CK_RV WrapKeyAsym ( CK_MECHANISM_PTR pMechanism, Token *token, OSObject *wrapKey, ByteString &keydata, ByteString &wrapped ); CK_RV WrapKeySym ( CK_MECHANISM_PTR pMechanism, Token *token, OSObject *wrapKey, ByteString &keydata, ByteString &wrapped ); CK_RV UnwrapKeyAsym ( CK_MECHANISM_PTR pMechanism, ByteString &wrapped, Token* token, OSObject *unwrapKey, ByteString &keydata ); CK_RV UnwrapKeySym ( CK_MECHANISM_PTR pMechanism, ByteString &wrapped, Token* token, OSObject *unwrapKey, ByteString &keydata ); CK_RV MechParamCheckRSAPKCSOAEP(CK_MECHANISM_PTR pMechanism); }; softhsm-2.0.0/src/lib/object_store/0000775000175000017500000000000012552220147014216 500000000000000softhsm-2.0.0/src/lib/object_store/SessionObject.h0000664000175000017500000001042512533040716017064 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObject.h This class implements session objects (i.e. objects that are non-persistent) *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONOBJECT_H #define _SOFTHSM_V2_SESSIONOBJECT_H #include "config.h" #include "ByteString.h" #include "OSAttribute.h" #include "MutexFactory.h" #include #include #include "cryptoki.h" #include "OSObject.h" // Forward declaration of the session object store class SessionObjectStore; class SessionObject : public OSObject { public: // Constructor SessionObject(SessionObjectStore* inParent, CK_SLOT_ID inSlotID, CK_SESSION_HANDLE inHSession, bool inIsPrivate = false); // Destructor virtual ~SessionObject(); // Check if the specified attribute exists virtual bool attributeExists(CK_ATTRIBUTE_TYPE type); // Retrieve the specified attribute virtual OSAttribute getAttribute(CK_ATTRIBUTE_TYPE type); virtual bool getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val); virtual unsigned long getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val); virtual ByteString getByteStringValue(CK_ATTRIBUTE_TYPE type); // Retrieve the next attribute type virtual CK_ATTRIBUTE_TYPE nextAttributeType(CK_ATTRIBUTE_TYPE type); // Set the specified attribute virtual bool setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute); // The validity state of the object virtual bool isValid(); bool hasSlotID(CK_SLOT_ID inSlotID); // Called by the session object store when a session is closed. If it's the // session this object was associated with, the function returns true and the // object is invalidated bool removeOnSessionClose(CK_SESSION_HANDLE inHSession); // Called by the session object store when all the sessions for a token // have been closed. bool removeOnAllSessionsClose(CK_SLOT_ID inSlotID); // Called by the session object store when a token is logged out. // Remove when this session object is a private object for this token. bool removeOnTokenLogout(CK_SLOT_ID inSlotID); // These functions are just stubs for session objects virtual bool startTransaction(Access access); virtual bool commitTransaction(); virtual bool abortTransaction(); // Destroys the object; WARNING: pointers to the object become invalid after this // call! virtual bool destroyObject(); // Invalidate the object void invalidate(); private: // Discard the object's attributes void discardAttributes(); // The object's raw attributes std::map attributes; // The object's validity state bool valid; // Mutex object for thread-safeness Mutex* objectMutex; // The slotID of the object is associated with. CK_SLOT_ID slotID; // The session the object is associated with. CK_SESSION_HANDLE hSession; // Indicates whether this object is private bool isPrivate; // The parent SessionObjectStore SessionObjectStore* parent; }; #endif // !_SOFTHSM_V2_SESSIONOBJECT_H softhsm-2.0.0/src/lib/object_store/File.cpp0000664000175000017500000003177512533040716015537 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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 vector of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this vector of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** File.h This class wraps standard C file I/O in a convenient way for the object store *****************************************************************************/ #include "config.h" #include "File.h" #include "log.h" #include #include #include #ifndef _WIN32 #include #include #else #include #define F_SETLK 12 #define F_SETLKW 13 #define F_RDLCK 1 #define F_UNLCK 2 #define F_WRLCK 3 #endif #include #include #include enum AttributeKind { akUnknown, akBoolean, akInteger, akBinary, akArray }; // Constructor // // N.B.: the create flag only has a function when a file is opened read/write // N.B.: the truncate flag only has a function when the create one is true File::File(std::string inPath, bool forRead /* = true */, bool forWrite /* = false */, bool create /* = false */, bool truncate /* = true */) { stream = NULL; isReadable = forRead; isWritable = forWrite; locked = false; path = inPath; valid = false; if (forRead || forWrite) { std::string fileMode = ""; int flags, fd; #ifndef _WIN32 flags = 0; if (forRead && !forWrite) flags |= O_RDONLY; if (!forRead && forWrite) flags |= O_WRONLY | O_CREAT | O_TRUNC; if (forRead && forWrite) flags |= O_RDWR; if (forRead && forWrite && create) flags |= O_CREAT; if (forRead && forWrite && create && truncate) flags |= O_TRUNC; // Open the file fd = open(path.c_str(), flags, 0600); if (fd == -1) { valid = false; return; } if (forRead && !forWrite) fileMode = "r"; if (!forRead && forWrite) fileMode = "w"; if (forRead && forWrite && !create) fileMode = "r+"; if (forRead && forWrite && create) fileMode = "w+"; // Open the stream valid = ((stream = fdopen(fd, fileMode.c_str())) != NULL); #else flags = _O_BINARY; if (forRead && !forWrite) flags |= _O_RDONLY; if (!forRead && forWrite) flags |= _O_WRONLY | _O_CREAT | _O_TRUNC; if (forRead && forWrite) flags |= _O_RDWR; if (forRead && forWrite && create) flags |= _O_CREAT; if (forRead && forWrite && create && truncate) flags |= _O_TRUNC; // Open the file fd = _open(path.c_str(), flags, _S_IREAD | _S_IWRITE); if (fd == -1) { valid = false; return; } if (forRead && !forWrite) fileMode = "rb"; if (!forRead && forWrite) fileMode = "wb"; if (forRead && forWrite && !create) fileMode = "rb+"; if (forRead && forWrite && create) fileMode = "wb+"; // Open the stream valid = ((stream = _fdopen(fd, fileMode.c_str())) != NULL); #endif } } // Destructor File::~File() { if (locked) { unlock(); } if (stream != NULL) { fclose(stream); } } // Check if the file is valid bool File::isValid() { return valid; } // Check if the file is readable bool File::isRead() { return isReadable; } // Check if the file is writable bool File::isWrite() { return isWritable; } // Check if the file is empty bool File::isEmpty() { #ifndef _WIN32 struct stat s; if (fstat(fileno(stream), &s) != 0) { valid = false; return false; } return (s.st_size == 0); #else struct _stat s; if (_fstat(_fileno(stream), &s) != 0) { valid = false; return false; } return (s.st_size == 0); #endif } // Check if the end-of-file was reached bool File::isEOF() { return valid && feof(stream); } // Read an unsigned long value; warning: not thread safe without locking! bool File::readULong(unsigned long& value) { if (!valid) return false; ByteString ulongVal; ulongVal.resize(8); if (fread(&ulongVal[0], 1, 8, stream) != 8) { return false; } value = ulongVal.long_val(); return true; } // Read a ByteString value; warning: not thread safe without locking! bool File::readByteString(ByteString& value) { if (!valid) return false; // Retrieve the length to read from the file unsigned long len; if (!readULong(len)) { return false; } // Read the byte string from the file value.resize(len); if (len == 0) { return true; } if (fread(&value[0], 1, len, stream) != len) { return false; } return true; } // Read a boolean value; warning: not thread safe without locking! bool File::readBool(bool& value) { if (!valid) return false; // Read the boolean from the file unsigned char boolValue; if (fread(&boolValue, 1, 1, stream) != 1) { return false; } value = boolValue ? true : false; return true; } // Read an array value; warning: not thread safe without locking! bool File::readArray(std::map& value) { if (!valid) return false; // Retrieve the length to read from the file unsigned long len; if (!readULong(len)) { return false; } while (len != 0) { unsigned long attrType; if (!readULong(attrType)) { return false; } if (8 > len) { return false; } len -= 8; unsigned long attrKind; if (!readULong(attrKind)) { return false; } if (8 > len) { return false; } len -= 8; switch (attrKind) { case akBoolean: { bool val; if (!readBool(val)) { return false; } if (1 > len) { return false; } len -= 1; value.insert(std::pair (attrType, val)); } break; case akInteger: { unsigned long val; if (!readULong(val)) { return false; } if (8 > len) { return false; } len -= 8; value.insert(std::pair (attrType, val)); } break; case akBinary: { ByteString val; if (!readByteString(val)) { return false; } if (8 + val.size() > len) { return false; } len -= 8 + val.size(); value.insert(std::pair (attrType, val)); } break; default: return false; } } return true; } // Read a string value; warning: not thread safe without locking! bool File::readString(std::string& value) { if (!valid) return false; // Retrieve the length to read from the file unsigned long len; if (!readULong(len)) { return false; } // Read the string from the file value.resize(len); if (fread(&value[0], 1, len, stream) != len) { return false; } return true; } // Write an unsigned long value; warning: not thread safe without locking! bool File::writeULong(const unsigned long value) { if (!valid) return false; ByteString toWrite(value); // Write the value to the file if (fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size()) { return false; } return true; } // Write a ByteString value; warning: not thread safe without locking! bool File::writeByteString(const ByteString& value) { if (!valid) return false; ByteString toWrite = value.serialise(); // Write the value to the file if (fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size()) { return false; } return true; } // Write a string value; warning: not thread safe without locking! bool File::writeString(const std::string& value) { if (!valid) return false; ByteString toWrite((const unsigned long) value.size()); // Write the value to the file if ((fwrite(toWrite.const_byte_str(), 1, toWrite.size(), stream) != toWrite.size()) || (fwrite(&value[0], 1, value.size(), stream) != value.size())) { return false; } return true; } // Write an array value; warning: not thread safe without locking! bool File::writeArray(const std::map& value) { if (!valid) return false; // compute length unsigned long len = 0; for (std::map::const_iterator i = value.begin(); i != value.end(); ++i) { OSAttribute attr = i->second; // count attribute type and kind len += 8 + 8; if (attr.isBooleanAttribute()) { len += 1; } else if (attr.isUnsignedLongAttribute()) { len += 8; } else if (attr.isByteStringAttribute()) { ByteString val = attr.getByteStringValue(); len += 8 + val.size(); } else { return false; } } // write length if (!writeULong(len)) { return false; } // write each attribute for (std::map::const_iterator i = value.begin(); i != value.end(); ++i) { OSAttribute attr = i->second; unsigned long attrType = (unsigned long) i->first; if (!writeULong(attrType)) { return false; } if (attr.isBooleanAttribute()) { unsigned long attrKind = akBoolean; if (!writeULong(attrKind)) { return false; } bool val = attr.getBooleanValue(); if (!writeBool(val)) { return false; } } else if (attr.isUnsignedLongAttribute()) { unsigned long attrKind = akInteger; if (!writeULong(attrKind)) { return false; } unsigned long val = attr.getUnsignedLongValue(); if (!writeULong(val)) { return false; } } else if (attr.isByteStringAttribute()) { unsigned long attrKind = akBinary; if (!writeULong(attrKind)) { return false; } ByteString val = attr.getByteStringValue(); if (!writeByteString(val)) { return false; } } } return true; } // Write a boolean value; warning: not thread safe without locking! bool File::writeBool(const bool value) { if (!valid) return false; unsigned char toWrite = value ? 0xFF : 0x00; // Write the value to the file if (fwrite(&toWrite, 1, 1, stream) != 1) { return false; } return true; } // Rewind the file bool File::rewind() { if (!valid) return false; ::rewind(stream); return true; } // Truncate the file bool File::truncate() { if (!valid) return false; #ifndef _WIN32 return (::ftruncate(fileno(stream), 0) == 0); #else return (_chsize(_fileno(stream), 0) == 0); #endif } // Seek to the specified position relative to the start of the file; if no // argument is specified this operation seeks to the end of the file bool File::seek(long offset /* = -1 */) { if (offset == -1) { return valid && (valid = !fseek(stream, 0, SEEK_END)); } else { return valid && (valid = !fseek(stream, offset, SEEK_SET)); } } // Lock the file bool File::lock(bool block /* = true */) { #ifndef _WIN32 struct flock fl; fl.l_type = isWrite() ? F_WRLCK : F_RDLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = 0; if (locked || !valid) return false; if (fcntl(fileno(stream), block ? F_SETLKW : F_SETLK, &fl) != 0) { ERROR_MSG("Could not lock the file: %s", strerror(errno)); return false; } #else HANDLE hFile; DWORD flags = 0; OVERLAPPED o; if (isWrite()) flags |= LOCKFILE_EXCLUSIVE_LOCK; if (!block) flags |= LOCKFILE_FAIL_IMMEDIATELY; if (locked || !valid) return false; hFile = (HANDLE) _get_osfhandle(_fileno(stream)); if (hFile == INVALID_HANDLE_VALUE) { ERROR_MSG("Invalid handle"); return false; } memset(&o, 0, sizeof(o)); if (!LockFileEx(hFile, flags, 0, 1, 0, &o)) { DWORD rv = GetLastError(); ERROR_MSG("Could not lock the file: 0x%08x", rv); return false; } #endif locked = true; return true; } // Unlock the file bool File::unlock() { #ifndef _WIN32 struct flock fl; fl.l_type = F_UNLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = 0; if (!locked || !valid) return false; if (fcntl(fileno(stream), F_SETLK, &fl) != 0) { valid = false; ERROR_MSG("Could not unlock the file: %s", strerror(errno)); return false; } #else HANDLE hFile; OVERLAPPED o; if (!locked || !valid) return false; hFile = (HANDLE) _get_osfhandle(_fileno(stream)); if (hFile == INVALID_HANDLE_VALUE) { ERROR_MSG("Invalid handle"); return false; } memset(&o, 0, sizeof(o)); if (!UnlockFileEx(hFile, 0, 1, 0, &o)) { DWORD rv = GetLastError(); valid = false; ERROR_MSG("Could not unlock the file: 0x%08x", rv); return false; } #endif locked = false; return valid; } // Flush the buffered stream to background storage bool File::flush() { return valid && !fflush(stream); } softhsm-2.0.0/src/lib/object_store/ObjectFile.cpp0000664000175000017500000003533512533040716016662 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectFile.h This class represents object files *****************************************************************************/ #include "config.h" #include "ObjectFile.h" #include "OSToken.h" #include "OSPathSep.h" #ifndef _WIN32 #include #endif #include #include // Attribute types #define BOOLEAN_ATTR 0x1 #define ULONG_ATTR 0x2 #define BYTESTR_ATTR 0x3 #define ARRAY_ATTR 0x4 // Constructor ObjectFile::ObjectFile(OSToken* parent, std::string inPath, std::string inLockpath, bool isNew /* = false */) { path = inPath; gen = Generation::create(path); objectMutex = MutexFactory::i()->getMutex(); valid = (gen != NULL) && (objectMutex != NULL); token = parent; inTransaction = false; transactionLockFile = NULL; lockpath = inLockpath; if (!valid) return; if (!isNew) { DEBUG_MSG("Opened existing object %s", path.c_str()); refresh(true); } else { DEBUG_MSG("Created new object %s", path.c_str()); // Create an empty object file store(); } } // Destructor ObjectFile::~ObjectFile() { discardAttributes(); if (gen != NULL) { delete gen; } MutexFactory::i()->recycleMutex(objectMutex); } // Check if the specified attribute exists bool ObjectFile::attributeExists(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); return valid && (attributes[type] != NULL); } // Retrieve the specified attribute OSAttribute ObjectFile::getAttribute(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return OSAttribute((unsigned long)0); } return *attr; } bool ObjectFile::getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val) { MutexLocker lock(objectMutex); OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return val; } if (attr->isBooleanAttribute()) { return attr->getBooleanValue(); } else { ERROR_MSG("The attribute is not a boolean: 0x%08X", type); return val; } } unsigned long ObjectFile::getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val) { MutexLocker lock(objectMutex); OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return val; } if (attr->isUnsignedLongAttribute()) { return attr->getUnsignedLongValue(); } else { ERROR_MSG("The attribute is not an unsigned long: 0x%08X", type); return val; } } ByteString ObjectFile::getByteStringValue(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); ByteString val; OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return val; } if (attr->isByteStringAttribute()) { return attr->getByteStringValue(); } else { ERROR_MSG("The attribute is not a byte string: 0x%08X", type); return val; } } // Retrieve the next attribute type CK_ATTRIBUTE_TYPE ObjectFile::nextAttributeType(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); std::map::iterator n = attributes.upper_bound(type); // skip null attributes while ((n != attributes.end()) && (n->second == NULL)) ++n; // return type or CKA_CLASS (= 0) if (n == attributes.end()) { return CKA_CLASS; } else { return n->first; } } // Set the specified attribute bool ObjectFile::setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute) { if (!valid) { DEBUG_MSG("Cannot update invalid object %s", path.c_str()); return false; } { MutexLocker lock(objectMutex); if (attributes[type] != NULL) { delete attributes[type]; attributes[type] = NULL; } attributes[type] = new OSAttribute(attribute); } store(); return valid; } // The validity state of the object (refresh from disk as a side effect) bool ObjectFile::isValid() { refresh(); return valid; } // Invalidate the object file externally; this method is normally // only called by the OSToken class in case an object file has // been deleted. void ObjectFile::invalidate() { valid = false; discardAttributes(); } // Refresh the object if necessary void ObjectFile::refresh(bool isFirstTime /* = false */) { // Check if we're in the middle of a transaction if (inTransaction) { return; } // Refresh the associated token if set if (!isFirstTime && (token != NULL)) { // This may cause this instance to become invalid token->index(); } // Check the generation if (!isFirstTime && (!valid || !gen->wasUpdated())) { return; } File objectFile(path); if (!objectFile.isValid()) { valid = false; return; } DEBUG_MSG("Object %s has changed", path.c_str()); // Discard the existing set of attributes discardAttributes(); objectFile.lock(); MutexLocker lock(objectMutex); // Read back the generation number unsigned long curGen; if (!objectFile.readULong(curGen)) { if (!objectFile.isEOF()) { DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; objectFile.unlock(); return; } } else { gen->set(curGen); } // Read back the attributes while (!objectFile.isEOF()) { unsigned long p11AttrType; unsigned long osAttrType; if (!objectFile.readULong(p11AttrType)) { if (objectFile.isEOF()) { break; } DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; objectFile.unlock(); return; } if (!objectFile.readULong(osAttrType)) { DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; return; } // Depending on the type, read back the actual value if (osAttrType == BOOLEAN_ATTR) { bool value; if (!objectFile.readBool(value)) { DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; return; } if (attributes[p11AttrType] != NULL) { delete attributes[p11AttrType]; } attributes[p11AttrType] = new OSAttribute(value); } else if (osAttrType == ULONG_ATTR) { unsigned long value; if (!objectFile.readULong(value)) { DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; return; } if (attributes[p11AttrType] != NULL) { delete attributes[p11AttrType]; } attributes[p11AttrType] = new OSAttribute(value); } else if (osAttrType == BYTESTR_ATTR) { ByteString value; if (!objectFile.readByteString(value)) { DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; return; } if (attributes[p11AttrType] != NULL) { delete attributes[p11AttrType]; } attributes[p11AttrType] = new OSAttribute(value); } else if (osAttrType == ARRAY_ATTR) { std::map value; if (!objectFile.readArray(value)) { DEBUG_MSG("Corrupt object file %s", path.c_str()); valid = false; return; } if (attributes[p11AttrType] != NULL) { delete attributes[p11AttrType]; } attributes[p11AttrType] = new OSAttribute(value); } else { DEBUG_MSG("Corrupt object file %s with unknown attribute of type %d", path.c_str(), osAttrType); valid = false; return; } } objectFile.unlock(); valid = true; } // Common write part in store() // called with objectFile locked and returns with objectFile unlocked bool ObjectFile::writeAttributes(File &objectFile) { if (!gen->sync(objectFile)) { DEBUG_MSG("Failed to synchronize generation number from object %s", path.c_str()); objectFile.unlock(); return false; } if (!objectFile.truncate()) { DEBUG_MSG("Failed to reset object %s", path.c_str()); objectFile.unlock(); return false; } gen->update(); unsigned long newGen = gen->get(); if (!objectFile.writeULong(newGen)) { DEBUG_MSG("Failed to write new generation number to object %s", path.c_str()); gen->rollback(); objectFile.unlock(); return false; } for (std::map::iterator i = attributes.begin(); i != attributes.end(); i++) { if (i->second == NULL) { continue; } unsigned long p11AttrType = i->first; if (!objectFile.writeULong(p11AttrType)) { DEBUG_MSG("Failed to write PKCS #11 attribute type to object %s", path.c_str()); objectFile.unlock(); return false; } if (i->second->isBooleanAttribute()) { unsigned long osAttrType = BOOLEAN_ATTR; bool value = i->second->getBooleanValue(); if (!objectFile.writeULong(osAttrType) || !objectFile.writeBool(value)) { DEBUG_MSG("Failed to write attribute to object %s", path.c_str()); objectFile.unlock(); return false; } } else if (i->second->isUnsignedLongAttribute()) { unsigned long osAttrType = ULONG_ATTR; unsigned long value = i->second->getUnsignedLongValue(); if (!objectFile.writeULong(osAttrType) || !objectFile.writeULong(value)) { DEBUG_MSG("Failed to write attribute to object %s", path.c_str()); objectFile.unlock(); return false; } } else if (i->second->isByteStringAttribute()) { unsigned long osAttrType = BYTESTR_ATTR; const ByteString& value = i->second->getByteStringValue(); if (!objectFile.writeULong(osAttrType) || !objectFile.writeByteString(value)) { DEBUG_MSG("Failed to write attribute to object %s", path.c_str()); objectFile.unlock(); return false; } } else if (i->second->isArrayAttribute()) { unsigned long osAttrType = ARRAY_ATTR; const std::map& value = i->second->getArrayValue(); if (!objectFile.writeULong(osAttrType) || !objectFile.writeArray(value)) { DEBUG_MSG("Failed to write attribute to object %s", path.c_str()); objectFile.unlock(); return false; } } else { DEBUG_MSG("Unknown attribute type for object %s", path.c_str()); objectFile.unlock(); return false; } } objectFile.unlock(); return true; } // Write the object to background storage void ObjectFile::store(bool isCommit /* = false */) { // Check if we're in the middle of a transaction if (!isCommit && inTransaction) { return; } if (!valid) { DEBUG_MSG("Cannot write back an invalid object %s", path.c_str()); return; } File objectFile(path, true, true, true, false); if (!objectFile.isValid()) { DEBUG_MSG("Cannot open object %s for writing", path.c_str()); valid = false; return; } objectFile.lock(); if (!isCommit) { MutexLocker lock(objectMutex); File lockFile(lockpath, false, true, true); if (!writeAttributes(objectFile)) { valid = false; return; } } else { if (!writeAttributes(objectFile)) { valid = false; return; } } valid = true; } // Discard the cached attributes void ObjectFile::discardAttributes() { MutexLocker lock(objectMutex); std::map cleanUp = attributes; attributes.clear(); for (std::map::iterator i = cleanUp.begin(); i != cleanUp.end(); i++) { if (i->second == NULL) { continue; } delete i->second; i->second = NULL; } } // Returns the file name of the object std::string ObjectFile::getFilename() const { if ((path.find_last_of(OS_PATHSEP) != std::string::npos) && (path.find_last_of(OS_PATHSEP) < path.size())) { return path.substr(path.find_last_of(OS_PATHSEP) + 1); } else { return path; } } // Returns the file name of the lock std::string ObjectFile::getLockname() const { if ((lockpath.find_last_of(OS_PATHSEP) != std::string::npos) && (lockpath.find_last_of(OS_PATHSEP) < lockpath.size())) { return lockpath.substr(lockpath.find_last_of(OS_PATHSEP) + 1); } else { return lockpath; } } // Start an attribute set transaction; this method is used when - for // example - a key is generated and all its attributes need to be // persisted in one go. // // N.B.: Starting a transaction locks the object! bool ObjectFile::startTransaction(Access) { MutexLocker lock(objectMutex); if (inTransaction) { return false; } transactionLockFile = new File(lockpath, false, true, true); if (!transactionLockFile->isValid() || !transactionLockFile->lock()) { delete transactionLockFile; transactionLockFile = NULL; ERROR_MSG("Failed to lock file %s for attribute transaction", lockpath.c_str()); return false; } inTransaction = true; return true; } // Commit an attribute transaction bool ObjectFile::commitTransaction() { MutexLocker lock(objectMutex); if (!inTransaction) { return false; } if (transactionLockFile == NULL) { ERROR_MSG("Transaction lock file instance invalid!"); return false; } // Special store case store(true); if (!valid) { return false; } transactionLockFile->unlock(); delete transactionLockFile; transactionLockFile = NULL; inTransaction = false; return true; } // Abort an attribute transaction; loads back the previous version of the object from disk bool ObjectFile::abortTransaction() { { MutexLocker lock(objectMutex); if (!inTransaction) { return false; } if (transactionLockFile == NULL) { ERROR_MSG("Transaction lock file instance invalid!"); return false; } transactionLockFile->unlock(); delete transactionLockFile; transactionLockFile = NULL; inTransaction = false; } // Force reload from disk refresh(true); return true; } // Destroy the object; WARNING: pointers to the object become invalid after this call bool ObjectFile::destroyObject() { if (token == NULL) { ERROR_MSG("Cannot destroy an object that is not associated with a token"); return false; } return token->deleteObject(this); } softhsm-2.0.0/src/lib/object_store/SessionObjectStore.cpp0000664000175000017500000001341412533040716020435 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObjectStore.cpp The token class; a token is stored in a directory containing several files. Each object is stored in a separate file and a token object is present that has the token specific attributes *****************************************************************************/ #include "config.h" #include "log.h" #include "OSAttributes.h" #include "OSAttribute.h" #include "SessionObject.h" #include "cryptoki.h" #include "SessionObjectStore.h" #include #include #include #include #include // Constructor SessionObjectStore::SessionObjectStore() { storeMutex = MutexFactory::i()->getMutex(); } // Destructor SessionObjectStore::~SessionObjectStore() { // Clean up objects.clear(); std::set cleanUp = allObjects; allObjects.clear(); for (std::set::iterator i = cleanUp.begin(); i != cleanUp.end(); i++) { if ((*i) == NULL) continue; SessionObject* that = *i; delete that; } MutexFactory::i()->recycleMutex(storeMutex); } // Retrieve objects std::set SessionObjectStore::getObjects() { // Make sure that no other thread is in the process of changing // the object list when we return it MutexLocker lock(storeMutex); return objects; } void SessionObjectStore::getObjects(CK_SLOT_ID slotID, std::set &inObjects) { // Make sure that no other thread is in the process of changing // the object list when we return it MutexLocker lock(storeMutex); std::set::iterator it; for (it=objects.begin(); it!=objects.end(); ++it) { if ((*it)->hasSlotID(slotID)) inObjects.insert(*it); } } // Create a new object SessionObject* SessionObjectStore::createObject(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession, bool isPrivate) { // Create the new object file SessionObject* newObject = new SessionObject(this, slotID, hSession, isPrivate); if (!newObject->isValid()) { ERROR_MSG("Failed to create new object"); delete newObject; return NULL; } // Now add it to the set of objects MutexLocker lock(storeMutex); objects.insert(newObject); allObjects.insert(newObject); DEBUG_MSG("(0x%08X) Created new object (0x%08X)", this, newObject); return newObject; } // Delete an object bool SessionObjectStore::deleteObject(SessionObject* object) { if (objects.find(object) == objects.end()) { ERROR_MSG("Cannot delete non-existent object 0x%08X", object); return false; } MutexLocker lock(storeMutex); // Invalidate the object instance object->invalidate(); objects.erase(object); return true; } // Indicate that a session has been closed; invalidates all objects // associated with this session void SessionObjectStore::sessionClosed(CK_SESSION_HANDLE hSession) { MutexLocker lock(storeMutex); std::set checkObjects = objects; for (std::set::iterator i = checkObjects.begin(); i != checkObjects.end(); i++) { if ((*i)->removeOnSessionClose(hSession)) { // Since the object remains in the allObjects set, any pointers to it will // remain valid but it will no longer be returned when the set of objects // is requested objects.erase(*i); } } } void SessionObjectStore::allSessionsClosed(CK_SLOT_ID slotID) { MutexLocker lock(storeMutex); std::set checkObjects = objects; for (std::set::iterator i = checkObjects.begin(); i != checkObjects.end(); i++) { if ((*i)->removeOnAllSessionsClose(slotID)) { // Since the object remains in the allObjects set, any pointers to it will // remain valid but it will no longer be returned when the set of objects // is requested objects.erase(*i); } } } void SessionObjectStore::tokenLoggedOut(CK_SLOT_ID slotID) { MutexLocker lock(storeMutex); std::set checkObjects = objects; for (std::set::iterator i = checkObjects.begin(); i != checkObjects.end(); i++) { if ((*i)->removeOnTokenLogout(slotID)) { // Since the object remains in the allObjects set, any pointers to it will // remain valid but it will no longer be returned when the set of objects // is requested objects.erase(*i); } } } // Clear the whole store void SessionObjectStore::clearStore() { MutexLocker lock(storeMutex); objects.clear(); std::set clearObjects = allObjects; allObjects.clear(); for (std::set::iterator i = clearObjects.begin(); i != clearObjects.end(); i++) { delete *i; } } softhsm-2.0.0/src/lib/object_store/Makefile.am0000664000175000017500000000145012533040716016173 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../common \ -I$(srcdir)/.. \ @SQLITE3_INCLUDES@ noinst_LTLIBRARIES = libsofthsm_objectstore.la libsofthsm_objectstore_la_SOURCES = ObjectStore.cpp \ UUID.cpp \ Directory.cpp \ File.cpp \ Generation.cpp \ OSAttribute.cpp \ OSToken.cpp \ ObjectFile.cpp \ SessionObject.cpp \ SessionObjectStore.cpp \ FindOperation.cpp \ ObjectStoreToken.cpp if BUILD_OBJECTSTORE_BACKEND_DB libsofthsm_objectstore_la_SOURCES += DB.cpp \ DBObject.cpp \ DBToken.cpp endif libsofthsm_objectstore_la_LDFLAGS = @SQLITE3_LIBS@ SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/object_store/ObjectStore.h0000664000175000017500000000533612533040716016542 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectStore.h The object store manages the separate tokens that the SoftHSM supports. Each token is organised as a directory containing files that are contain the token's objects. The object store is initialised with a root directory from which it enumerates the tokens. *****************************************************************************/ #ifndef _SOFTHSM_V2_OBJECTSTORE_H #define _SOFTHSM_V2_OBJECTSTORE_H #include "config.h" #include "ByteString.h" #include "ObjectStoreToken.h" #include "MutexFactory.h" #include #include class ObjectStore { public: // Constructor ObjectStore(std::string inStorePath); // Destructor virtual ~ObjectStore(); // Return the number of tokens that is present size_t getTokenCount(); // Return a pointer to the n-th token (counting starts at 0) ObjectStoreToken* getToken(size_t whichToken); // Create a new token ObjectStoreToken* newToken(const ByteString& label); // Destroy a token bool destroyToken(ObjectStoreToken* token); // Check if the object store is valid bool isValid(); private: // The tokens std::vector tokens; // All tokens std::vector allTokens; // The object store root directory std::string storePath; // The status bool valid; // Object store synchronisation Mutex* storeMutex; }; #endif // !_SOFTHSM_V2_OBJECTSTORE_H softhsm-2.0.0/src/lib/object_store/ObjectStoreToken.cpp0000664000175000017500000000643112533040716020073 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectStoreToken.cpp The object store abstract token base class *****************************************************************************/ #include "config.h" #include "log.h" #include "ObjectStoreToken.h" // OSToken is a concrete implementation of ObjectStoreToken base class. #include "OSToken.h" #ifdef HAVE_OBJECTSTORE_BACKEND_DB // DBToken is a concrete implementation of ObjectSToreToken that stores the objects and attributes in an SQLite3 database. #include "DBToken.h" #endif typedef ObjectStoreToken* (*CreateToken)(const std::string , const std::string , const ByteString& , const ByteString& ); typedef ObjectStoreToken* (*AccessToken)(const std::string &, const std::string &); static CreateToken static_createToken = reinterpret_cast(OSToken::createToken); static AccessToken static_accessToken = reinterpret_cast(OSToken::accessToken); // Create a new token /*static*/ bool ObjectStoreToken::selectBackend(const std::string &backend) { if (backend == "file") { static_createToken = reinterpret_cast(OSToken::createToken); static_accessToken = reinterpret_cast(OSToken::accessToken); } #ifdef HAVE_OBJECTSTORE_BACKEND_DB else if (backend == "db") { static_createToken = reinterpret_cast(DBToken::createToken); static_accessToken = reinterpret_cast(DBToken::accessToken); } #endif else { ERROR_MSG("Unknown value (%s) for objectstore.backend in configuration", backend.c_str()); return false; } return true; } ObjectStoreToken* ObjectStoreToken::createToken(const std::string basePath, const std::string tokenDir, const ByteString& label, const ByteString& serial) { return static_createToken(basePath,tokenDir,label,serial); } // Access an existing token /*static*/ ObjectStoreToken *ObjectStoreToken::accessToken(const std::string &basePath, const std::string &tokenDir) { return static_accessToken(basePath, tokenDir); } softhsm-2.0.0/src/lib/object_store/Generation.h0000664000175000017500000000502112533040716016401 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Generation.h Helper for generation number handling. *****************************************************************************/ #ifndef _SOFTHSM_V2_GENERATION_H #define _SOFTHSM_V2_GENERATION_H #include "config.h" #include #include "File.h" #include "MutexFactory.h" class Generation { public: // Factory static Generation* create(const std::string inPath, bool inIsToken = false); // Destructor virtual ~Generation(); // Synchronize from locked disk file bool sync(File &objectfile); // Check if the target was updated bool wasUpdated(); // Note pending update void update(); // Commit (for the token case) void commit(); // Set the current value when read from disk void set(unsigned long onDisk); // Return new value unsigned long get(); // Rollback (called when the new value failed to be written) void rollback(); private: // Constructor Generation(const std::string path, bool isToken); // The file path std::string path; // isToken bool isToken; // Pending update bool pendingUpdate; // Current value unsigned long currentValue; // For thread safeness Mutex* genMutex; }; #endif // !_SOFTHSM_V2_GENERATION_H softhsm-2.0.0/src/lib/object_store/DB.cpp0000664000175000017500000005326412533040716015142 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DB.cpp Specifies classes to access the Token Database *****************************************************************************/ #define HAVE_SQL_TRACE 0 #include "config.h" #include "OSPathSep.h" #include "log.h" #include #include #include #include #include #include #include #include #include #include #include "DB.h" #if HAVE_SQL_TRACE static void xTrace(void*connectionLabel,const char*zSql) { const char *label = static_cast(connectionLabel); if (label) std::cout << std::endl << label << ": " << zSql ; else std::cout << std::endl << zSql ; } #endif static int static_log_err(const char *format, va_list ap) { std::vector logMessage; logMessage.resize(4096); vsnprintf(&logMessage[0], 4096, format, ap); ERROR_MSG(&logMessage[0]); return 0; } static DB::LogErrorHandler static_LogErrorhandler = static_log_err; void DB::logError(const std::string &format, ...) { if (!static_LogErrorhandler) return; va_list args; va_start(args, format); static_LogErrorhandler(format.c_str(),args); va_end(args); } DB::LogErrorHandler DB::setLogErrorHandler(DB::LogErrorHandler handler) { LogErrorHandler temp = static_LogErrorhandler; static_LogErrorhandler = handler; return temp; } void DB::resetLogErrorHandler() { static_LogErrorhandler = static_log_err; } static void reportErrorDB(sqlite3 *db) { if (!db) { DB::logError("sqlite3 pointer is NULL"); return; } int rv = sqlite3_errcode(db); if (rv == SQLITE_OK || rv == SQLITE_ROW || rv == SQLITE_DONE) return; #ifdef HAVE_SILENT_BUSY_AND_LOCKED_ERRORS // Either the database file is locked (SQLITE_BUSY) // or a table in the database is locked (SQLITE_LOCKED) if (rv == SQLITE_BUSY || rv == SQLITE_LOCKED) return; #endif DB::logError("SQLITE3: %s (%d)", sqlite3_errmsg(db), rv); } static void reportError(sqlite3_stmt *stmt) { if (!stmt) { DB::logError("sqlite3_stmt pointer is NULL"); return; } reportErrorDB(sqlite3_db_handle(stmt)); } static time_t sqlite3_gmtime(struct tm *tm) { // We don't want to depend on timegm() so we use a workaround via the // gmtime_r() function to determine this. // As input we use a moment in time just 10 days after the POSIX epoch. // The POSIX epoch is defined as the moment in time at midnight Coordinated // Universal Time (UTC) of Thursday, January 1, 1970. A time_t value is // the number of seconds elapsed since epoch. struct tm ref_tm = {0,0,0,0,0,0,0,0,0,0,0}; ref_tm.tm_year = 70; // Years since 1900; ref_tm.tm_mday = 10; // 10th // We need the time difference between local time and UTC time. // mktime will interpret the UTC time stored in tm as local time // so let's assume we are in a time zone 1 hour ahead of UTC (UTC+1) // then a time of 13:00 interpreted as local time needs 1 hour subtracted // to arrive at UTC time. This UTC time is then converted to a POSIX // time_t value. time_t posix_time = mktime(&ref_tm); // Use gmtime_r to convert the POSIX time back to a tm struct. // No time adjustment is done this time because POSIX time is // defined in terms of UTC. gmtime_r(&posix_time, &ref_tm); if (ref_tm.tm_isdst != 0) { DB::logError("expected gmtime_r to return zero in tm_isdst member of tm struct"); return ((time_t)-1); } // Using mktime again to convert tm. This will again subtract 1 hour from // the time (under the assumption that we are 1 hour ahead of UTC). // We can now use this to determine how much local time differred // from UTC time on january the 10th 1970 long diff_time = posix_time - mktime(&ref_tm); // We explicitly set tm_isdst to zero to prevent errors // when the time we are trying to convert is occuring at // the moment when a dst change is in progress. // We require mktime to respect our setting of tm_isdst // indicating that no dst is in effect. tm->tm_isdst = 0; // Tell (and force) mktime not to take dst into account. // We now can calculate and return a correct POSIX time. // So, although mktime() interprets gm_tm as local time adjusts for // the time difference between local time and UTC time. We then undo // that adjustment by adding diff_time. return mktime(tm) + diff_time; } /************************** * Handle **************************/ class DB::Handle { public: int _refcount; sqlite3_stmt *_stmt; Handle(sqlite3_stmt *stmt) : _refcount(1), _stmt(stmt) { } ~Handle() { if (_stmt) { sqlite3_finalize(_stmt); _stmt = NULL; } } Handle *retain() { if (_refcount) { _refcount++; return this; } return NULL; } void release() { if (_refcount) { _refcount--; if (_refcount) return; delete this; } } bool reset() { if (sqlite3_reset(_stmt) != SQLITE_OK) { reportError(_stmt); return false; } return true; } Statement::ReturnCode step() { int rv = sqlite3_step(_stmt); if (rv != SQLITE_ROW && rv != SQLITE_DONE) { reportError(_stmt); return Statement::ReturnCodeError; } if (rv==SQLITE_ROW) { return Statement::ReturnCodeRow; } return Statement::ReturnCodeDone; } private: // disable evil constructors Handle(const Handle &); Handle & operator=(const Handle &); }; DB::Statement::Statement() : _handle(NULL) { } DB::Statement::Statement(sqlite3_stmt *statement) : _handle(new Handle(statement)) { } DB::Statement::Statement(const DB::Statement &statement) : _handle(statement._handle) { if (_handle) _handle = _handle->retain(); } DB::Statement &DB::Statement::operator=(const DB::Statement &statement) { if (this != &statement) { Handle *tmp = NULL; if (statement._handle) { tmp = statement._handle->retain(); } if (_handle) { _handle->release(); } _handle = tmp; } return *this; } DB::Statement::~Statement() { if (_handle) { _handle->release(); _handle = NULL; } } bool DB::Statement::isValid() { return _handle != NULL && _handle->_stmt != NULL; } int DB::Statement::refcount() { return _handle ? _handle->_refcount : 0; } bool DB::Statement::reset() { if (!isValid()) { DB::logError("Statement::reset: statement is not valid"); return false; } return _handle->reset(); } DB::Statement::ReturnCode DB::Statement::step() { if (!isValid()) { DB::logError("Statement::step: statement is not valid"); return ReturnCodeError; } return _handle->step(); } DB::Handle *DB::Statement::handle() const { return _handle; } /************************** * Bindings **************************/ DB::Bindings::Bindings() : Statement() { } DB::Bindings::Bindings(const Statement &statement) : Statement(statement) { } bool DB::Bindings::clear() { if (!isValid()) { DB::logError("Bindings::clear: statement is not valid"); return false; } if (sqlite3_clear_bindings(_handle->_stmt) != SQLITE_OK) { reportError(_handle->_stmt); return false; } return true; } bool DB::Bindings::bindBlob(int index, const void *value, int n, void(*destruct)(void*)) { if (!isValid()) { DB::logError("Bindings::bindBlob: statement is not valid"); return false; } if (sqlite3_bind_blob(_handle->_stmt, index, value, n, destruct) != SQLITE_OK) { reportError(_handle->_stmt); return false; } return true; } bool DB::Bindings::bindDouble(int index, double value) { if (!isValid()) { DB::logError("Bindings::bindDouble: statement is not valid"); return false; } if (sqlite3_bind_double(_handle->_stmt, index, value) != SQLITE_OK) { reportError(_handle->_stmt); return false; } return true; } bool DB::Bindings::bindInt(int index, int value) { if (!isValid()) { DB::logError("Bindings::bindInt: statement is not valid"); return false; } if (sqlite3_bind_int(_handle->_stmt, index, value) != SQLITE_OK) { reportError(_handle->_stmt); return false; } return true; } bool DB::Bindings::bindInt64(int index, long long value) { if (!isValid()) { DB::logError("Bindings::bindInt64: statement is not valid"); return false; } if (sqlite3_bind_int64(_handle->_stmt, index, value) != SQLITE_OK) { reportError(_handle->_stmt); return false; } return true; } //bool DB::Bindings::bindNull(int index) //{ //#if 0 // int sqlite3_bind_null(sqlite3_stmt*, int); //#endif // return false; //} bool DB::Bindings::bindText(int index, const char *value, int n, void (*destruct)(void *)) { if (!isValid()) { DB::logError("Bindings::bindText: statement is not valid"); return false; } if (sqlite3_bind_text(_handle->_stmt, index, value, n, destruct) != SQLITE_OK) { reportError(_handle->_stmt); return false; } return true; } //bool DB::Bindings::bindZeroBlob(int index, int n) //{ //#if 0 // int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); //#endif // return false; //} /************************** * Result **************************/ DB::Result::Result() : Statement() { } DB::Result::Result(const Statement &statement) : Statement(statement) { } #if 0 unsigned int DB::Result::getField(const std::string &fieldname) { unsigned int fieldidx = fields[fieldname]; if (fieldidx == 0) DB::logError("Result: invalid field name \"%s\"",fieldname.c_str()); return fieldidx; } #endif bool DB::Result::fieldIsNull(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::fieldIsNull: statement is not valid"); return true; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return true; } int column_type = sqlite3_column_type(_handle->_stmt, fieldidx-1); return column_type == SQLITE_NULL; } time_t DB::Result::getDatetime(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getDatetime: statement is not valid"); return ((time_t)-1); } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return ((time_t)-1); } const unsigned char *value = sqlite3_column_text(_handle->_stmt, fieldidx-1); int valuelen = sqlite3_column_bytes(_handle->_stmt, fieldidx-1); unsigned long years,mons,days,hours,mins,secs; struct tm gm_tm = {0,0,0,0,0,0,0,0,0,0,0}; gm_tm.tm_isdst = 0; // Tell mktime not to take dst into account. gm_tm.tm_year = 70; // 1970 gm_tm.tm_mday = 1; // 1th day of the month const char *p = (const char *)value; char *pnext; bool bdateonly = true; switch (valuelen) { case 19: // 2011-12-31 23:59:59 bdateonly = false; // falls through to next case case 10: // 2011-12-31 years = strtoul(p,&pnext,10); gm_tm.tm_year = ((int)years)-1900; /* years since 1900 */ p = pnext+1; mons = strtoul(p,&pnext,10); gm_tm.tm_mon = ((int)mons)-1; /* months since January [0-11] */ p = pnext+1; days = strtoul(p,&pnext,10); gm_tm.tm_mday = ((int)days); /* day of the month [1-31] */ p = pnext+1; if (bdateonly) break; // falls through to next case case 8: // 23:59:59 hours = strtoul(p,&pnext,10); gm_tm.tm_hour = (int)hours; /* hours since midnight [0-23] */ if ((pnext-p) != 2) { DB::logError("Result: invalid hours in time: '%s'",value); return 0; } p = pnext+1; mins = strtoul(p,&pnext,10); gm_tm.tm_min = (int)mins; /* minutes after the hour [0-59] */ if ((pnext-p) != 2) { DB::logError("Result: invalid minutes in time: '%s'",value); return 0; } p = pnext+1; secs = strtoul(p,&pnext,10); gm_tm.tm_sec = (int)secs; /* seconds after the minute [0-60] */ if ((pnext-p) != 2) { DB::logError("Result: invalid seconds in time: '%s'",value); return 0; } break; default: DB::logError("Result: invalid date/time value: '%s'",value); return 0; } return sqlite3_gmtime(&gm_tm); } unsigned char DB::Result::getUChar(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getUChar: statement is not valid"); return 0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0; } int value = sqlite3_column_int(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return (unsigned char)value; } float DB::Result::getFloat(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getFloat: statement is not valid"); return 0.0f; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0.0f; } double value = sqlite3_column_double(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return (float)value; } double DB::Result::getDouble(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getDouble: statement is not valid"); return 0.0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0.0; } double value = sqlite3_column_double(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return value; } int DB::Result::getInt(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getInt: statement is not valid"); return 0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0; } int value = sqlite3_column_int(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return value; } unsigned int DB::Result::getUInt(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getUInt: statement is not valid"); return 0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0; } int value = sqlite3_column_int(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return (unsigned int)value; } long long DB::Result::getLongLong(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getLongLong: statement is not valid"); return 0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0; } sqlite3_int64 value = sqlite3_column_int64(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return value; } unsigned long long DB::Result::getULongLong(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getULongLong: statement is not valid"); return 0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0; } sqlite3_int64 value = sqlite3_column_int64(_handle->_stmt, fieldidx-1); reportError(_handle->_stmt); return (unsigned long long)value; } const char *DB::Result::getString(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getString: statement is not valid"); return NULL; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return NULL; } const unsigned char *value = sqlite3_column_text(_handle->_stmt,fieldidx-1); reportError(_handle->_stmt); return (const char *)value; } const unsigned char *DB::Result::getBinary(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getBinary: statement is not valid"); return NULL; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return NULL; } const unsigned char *value = (const unsigned char *)sqlite3_column_blob(_handle->_stmt,fieldidx-1); reportError(_handle->_stmt); return value; } size_t DB::Result::getFieldLength(unsigned int fieldidx) { if (!isValid()) { DB::logError("Result::getFieldLength: statement is not valid"); return 0; } if (fieldidx == 0) { DB::logError("Result: zero is an invalid field index"); return 0; } int value = sqlite3_column_bytes(_handle->_stmt,fieldidx-1); reportError(_handle->_stmt); return (size_t)value; } bool DB::Result::firstRow() { if (!isValid()) { DB::logError("Result::firstRow: statement is not valid"); return false; } return _handle->reset() && _handle->step()==Statement::ReturnCodeRow; } bool DB::Result::nextRow() { if (!isValid()) { DB::logError("Result::nextRow: statement is not valid"); return false; } return _handle->step()==Statement::ReturnCodeRow; } /************************** * Connection **************************/ DB::Connection *DB::Connection::Create(const std::string &dbdir, const std::string &dbname) { if (dbdir.length() == 0) { DB::logError("Connection::Create: database directory parameter dbdir is empty"); return NULL; } if (dbname.length() == 0) { DB::logError("Connection::Create: database name parameter dbname is empty"); return NULL; } return new Connection(dbdir,dbname); } DB::Connection::Connection(const std::string &dbdir, const std::string &dbname) : _dbdir(dbdir) , _dbpath(dbdir + OS_PATHSEP + dbname) , _db(NULL) { } DB::Connection::~Connection() { close(); } const std::string &DB::Connection::dbdir() { return _dbdir; } const std::string &DB::Connection::dbpath() { return _dbpath; } DB::Statement DB::Connection::prepare(const std::string &format, ...){ // pstatement will hold a dynamically allocated string that needs to be deleted. char *pstatement = NULL; // short form char statement[128]; va_list args; va_start(args, format); int cneeded = vsnprintf(statement,sizeof(statement),format.c_str(),args); va_end(args); if (cneeded<0) { DB::logError("Connection::prepare: vsnprintf encoding error"); return Statement(); } if (((size_t)cneeded)>=sizeof(statement)) { // long form pstatement = new char[cneeded+1]; if (!pstatement) { DB::logError("Connection::prepare: out of memory"); return Statement(); } va_start(args, format); bool ok = vsnprintf(pstatement,cneeded+1,format.c_str(),args)==cneeded; va_end(args); if (!ok) { DB::logError("Connection::prepare: vsnprintf error"); delete[] pstatement; return Statement(); } } sqlite3_stmt *stmt = NULL; int rv = sqlite3_prepare_v2(_db, pstatement ? pstatement : statement, cneeded+1, &stmt, NULL); if (pstatement) delete[] pstatement; if (rv != SQLITE_OK) { reportErrorDB(_db); if (stmt) sqlite3_finalize(stmt); return Statement(); } if (!stmt) { DB::logError("Connection::prepare: expected sqlite3_prepare_v2 to return a compiled " "statement, got NULL, out of memory ?"); return Statement(); } return Statement(stmt); } DB::Result DB::Connection::perform(DB::Statement &statement) { return (statement.step()==Statement::ReturnCodeRow) ? Result(statement) : Result(); } bool DB::Connection::execute(DB::Statement &statement) { return statement.step()==Statement::ReturnCodeDone; } bool DB::Connection::connect(const char * #if HAVE_SQL_TRACE connectionLabel #endif ) { // Create and set file permissions if the DB does not exist. int fd = open(_dbpath.c_str(), O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { DB::logError("Could not open database: %s (errno %i)", _dbpath.c_str(), errno); return false; } ::close(fd); int rv = sqlite3_open_v2(_dbpath.c_str(), &_db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, NULL); if (rv != SQLITE_OK) { reportErrorDB(_db); return false; } int foreignKeyEnabled = 0; rv = sqlite3_db_config(_db,SQLITE_DBCONFIG_ENABLE_FKEY,1,&foreignKeyEnabled); if (rv != SQLITE_OK) { reportErrorDB(_db); return false; } if (foreignKeyEnabled != 1) { DB::logError("Connection::connect: foreign key support not enabled"); return false; } rv = sqlite3_busy_timeout(_db, 15000); // 15 seconds if (rv != SQLITE_OK) { reportErrorDB(_db); return false; } #if HAVE_SQL_TRACE sqlite3_trace(_db, xTrace, const_cast(connectionLabel)); #endif return true; } void DB::Connection::close() { if (_db) { sqlite3_close(_db); _db = NULL; } } bool DB::Connection::setBusyTimeout(int ms) { int rv = sqlite3_busy_timeout(_db, ms); if (rv != SQLITE_OK) { reportErrorDB(_db); return false; } return true; } bool DB::Connection::tableExists(const std::string &tablename) { Statement statement = prepare("select name from sqlite_master where type='table' and name='%s';",tablename.c_str()); return statement.step()==Statement::ReturnCodeRow && statement.step()==Statement::ReturnCodeDone; } long long DB::Connection::lastInsertRowId() { return sqlite3_last_insert_rowid(_db); } bool DB::Connection::inTransaction() { return sqlite3_get_autocommit(_db)==0; } bool DB::Connection::beginTransactionRO() { Statement statement = prepare("begin"); return statement.step()==Statement::ReturnCodeDone; } bool DB::Connection::endTransactionRO() { Statement statement = prepare("end"); return statement.step()==Statement::ReturnCodeDone; } bool DB::Connection::beginTransactionRW() { Statement statement = prepare("begin immediate"); return statement.step()==Statement::ReturnCodeDone; } bool DB::Connection::commitTransaction() { Statement statement = prepare("commit"); return statement.step()==Statement::ReturnCodeDone; } bool DB::Connection::rollbackTransaction() { Statement statement = prepare("rollback"); return statement.step()==Statement::ReturnCodeDone; } softhsm-2.0.0/src/lib/object_store/UUID.h0000664000175000017500000000354512533040716015065 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** UUID.h UUID generation helper functions; for now, this just wraps the OSF/DCE's UUID generation implementation, but if SoftHSM gets ported to non UNIX/BSD- like OSes this may incorporate other implementations *****************************************************************************/ #ifndef _SOFTHSM_V2_UUID_H #define _SOFTHSM_V2_UUID_H #include "config.h" #include namespace UUID { // Generate a new UUID string std::string newUUID(); }; #endif // !_SOFTHSM_V2_UUID_H softhsm-2.0.0/src/lib/object_store/OSAttribute.h0000664000175000017500000000563412533040716016525 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSAttribute.h This class represents the object store view on an object's attribute *****************************************************************************/ #ifndef _SOFTHSM_V2_OSATTRIBUTE_H #define _SOFTHSM_V2_OSATTRIBUTE_H #include "config.h" #include "ByteString.h" #include class OSAttribute { public: // Copy constructor OSAttribute(const OSAttribute& in); // Constructor for a boolean type attribute OSAttribute(const bool value); // Constructor for an unsigned long type attribute OSAttribute(const unsigned long value); // Constructor for a byte string type attribute OSAttribute(const ByteString& value); // Constructor for an array type attribute OSAttribute(const std::map& value); // Destructor virtual ~OSAttribute() { } // Check the attribute type bool isBooleanAttribute() const; bool isUnsignedLongAttribute() const; bool isByteStringAttribute() const; bool isArrayAttribute() const; // Retrieve the attribute value bool getBooleanValue() const; unsigned long getUnsignedLongValue() const; const ByteString& getByteStringValue() const; const std::map& getArrayValue() const; // Helper for template (aka array) matching bool peekValue(ByteString& value) const; private: // The attribute type enum { BOOL, ULONG, BYTESTR, ARRAY } attributeType; // The attribute value bool boolValue; unsigned long ulongValue; ByteString byteStrValue; std::map arrayValue; }; #endif // !_SOFTHSM_V2_OSATTRIBUTE_H softhsm-2.0.0/src/lib/object_store/ObjectFile.h0000664000175000017500000001144312533040716016321 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectFile.h This class represents object files *****************************************************************************/ #ifndef _SOFTHSM_V2_OBJECTFILE_H #define _SOFTHSM_V2_OBJECTFILE_H #include "config.h" #include "File.h" #include "Generation.h" #include "ByteString.h" #include "OSAttribute.h" #include "MutexFactory.h" #include #include #include #include "cryptoki.h" #include "OSObject.h" // OSToken forward declaration class OSToken; class ObjectFile : public OSObject { public: // Constructor ObjectFile(OSToken* parent, const std::string inPath, const std::string inLockpath, bool isNew = false); // Destructor virtual ~ObjectFile(); // Check if the specified attribute exists virtual bool attributeExists(CK_ATTRIBUTE_TYPE type); // Retrieve the specified attribute virtual OSAttribute getAttribute(CK_ATTRIBUTE_TYPE type); virtual bool getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val); virtual unsigned long getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val); virtual ByteString getByteStringValue(CK_ATTRIBUTE_TYPE type); // Retrieve the next attribute type virtual CK_ATTRIBUTE_TYPE nextAttributeType(CK_ATTRIBUTE_TYPE type); // Set the specified attribute virtual bool setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute); // The validity state of the object (refresh from disk as a side effect) virtual bool isValid(); // Invalidate the object file externally; this method is normally // only called by the OSToken class in case an object file has // been deleted. void invalidate(); // Returns the file name of the object std::string getFilename() const; // Returns the file name of the lock std::string getLockname() const; // Start an attribute set transaction; this method is used when - for // example - a key is generated and all its attributes need to be // persisted in one go. // // N.B.: Starting a transaction locks the object! // // Function returns false in case a transaction is already in progress virtual bool startTransaction(Access access); // Commit an attribute transaction; returns false if no transaction is in progress virtual bool commitTransaction(); // Abort an attribute transaction; loads back the previous version of the object from disk; // returns false if no transaction was in progress virtual bool abortTransaction(); // Destroys the object; WARNING: pointers to the object become invalid after this // call! virtual bool destroyObject(); private: // OSToken instances can read valid (vs calling IsValid() from index()) friend class OSToken; // Refresh the object if necessary void refresh(bool isFirstTime = false); // Write the object to background storage void store(bool isCommit = false); // Store subroutine bool writeAttributes(File &objectFile); // Discard the cached attributes void discardAttributes(); // The path to the file std::string path; // The Generation object that is used to detect changes in the // object file from other SoftHSM instances Generation* gen; // The object's raw attributes std::map attributes; // The object's validity state bool valid; // The token this object is associated with OSToken* token; // Mutex object for thread-safeness Mutex* objectMutex; // Is the object undergoing an attribute transaction? bool inTransaction; File* transactionLockFile; std::string lockpath; }; #endif // !_SOFTHSM_V2_OBJECTFILE_H softhsm-2.0.0/src/lib/object_store/FindOperation.cpp0000664000175000017500000000515512533040716017412 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** FindOperation.cpp This class represents the find operation that can be used to collect objects that match the attributes contained in a given template. *****************************************************************************/ #include "config.h" #include "FindOperation.h" FindOperation::FindOperation() { } FindOperation *FindOperation::create() { return new FindOperation(); } void FindOperation::recycle() { delete this; } void FindOperation::setHandles(const std::set &handles) { _handles = handles; } CK_ULONG FindOperation::retrieveHandles(CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulCount) { CK_ULONG ulReturn = 0; std::set::const_iterator it; for (it=_handles.begin(); it != _handles.end(); ++it) { if (ulReturn >= ulCount) break; phObject[ulReturn++] = *it; } return ulReturn; } CK_ULONG FindOperation::eraseHandles(CK_ULONG ulIndex, CK_ULONG ulCount) { std::set::const_iterator it; for (it=_handles.begin(); it != _handles.end() && ulIndex != 0; --ulIndex) { ++it; } CK_ULONG ulReturn = 0; for ( ; it != _handles.end() && ulReturn < ulCount; ++ulReturn) { _handles.erase(it++); } return ulReturn; } softhsm-2.0.0/src/lib/object_store/DBToken.h0000664000175000017500000001014212533040716015574 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBToken.h The token class; a token is stored in a directory containing a single database file. Each object is stored in multiple tables with every attribute base type stored in a different table. *****************************************************************************/ #ifndef _SOFTHSM_V2_DBTOKEN_H #define _SOFTHSM_V2_DBTOKEN_H #include "config.h" #include "ByteString.h" #include "MutexFactory.h" #include "OSAttribute.h" #include "cryptoki.h" #include "OSObject.h" #include "ObjectStoreToken.h" #include #include namespace DB { class Connection; } class DBToken : public ObjectStoreToken { public: // Constructor to create a new token DBToken(const std::string &baseDir, const std::string &tokenName, const ByteString& label, const ByteString& serial); // Constructor to access an existing token DBToken(const std::string &baseDir, const std::string &tokenName); // Create a new token static DBToken* createToken(const std::string basePath, const std::string tokenDir, const ByteString& label, const ByteString& serial); // Access an existing token static DBToken* accessToken(const std::string &basePath, const std::string &tokenDir); // Destructor virtual ~DBToken(); // Set the SO PIN virtual bool setSOPIN(const ByteString& soPINBlob); // Get the SO PIN virtual bool getSOPIN(ByteString& soPINBlob); // Set the user PIN virtual bool setUserPIN(ByteString userPINBlob); // Get the user PIN virtual bool getUserPIN(ByteString& userPINBlob); // Get the token flags virtual bool getTokenFlags(CK_ULONG& flags); // Set the token flags virtual bool setTokenFlags(const CK_ULONG flags); // Retrieve the token label virtual bool getTokenLabel(ByteString& label); // Retrieve the token serial virtual bool getTokenSerial(ByteString& serial); // Retrieve objects virtual std::set getObjects(); // Insert objects into the given set virtual void getObjects(std::set &objects); // Create a new object virtual OSObject* createObject(); // Delete an object virtual bool deleteObject(OSObject* object); // Checks if the token is consistent virtual bool isValid(); // Invalidate the token (for instance if it is deleted) virtual void invalidate(); // Delete the token virtual bool clearToken(); private: DB::Connection *_connection; // All the objects ever associated with this token // // This map is kept to be able to clean up when the token // instance is discarded; in case the contents of a token // change, some objects may disappear but we cannot simply // delete them since they may still be referenced from an // object outside of this class. std::map _allObjects; // For thread safeness Mutex* _tokenMutex; }; #endif // !_SOFTHSM_V2_DBTOKEN_H softhsm-2.0.0/src/lib/object_store/File.h0000664000175000017500000000754612533040716015203 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** File.h This class wraps standard C file I/O in a convenient way for the object store *****************************************************************************/ #ifndef _SOFTHSM_V2_FILE_H #define _SOFTHSM_V2_FILE_H #include "config.h" #include "OSAttribute.h" #include #include class File { public: // Constructor File(std::string inPath, bool forRead = true, bool forWrite = false, bool create = false, bool truncate = true); // Destructor virtual ~File(); // Check if the file is valid bool isValid(); // Check if the file is readable bool isRead(); // Check if the file is writable bool isWrite(); // Check if the file is empty bool isEmpty(); // Check if the end-of-file was reached bool isEOF(); // Read an unsigned long value; warning: not thread safe without locking! bool readULong(unsigned long& value); // Read a ByteString value; warning: not thread safe without locking! bool readByteString(ByteString& value); // Read a string value; warning: not thread safe without locking! bool readString(std::string& value); // Read a boolean value; warning: not thread safe without locking! bool readBool(bool& value); // Read an array value; warning: not thread safe without locking! bool readArray(std::map& value); // Write an unsigned long value; warning: not thread safe without locking! bool writeULong(const unsigned long value); // Write a ByteString value; warning: not thread safe without locking! bool writeByteString(const ByteString& value); // Write a string value; warning: not thread safe without locking! bool writeString(const std::string& value); // Write a boolean value; warning: not thread safe without locking! bool writeBool(const bool value); // Write an array value; warning: not thread safe without locking! bool writeArray(const std::map& value); // Rewind the file bool rewind(); // Truncate the file bool truncate(); // Seek to the specified position relative to the start of the file; if no // argument is specified this operation seeks to the end of the file bool seek(long offset = -1); // Lock the file bool lock(bool block = true); // Unlock the file bool unlock(); // Flush the buffered stream to background storage bool flush(); private: // The file path std::string path; // The status bool valid; bool locked; // Read, write or both? bool isReadable, isWritable; // The FILE stream FILE* stream; }; #endif // !_SOFTHSM_V2_FILE_H softhsm-2.0.0/src/lib/object_store/Directory.h0000664000175000017500000000507312533040716016261 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Directory.h Helper functions for accessing directories. *****************************************************************************/ #ifndef _SOFTHSM_V2_DIRECTORY_H #define _SOFTHSM_V2_DIRECTORY_H #include "config.h" #include "MutexFactory.h" #include #include class Directory { public: // Constructor Directory(std::string inPath); // Destructor virtual ~Directory(); // Check if the directory is valid bool isValid(); // Return a list of all files in a directory std::vector getFiles(); // Return a list of all subdirectories in a directory std::vector getSubDirs(); // Refresh the directory listing bool refresh(); // Create a new subdirectory bool mkdir(std::string name); // Delete a subdirectory in the directory bool rmdir(std::string name, bool doRefresh = false); // Delete a file in the directory bool remove(std::string name); private: // The directory path std::string path; // The status bool valid; // All files in the directory std::vector files; // All subdirectories in the directory std::vector subDirs; // For thread safeness Mutex* dirMutex; }; #endif // !_SOFTHSM_V2_DIRECTORY_H softhsm-2.0.0/src/lib/object_store/SessionObject.cpp0000664000175000017500000001542612533040716017425 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObject.cpp This class implements session objects (i.e. objects that are non-persistent) *****************************************************************************/ #include "config.h" #include "SessionObject.h" #include "SessionObjectStore.h" // Constructor SessionObject::SessionObject(SessionObjectStore* inParent, CK_SLOT_ID inSlotID, CK_SESSION_HANDLE inHSession, bool inIsPrivate) { hSession = inHSession; slotID = inSlotID; isPrivate = inIsPrivate; objectMutex = MutexFactory::i()->getMutex(); valid = (objectMutex != NULL); parent = inParent; } // Destructor SessionObject::~SessionObject() { discardAttributes(); MutexFactory::i()->recycleMutex(objectMutex); } // Check if the specified attribute exists bool SessionObject::attributeExists(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); return valid && (attributes[type] != NULL); } // Retrieve the specified attribute OSAttribute SessionObject::getAttribute(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return OSAttribute((unsigned long)0); } return *attr; } bool SessionObject::getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val) { MutexLocker lock(objectMutex); OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return val; } if (attr->isBooleanAttribute()) { return attr->getBooleanValue(); } else { ERROR_MSG("The attribute is not a boolean: 0x%08X", type); return val; } } unsigned long SessionObject::getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val) { MutexLocker lock(objectMutex); OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return val; } if (attr->isUnsignedLongAttribute()) { return attr->getUnsignedLongValue(); } else { ERROR_MSG("The attribute is not an unsigned long: 0x%08X", type); return val; } } ByteString SessionObject::getByteStringValue(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); ByteString val; OSAttribute* attr = attributes[type]; if (attr == NULL) { ERROR_MSG("The attribute does not exist: 0x%08X", type); return val; } if (attr->isByteStringAttribute()) { return attr->getByteStringValue(); } else { ERROR_MSG("The attribute is not a byte string: 0x%08X", type); return val; } } // Retrieve the next attribute type CK_ATTRIBUTE_TYPE SessionObject::nextAttributeType(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(objectMutex); std::map::iterator n = attributes.upper_bound(type); // skip null attributes while ((n != attributes.end()) && (n->second == NULL)) ++n; // return type or CKA_CLASS (= 0) if (n == attributes.end()) { return CKA_CLASS; } else { return n->first; } } // Set the specified attribute bool SessionObject::setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute) { MutexLocker lock(objectMutex); if (!valid) { DEBUG_MSG("Cannot update invalid session object 0x%08X", this); return false; } if (attributes[type] != NULL) { delete attributes[type]; attributes[type] = NULL; } attributes[type] = new OSAttribute(attribute); return true; } // The validity state of the object bool SessionObject::isValid() { return valid; } bool SessionObject::hasSlotID(CK_SLOT_ID inSlotID) { return slotID == inSlotID; } // Called by the session object store when a session is closed. If it's the // session this object was associated with, the function returns true and the // object is invalidated bool SessionObject::removeOnSessionClose(CK_SESSION_HANDLE inHSession) { if (hSession == inHSession) { // Save space discardAttributes(); valid = false; return true; } return false; } // Called by the session object store when a token is logged out. // Remove when this session object is a private object for this token. bool SessionObject::removeOnAllSessionsClose(CK_SLOT_ID inSlotID) { if (slotID == inSlotID) { discardAttributes(); valid = false; return true; } return false; } // Called by the session object store when a token is logged out. // Remove when this session object is a private object for this token. bool SessionObject::removeOnTokenLogout(CK_SLOT_ID inSlotID) { if (slotID == inSlotID && isPrivate) { discardAttributes(); valid = false; return true; } return false; } // Discard the object's attributes void SessionObject::discardAttributes() { MutexLocker lock(objectMutex); std::map cleanUp = attributes; attributes.clear(); for (std::map::iterator i = cleanUp.begin(); i != cleanUp.end(); i++) { if (i->second == NULL) { continue; } delete i->second; i->second = NULL; } } // These functions are just stubs for session objects bool SessionObject::startTransaction(Access) { return true; } bool SessionObject::commitTransaction() { return true; } bool SessionObject::abortTransaction() { return true; } bool SessionObject::destroyObject() { if (parent == NULL) { ERROR_MSG("Cannot destroy object that is not associated with a session object store"); return false; } return parent->deleteObject(this); } // Invalidate the object void SessionObject::invalidate() { valid = false; discardAttributes(); } softhsm-2.0.0/src/lib/object_store/OSPathSep.h0000664000175000017500000000330312533040716016115 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSPathSep.h Determine the OS specific path separator *****************************************************************************/ #ifndef _SOFTHSM_V2_OSPATHSEP_H #define _SOFTHSM_V2_OSPATHSEP_H #include "config.h" #ifdef _WIN32 #define OS_PATHSEP "\\" #else #define OS_PATHSEP "/" #endif #endif // !_SOFTHSM_V2_OSPATHSEP_H softhsm-2.0.0/src/lib/object_store/DBObject.h0000664000175000017500000001132512533040716015726 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBObject.h This class represents object records in a database *****************************************************************************/ #ifndef _SOFTHSM_V2_DBOBJECT_H #define _SOFTHSM_V2_DBOBJECT_H #include "config.h" #include "OSAttribute.h" #include "cryptoki.h" #include "OSObject.h" #include "ObjectStoreToken.h" #include "MutexFactory.h" #include namespace DB { class Connection; } class DBObject : public OSObject { public: // Constructor for creating or accessing an object, don't do anything yet. DBObject(DB::Connection *connection, ObjectStoreToken *token = NULL); // Constructor for accessing an object with an objectId known to exists DBObject(DB::Connection *connection, ObjectStoreToken *token, long long objectId); // Destructor virtual ~DBObject(); // Will drop any internal references to the connection void dropConnection(); // create tables to support storage of attributes for the object. bool createTables(); // drop tables that support storage of attributes for the object. bool dropTables(); // Find an existing object. bool find(long long objectId); // Insert a new object into the database and retrieve the object id associated with it. bool insert(); // Remove an existing object from the database and reset the object id to zero. bool remove(); // Object id associated with this object. long long objectId(); // Check if the specified attribute exists virtual bool attributeExists(CK_ATTRIBUTE_TYPE type); // Retrieve the specified attribute virtual OSAttribute getAttribute(CK_ATTRIBUTE_TYPE type); virtual bool getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val); virtual unsigned long getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val); virtual ByteString getByteStringValue(CK_ATTRIBUTE_TYPE type); // Retrieve the next attribute type virtual CK_ATTRIBUTE_TYPE nextAttributeType(CK_ATTRIBUTE_TYPE type); // Set the specified attribute virtual bool setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute); // The validity state of the object virtual bool isValid(); // Start an attribute set transaction; this method is used when - for // example - a key is generated and all its attributes need to be // persisted in one go. // // N.B.: Starting a transaction locks the object! // // Function returns false in case a transaction is already in progress virtual bool startTransaction(Access access); // Commit an attribute transaction; returns false if no transaction is in progress virtual bool commitTransaction(); // Abort an attribute transaction; loads back the previous version of the object from disk; // returns false if no transaction was in progress virtual bool abortTransaction(); // Destroys the object (warning, any pointers to the object are no longer // valid after this call because delete is called!) virtual bool destroyObject(); private: // Disable copy constructor and assignment DBObject(); DBObject(const DBObject&); DBObject & operator= (const DBObject &); // Mutex object for thread-safeness Mutex* _mutex; DB::Connection *_connection; ObjectStoreToken *_token; long long _objectId; std::map _attributes; std::map *_transaction; OSAttribute* getAttributeDB(CK_ATTRIBUTE_TYPE type); OSAttribute* accessAttribute(CK_ATTRIBUTE_TYPE type); }; #endif // !_SOFTHSM_V2_DBOBJECT_H softhsm-2.0.0/src/lib/object_store/OSObject.h0000664000175000017500000000672312533040716015770 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSObject.h This file contains the abstract interface for ObjectStore objects. It is implemented by persistent objects in the form of the ObjectFile class and by session objects in the form of the SessionObject class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSOBJECT_H #define _SOFTHSM_V2_OSOBJECT_H #include "config.h" #include "OSAttribute.h" #include "cryptoki.h" class OSObject { public: // Destructor virtual ~OSObject() { } // Check if the specified attribute exists virtual bool attributeExists(CK_ATTRIBUTE_TYPE type) = 0; // Retrieve the specified attribute virtual OSAttribute getAttribute(CK_ATTRIBUTE_TYPE type) = 0; virtual bool getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val) = 0; virtual unsigned long getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val) = 0; virtual ByteString getByteStringValue(CK_ATTRIBUTE_TYPE type) = 0; // Retrieve the next attribute type virtual CK_ATTRIBUTE_TYPE nextAttributeType(CK_ATTRIBUTE_TYPE type) = 0; // Set the specified attribute virtual bool setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute) = 0; // The validity state of the object virtual bool isValid() = 0; // Start an attribute set transaction; this method is used when - for // example - a key is generated and all its attributes need to be // persisted in one go. // // N.B.: Starting a transaction locks the object! // // Function returns false in case a transaction is already in progress enum Access { ReadOnly, ReadWrite }; virtual bool startTransaction(Access access = ReadWrite) = 0; // Commit an attribute transaction; returns false if no transaction is in progress virtual bool commitTransaction() = 0; // Abort an attribute transaction; loads back the previous version of the object from disk; // returns false if no transaction was in progress virtual bool abortTransaction() = 0; // Destroys the object (warning, any pointers to the object are no longer // valid after this call because delete is called!) virtual bool destroyObject() = 0; }; #endif // !_SOFTHSM_V2_OSOBJECT_H softhsm-2.0.0/src/lib/object_store/test/0000775000175000017500000000000012552220147015175 500000000000000softhsm-2.0.0/src/lib/object_store/test/ObjectStoreTests.cpp0000664000175000017500000002207712533040716021100 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectStoreTests.cpp Contains test cases to test the object store implementation *****************************************************************************/ #include #include #include #include "ObjectStoreTests.h" #include "ObjectStore.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(ObjectStoreTests); // FIXME: all pathnames in this file are *NIX/BSD specific void ObjectStoreTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void ObjectStoreTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void ObjectStoreTests::testEmptyStore() { // Create the store for an empty dir #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); } void ObjectStoreTests::testNewTokens() { ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; { // Create an empty store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); // Create a new token ObjectStoreToken* token1 = store.newToken(label1); CPPUNIT_ASSERT(token1 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 1); // Create another new token ObjectStoreToken* token2 = store.newToken(label2); CPPUNIT_ASSERT(token2 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); } // Now reopen that same store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store.getToken(0); ObjectStoreToken* token2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2; CPPUNIT_ASSERT(token1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(token2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel2 == label1)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); ByteString retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(token1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(token2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testExistingTokens() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testDeleteToken() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); // Now, delete token #1 CPPUNIT_ASSERT(store.destroyToken(retrieveToken1)); CPPUNIT_ASSERT(store.getTokenCount() == 1); ObjectStoreToken* retrieveToken_ = store.getToken(0); ByteString retrieveLabel_,retrieveSerial_; CPPUNIT_ASSERT(retrieveToken_->getTokenLabel(retrieveLabel_)); CPPUNIT_ASSERT(retrieveToken_->getTokenSerial(retrieveSerial_)); CPPUNIT_ASSERT(((retrieveLabel_ == label1) && (retrieveSerial_ == serial1)) || ((retrieveLabel_ == label2) && (retrieveSerial_ == serial2))); // Now add a new token ByteString label3 = "DEADC0FFEEBEEF"; // Create a new token ObjectStoreToken* tokenNew = store.newToken(label3); CPPUNIT_ASSERT(tokenNew != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1_ = store.getToken(0); ObjectStoreToken* retrieveToken2_ = store.getToken(1); CPPUNIT_ASSERT(retrieveToken1_ != NULL); CPPUNIT_ASSERT(retrieveToken2_ != NULL); CPPUNIT_ASSERT(retrieveToken1_->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1_->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label3) || (retrieveLabel2 == label3)); CPPUNIT_ASSERT(((retrieveLabel1 == label1) && (retrieveLabel2 != label2)) || ((retrieveLabel1 == label2) && (retrieveLabel2 != label1))); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); } softhsm-2.0.0/src/lib/object_store/test/SessionObjectTests.cpp0000664000175000017500000003760712533040716021434 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObjectTests.cpp Contains test cases to test the session object implementation *****************************************************************************/ #include #include #include #include "SessionObjectTests.h" #include "SessionObject.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(SessionObjectTests); void SessionObjectTests::setUp() { } void SessionObjectTests::tearDown() { } void SessionObjectTests::testBoolAttr() { SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; bool value2 = false; bool value3 = true; bool value4 = true; bool value5 = false; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SENSITIVE, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_EXTRACTABLE, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_NEVER_EXTRACTABLE, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr5)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SENSITIVE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_EXTRACTABLE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_NEVER_EXTRACTABLE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SIGN)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SENSITIVE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_EXTRACTABLE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_NEVER_EXTRACTABLE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SENSITIVE).getBooleanValue() == false); CPPUNIT_ASSERT(testObject.getAttribute(CKA_EXTRACTABLE).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_NEVER_EXTRACTABLE).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue() == false); bool value6 = true; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VERIFY, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VERIFY).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VERIFY).getBooleanValue() == value6); CPPUNIT_ASSERT(testObject.getBooleanValue(CKA_VERIFY, false) == value6); } void SessionObjectTests::testULongAttr() { SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); unsigned long value1 = 0x12345678; unsigned long value2 = 0x87654321; unsigned long value3 = 0x01010101; unsigned long value4 = 0x10101010; unsigned long value5 = 0xABCDEF; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_MODULUS_BITS, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_AUTH_PIN_FLAGS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBPRIME_BITS, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_KEY_TYPE, attr5)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_MODULUS_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_AUTH_PIN_FLAGS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBPRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_KEY_TYPE)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_AUTH_PIN_FLAGS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBPRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_KEY_TYPE).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS_BITS).getUnsignedLongValue() == 0x12345678); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_AUTH_PIN_FLAGS).getUnsignedLongValue() == 0x01010101); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBPRIME_BITS).getUnsignedLongValue() == 0x10101010); CPPUNIT_ASSERT(testObject.getAttribute(CKA_KEY_TYPE).getUnsignedLongValue() == 0xABCDEF); unsigned long value6 = 0x90909090; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_CLASS, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_CLASS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_CLASS).getUnsignedLongValue() == value6); CPPUNIT_ASSERT(testObject.getUnsignedLongValue(CKA_CLASS, 0x0) == value6); } void SessionObjectTests::testByteStrAttr() { ByteString value1 = "010203040506070809"; ByteString value2 = "ABABABABABABABABABABABABABABABABAB"; ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; ByteString value4 = "98A7E5D798A7E5D798A7E5D798A7E5D798A7E5D798A7E5D7"; ByteString value5 = "ABCDABCDABCDABCDABCDABCDABCDABCD"; SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_MODULUS, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_COEFFICIENT, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PUBLIC_EXPONENT, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBJECT, attr5)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_MODULUS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_COEFFICIENT)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PUBLIC_EXPONENT)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBJECT)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_COEFFICIENT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PUBLIC_EXPONENT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS).getByteStringValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_COEFFICIENT).getByteStringValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PUBLIC_EXPONENT).getByteStringValue() == value4); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).getByteStringValue() == value5); ByteString value6 = "909090908080808080807070707070FF"; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ISSUER, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ISSUER).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getByteStringValue(CKA_ISSUER) == value6); } void SessionObjectTests::testArrayAttr() { SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); std::map mattr; mattr.insert(std::pair (CKA_TOKEN, attr1)); mattr.insert(std::pair (CKA_PRIME_BITS, attr2)); mattr.insert(std::pair (CKA_VALUE_BITS, attr3)); OSAttribute attra(mattr); CPPUNIT_ASSERT(testObject.setAttribute(CKA_WRAP_TEMPLATE, attra)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_WRAP_TEMPLATE)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_UNWRAP_TEMPLATE)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_WRAP_TEMPLATE).isArrayAttribute()); std::map mattrb = testObject.getAttribute(CKA_WRAP_TEMPLATE).getArrayValue(); CPPUNIT_ASSERT(mattrb.size() == 3); CPPUNIT_ASSERT(mattrb.find(CKA_TOKEN) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(mattrb.find(CKA_PRIME_BITS) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(mattrb.find(CKA_VALUE_BITS) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_VALUE_BITS).getByteStringValue() == value3); } void SessionObjectTests::testMixedAttr() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); } void SessionObjectTests::testDoubleAttr() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; ByteString value3a = "466487346943785684957634"; SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); bool value1a = false; unsigned long value2a = 0x76767676; OSAttribute attr1a(value1a); OSAttribute attr2a(value2a); OSAttribute attr3a(value3a); // Change the attributes CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3a)); // Check the attributes CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); CPPUNIT_ASSERT(testObject.isValid()); } void SessionObjectTests::testCloseSession() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); // Now close the session testObject.removeOnSessionClose(1); CPPUNIT_ASSERT(!testObject.isValid()); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_VALUE_BITS)); } void SessionObjectTests::testDestroyObjectFails() { // Create test object instance SessionObject testObject(NULL, 1, 1); CPPUNIT_ASSERT(testObject.isValid()); OSObject* testIF = (OSObject*) &testObject; CPPUNIT_ASSERT(!testIF->destroyObject()); } softhsm-2.0.0/src/lib/object_store/test/OSTokenTests.h0000664000175000017500000000420212533040716017632 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSTokenTests.h Contains test cases to test the object file implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSTOKENTESTS_H #define _SOFTHSM_V2_OSTOKENTESTS_H #include class OSTokenTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OSTokenTests); CPPUNIT_TEST(testNewToken); CPPUNIT_TEST(testExistingToken); CPPUNIT_TEST(testNonExistentToken); CPPUNIT_TEST(testCreateDeleteObjects); CPPUNIT_TEST(testClearToken); CPPUNIT_TEST_SUITE_END(); public: void testNewToken(); void testExistingToken(); void testNonExistentToken(); void testCreateDeleteObjects(); void testClearToken(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_OSTOKENTESTS_H softhsm-2.0.0/src/lib/object_store/test/Makefile.am0000664000175000017500000000170312533040716017153 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../data_mgr \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ `cppunit-config --cflags` check_PROGRAMS = objstoretest objstoretest_SOURCES = objstoretest.cpp \ DirectoryTests.cpp \ UUIDTests.cpp \ FileTests.cpp \ ObjectFileTests.cpp \ OSTokenTests.cpp \ ObjectStoreTests.cpp \ SessionObjectTests.cpp \ SessionObjectStoreTests.cpp if BUILD_OBJECTSTORE_BACKEND_DB objstoretest_SOURCES += DBTests.cpp \ DBObjectTests.cpp \ DBTokenTests.cpp \ DBObjectStoreTests.cpp endif objstoretest_LDADD = ../../libsofthsm_convarch.la objstoretest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread TESTS = objstoretest EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/object_store/test/SessionObjectStoreTests.h0000664000175000017500000000412312533040716022101 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObjectStoreTests.h Contains test cases to test the session object store implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONOBJECTSTORETESTS_H #define _SOFTHSM_V2_SESSIONOBJECTSTORETESTS_H #include class SessionObjectStoreTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SessionObjectStoreTests); CPPUNIT_TEST(testCreateDeleteObjects); CPPUNIT_TEST(testMultiSession); CPPUNIT_TEST(testWipeStore); CPPUNIT_TEST_SUITE_END(); public: void testCreateDeleteObjects(); void testMultiSession(); void testWipeStore(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_SESSIONOBJECTSTORETESTS_H softhsm-2.0.0/src/lib/object_store/test/DBObjectTests.h0000664000175000017500000000615012533040716017730 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBObjectTests.h Contains test cases to test the database token object implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_DBOBJECTTESTS_H #define _SOFTHSM_V2_DBOBJECTTESTS_H #include #include "DB.h" class test_a_dbobject : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test_a_dbobject); CPPUNIT_TEST(should_be_insertable); CPPUNIT_TEST(should_be_selectable); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void should_be_insertable(); void should_be_selectable(); protected: DB::Connection *connection; DB::Connection *connection2; private: }; class test_a_dbobject_with_an_object : public test_a_dbobject { CPPUNIT_TEST_SUITE(test_a_dbobject_with_an_object); CPPUNIT_TEST(should_store_boolean_attributes); CPPUNIT_TEST(should_store_unsigned_long_attributes); CPPUNIT_TEST(should_store_binary_attributes); CPPUNIT_TEST(should_store_array_attributes); CPPUNIT_TEST(should_store_mixed_attributes); CPPUNIT_TEST(should_store_double_attributes); CPPUNIT_TEST(can_refresh_attributes); CPPUNIT_TEST(should_cleanup_statements_during_transactions); CPPUNIT_TEST(should_use_transactions); CPPUNIT_TEST(should_fail_to_delete); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void should_store_boolean_attributes(); void should_store_unsigned_long_attributes(); void should_store_binary_attributes(); void should_store_array_attributes(); void should_store_mixed_attributes(); void should_store_double_attributes(); void can_refresh_attributes(); void should_cleanup_statements_during_transactions(); void should_use_transactions(); void should_fail_to_delete(); }; #endif // !_SOFTHSM_V2_DBOBJECTTESTS_H softhsm-2.0.0/src/lib/object_store/test/ObjectStoreTests.h0000664000175000017500000000411412533040716020535 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectStoreTests.h Contains test cases to test the object store implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OBJECTSTORETESTS_H #define _SOFTHSM_V2_OBJECTSTORETESTS_H #include class ObjectStoreTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ObjectStoreTests); CPPUNIT_TEST(testEmptyStore); CPPUNIT_TEST(testNewTokens); CPPUNIT_TEST(testExistingTokens); CPPUNIT_TEST(testDeleteToken); CPPUNIT_TEST_SUITE_END(); public: void testEmptyStore(); void testNewTokens(); void testExistingTokens(); void testDeleteToken(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_OBJECTSTORETESTS_H softhsm-2.0.0/src/lib/object_store/test/DirectoryTests.h0000664000175000017500000000363012533040716020260 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DirectoryTests.h Contains test cases to test the Directory implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_DIRECTORYTESTS_H #define _SOFTHSM_V2_DIRECTORYTESTS_H #include class DirectoryTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DirectoryTests); CPPUNIT_TEST(testDirectory); CPPUNIT_TEST_SUITE_END(); public: void testDirectory(); void setUp(); void tearDown(); private: }; #endif // !_SOFTHSM_V2_DIRECTORYTESTS_H softhsm-2.0.0/src/lib/object_store/test/SessionObjectStoreTests.cpp0000664000175000017500000002206612533040716022442 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObjectStoreTests.cpp Contains test cases to test the session object store implementation *****************************************************************************/ #include #include #include #include #include "SessionObjectStoreTests.h" #include "SessionObjectStore.h" #include "SessionObject.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(SessionObjectStoreTests); void SessionObjectStoreTests::setUp() { } void SessionObjectStoreTests::tearDown() { } void SessionObjectStoreTests::testCreateDeleteObjects() { // Test IDs ByteString id[5] = { "112233445566", "AABBCCDDEEFF", "ABABABABABAB", "557788991122", "005500550055" }; OSAttribute idAtt[5] = { id[0], id[1], id[2], id[3], id[4] }; ByteString label = "AABBCCDDEEFF"; ByteString serial = "1234567890"; // Get access to the session object store SessionObjectStore* testStore = new SessionObjectStore(); // Create 3 objects in the store SessionObject* obj1 = testStore->createObject(1, 1); CPPUNIT_ASSERT(obj1 != NULL); SessionObject* obj2 = testStore->createObject(1, 1); CPPUNIT_ASSERT(obj2 != NULL); SessionObject* obj3 = testStore->createObject(1, 1); CPPUNIT_ASSERT(obj3 != NULL); // Now set the IDs of the 3 objects obj1->setAttribute(CKA_ID, idAtt[0]); obj2->setAttribute(CKA_ID, idAtt[1]); obj3->setAttribute(CKA_ID, idAtt[2]); // Check that the store contains 3 objects CPPUNIT_ASSERT(testStore->getObjects().size() == 3); // Check that all three objects are distinct and present std::set objects = testStore->getObjects(); bool present1[3] = { false, false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); for (int j = 0; j < 3; j++) { if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[j]) { present1[j] = true; } } } for (int j = 0; j < 3; j++) { CPPUNIT_ASSERT(present1[j] == true); } // Now delete the second object for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[1]) { CPPUNIT_ASSERT(testStore->deleteObject(*i)); break; } } // Verify that it was indeed removed CPPUNIT_ASSERT(testStore->getObjects().size() == 2); objects = testStore->getObjects(); bool present3[2] = { false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present3[0] = true; } if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present3[1] = true; } } for (int j = 0; j < 2; j++) { CPPUNIT_ASSERT(present3[j] == true); } delete testStore; } void SessionObjectStoreTests::testMultiSession() { // Get access to the store SessionObjectStore* store = new SessionObjectStore(); // Check that the store is empty CPPUNIT_ASSERT(store->getObjects().size() == 0); // Test IDs ByteString id[5] = { "112233445566", "AABBCCDDEEFF", "ABABABABABAB", "557788991122", "005500550055" }; OSAttribute idAtt[5] = { id[0], id[1], id[2], id[3], id[4] }; // Create 3 objects in the store for three different sessions SessionObject* obj1 = store->createObject(1, 1); CPPUNIT_ASSERT(obj1 != NULL); SessionObject* obj2 = store->createObject(1, 2); CPPUNIT_ASSERT(obj2 != NULL); SessionObject* obj3 = store->createObject(1, 3); CPPUNIT_ASSERT(obj3 != NULL); // Now set the IDs of the 3 objects obj1->setAttribute(CKA_ID, idAtt[0]); obj2->setAttribute(CKA_ID, idAtt[1]); obj3->setAttribute(CKA_ID, idAtt[2]); // Check that the store contains 3 objects CPPUNIT_ASSERT(store->getObjects().size() == 3); // Check that all three objects are distinct and present std::set objects = store->getObjects(); bool present1[3] = { false, false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); for (int j = 0; j < 3; j++) { if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[j]) { present1[j] = true; } } } for (int j = 0; j < 3; j++) { CPPUNIT_ASSERT(present1[j] == true); } // Now indicate that the second session has been closed store->sessionClosed(2); // Verify that it was indeed removed CPPUNIT_ASSERT(store->getObjects().size() == 2); objects = store->getObjects(); bool present3[2] = { false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present3[0] = true; } if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present3[1] = true; } } for (int j = 0; j < 2; j++) { CPPUNIT_ASSERT(present3[j] == true); } // Create two more objects for session 7 SessionObject* obj4 = store->createObject(1, 7); CPPUNIT_ASSERT(obj4 != NULL); SessionObject* obj5 = store->createObject(1, 7); CPPUNIT_ASSERT(obj5 != NULL); CPPUNIT_ASSERT(store->getObjects().size() == 4); // Close session 1 store->sessionClosed(1); CPPUNIT_ASSERT(store->getObjects().size() == 3); objects = store->getObjects(); CPPUNIT_ASSERT(objects.find(obj1) == objects.end()); CPPUNIT_ASSERT(objects.find(obj2) == objects.end()); CPPUNIT_ASSERT(objects.find(obj3) != objects.end()); CPPUNIT_ASSERT(objects.find(obj4) != objects.end()); CPPUNIT_ASSERT(objects.find(obj5) != objects.end()); CPPUNIT_ASSERT(!obj1->isValid()); CPPUNIT_ASSERT(!obj2->isValid()); CPPUNIT_ASSERT(obj3->isValid()); CPPUNIT_ASSERT(obj4->isValid()); CPPUNIT_ASSERT(obj5->isValid()); // Close session 7 store->sessionClosed(7); CPPUNIT_ASSERT(store->getObjects().size() == 1); objects = store->getObjects(); CPPUNIT_ASSERT(objects.find(obj1) == objects.end()); CPPUNIT_ASSERT(objects.find(obj2) == objects.end()); CPPUNIT_ASSERT(objects.find(obj3) != objects.end()); CPPUNIT_ASSERT(objects.find(obj4) == objects.end()); CPPUNIT_ASSERT(objects.find(obj5) == objects.end()); CPPUNIT_ASSERT(!obj1->isValid()); CPPUNIT_ASSERT(!obj2->isValid()); CPPUNIT_ASSERT(obj3->isValid()); CPPUNIT_ASSERT(!obj4->isValid()); CPPUNIT_ASSERT(!obj5->isValid()); delete store; } void SessionObjectStoreTests::testWipeStore() { // Get access to the store SessionObjectStore* store = new SessionObjectStore(); // Check that the store is empty CPPUNIT_ASSERT(store->getObjects().size() == 0); // Create 3 objects in the store for three different sessions SessionObject* obj1 = store->createObject(1, 1); CPPUNIT_ASSERT(obj1 != NULL); SessionObject* obj2 = store->createObject(1, 2); CPPUNIT_ASSERT(obj2 != NULL); SessionObject* obj3 = store->createObject(1, 3); CPPUNIT_ASSERT(obj3 != NULL); // Wipe the store store->clearStore(); // Check that the store is empty CPPUNIT_ASSERT(store->getObjects().size() == 0); delete store; } softhsm-2.0.0/src/lib/object_store/test/DBTests.cpp0000664000175000017500000005233612533040716017143 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBTests.cpp Contains lowest level test cases for the database backend implementation. *****************************************************************************/ #include #include #include #include "DBTests.h" CPPUNIT_TEST_SUITE_REGISTRATION(test_a_db); static int dummy_print(const char *, va_list ) { return 0; } void test_a_db::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); null = NULL; } void test_a_db::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void test_a_db::checks_for_empty_connection_parameters() { DB::LogErrorHandler eh = DB::setLogErrorHandler(dummy_print); DB::Connection *connection = DB::Connection::Create("","TestToken"); CPPUNIT_ASSERT_EQUAL(connection, null); connection = DB::Connection::Create("testdir",""); CPPUNIT_ASSERT_EQUAL(connection, null); connection = DB::Connection::Create("",""); CPPUNIT_ASSERT_EQUAL(connection, null); DB::setLogErrorHandler(eh); } void test_a_db::can_be_connected_to_database() { DB::Connection *connection = DB::Connection::Create("testdir","TestToken"); CPPUNIT_ASSERT(connection != null); bool isConnected = connection->connect(); delete connection; CPPUNIT_ASSERT(isConnected); #ifndef _WIN32 CPPUNIT_ASSERT_EQUAL(system("test -f ./testdir/TestToken"), 0); #else CPPUNIT_ASSERT(GetFileAttributes("testdir\\TestToken") != INVALID_FILE_ATTRIBUTES); #endif } CPPUNIT_TEST_SUITE_REGISTRATION(test_a_db_with_a_connection); void test_a_db_with_a_connection::setUp() { test_a_db::setUp(); connection = DB::Connection::Create("testdir","TestToken"); CPPUNIT_ASSERT(connection != null); CPPUNIT_ASSERT(connection->connect()); } void test_a_db_with_a_connection::tearDown() { CPPUNIT_ASSERT(connection != null); connection->close(); delete connection; test_a_db::tearDown(); } void test_a_db_with_a_connection::can_prepare_statements() { DB::Statement statement = connection->prepare("PRAGMA database_list;"); CPPUNIT_ASSERT(statement.isValid()); } void test_a_db_with_a_connection::can_perform_statements() { DB::Statement statement = connection->prepare("PRAGMA database_list;"); CPPUNIT_ASSERT(statement.isValid()); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); // only expect a single row in the result, so nextRow should now fail CPPUNIT_ASSERT(!result.nextRow()); } void test_a_db_with_a_connection::maintains_correct_refcounts() { DB::Statement statement = connection->prepare("PRAGMA database_list;"); CPPUNIT_ASSERT_EQUAL(statement.refcount(), 1); { DB::Statement statement1 = statement; DB::Statement statement2 = statement; CPPUNIT_ASSERT_EQUAL(statement.refcount(), 3); CPPUNIT_ASSERT(statement1.isValid()); CPPUNIT_ASSERT(statement2.isValid()); } CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT_EQUAL(statement.refcount(), 1); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); // Statement is referenced by the result because it provides the query record cursor state. CPPUNIT_ASSERT_EQUAL(statement.refcount(), 2); result = DB::Result(); CPPUNIT_ASSERT_EQUAL(statement.refcount(), 1); } void test_a_db_with_a_connection::can_create_tables() { CPPUNIT_ASSERT(!connection->tableExists("object")); DB::Statement cr_object = connection->prepare("create table object (id integer primary key autoincrement);"); CPPUNIT_ASSERT(connection->execute(cr_object)); CPPUNIT_ASSERT(connection->tableExists("object")); } CPPUNIT_TEST_SUITE_REGISTRATION(test_a_db_with_a_connection_with_tables); void test_a_db_with_a_connection_with_tables::setUp() { test_a_db_with_a_connection::setUp(); can_create_tables(); // attribute_text CPPUNIT_ASSERT(!connection->tableExists("attribute_text")); DB::Statement cr_attr_text = connection->prepare( "create table attribute_text (" "value text," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); CPPUNIT_ASSERT(connection->execute(cr_attr_text)); CPPUNIT_ASSERT(connection->tableExists("attribute_text")); // attribute_integer CPPUNIT_ASSERT(!connection->tableExists("attribute_integer")); DB::Statement cr_attr_integer = connection->prepare( "create table attribute_integer (" "value integer," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); CPPUNIT_ASSERT(connection->execute(cr_attr_integer)); CPPUNIT_ASSERT(connection->tableExists("attribute_integer")); // attribute_blob CPPUNIT_ASSERT(!connection->tableExists("attribute_blob")); DB::Statement cr_attr_blob = connection->prepare( "create table attribute_blob (" "value blob," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); CPPUNIT_ASSERT(connection->execute(cr_attr_blob)); CPPUNIT_ASSERT(connection->tableExists("attribute_blob")); // attribute_boolean CPPUNIT_ASSERT(!connection->tableExists("attribute_boolean")); DB::Statement cr_attr_boolean = connection->prepare( "create table attribute_boolean (" "value boolean," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); CPPUNIT_ASSERT(connection->execute(cr_attr_boolean)); CPPUNIT_ASSERT(connection->tableExists("attribute_boolean")); // attribute_datetime CPPUNIT_ASSERT(!connection->tableExists("attribute_datetime")); DB::Statement cr_attr_datetime = connection->prepare( "create table attribute_datetime (" "value datetime," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); CPPUNIT_ASSERT(connection->execute(cr_attr_datetime)); CPPUNIT_ASSERT(connection->tableExists("attribute_datetime")); // attribute_real CPPUNIT_ASSERT(!connection->tableExists("attribute_real")); DB::Statement cr_attr_real = connection->prepare( "create table attribute_real (" "value real," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); CPPUNIT_ASSERT(connection->execute(cr_attr_real)); CPPUNIT_ASSERT(connection->tableExists("attribute_real")); } void test_a_db_with_a_connection_with_tables::tearDown() { test_a_db_with_a_connection::tearDown(); } void test_a_db_with_a_connection_with_tables::can_insert_records() { DB::Statement statement = connection->prepare("insert into object default values"); CPPUNIT_ASSERT(connection->execute(statement)); long long object_id = connection->lastInsertRowId(); CPPUNIT_ASSERT(object_id != 0); statement = connection->prepare( "insert into attribute_text (value,type,object_id) values ('%s',%d,%lld)", "testing testing testing", 1234, object_id); CPPUNIT_ASSERT(connection->execute(statement)); } void test_a_db_with_a_connection_with_tables::can_retrieve_records() { can_insert_records(); DB::Statement statement = connection->prepare( "select value from attribute_text as t where t.type=%d", 1234); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT_EQUAL(std::string(result.getString(1)), std::string("testing testing testing")); } void test_a_db_with_a_connection_with_tables::can_cascade_delete_objects_and_attributes() { can_insert_records(); DB::Statement statement = connection->prepare("select id from object"); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); long long object_id = result.getLongLong(1); statement = connection->prepare("delete from object where id=%lld",object_id); CPPUNIT_ASSERT(connection->execute(statement)); statement = connection->prepare("select * from attribute_text where object_id=%lld",object_id); result = connection->perform(statement); // Check cascade delete was successful. CPPUNIT_ASSERT(!result.isValid()); } void test_a_db_with_a_connection_with_tables::can_update_text_attribute() { can_insert_records(); // query all objects DB::Statement statement = connection->prepare("select id from object"); CPPUNIT_ASSERT(statement.isValid()); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); long long object_id = result.getLongLong(1); // field indices start at 1 statement = connection->prepare( "update attribute_text set value='test test test' where type=%d and object_id=%lld", 1234, object_id); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); } void test_a_db_with_a_connection_with_tables::can_update_text_attribute_bound_value() { can_insert_records(); // query all objects DB::Statement statement = connection->prepare("select id from object"); CPPUNIT_ASSERT(statement.isValid()); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); long long object_id = result.getLongLong(1); // field indices start at 1 statement = connection->prepare( "update attribute_text set value=? where type=%d and object_id=%lld", 1234, object_id); CPPUNIT_ASSERT(statement.isValid()); std::string msg("testing quote ' and accents é."); CPPUNIT_ASSERT(DB::Bindings(statement).bindText(1,msg.c_str(),msg.size(),NULL)); CPPUNIT_ASSERT(connection->execute(statement)); statement = connection->prepare( "select value from attribute_text as t where t.type=%d and t.object_id=%lld", 1234, object_id); result = connection->perform(statement); CPPUNIT_ASSERT_EQUAL(std::string(result.getString(1)), msg); } void test_a_db_with_a_connection_with_tables::can_update_integer_attribute_bound_value() { // insert new object DB::Statement statement = connection->prepare( "insert into object default values"); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); long long object_id = connection->lastInsertRowId(); CPPUNIT_ASSERT(object_id != 0); // insert integer attribute statement = connection->prepare( "insert into attribute_integer (value,type,object_id) values (%lld,%d,%lld)", 1111, 1235, object_id); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); // prepare update integer attribute statement statement = connection->prepare( "update attribute_integer set value=? where type=%d and object_id=%lld", 1235, object_id); CPPUNIT_ASSERT(statement.isValid()); // bind long long value to the parameter an update the record CPPUNIT_ASSERT(DB::Bindings(statement).bindInt64(1,2222)); CPPUNIT_ASSERT(connection->execute(statement)); // Retrieve the value from the record DB::Statement retrieveStmt = connection->prepare( "select value from attribute_integer as t where t.type=%d and t.object_id=%lld", 1235, object_id); CPPUNIT_ASSERT(retrieveStmt.isValid()); DB::Result result = connection->perform(retrieveStmt); CPPUNIT_ASSERT_EQUAL(result.getLongLong(1), (long long)2222); // verify that binding to a parameter before resetting the statement will fail. DB::LogErrorHandler eh = DB::setLogErrorHandler(dummy_print); DB::Bindings bindings(statement); CPPUNIT_ASSERT(!bindings.bindInt(1,3333)); DB::setLogErrorHandler(eh); // reset statement and bind another value to the statement CPPUNIT_ASSERT(bindings.reset()); CPPUNIT_ASSERT(bindings.bindInt(1,3333)); // perform the update statement again with the newly bound value CPPUNIT_ASSERT(connection->execute(statement)); // reset the retrieve statement and perform it again to get the latest value of the integer attribute CPPUNIT_ASSERT(retrieveStmt.reset()); result = connection->perform(retrieveStmt); CPPUNIT_ASSERT(result.isValid()); CPPUNIT_ASSERT_EQUAL(result.getLongLong(1), (long long)3333); } void test_a_db_with_a_connection_with_tables::can_update_blob_attribute_bound_value() { // insert new object DB::Statement statement = connection->prepare( "insert into object default values"); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); long long object_id = connection->lastInsertRowId(); CPPUNIT_ASSERT(object_id != 0); // insert blob attribute statement = connection->prepare( "insert into attribute_blob (value,type,object_id) values (X'012345',%d,%lld)", 1236, object_id); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); // prepare update blob attribute statement statement = connection->prepare( "update attribute_blob set value=? where type=%d and object_id=%lld", 1236, object_id); CPPUNIT_ASSERT(statement.isValid()); // bind blob (with embedded zero!) to the parameter const char data[] = {10,11,0,12,13,14,15,16}; std::string msg(data,sizeof(data)); CPPUNIT_ASSERT(DB::Bindings(statement).bindBlob(1,msg.data(),msg.size(),NULL)); // update the blob value of the attribute CPPUNIT_ASSERT(connection->execute(statement)); // retrieve the blob value from the attribute statement = connection->prepare( "select value from attribute_blob as t where t.type=%d and t.object_id=%lld", 1236, object_id); CPPUNIT_ASSERT(statement.isValid()); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); // check that the retrieved blob value matches the original data. CPPUNIT_ASSERT_EQUAL(result.getFieldLength(1), sizeof(data)); std::string msgstored((const char *)result.getBinary(1),result.getFieldLength(1)); CPPUNIT_ASSERT_EQUAL(msg, msgstored); } void test_a_db_with_a_connection_with_tables::will_not_insert_non_existing_attribute_on_update() { DB::Statement statement; DB::Result result; // Insert new object statement = connection->prepare( "insert into object default values"); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); long long object_id = connection->lastInsertRowId(); CPPUNIT_ASSERT(object_id != 0); // Updating an attribute before it is created will succeed, but will not insert an attribute. statement = connection->prepare( "update attribute_boolean set value=1 where type=%d and object_id=%lld", 1237, object_id); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); // Retrieve the boolean value from the attribute should fail statement = connection->prepare( "select value from attribute_boolean as t where t.type=%d and t.object_id=%lld", 1237, object_id); CPPUNIT_ASSERT(statement.isValid()); result = connection->perform(statement); CPPUNIT_ASSERT(!result.isValid()); } void test_a_db_with_a_connection_with_tables::can_update_boolean_attribute_bound_value() { //SQLite doesn't have a boolean data type, use 0 (false) and 1 (true) DB::Statement statement; DB::Result result; // Insert new object statement = connection->prepare( "insert into object default values"); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); long long object_id = connection->lastInsertRowId(); CPPUNIT_ASSERT(object_id != 0); // insert boolean attribute statement = connection->prepare( "insert into attribute_boolean (value,type,object_id) values (1,%d,%lld)", 1237, object_id); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); // prepare update boolean attribute statement statement = connection->prepare( "update attribute_boolean set value=? where type=%d and object_id=%lld", 1237, object_id); CPPUNIT_ASSERT(statement.isValid()); // Bind 0 (false) to the first parameter CPPUNIT_ASSERT(DB::Bindings(statement).bindInt(1,0)); // Execute the statement to update the attribute value. CPPUNIT_ASSERT(connection->execute(statement)); // Retrieve the boolean value from the attribute statement = connection->prepare( "select value from attribute_boolean as t where t.type=%d and t.object_id=%lld", 1237, object_id); CPPUNIT_ASSERT(statement.isValid()); result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); // check that the retrieved value matches the original value CPPUNIT_ASSERT_EQUAL(result.getInt(1), 0); } void test_a_db_with_a_connection_with_tables::can_update_real_attribute_bound_value() { // insert new object DB::Statement statement = connection->prepare( "insert into object default values"); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); long long object_id = connection->lastInsertRowId(); CPPUNIT_ASSERT(object_id != 0); // insert real value statement = connection->prepare( "insert into attribute_real (value,type,object_id) values(%f,%d,%lld)", 1.238, 1238, object_id); CPPUNIT_ASSERT(statement.isValid()); CPPUNIT_ASSERT(connection->execute(statement)); // prepare update real attribute statement statement = connection->prepare( "update attribute_real set value=? where type=%d and object_id=%lld", 1238, object_id); CPPUNIT_ASSERT(statement.isValid()); // Bind 3333.3333 to the first parameter CPPUNIT_ASSERT(DB::Bindings(statement).bindDouble(1,3333.3333)); // Execute the statement to update the attribute value CPPUNIT_ASSERT(connection->execute(statement)); // Retrieve the double value from the attribute statement = connection->prepare( "select value from attribute_real as t where t.type=%d and t.object_id=%lld", 1238, object_id); CPPUNIT_ASSERT(statement.isValid()); DB::Result result = connection->perform(statement); CPPUNIT_ASSERT(result.isValid()); // check that the retrieved value matches the original value. CPPUNIT_ASSERT_DOUBLES_EQUAL(result.getDouble(1), 3333.3333, 0.00001); } void test_a_db_with_a_connection_with_tables::supports_transactions() { DB::LogErrorHandler eh = DB::setLogErrorHandler(dummy_print); CPPUNIT_ASSERT(!connection->rollbackTransaction()); DB::setLogErrorHandler(eh); CPPUNIT_ASSERT(connection->beginTransactionRW()); CPPUNIT_ASSERT(connection->rollbackTransaction()); eh = DB::setLogErrorHandler(dummy_print); CPPUNIT_ASSERT(!connection->commitTransaction()); DB::setLogErrorHandler(eh); CPPUNIT_ASSERT(connection->beginTransactionRW()); can_update_real_attribute_bound_value(); CPPUNIT_ASSERT(connection->commitTransaction()); } CPPUNIT_TEST_SUITE_REGISTRATION(test_a_db_with_a_connection_with_tables_with_a_second_connection_open); void test_a_db_with_a_connection_with_tables_with_a_second_connection_open::setUp() { test_a_db_with_a_connection_with_tables::setUp(); connection2 = DB::Connection::Create("testdir","TestToken"); CPPUNIT_ASSERT(connection2 != null); CPPUNIT_ASSERT(connection2->connect()); connection2->setBusyTimeout(10); } void test_a_db_with_a_connection_with_tables_with_a_second_connection_open::tearDown() { CPPUNIT_ASSERT(connection2 != null); connection2->close(); delete connection2; test_a_db_with_a_connection_with_tables::tearDown(); } void test_a_db_with_a_connection_with_tables_with_a_second_connection_open::handles_nested_transactions() { DB::LogErrorHandler eh = DB::setLogErrorHandler(dummy_print); DB::Connection *connection1 = connection; CPPUNIT_ASSERT(connection1->beginTransactionRW()); CPPUNIT_ASSERT(connection2->beginTransactionRO()); CPPUNIT_ASSERT(connection2->rollbackTransaction()); CPPUNIT_ASSERT(!connection2->beginTransactionRW()); CPPUNIT_ASSERT(connection1->commitTransaction()); DB::setLogErrorHandler(eh); } void test_a_db_with_a_connection_with_tables_with_a_second_connection_open::supports_transactions_with_other_connections_open() { CPPUNIT_ASSERT(connection2->beginTransactionRO()); supports_transactions(); // Retrieve the double value from the attribute DB::Statement statement = connection2->prepare( "select value from attribute_real as t where t.type=%d and t.object_id=%lld", 1238, connection->lastInsertRowId()); CPPUNIT_ASSERT(statement.isValid()); DB::Result result = connection2->perform(statement); CPPUNIT_ASSERT(result.isValid()); // check that the retrieved value matches the original value. CPPUNIT_ASSERT_DOUBLES_EQUAL(result.getDouble(1), 3333.3333, 0.00001); CPPUNIT_ASSERT(connection2->commitTransaction()); } softhsm-2.0.0/src/lib/object_store/test/DBObjectTests.cpp0000664000175000017500000007103012533040716020262 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBObjectTests.cpp Contains test cases to test the database token object implementation *****************************************************************************/ #include #include #include #include "DBObjectTests.h" #include "DBObject.h" #include #ifndef HAVE_SQLITE3_H #error expected sqlite3 to be available #endif CPPUNIT_TEST_SUITE_REGISTRATION(test_a_dbobject); void test_a_dbobject::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); connection = DB::Connection::Create("testdir","TestToken"); CPPUNIT_ASSERT(connection != NULL); CPPUNIT_ASSERT(connection->connect("<1>")); connection->setBusyTimeout(10); DBObject testObject(connection); CPPUNIT_ASSERT(testObject.startTransaction(DBObject::ReadWrite)); CPPUNIT_ASSERT(testObject.createTables()); CPPUNIT_ASSERT(testObject.commitTransaction()); connection2 = DB::Connection::Create("testdir","TestToken"); CPPUNIT_ASSERT(connection2 != NULL); CPPUNIT_ASSERT(connection2->connect("<2>")); connection2->setBusyTimeout(10); } void test_a_dbobject::tearDown() { CPPUNIT_ASSERT(connection != NULL); connection->close(); delete connection; CPPUNIT_ASSERT(connection2 != NULL); connection2->close(); delete connection2; #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void test_a_dbobject::should_be_insertable() { DBObject tokenObject(connection); CPPUNIT_ASSERT(!tokenObject.isValid()); CPPUNIT_ASSERT(tokenObject.insert()); CPPUNIT_ASSERT(tokenObject.isValid()); CPPUNIT_ASSERT_EQUAL(tokenObject.objectId(), (long long)1); } void test_a_dbobject::should_be_selectable() { should_be_insertable(); DBObject tokenObject(connection); CPPUNIT_ASSERT(tokenObject.find(1)); CPPUNIT_ASSERT(tokenObject.isValid()); } CPPUNIT_TEST_SUITE_REGISTRATION(test_a_dbobject_with_an_object); void test_a_dbobject_with_an_object::setUp() { test_a_dbobject::setUp(); DBObject tokenObject(connection); CPPUNIT_ASSERT(tokenObject.startTransaction(DBObject::ReadWrite)); CPPUNIT_ASSERT(!tokenObject.isValid()); CPPUNIT_ASSERT(tokenObject.insert()); CPPUNIT_ASSERT(tokenObject.isValid()); CPPUNIT_ASSERT_EQUAL(tokenObject.objectId(), (long long)1); CPPUNIT_ASSERT(tokenObject.commitTransaction()); } void test_a_dbobject_with_an_object::tearDown() { test_a_dbobject::tearDown(); } void test_a_dbobject_with_an_object::should_store_boolean_attributes() { { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; bool value2 = false; bool value3 = true; bool value4 = true; bool value5 = false; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SENSITIVE, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_EXTRACTABLE, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_NEVER_EXTRACTABLE, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr5)); } { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SENSITIVE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_EXTRACTABLE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_NEVER_EXTRACTABLE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SIGN)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SENSITIVE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_EXTRACTABLE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_NEVER_EXTRACTABLE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue()); CPPUNIT_ASSERT(!testObject.getAttribute(CKA_SENSITIVE).getBooleanValue()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_EXTRACTABLE).getBooleanValue()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_NEVER_EXTRACTABLE).getBooleanValue()); CPPUNIT_ASSERT(!testObject.getAttribute(CKA_SIGN).getBooleanValue()); bool value6 = true; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VERIFY, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VERIFY).isBooleanAttribute()); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_VERIFY).getBooleanValue(), value6); CPPUNIT_ASSERT_EQUAL(testObject.getBooleanValue(CKA_VERIFY, false), value6); } } void test_a_dbobject_with_an_object::should_store_unsigned_long_attributes() { // Add unsigned long attributes to the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); unsigned long value1 = 0x12345678; unsigned long value2 = 0x87654321; unsigned long value3 = 0x01010101; unsigned long value4 = 0x10101010; unsigned long value5 = 0xABCDEF; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_MODULUS_BITS, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_AUTH_PIN_FLAGS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBPRIME_BITS, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_KEY_TYPE, attr5)); } // Now read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_MODULUS_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_AUTH_PIN_FLAGS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBPRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_KEY_TYPE)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_AUTH_PIN_FLAGS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBPRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_KEY_TYPE).isUnsignedLongAttribute()); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_MODULUS_BITS).getUnsignedLongValue(), (unsigned long)0x12345678); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue(), (unsigned long)0x87654321); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_AUTH_PIN_FLAGS).getUnsignedLongValue(), (unsigned long)0x01010101); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_SUBPRIME_BITS).getUnsignedLongValue(), (unsigned long)0x10101010); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_KEY_TYPE).getUnsignedLongValue(), (unsigned long)0xABCDEF); unsigned long value6 = 0x90909090; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_CLASS, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_CLASS).isUnsignedLongAttribute()); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_CLASS).getUnsignedLongValue(), value6); CPPUNIT_ASSERT_EQUAL(testObject.getUnsignedLongValue(CKA_CLASS, 0x0), value6); } } void test_a_dbobject_with_an_object::should_store_binary_attributes() { ByteString value1 = "010203040506070809"; ByteString value2 = "ABABABABABABABABABABABABABABABABAB"; unsigned long value3 = 0xBDED; ByteString value4 = "98A7E5D798A7E5D798A7E5D798A7E5D798A7E5D798A7E5D7"; ByteString value5 = "ABCDABCDABCDABCDABCDABCDABCDABCD"; // Create the test object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_MODULUS, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_COEFFICIENT, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PUBLIC_EXPONENT, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBJECT, attr5)); } // Now read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_MODULUS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_COEFFICIENT)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PUBLIC_EXPONENT)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBJECT)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_COEFFICIENT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PUBLIC_EXPONENT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS).getByteStringValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_COEFFICIENT).getByteStringValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PUBLIC_EXPONENT).getByteStringValue() == value4); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).getByteStringValue() == value5); ByteString value6 = "909090908080808080807070707070FF"; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ISSUER, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ISSUER).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getByteStringValue(CKA_ISSUER) == value6); } } void test_a_dbobject_with_an_object::should_store_array_attributes() { bool value1 = true; unsigned long value2 = 0x87654321; ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; // Create the test object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); std::map mattr; mattr.insert(std::pair (CKA_TOKEN, attr1)); mattr.insert(std::pair (CKA_PRIME_BITS, attr2)); mattr.insert(std::pair (CKA_VALUE_BITS, attr3)); OSAttribute attra(mattr); CPPUNIT_ASSERT(testObject.setAttribute(CKA_WRAP_TEMPLATE, attra)); } // Now read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_WRAP_TEMPLATE)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_UNWRAP_TEMPLATE)); std::map mattrb = testObject.getAttribute(CKA_WRAP_TEMPLATE).getArrayValue(); CPPUNIT_ASSERT(mattrb.size() == 3); CPPUNIT_ASSERT(mattrb.find(CKA_TOKEN) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(mattrb.find(CKA_PRIME_BITS) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(mattrb.find(CKA_VALUE_BITS) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_VALUE_BITS).getByteStringValue() == value3); } } void test_a_dbobject_with_an_object::should_store_mixed_attributes() { bool value1 = true; unsigned long value2 = 0x87654321; unsigned long value3 = 0xBDEBDBED; // Create the test object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); } // Now read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue()); CPPUNIT_ASSERT_EQUAL(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue(), value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3); } } void test_a_dbobject_with_an_object::should_store_double_attributes() { bool value1 = true; bool value1a = false; // Create the test object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr1)); } // Now read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SIGN)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue()); OSAttribute attr1(value1a); // Change the attributes CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr1)); // Check the attributes CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue() == value1a); } // Now re-read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SIGN)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue() == value1a); } } void test_a_dbobject_with_an_object::can_refresh_attributes() { bool value1 = true; bool value1a = false; ByteString value2 = "BDEBDBEDBBDBEBDEBE792759537328"; ByteString value2a = "466487346943785684957634"; ByteString value3 = "0102010201020102010201020102010201020102"; // Create the test object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); OSAttribute attr2(value2); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBJECT, attr2)); } // Now read back the object { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SIGN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBJECT)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).getByteStringValue() == value2); OSAttribute attr1(value1a); OSAttribute attr2(value2a); // Change the attributes CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBJECT, attr2)); // Check the attributes CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).getByteStringValue() == value2a); // Open the object a second time DBObject testObject2(connection); CPPUNIT_ASSERT(testObject2.find(1)); CPPUNIT_ASSERT(testObject2.isValid()); // Check the attributes on the second instance CPPUNIT_ASSERT(testObject2.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_SUBJECT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_SIGN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_SUBJECT).getByteStringValue() == value2a); // Add an attribute on the second object OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ID, attr3)); // Check the attribute CPPUNIT_ASSERT(testObject2.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).getByteStringValue() == value3); // Now check that the first instance also knows about it CPPUNIT_ASSERT(testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).getByteStringValue() == value3); } } void test_a_dbobject_with_an_object::should_cleanup_statements_during_transactions() { // Create an object for accessing object 1 on the first connection. DBObject testObject(connection); // check transaction start(ro)/abort sequence CPPUNIT_ASSERT(testObject.startTransaction(OSObject::ReadOnly)); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.abortTransaction()); } void test_a_dbobject_with_an_object::should_use_transactions() { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; unsigned long value3 = 0xBDEBDBED; ByteString value4 = "AAAAAAAAAAAAAAAFFFFFFFFFFFFFFF"; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ID, attr4)); // Create secondary instance for the same object. // This needs to have a different connection to the database to simulate // another process accessing the data. DBObject testObject2(connection2); CPPUNIT_ASSERT(testObject2.find(1)); CPPUNIT_ASSERT(testObject2.isValid()); // Check that it has the same attributes CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).isByteStringAttribute()); // Check that the attributes have the same values as set on testObject. CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).getByteStringValue() == value4); // New values bool value1a = false; unsigned long value2a = 0x12345678; unsigned long value3a = 0xABABABAB; ByteString value4a = "EDEDEDEDEDEDEDEDEDEDEDEDEDEDED"; OSAttribute attr1a(value1a); OSAttribute attr2a(value2a); OSAttribute attr3a(value3a); OSAttribute attr4a(value4a); // Start transaction on object CPPUNIT_ASSERT(testObject.startTransaction(DBObject::ReadWrite)); // Change the attributes CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ID, attr4a)); // Verify that the attributes were set CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).getByteStringValue() == value4a); // Verify that they are unchanged on the other instance CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).getByteStringValue() == value4); // Commit the transaction CPPUNIT_ASSERT(testObject.commitTransaction()); // Verify that non-modifiable attributes did not propagate but modifiable attributes // have now changed on the other instance CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).isByteStringAttribute()); // NOTE: 3 attributes below cannot be modified after creation and therefore are not required to propagate. CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() != value1a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() != value2a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() != value3a); // CKA_ID attribute can be modified after creation and therefore should have propagated. CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).getByteStringValue() == value4a); // Start transaction on object CPPUNIT_ASSERT(testObject.startTransaction(DBObject::ReadWrite)); // Change the attributes CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ID, attr4)); // Verify that the attributes were set CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).getByteStringValue() == value4); // Create a fresh third instance for the same object to force the data to be retrieved from the database. DBObject testObject3(connection2); CPPUNIT_ASSERT(testObject3.find(1)); CPPUNIT_ASSERT(testObject3.isValid()); // Verify that they are unchanged on the other instance, while the transaction is still in progress. CPPUNIT_ASSERT(testObject3.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_ID).isByteStringAttribute()); // Verify that the attributes from the database are still hodling the same value as when the transaction started. CPPUNIT_ASSERT(testObject3.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3a); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_ID).getByteStringValue() == value4a); // Abort the transaction CPPUNIT_ASSERT(testObject.abortTransaction()); // Verify that after aborting the transaction the values in testObject have reverted back to their // original state. CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).isByteStringAttribute()); // After aborting a transaction the testObject should be back to pre transaction state. CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).getByteStringValue() == value4a); // Verify that testObject3 still has the original values. CPPUNIT_ASSERT(testObject3.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_VALUE_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_ID).isByteStringAttribute()); // Verify that testObject3 still has the original values. CPPUNIT_ASSERT(testObject3.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_VALUE_BITS).getUnsignedLongValue() == value3a); CPPUNIT_ASSERT(testObject3.getAttribute(CKA_ID).getByteStringValue() == value4a); } void test_a_dbobject_with_an_object::should_fail_to_delete() { DBObject testObject(connection); CPPUNIT_ASSERT(testObject.find(1)); CPPUNIT_ASSERT(testObject.isValid()); // We don't attach the object to a token, and therefore should not be able to destroy it. CPPUNIT_ASSERT(!testObject.destroyObject()); } softhsm-2.0.0/src/lib/object_store/test/DBObjectStoreTests.h0000664000175000017500000000535312533040716020751 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBObjectStoreTests.h Contains test cases to test the object store implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_DBOBJECTSTORETESTS_H #define _SOFTHSM_V2_DBOBJECTSTORETESTS_H #include #include "ObjectStore.h" #include "ObjectStoreToken.h" class test_a_newly_created_object_store : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test_a_newly_created_object_store); CPPUNIT_TEST(contains_no_items); CPPUNIT_TEST(can_create_a_new_token); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void contains_no_items(); void can_create_a_new_token(); protected: ObjectStore *store; ObjectStoreToken *nulltoken; private: }; class test_a_newly_created_object_store_containing_two_tokens : public test_a_newly_created_object_store { CPPUNIT_TEST_SUITE(test_a_newly_created_object_store_containing_two_tokens); CPPUNIT_TEST(has_two_tokens); CPPUNIT_TEST(can_access_both_tokens); CPPUNIT_TEST(assigned_labels_correctly_to_tokens); CPPUNIT_TEST(assigned_a_unique_serial_number_to_each_token); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void has_two_tokens(); void can_access_both_tokens(); void assigned_labels_correctly_to_tokens(); void assigned_a_unique_serial_number_to_each_token(); }; #endif // !_SOFTHSM_V2_DBOBJECTSTORETESTS_H softhsm-2.0.0/src/lib/object_store/test/DirectoryTests.cpp0000664000175000017500000001317712533040716020622 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DirectoryTests.cpp Contains test cases to test the directory implementation *****************************************************************************/ #include #include #include #include "DirectoryTests.h" #include "Directory.h" CPPUNIT_TEST_SUITE_REGISTRATION(DirectoryTests); void DirectoryTests::setUp() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("mkdir testdir")); CPPUNIT_ASSERT(!system("mkdir testdir/anotherdir")); CPPUNIT_ASSERT(!system("mkdir testdir/anotherdir2")); CPPUNIT_ASSERT(!system("mkdir testdir/anotherdir3")); CPPUNIT_ASSERT(!system("echo someStuff > testdir/afile")); CPPUNIT_ASSERT(!system("echo someOtherStuff > testdir/anotherFile")); CPPUNIT_ASSERT(!system("echo justStuff > testdir/justaFile")); #else CPPUNIT_ASSERT(!system("mkdir testdir")); CPPUNIT_ASSERT(!system("mkdir testdir\\anotherdir")); CPPUNIT_ASSERT(!system("mkdir testdir\\anotherdir2")); CPPUNIT_ASSERT(!system("mkdir testdir\\anotherdir3")); CPPUNIT_ASSERT(!system("echo someStuff > testdir\\afile")); CPPUNIT_ASSERT(!system("echo someOtherStuff > testdir\\anotherFile")); CPPUNIT_ASSERT(!system("echo justStuff > testdir\\justaFile")); #endif } void DirectoryTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void DirectoryTests::testDirectory() { #ifndef _WIN32 Directory testdir("./testdir"); #else Directory testdir(".\\testdir"); #endif CPPUNIT_ASSERT(testdir.isValid()); std::vector files = testdir.getFiles(); std::vector subDirs = testdir.getSubDirs(); CPPUNIT_ASSERT(files.size() == 3); CPPUNIT_ASSERT(subDirs.size() == 3); CPPUNIT_ASSERT(testdir.refresh()); CPPUNIT_ASSERT(files.size() == 3); CPPUNIT_ASSERT(subDirs.size() == 3); bool fileSeen[3] = { false, false, false }; for (std::vector::iterator i = files.begin(); i != files.end(); i++) { if (!i->compare("afile")) { fileSeen[0] = true; } else if (!i->compare("anotherFile")) { fileSeen[1] = true; } else if (!i->compare("justaFile")) { fileSeen[2] = true; } else { CPPUNIT_ASSERT(false); } } CPPUNIT_ASSERT(fileSeen[0] && fileSeen[1] && fileSeen[2]); bool dirSeen[3] = { false, false, false }; for (std::vector::iterator i = subDirs.begin(); i != subDirs.end(); i++) { if (!i->compare("anotherdir")) { dirSeen[0] = true; } else if (!i->compare("anotherdir2")) { dirSeen[1] = true; } else if (!i->compare("anotherdir3")) { dirSeen[2] = true; } else { CPPUNIT_ASSERT(false); } } CPPUNIT_ASSERT(dirSeen[0] && dirSeen[1] && dirSeen[2]); // Create a directory CPPUNIT_ASSERT(testdir.mkdir("newDir")); subDirs = testdir.getSubDirs(); bool dirSeen2[4] = { false, false, false, false }; for (std::vector::iterator i = subDirs.begin(); i != subDirs.end(); i++) { if (!i->compare("anotherdir")) { dirSeen2[0] = true; } else if (!i->compare("anotherdir2")) { dirSeen2[1] = true; } else if (!i->compare("anotherdir3")) { dirSeen2[2] = true; } else if (!i->compare("newDir")) { dirSeen2[3] = true; } else { CPPUNIT_ASSERT(false); } } CPPUNIT_ASSERT(dirSeen2[0] && dirSeen2[1] && dirSeen2[2] && dirSeen2[3]); // Remove a directory CPPUNIT_ASSERT(testdir.rmdir("anotherdir2", true)); subDirs = testdir.getSubDirs(); bool dirSeen3[3] = { false, false, false }; for (std::vector::iterator i = subDirs.begin(); i != subDirs.end(); i++) { if (!i->compare("anotherdir")) { dirSeen3[0] = true; } else if (!i->compare("newDir")) { dirSeen3[1] = true; } else if (!i->compare("anotherdir3")) { dirSeen3[2] = true; } else { CPPUNIT_ASSERT(false); } } CPPUNIT_ASSERT(dirSeen3[0] && dirSeen3[1] && dirSeen3[2]); // Remove a file CPPUNIT_ASSERT(testdir.remove("anotherFile")); files = testdir.getFiles(); bool fileSeen2[2] = { false, false }; for (std::vector::iterator i = files.begin(); i != files.end(); i++) { if (!i->compare("afile")) { fileSeen2[0] = true; } else if (!i->compare("justaFile")) { fileSeen2[1] = true; } else { CPPUNIT_ASSERT(false); } } CPPUNIT_ASSERT(fileSeen2[0] && fileSeen2[1]); } softhsm-2.0.0/src/lib/object_store/test/DBObjectStoreTests.cpp0000664000175000017500000001205512533040716021301 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBObjectStoreTests.cpp Contains test cases to test the object store implementation *****************************************************************************/ #include #include #include #include "DBObjectStoreTests.h" #include #ifndef HAVE_SQLITE3_H #error expected sqlite3 to be available #endif CPPUNIT_TEST_SUITE_REGISTRATION(test_a_newly_created_object_store); void test_a_newly_created_object_store::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); ObjectStoreToken::selectBackend("db"); store = new ObjectStore("testdir"); nulltoken = NULL; } void test_a_newly_created_object_store::tearDown() { delete store; ObjectStoreToken::selectBackend("file"); #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void test_a_newly_created_object_store::contains_no_items() { CPPUNIT_ASSERT_EQUAL(store->getTokenCount(), (size_t)0); } void test_a_newly_created_object_store::can_create_a_new_token() { ByteString label1 = "DEADC0FFEE"; ObjectStoreToken *token1 = store->newToken(label1); CPPUNIT_ASSERT(token1 != nulltoken); CPPUNIT_ASSERT_EQUAL(store->getTokenCount(), (size_t)1); } CPPUNIT_TEST_SUITE_REGISTRATION(test_a_newly_created_object_store_containing_two_tokens); void test_a_newly_created_object_store_containing_two_tokens::setUp() { test_a_newly_created_object_store::setUp(); ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ObjectStoreToken* token1 = store->newToken(label1); CPPUNIT_ASSERT(token1 != nulltoken); CPPUNIT_ASSERT_EQUAL(store->getTokenCount(), (size_t)1); ObjectStoreToken* token2 = store->newToken(label2); CPPUNIT_ASSERT(token2 != nulltoken); CPPUNIT_ASSERT_EQUAL(store->getTokenCount(), (size_t)2); } void test_a_newly_created_object_store_containing_two_tokens::tearDown() { ObjectStoreToken* token1 = store->getToken(0); ObjectStoreToken* token2 = store->getToken(1); CPPUNIT_ASSERT(store->destroyToken(token1)); CPPUNIT_ASSERT(store->destroyToken(token2)); test_a_newly_created_object_store::tearDown(); } void test_a_newly_created_object_store_containing_two_tokens::has_two_tokens() { CPPUNIT_ASSERT_EQUAL(store->getTokenCount(), (size_t)2); } void test_a_newly_created_object_store_containing_two_tokens::can_access_both_tokens() { // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store->getToken(0); ObjectStoreToken* token2 = store->getToken(1); CPPUNIT_ASSERT(token1 != nulltoken); CPPUNIT_ASSERT(token2 != nulltoken); } void test_a_newly_created_object_store_containing_two_tokens::assigned_labels_correctly_to_tokens() { ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store->getToken(0); ObjectStoreToken* token2 = store->getToken(1); ByteString retrieveLabel1, retrieveLabel2; CPPUNIT_ASSERT(token1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(token2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(label1 == retrieveLabel1 || label1 == retrieveLabel2); CPPUNIT_ASSERT(label2 == retrieveLabel1 || label2 == retrieveLabel2); CPPUNIT_ASSERT(label1 != label2); } void test_a_newly_created_object_store_containing_two_tokens::assigned_a_unique_serial_number_to_each_token() { // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store->getToken(0); ObjectStoreToken* token2 = store->getToken(1); ByteString retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(token1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(token2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } softhsm-2.0.0/src/lib/object_store/test/FileTests.cpp0000664000175000017500000002027312533040716017530 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** FileTests.cpp Contains test cases to test the file implementation *****************************************************************************/ #include #include #include #include "FileTests.h" #include "File.h" #include "Directory.h" #include "CryptoFactory.h" #include "RNG.h" CPPUNIT_TEST_SUITE_REGISTRATION(FileTests); // FIXME: all pathnames in this file are *NIX/BSD specific void FileTests::setUp() { #ifndef _WIN32 int rv = system("rm -rf testdir"); #else int rv = system("rmdir /s /q testdir 2> nul"); #endif (void) rv; CPPUNIT_ASSERT(!system("mkdir testdir")); } void FileTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void FileTests::testExistNotExist() { // Test pre-condition CPPUNIT_ASSERT(!exists("nonExistentFile")); // Attempt to open a file known not to exist #ifndef _WIN32 File doesntExist("testdir/nonExistentFile"); #else File doesntExist("testdir\\nonExistentFile"); #endif CPPUNIT_ASSERT(!doesntExist.isValid()); // Attempt to open a file known to exist #ifndef _WIN32 CPPUNIT_ASSERT(!system("echo someStuff > testdir/existingFile")); #else CPPUNIT_ASSERT(!system("echo someStuff > testdir\\existingFile")); #endif CPPUNIT_ASSERT(exists("existingFile")); #ifndef _WIN32 File exists("testdir/existingFile"); #else File exists("testdir\\existingFile"); #endif CPPUNIT_ASSERT(exists.isValid()); } void FileTests::testCreateNotCreate() { // Test pre-condition CPPUNIT_ASSERT(!exists("nonExistentFile")); CPPUNIT_ASSERT(!exists("nonExistentFile2")); // Attempt to open a file known not to exist #ifndef _WIN32 File doesntExist("testdir/nonExistentFile", true, true, false); #else File doesntExist("testdir\\nonExistentFile", true, true, false); #endif CPPUNIT_ASSERT(!doesntExist.isValid()); CPPUNIT_ASSERT(!exists("nonExistentFile")); // Attempt to open a file known not to exist in create mode #ifndef _WIN32 File willBeCreated("testdir/nonExistentFile2", true, true, true); #else File willBeCreated("testdir\\nonExistentFile2", true, true, true); #endif CPPUNIT_ASSERT(willBeCreated.isValid()); CPPUNIT_ASSERT(exists("nonExistentFile2")); } void FileTests::testLockUnlock() { // Create pre-condition #ifndef _WIN32 CPPUNIT_ASSERT(!system("echo someStuff > testdir/existingFile")); #else CPPUNIT_ASSERT(!system("echo someStuff > testdir\\existingFile")); #endif CPPUNIT_ASSERT(exists("existingFile")); #ifndef _WIN32 File file1("testdir/existingFile"); File file2("testdir/existingFile"); #else File file1("testdir\\existingFile"); File file2("testdir\\existingFile"); #endif CPPUNIT_ASSERT(file1.lock(false)); CPPUNIT_ASSERT(!file1.lock(false)); CPPUNIT_ASSERT(file2.lock(false)); CPPUNIT_ASSERT(file2.unlock()); CPPUNIT_ASSERT(file1.unlock()); CPPUNIT_ASSERT(file1.lock()); CPPUNIT_ASSERT(file2.lock()); CPPUNIT_ASSERT(file2.unlock()); CPPUNIT_ASSERT(file1.unlock()); } void FileTests::testWriteRead() { // Generate some test data RNG* rng = CryptoFactory::i()->getRNG(); ByteString testData1; CPPUNIT_ASSERT(rng->generateRandom(testData1, 187)); // More test data std::string testString = "This is a test of the File class"; // Create a file for writing { #ifndef _WIN32 File newFile("testdir/newFile", false, true); #else File newFile("testdir\\newFile", false, true); #endif CPPUNIT_ASSERT(newFile.isValid()); // Write two booleans into the file CPPUNIT_ASSERT(newFile.writeBool(true)); CPPUNIT_ASSERT(newFile.writeBool(false)); // Write an ulong into the file CPPUNIT_ASSERT(newFile.writeULong(0x12345678)); // Write a ByteString into the file CPPUNIT_ASSERT(newFile.writeByteString(testData1)); // Write a string into the file CPPUNIT_ASSERT(newFile.writeString(testString)); } CPPUNIT_ASSERT(exists("newFile")); // Read the created file back { #ifndef _WIN32 File newFile("testdir/newFile"); #else File newFile("testdir\\newFile"); #endif CPPUNIT_ASSERT(newFile.isValid()); // Read back the two booleans bool b1, b2; CPPUNIT_ASSERT(newFile.readBool(b1) && newFile.readBool(b2)); CPPUNIT_ASSERT(b1 && !b2); // Read back the ulong unsigned long ulongValue; CPPUNIT_ASSERT(newFile.readULong(ulongValue)); CPPUNIT_ASSERT(ulongValue == 0x12345678); // Read back the byte string ByteString bsValue; CPPUNIT_ASSERT(newFile.readByteString(bsValue)); CPPUNIT_ASSERT(bsValue == testData1); // Read back the string value std::string stringVal; CPPUNIT_ASSERT(newFile.readString(stringVal)); CPPUNIT_ASSERT(!testString.compare(stringVal)); // Check for EOF CPPUNIT_ASSERT(!newFile.readBool(b1)); CPPUNIT_ASSERT(newFile.isEOF()); } } void FileTests::testSeek() { ByteString t1 = "112233445566778899"; // 9 long ByteString t2 = "AABBCCDDEEFFAABBCCDDEEFF"; // 12 long { // Create the test file #ifndef _WIN32 File testFile("testdir/testFile", false, true, true); #else File testFile("testdir\\testFile", false, true, true); #endif CPPUNIT_ASSERT(testFile.isValid()); // Write the test data to the test file CPPUNIT_ASSERT(testFile.writeByteString(t1) && testFile.writeByteString(t2)); } // Open the test file for reading #ifndef _WIN32 File testFile("testdir/testFile"); #else File testFile("testdir\\testFile"); #endif CPPUNIT_ASSERT(testFile.isValid()); // First, read back the test data ByteString tr1, tr2; CPPUNIT_ASSERT(testFile.readByteString(tr1) && testFile.readByteString(tr2)); CPPUNIT_ASSERT(tr1 == t1); CPPUNIT_ASSERT(tr2 == t2); // Seek to the length field of the second byte string CPPUNIT_ASSERT(testFile.seek(8+9)); // Read back the size as an ulong value unsigned long value; unsigned long expectedValue = (unsigned long)0x1122334455667788ULL; CPPUNIT_ASSERT(testFile.readULong(value)); CPPUNIT_ASSERT(value == 12); // Seek to the start of the first byte string's data CPPUNIT_ASSERT(testFile.seek(8)); // Read back the ulong value stored there CPPUNIT_ASSERT(testFile.readULong(value)); CPPUNIT_ASSERT(value == expectedValue); // Seek to the start of second byte string CPPUNIT_ASSERT(testFile.seek(8+9)); // Read it ByteString trr2; CPPUNIT_ASSERT(testFile.readByteString(trr2)); CPPUNIT_ASSERT(trr2 == t2); // Rewind the file CPPUNIT_ASSERT(testFile.rewind()); // Read back both byte strings ByteString trrr1, trrr2; CPPUNIT_ASSERT(testFile.readByteString(trrr1) && testFile.readByteString(trrr2)); CPPUNIT_ASSERT(trrr1 == t1); CPPUNIT_ASSERT(trrr2 == t2); } bool FileTests::exists(std::string name) { #ifndef _WIN32 Directory dir("./testdir"); #else Directory dir(".\\testdir"); #endif CPPUNIT_ASSERT(dir.isValid()); std::vector files = dir.getFiles(); for (std::vector::iterator i = files.begin(); i != files.end(); i++) { if (!i->compare(name)) { return true; } } return false; } softhsm-2.0.0/src/lib/object_store/test/DBTests.h0000664000175000017500000001052112533040716016576 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBTests.h Contains lowest level test cases for the database backend implementation. *****************************************************************************/ #ifndef _SOFTHSM_V2_DBTESTS_H #define _SOFTHSM_V2_DBTESTS_H #include #include "DB.h" class test_a_db : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test_a_db); CPPUNIT_TEST(checks_for_empty_connection_parameters); CPPUNIT_TEST(can_be_connected_to_database); CPPUNIT_TEST_SUITE_END(); public: void checks_for_empty_connection_parameters(); void can_be_connected_to_database(); void setUp(); void tearDown(); protected: DB::Connection *null; private: }; class test_a_db_with_a_connection : public test_a_db { CPPUNIT_TEST_SUITE(test_a_db_with_a_connection); CPPUNIT_TEST(can_prepare_statements); CPPUNIT_TEST(can_perform_statements); CPPUNIT_TEST(maintains_correct_refcounts); CPPUNIT_TEST(can_create_tables); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void can_prepare_statements(); void can_perform_statements(); void maintains_correct_refcounts(); void can_create_tables(); protected: DB::Connection *connection; private: }; class test_a_db_with_a_connection_with_tables : public test_a_db_with_a_connection { CPPUNIT_TEST_SUITE(test_a_db_with_a_connection_with_tables); CPPUNIT_TEST(can_insert_records); CPPUNIT_TEST(can_retrieve_records); CPPUNIT_TEST(can_cascade_delete_objects_and_attributes); CPPUNIT_TEST(can_update_text_attribute); CPPUNIT_TEST(can_update_text_attribute_bound_value); CPPUNIT_TEST(can_update_integer_attribute_bound_value); CPPUNIT_TEST(can_update_blob_attribute_bound_value); CPPUNIT_TEST(will_not_insert_non_existing_attribute_on_update); CPPUNIT_TEST(can_update_boolean_attribute_bound_value); CPPUNIT_TEST(can_update_real_attribute_bound_value); CPPUNIT_TEST(supports_transactions); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void can_insert_records(); void can_retrieve_records(); void can_cascade_delete_objects_and_attributes(); void can_update_text_attribute(); void can_update_text_attribute_bound_value(); void can_update_integer_attribute_bound_value(); void can_update_blob_attribute_bound_value(); void will_not_insert_non_existing_attribute_on_update(); void can_update_boolean_attribute_bound_value(); void can_update_real_attribute_bound_value(); void supports_transactions(); protected: private: }; class test_a_db_with_a_connection_with_tables_with_a_second_connection_open : public test_a_db_with_a_connection_with_tables { CPPUNIT_TEST_SUITE(test_a_db_with_a_connection_with_tables_with_a_second_connection_open); CPPUNIT_TEST(handles_nested_transactions); CPPUNIT_TEST(supports_transactions_with_other_connections_open); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void handles_nested_transactions(); void supports_transactions_with_other_connections_open(); protected: DB::Connection *connection2; private: }; #endif // !_SOFTHSM_V2_DBTESTS_H softhsm-2.0.0/src/lib/object_store/test/DBTokenTests.h0000664000175000017500000000460012533040716017600 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBTokenTests.h Contains test cases to test the database token implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_DBTOKENTESTS_H #define _SOFTHSM_V2_DBTOKENTESTS_H #include #include "DBToken.h" class test_a_dbtoken : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(test_a_dbtoken); CPPUNIT_TEST(should_be_creatable); CPPUNIT_TEST(should_support_pin_setting_getting); CPPUNIT_TEST(should_allow_object_enumeration); CPPUNIT_TEST(should_fail_to_open_nonexistant_tokens); CPPUNIT_TEST(support_create_delete_objects); CPPUNIT_TEST(support_clearing_a_token); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void should_be_creatable(); void should_support_pin_setting_getting(); void should_allow_object_enumeration(); void should_fail_to_open_nonexistant_tokens(); void support_create_delete_objects(); void support_clearing_a_token(); protected: private: }; #endif // !_SOFTHSM_V2_DBTOKENTESTS_H softhsm-2.0.0/src/lib/object_store/test/objstoretest.cpp0000664000175000017500000000400612533040716020351 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** objstoretest.cpp The main test executor for tests on the object store in SoftHSM v2 *****************************************************************************/ #include #include #include "CryptoFactory.h" #include "SecureMemoryRegistry.h" int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); CryptoFactory::reset(); SecureMemoryRegistry::reset(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/object_store/test/Makefile.in0000664000175000017500000010514012552216620017164 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = objstoretest$(EXEEXT) @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__append_1 = DBTests.cpp \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBObjectTests.cpp \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBTokenTests.cpp \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBObjectStoreTests.cpp TESTS = objstoretest$(EXEEXT) subdir = src/lib/object_store/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am__objstoretest_SOURCES_DIST = objstoretest.cpp DirectoryTests.cpp \ UUIDTests.cpp FileTests.cpp ObjectFileTests.cpp \ OSTokenTests.cpp ObjectStoreTests.cpp SessionObjectTests.cpp \ SessionObjectStoreTests.cpp DBTests.cpp DBObjectTests.cpp \ DBTokenTests.cpp DBObjectStoreTests.cpp @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__objects_1 = DBTests.$(OBJEXT) \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBObjectTests.$(OBJEXT) \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBTokenTests.$(OBJEXT) \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBObjectStoreTests.$(OBJEXT) am_objstoretest_OBJECTS = objstoretest.$(OBJEXT) \ DirectoryTests.$(OBJEXT) UUIDTests.$(OBJEXT) \ FileTests.$(OBJEXT) ObjectFileTests.$(OBJEXT) \ OSTokenTests.$(OBJEXT) ObjectStoreTests.$(OBJEXT) \ SessionObjectTests.$(OBJEXT) SessionObjectStoreTests.$(OBJEXT) \ $(am__objects_1) objstoretest_OBJECTS = $(am_objstoretest_OBJECTS) objstoretest_DEPENDENCIES = ../../libsofthsm_convarch.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = objstoretest_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(objstoretest_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(objstoretest_SOURCES) DIST_SOURCES = $(am__objstoretest_SOURCES_DIST) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../crypto \ -I$(srcdir)/../../data_mgr \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ `cppunit-config --cflags` objstoretest_SOURCES = objstoretest.cpp DirectoryTests.cpp \ UUIDTests.cpp FileTests.cpp ObjectFileTests.cpp \ OSTokenTests.cpp ObjectStoreTests.cpp SessionObjectTests.cpp \ SessionObjectStoreTests.cpp $(am__append_1) objstoretest_LDADD = ../../libsofthsm_convarch.la objstoretest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` -pthread EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/object_store/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/object_store/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list objstoretest$(EXEEXT): $(objstoretest_OBJECTS) $(objstoretest_DEPENDENCIES) $(EXTRA_objstoretest_DEPENDENCIES) @rm -f objstoretest$(EXEEXT) $(AM_V_CXXLD)$(objstoretest_LINK) $(objstoretest_OBJECTS) $(objstoretest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DBObjectStoreTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DBObjectTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DBTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DBTokenTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DirectoryTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/FileTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSTokenTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ObjectFileTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ObjectStoreTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionObjectStoreTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionObjectTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/UUIDTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/objstoretest.Po@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? objstoretest.log: objstoretest$(EXEEXT) @p='objstoretest$(EXEEXT)'; \ b='objstoretest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/object_store/test/ObjectFileTests.cpp0000664000175000017500000007411612533040716020664 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectObjectFileTests.cpp Contains test cases to test the object file implementation *****************************************************************************/ #include #include #include #include #include "ObjectFileTests.h" #include "ObjectFile.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "CryptoFactory.h" #include "RNG.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(ObjectFileTests); // FIXME: all pathnames in this file are *NIX/BSD specific void ObjectFileTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void ObjectFileTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void ObjectFileTests::testBoolAttr() { // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; bool value2 = false; bool value3 = true; bool value4 = true; bool value5 = false; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SENSITIVE, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_EXTRACTABLE, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_NEVER_EXTRACTABLE, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SIGN, attr5)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SENSITIVE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_EXTRACTABLE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_NEVER_EXTRACTABLE)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SIGN)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SENSITIVE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_EXTRACTABLE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_NEVER_EXTRACTABLE).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SENSITIVE).getBooleanValue() == false); CPPUNIT_ASSERT(testObject.getAttribute(CKA_EXTRACTABLE).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_NEVER_EXTRACTABLE).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SIGN).getBooleanValue() == false); bool value6 = true; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VERIFY, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VERIFY).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VERIFY).getBooleanValue() == value6); CPPUNIT_ASSERT(testObject.getBooleanValue(CKA_VERIFY, false) == value6); } } void ObjectFileTests::testULongAttr() { // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); unsigned long value1 = 0x12345678; unsigned long value2 = 0x87654321; unsigned long value3 = 0x01010101; unsigned long value4 = 0x10101010; unsigned long value5 = 0xABCDEF; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_MODULUS_BITS, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_AUTH_PIN_FLAGS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBPRIME_BITS, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_KEY_TYPE, attr5)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_MODULUS_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_AUTH_PIN_FLAGS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBPRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_KEY_TYPE)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_AUTH_PIN_FLAGS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBPRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_KEY_TYPE).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS_BITS).getUnsignedLongValue() == 0x12345678); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_AUTH_PIN_FLAGS).getUnsignedLongValue() == 0x01010101); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBPRIME_BITS).getUnsignedLongValue() == 0x10101010); CPPUNIT_ASSERT(testObject.getAttribute(CKA_KEY_TYPE).getUnsignedLongValue() == 0xABCDEF); unsigned long value6 = 0x90909090; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_CLASS, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_CLASS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_CLASS).getUnsignedLongValue() == value6); CPPUNIT_ASSERT(testObject.getUnsignedLongValue(CKA_CLASS, 0x0) == value6); } } void ObjectFileTests::testByteStrAttr() { ByteString value1 = "010203040506070809"; ByteString value2 = "ABABABABABABABABABABABABABABABABAB"; ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; ByteString value4 = "98A7E5D798A7E5D798A7E5D798A7E5D798A7E5D798A7E5D7"; ByteString value5 = "ABCDABCDABCDABCDABCDABCDABCDABCD"; // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); OSAttribute attr4(value4); OSAttribute attr5(value5); CPPUNIT_ASSERT(testObject.setAttribute(CKA_MODULUS, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_COEFFICIENT, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PUBLIC_EXPONENT, attr4)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_SUBJECT, attr5)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_MODULUS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_COEFFICIENT)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PUBLIC_EXPONENT)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_SUBJECT)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_COEFFICIENT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PUBLIC_EXPONENT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_MODULUS).getByteStringValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_COEFFICIENT).getByteStringValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PUBLIC_EXPONENT).getByteStringValue() == value4); CPPUNIT_ASSERT(testObject.getAttribute(CKA_SUBJECT).getByteStringValue() == value5); ByteString value6 = "909090908080808080807070707070FF"; OSAttribute attr6(value6); CPPUNIT_ASSERT(testObject.setAttribute(CKA_ISSUER, attr6)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ISSUER).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getByteStringValue(CKA_ISSUER) == value6); } } void ObjectFileTests::testArrayAttr() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); std::map mattr; mattr.insert(std::pair (CKA_TOKEN, attr1)); mattr.insert(std::pair (CKA_PRIME_BITS, attr2)); mattr.insert(std::pair (CKA_VALUE_BITS, attr3)); OSAttribute attra(mattr); CPPUNIT_ASSERT(testObject.setAttribute(CKA_WRAP_TEMPLATE, attra)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_WRAP_TEMPLATE)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_UNWRAP_TEMPLATE)); std::map mattrb = testObject.getAttribute(CKA_WRAP_TEMPLATE).getArrayValue(); CPPUNIT_ASSERT(mattrb.size() == 3); CPPUNIT_ASSERT(mattrb.find(CKA_TOKEN) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(mattrb.find(CKA_PRIME_BITS) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(mattrb.find(CKA_VALUE_BITS) != mattrb.end()); CPPUNIT_ASSERT(mattrb.at(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(mattrb.at(CKA_VALUE_BITS).getByteStringValue() == value3); } } void ObjectFileTests::testMixedAttr() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); } } void ObjectFileTests::testDoubleAttr() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; ByteString value3a = "466487346943785684957634"; // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); bool value1 = false; unsigned long value2 = 0x76767676; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3a); // Change the attributes CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); // Check the attributes CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); } // Now re-read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); bool value1 = false; unsigned long value2 = 0x76767676; CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); } } void ObjectFileTests::testRefresh() { ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; ByteString value3a = "466487346943785684957634"; // Create the test object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); } // Now read back the object { #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_TOKEN)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_PRIME_BITS)); CPPUNIT_ASSERT(testObject.attributeExists(CKA_VALUE_BITS)); CPPUNIT_ASSERT(!testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == true); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == 0x87654321); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); bool value1 = false; unsigned long value2 = 0x76767676; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3a); // Change the attributes CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); // Check the attributes CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); // Open the object a second time #ifndef _WIN32 ObjectFile testObject2(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject2(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject2.isValid()); // Check the attributes on the second instance CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); // Add an attribute on the second object ByteString id = "0102010201020102010201020102010201020102"; OSAttribute attr4(id); CPPUNIT_ASSERT(testObject2.setAttribute(CKA_ID, attr4)); // Check the attribute CPPUNIT_ASSERT(testObject2.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_ID).getByteStringValue() == id); // Now check that the first instance also knows about it CPPUNIT_ASSERT(testObject.isValid()); CPPUNIT_ASSERT(testObject.attributeExists(CKA_ID)); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_ID).getByteStringValue() == id); // Now change another attribute unsigned long value2a = 0x89898989; OSAttribute attr2a(value2a); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2a)); // Check the attribute CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); // Now check that the second instance also knows about the change CPPUNIT_ASSERT(testObject2.isValid()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); } } void ObjectFileTests::testCorruptFile() { #ifndef _WIN32 FILE* stream = fopen("testdir/test.object", "w"); #else FILE* stream = fopen("testdir\\test.object", "wb"); #endif RNG* rng = CryptoFactory::i()->getRNG(); ByteString randomData; CPPUNIT_ASSERT(stream != NULL); CPPUNIT_ASSERT(rng->generateRandom(randomData, 312)); CPPUNIT_ASSERT(fwrite(randomData.const_byte_str(), 1, randomData.size(), stream) == randomData.size()); CPPUNIT_ASSERT(!fclose(stream)); #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(!testObject.isValid()); } void ObjectFileTests::testTransactions() { // Create test object instance #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); bool value1 = true; unsigned long value2 = 0x87654321; ByteString value3 = "BDEBDBEDBBDBEBDEBE792759537328"; OSAttribute attr1(value1); OSAttribute attr2(value2); OSAttribute attr3(value3); CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); // Create secondary instance for the same object #ifndef _WIN32 ObjectFile testObject2(NULL, "testdir/test.object", "testdir/test.lock"); #else ObjectFile testObject2(NULL, "testdir\\test.object", "testdir\\test.lock"); #endif CPPUNIT_ASSERT(testObject2.isValid()); // Check that it has the same attributes CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); // New values bool value1a = false; unsigned long value2a = 0x12345678; ByteString value3a = "ABABABABABABABABABABABABABABAB"; OSAttribute attr1a(value1a); OSAttribute attr2a(value2a); OSAttribute attr3a(value3a); // Start transaction on object CPPUNIT_ASSERT(testObject.startTransaction(ObjectFile::ReadWrite)); // Change the attributes CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2a)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3a)); // Verify that the attributes were set CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); // Verify that they are unchanged on the other instance CPPUNIT_ASSERT(testObject2.isValid()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); // Commit the transaction CPPUNIT_ASSERT(testObject.commitTransaction()); // Verify that they have now changed on the other instance CPPUNIT_ASSERT(testObject2.isValid()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); // Start transaction on object CPPUNIT_ASSERT(testObject.startTransaction(ObjectFile::ReadWrite)); // Change the attributes CPPUNIT_ASSERT(testObject.setAttribute(CKA_TOKEN, attr1)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_PRIME_BITS, attr2)); CPPUNIT_ASSERT(testObject.setAttribute(CKA_VALUE_BITS, attr3)); // Verify that the attributes were set CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3); // Verify that they are unchanged on the other instance CPPUNIT_ASSERT(testObject2.isValid()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); // Abort the transaction CPPUNIT_ASSERT(testObject.abortTransaction()); // Verify that they are unchanged on both instances CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); CPPUNIT_ASSERT(testObject2.isValid()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).isBooleanAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).isUnsignedLongAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).isByteStringAttribute()); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_TOKEN).getBooleanValue() == value1a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_PRIME_BITS).getUnsignedLongValue() == value2a); CPPUNIT_ASSERT(testObject2.getAttribute(CKA_VALUE_BITS).getByteStringValue() == value3a); } void ObjectFileTests::testDestroyObjectFails() { // Create test object instance #ifndef _WIN32 ObjectFile testObject(NULL, "testdir/test.object", "testdir/test.lock", true); #else ObjectFile testObject(NULL, "testdir\\test.object", "testdir\\test.lock", true); #endif CPPUNIT_ASSERT(testObject.isValid()); OSObject* testIF = (OSObject*) &testObject; CPPUNIT_ASSERT(!testIF->destroyObject()); } softhsm-2.0.0/src/lib/object_store/test/FileTests.h0000664000175000017500000000416512533040716017177 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** FileTests.h Contains test cases to test the File implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_FILETESTS_H #define _SOFTHSM_V2_FILETESTS_H #include class FileTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(FileTests); CPPUNIT_TEST(testExistNotExist); CPPUNIT_TEST(testCreateNotCreate); CPPUNIT_TEST(testLockUnlock); CPPUNIT_TEST(testWriteRead); CPPUNIT_TEST(testSeek); CPPUNIT_TEST_SUITE_END(); public: void testExistNotExist(); void testCreateNotCreate(); void testLockUnlock(); void testWriteRead(); void testSeek(); void setUp(); void tearDown(); private: bool exists(std::string path); }; #endif // !_SOFTHSM_V2_FILETESTS_H softhsm-2.0.0/src/lib/object_store/test/DBTokenTests.cpp0000664000175000017500000003420512533040716020137 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBTokenTests.cpp Contains test cases to test the database token implementation *****************************************************************************/ #include #include #include #include "DBTokenTests.h" #include "DBToken.h" #include "DB.h" #include #ifndef HAVE_SQLITE3_H #error expected sqlite3 to be available #endif CPPUNIT_TEST_SUITE_REGISTRATION(test_a_dbtoken); static int dummy_print(const char *, va_list ) { return 0; } void test_a_dbtoken::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void test_a_dbtoken::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void test_a_dbtoken::should_be_creatable() { ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; ObjectStoreToken* newToken = new DBToken("testdir", "newToken", label, serial); CPPUNIT_ASSERT(newToken != NULL); CPPUNIT_ASSERT(newToken->isValid()); delete newToken; } void test_a_dbtoken::should_support_pin_setting_getting() { // Create a new token ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; ObjectStoreToken* newToken = new DBToken("testdir", "newToken", label, serial); CPPUNIT_ASSERT(newToken != NULL); CPPUNIT_ASSERT(newToken->isValid()); // Check the flags CK_ULONG flags; CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)( CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED)); // Set the SO PIN ByteString soPIN = "3132333435363738"; // 12345678 CPPUNIT_ASSERT(newToken->setSOPIN(soPIN)); // Set the user PIN ByteString userPIN = "31323334"; // 1234 CPPUNIT_ASSERT(newToken->setUserPIN(userPIN)); CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)(CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); delete newToken; // Now reopen the newly created token DBToken reopenedToken("testdir","newToken"); CPPUNIT_ASSERT(reopenedToken.isValid()); // Retrieve the flags, user PIN and so PIN ByteString retrievedSOPIN, retrievedUserPIN; CPPUNIT_ASSERT(reopenedToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(reopenedToken.getUserPIN(retrievedUserPIN)); CPPUNIT_ASSERT(reopenedToken.getTokenFlags(flags)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); CPPUNIT_ASSERT(retrievedUserPIN == userPIN); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)(CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); } void test_a_dbtoken::should_allow_object_enumeration() { ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; ByteString soPIN = "31323334"; // 1234 ByteString userPIN = "30303030"; // 0000 ByteString id[3] = { "112233445566", "AABBCCDDEEFF", "ABABABABABAB" }; { // Instantiate a new token ObjectStoreToken* newToken = new DBToken("testdir", "existingToken", label, serial); CPPUNIT_ASSERT(newToken != NULL); CPPUNIT_ASSERT(newToken->isValid()); CPPUNIT_ASSERT(newToken->setSOPIN(soPIN)); CPPUNIT_ASSERT(newToken->setUserPIN(userPIN)); // Test IDs OSAttribute idAtt[3] = { id[0], id[1], id[2] }; // Create 3 objects on the token OSObject* obj1 = newToken->createObject(); CPPUNIT_ASSERT(obj1 != NULL); OSObject* obj2 = newToken->createObject(); CPPUNIT_ASSERT(obj2 != NULL); OSObject* obj3 = newToken->createObject(); CPPUNIT_ASSERT(obj3 != NULL); // Now set the IDs of the 3 objects obj1->startTransaction(OSObject::ReadWrite); CPPUNIT_ASSERT(obj1->setAttribute(CKA_ID, idAtt[0])); obj1->commitTransaction(); obj2->startTransaction(OSObject::ReadWrite); CPPUNIT_ASSERT(obj2->setAttribute(CKA_ID, idAtt[1])); obj2->commitTransaction(); obj3->startTransaction(OSObject::ReadWrite); CPPUNIT_ASSERT(obj3->setAttribute(CKA_ID, idAtt[2])); obj3->commitTransaction(); delete newToken; } // Now open the token DBToken existingToken("testdir","existingToken"); CPPUNIT_ASSERT(existingToken.isValid()); // Retrieve SO PIN, user PIN, label, serial number and flags ByteString retrievedSOPIN, retrievedUserPIN, retrievedLabel, retrievedSerial; CK_ULONG flags; CPPUNIT_ASSERT(existingToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(existingToken.getUserPIN(retrievedUserPIN)); CPPUNIT_ASSERT(existingToken.getTokenLabel(retrievedLabel)); CPPUNIT_ASSERT(existingToken.getTokenSerial(retrievedSerial)); CPPUNIT_ASSERT(existingToken.getTokenFlags(flags)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); CPPUNIT_ASSERT(retrievedUserPIN == userPIN); CPPUNIT_ASSERT(retrievedLabel == label); CPPUNIT_ASSERT(retrievedSerial == serial); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)(CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); // Check that the token contains 3 objects CPPUNIT_ASSERT_EQUAL(existingToken.getObjects().size(), (size_t)3); // Check that all the tokens are presented bool present[3] = { false, false, false }; std::set objects = existingToken.getObjects(); for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present[0] = true; } else if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[1]) { present[1] = true; } else if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present[2] = true; } } CPPUNIT_ASSERT(present[0]); CPPUNIT_ASSERT(present[1]); CPPUNIT_ASSERT(present[2]); } void test_a_dbtoken::should_fail_to_open_nonexistant_tokens() { DBToken doesntExist("testdir","doesntExist"); CPPUNIT_ASSERT(!doesntExist.isValid()); } void test_a_dbtoken::support_create_delete_objects() { // Test IDs ByteString id[5] = { "112233445566", "AABBCCDDEEFF", "ABABABABABAB", "557788991122", "005500550055" }; OSAttribute idAtt[5] = { id[0], id[1], id[2], id[3], id[4] }; ByteString label = "AABBCCDDEEFF"; ByteString serial = "1234567890"; // Instantiate a new token ObjectStoreToken* testToken = new DBToken("testdir", "testToken", label, serial); CPPUNIT_ASSERT(testToken != NULL); CPPUNIT_ASSERT(testToken->isValid()); // Open the same token DBToken sameToken("testdir","testToken"); CPPUNIT_ASSERT(sameToken.isValid()); // Create 3 objects on the token OSObject* obj1 = testToken->createObject(); CPPUNIT_ASSERT(obj1 != NULL); OSObject* obj2 = testToken->createObject(); CPPUNIT_ASSERT(obj2 != NULL); OSObject* obj3 = testToken->createObject(); CPPUNIT_ASSERT(obj3 != NULL); // Now set the IDs of the 3 objects obj1->setAttribute(CKA_ID, idAtt[0]); obj2->setAttribute(CKA_ID, idAtt[1]); obj3->setAttribute(CKA_ID, idAtt[2]); // Check that the token contains 3 objects CPPUNIT_ASSERT_EQUAL(testToken->getObjects().size(), (size_t)3); // Check that all three objects are distinct and present std::set objects = testToken->getObjects(); bool present1[3] = { false, false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); for (int j = 0; j < 3; j++) { if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[j]) { present1[j] = true; } } } for (int j = 0; j < 3; j++) { CPPUNIT_ASSERT(present1[j]); } // Now check that the same objects are present in the other instance of the same token std::set otherObjects = sameToken.getObjects(); CPPUNIT_ASSERT_EQUAL(otherObjects.size(), (size_t)3); bool present2[3] = { false, false, false }; for (std::set::iterator i = otherObjects.begin(); i != otherObjects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); for (int j = 0; j < 3; j++) { if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[j]) { present2[j] = true; } } } for (int j = 0; j < 3; j++) { CPPUNIT_ASSERT(present2[j]); } // Now delete the second object for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[1]) { CPPUNIT_ASSERT(testToken->deleteObject(*i)); break; } } // Verify that it was indeed removed CPPUNIT_ASSERT_EQUAL(testToken->getObjects().size(),(size_t)2); objects = testToken->getObjects(); bool present3[2] = { false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present3[0] = true; } if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present3[1] = true; } } for (int j = 0; j < 2; j++) { CPPUNIT_ASSERT(present3[j]); } // Now check the other instance CPPUNIT_ASSERT_EQUAL(sameToken.getObjects().size(), (size_t)2); otherObjects = sameToken.getObjects(); bool present4[2] = { false, false }; for (std::set::iterator i = otherObjects.begin(); i != otherObjects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present4[0] = true; } if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present4[1] = true; } } for (int j = 0; j < 2; j++) { CPPUNIT_ASSERT(present4[j]); } // Release the test token delete testToken; } void test_a_dbtoken::support_clearing_a_token() { // Create a new token ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; ObjectStoreToken* newToken = new DBToken("testdir", "newToken", label, serial); CPPUNIT_ASSERT(newToken != NULL); CPPUNIT_ASSERT(newToken->isValid()); // Check the flags CK_ULONG flags; CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)(CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED)); // Set the SO PIN ByteString soPIN = "3132333435363738"; // 12345678 CPPUNIT_ASSERT(newToken->setSOPIN(soPIN)); // Set the user PIN ByteString userPIN = "31323334"; // 1234 CPPUNIT_ASSERT(newToken->setUserPIN(userPIN)); CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)(CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); CPPUNIT_ASSERT(newToken->createObject() != NULL); delete newToken; #if 1 // Reopen the newly created token and keep a reference around. DBToken referencingToken("testdir", "newToken"); CPPUNIT_ASSERT(referencingToken.isValid()); #endif // Now reopen the newly created token DBToken reopenedToken("testdir","newToken"); CPPUNIT_ASSERT(reopenedToken.isValid()); // Retrieve the flags, user PIN and so PIN ByteString retrievedSOPIN, retrievedUserPIN; CPPUNIT_ASSERT(reopenedToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(reopenedToken.getUserPIN(retrievedUserPIN)); CPPUNIT_ASSERT(reopenedToken.getTokenFlags(flags)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); CPPUNIT_ASSERT(retrievedUserPIN == userPIN); CPPUNIT_ASSERT_EQUAL(flags, (CK_ULONG)(CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); // Now clear the token CPPUNIT_ASSERT(reopenedToken.clearToken()); CPPUNIT_ASSERT(!reopenedToken.isValid()); DB::LogErrorHandler eh = DB::setLogErrorHandler(dummy_print); // Try to open it once more and make sure it has been deleted. DBToken clearedToken("testdir","newToken"); CPPUNIT_ASSERT(!clearedToken.isValid()); #if 1 // Verify that it is no longer possible to access the database... CPPUNIT_ASSERT(!referencingToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); std::set objects = referencingToken.getObjects(); CPPUNIT_ASSERT_EQUAL(objects.size(), (size_t)0); CPPUNIT_ASSERT(!referencingToken.isValid()); #endif DB::setLogErrorHandler(eh); } softhsm-2.0.0/src/lib/object_store/test/ObjectFileTests.h0000664000175000017500000000461712533040716020330 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectFileTests.h Contains test cases to test the object file implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OBJECTFILETESTS_H #define _SOFTHSM_V2_OBJECTFILETESTS_H #include class ObjectFileTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ObjectFileTests); CPPUNIT_TEST(testBoolAttr); CPPUNIT_TEST(testULongAttr); CPPUNIT_TEST(testByteStrAttr); CPPUNIT_TEST(testArrayAttr); CPPUNIT_TEST(testMixedAttr); CPPUNIT_TEST(testDoubleAttr); CPPUNIT_TEST(testRefresh); CPPUNIT_TEST(testCorruptFile); CPPUNIT_TEST(testTransactions); CPPUNIT_TEST(testDestroyObjectFails); CPPUNIT_TEST_SUITE_END(); public: void testBoolAttr(); void testULongAttr(); void testByteStrAttr(); void testArrayAttr(); void testMixedAttr(); void testDoubleAttr(); void testRefresh(); void testCorruptFile(); void testTransactions(); void testDestroyObjectFails(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_OBJECTFILETESTS_H softhsm-2.0.0/src/lib/object_store/test/SessionObjectTests.h0000664000175000017500000000447212533040716021073 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObjectTests.h Contains test cases to test the session object implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONOBJECTTESTS_H #define _SOFTHSM_V2_SESSIONOBJECTTESTS_H #include class SessionObjectTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SessionObjectTests); CPPUNIT_TEST(testBoolAttr); CPPUNIT_TEST(testULongAttr); CPPUNIT_TEST(testByteStrAttr); CPPUNIT_TEST(testArrayAttr); CPPUNIT_TEST(testMixedAttr); CPPUNIT_TEST(testDoubleAttr); CPPUNIT_TEST(testCloseSession); CPPUNIT_TEST(testDestroyObjectFails); CPPUNIT_TEST_SUITE_END(); public: void testBoolAttr(); void testULongAttr(); void testByteStrAttr(); void testArrayAttr(); void testMixedAttr(); void testDoubleAttr(); void testCloseSession(); void testDestroyObjectFails(); void setUp(); void tearDown(); }; #endif // !_SOFTHSM_V2_SESSIONOBJECTTESTS_H softhsm-2.0.0/src/lib/object_store/test/OSTokenTests.cpp0000664000175000017500000003517212533040716020177 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSTokenTests.cpp Contains test cases to test the object file implementation *****************************************************************************/ #include #include #include #include "OSTokenTests.h" #include "OSToken.h" #include "ObjectFile.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(OSTokenTests); // FIXME: all pathnames in this file are *NIX/BSD specific void OSTokenTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void OSTokenTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void OSTokenTests::testNewToken() { // Create a new token ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; #ifndef _WIN32 OSToken* newToken = OSToken::createToken("./testdir", "newToken", label, serial); #else OSToken* newToken = OSToken::createToken(".\\testdir", "newToken", label, serial); #endif CPPUNIT_ASSERT(newToken != NULL); // Check the flags CK_ULONG flags; CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED)); // Set the SO PIN ByteString soPIN = "3132333435363738"; // 12345678 CPPUNIT_ASSERT(newToken->setSOPIN(soPIN)); // Set the user PIN ByteString userPIN = "31323334"; // 1234 CPPUNIT_ASSERT(newToken->setUserPIN(userPIN)); CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); delete newToken; // Now reopen the newly created token #ifndef _WIN32 OSToken reopenedToken("./testdir/newToken"); #else OSToken reopenedToken(".\\testdir\\newToken"); #endif CPPUNIT_ASSERT(reopenedToken.isValid()); // Retrieve the flags, user PIN and so PIN ByteString retrievedSOPIN, retrievedUserPIN; CPPUNIT_ASSERT(reopenedToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(reopenedToken.getUserPIN(retrievedUserPIN)); CPPUNIT_ASSERT(reopenedToken.getTokenFlags(flags)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); CPPUNIT_ASSERT(retrievedUserPIN == userPIN); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); } void OSTokenTests::testExistingToken() { ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; ByteString soPIN = "31323334"; // 1234 ByteString userPIN = "30303030"; // 0000 ByteString id1 = "ABCDEF"; ByteString id2 = "FEDCBA"; ByteString id3 = "AABBCC"; { // Create the token dir #ifndef _WIN32 CPPUNIT_ASSERT(!system("mkdir testdir/existingToken")); #else CPPUNIT_ASSERT(!system("mkdir testdir\\existingToken")); #endif // Create the token object #ifndef _WIN32 ObjectFile tokenObject(NULL, "./testdir/existingToken/token.object", "./testdir/existingToken/token.lock", true); #else ObjectFile tokenObject(NULL, ".\\testdir\\existingToken\\token.object", ".\\testdir\\existingToken\\token.lock", true); #endif OSAttribute labelAtt(label); CPPUNIT_ASSERT(tokenObject.setAttribute(CKA_OS_TOKENLABEL, labelAtt)); OSAttribute serialAtt(serial); CPPUNIT_ASSERT(tokenObject.setAttribute(CKA_OS_TOKENSERIAL, serialAtt)); OSAttribute soPINAtt(soPIN); CPPUNIT_ASSERT(tokenObject.setAttribute(CKA_OS_SOPIN, soPINAtt)); OSAttribute userPINAtt(userPIN); CPPUNIT_ASSERT(tokenObject.setAttribute(CKA_OS_USERPIN, userPINAtt)); CK_ULONG flags = CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED; OSAttribute flagsAtt(flags); CPPUNIT_ASSERT(tokenObject.setAttribute(CKA_OS_TOKENFLAGS, flagsAtt)); // Create 3 objects #ifndef _WIN32 ObjectFile obj1(NULL, "./testdir/existingToken/1.object", "./testdir/existingToken/1.lock", true); ObjectFile obj2(NULL, "./testdir/existingToken/2.object", "./testdir/existingToken/2.lock", true); ObjectFile obj3(NULL, "./testdir/existingToken/3.object", "./testdir/existingToken/3.lock", true); #else ObjectFile obj1(NULL, ".\\testdir\\existingToken\\1.object", ".\\testdir\\existingToken\\1.lock", true); ObjectFile obj2(NULL, ".\\testdir\\existingToken\\2.object", ".\\testdir\\existingToken\\2.lock", true); ObjectFile obj3(NULL, ".\\testdir\\existingToken\\3.object", ".\\testdir\\existingToken\\3.lock", true); #endif OSAttribute id1Att(id1); OSAttribute id2Att(id2); OSAttribute id3Att(id3); CPPUNIT_ASSERT(obj1.setAttribute(CKA_ID, id1)); CPPUNIT_ASSERT(obj2.setAttribute(CKA_ID, id2)); CPPUNIT_ASSERT(obj3.setAttribute(CKA_ID, id3)); } // Now open the token #ifndef _WIN32 OSToken existingToken("./testdir/existingToken"); #else OSToken existingToken(".\\testdir\\existingToken"); #endif CPPUNIT_ASSERT(existingToken.isValid()); // Retrieve SO PIN, user PIN, label, serial number and flags ByteString retrievedSOPIN, retrievedUserPIN, retrievedLabel, retrievedSerial; CK_ULONG flags; CPPUNIT_ASSERT(existingToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(existingToken.getUserPIN(retrievedUserPIN)); CPPUNIT_ASSERT(existingToken.getTokenLabel(retrievedLabel)); CPPUNIT_ASSERT(existingToken.getTokenSerial(retrievedSerial)); CPPUNIT_ASSERT(existingToken.getTokenFlags(flags)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); CPPUNIT_ASSERT(retrievedUserPIN == userPIN); CPPUNIT_ASSERT(retrievedLabel == label); CPPUNIT_ASSERT(retrievedSerial == serial); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); // Check that the token contains 3 objects CPPUNIT_ASSERT(existingToken.getObjects().size() == 3); // Check that all the tokens are presented bool present[3] = { false, false, false }; std::set objects = existingToken.getObjects(); for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id1) { present[0] = true; } else if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id2) { present[1] = true; } else if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id3) { present[2] = true; } } CPPUNIT_ASSERT(present[0] == true); CPPUNIT_ASSERT(present[1] == true); CPPUNIT_ASSERT(present[2] == true); } void OSTokenTests::testNonExistentToken() { #ifndef _WIN32 OSToken doesntExist("./testdir/doesntExist"); #else OSToken doesntExist(".\\testdir\\doesntExist"); #endif CPPUNIT_ASSERT(!doesntExist.isValid()); } void OSTokenTests::testCreateDeleteObjects() { // Test IDs ByteString id[5] = { "112233445566", "AABBCCDDEEFF", "ABABABABABAB", "557788991122", "005500550055" }; OSAttribute idAtt[5] = { id[0], id[1], id[2], id[3], id[4] }; ByteString label = "AABBCCDDEEFF"; ByteString serial = "1234567890"; // Instantiate a new token #ifndef _WIN32 OSToken* testToken = OSToken::createToken("./testdir", "testToken", label, serial); #else OSToken* testToken = OSToken::createToken(".\\testdir", "testToken", label, serial); #endif CPPUNIT_ASSERT(testToken != NULL); CPPUNIT_ASSERT(testToken->isValid()); // Open the same token #ifndef _WIN32 OSToken sameToken("./testdir/testToken"); #else OSToken sameToken(".\\testdir\\testToken"); #endif CPPUNIT_ASSERT(sameToken.isValid()); // Create 3 objects on the token OSObject* obj1 = testToken->createObject(); CPPUNIT_ASSERT(obj1 != NULL); OSObject* obj2 = testToken->createObject(); CPPUNIT_ASSERT(obj2 != NULL); OSObject* obj3 = testToken->createObject(); CPPUNIT_ASSERT(obj3 != NULL); // Now set the IDs of the 3 objects obj1->setAttribute(CKA_ID, idAtt[0]); obj2->setAttribute(CKA_ID, idAtt[1]); obj3->setAttribute(CKA_ID, idAtt[2]); // Check that the token contains 3 objects CPPUNIT_ASSERT(testToken->getObjects().size() == 3); // Check that all three objects are distinct and present std::set objects = testToken->getObjects(); bool present1[3] = { false, false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); for (int j = 0; j < 3; j++) { if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[j]) { present1[j] = true; } } } for (int j = 0; j < 3; j++) { CPPUNIT_ASSERT(present1[j] == true); } // Now check that the same objects are present in the other instance of the same token std::set otherObjects = sameToken.getObjects(); CPPUNIT_ASSERT(otherObjects.size() == 3); bool present2[3] = { false, false, false }; for (std::set::iterator i = otherObjects.begin(); i != otherObjects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); for (int j = 0; j < 3; j++) { if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[j]) { present2[j] = true; } } } for (int j = 0; j < 3; j++) { CPPUNIT_ASSERT(present2[j] == true); } // Now delete the second object for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[1]) { CPPUNIT_ASSERT(testToken->deleteObject(*i)); break; } } // Verify that it was indeed removed CPPUNIT_ASSERT(testToken->getObjects().size() == 2); objects = testToken->getObjects(); bool present3[2] = { false, false }; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present3[0] = true; } if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present3[1] = true; } } for (int j = 0; j < 2; j++) { CPPUNIT_ASSERT(present3[j] == true); } // Now check the other instance CPPUNIT_ASSERT(sameToken.getObjects().size() == 2); otherObjects = sameToken.getObjects(); bool present4[2] = { false, false }; for (std::set::iterator i = otherObjects.begin(); i != otherObjects.end(); i++) { ByteString retrievedId; CPPUNIT_ASSERT((*i)->isValid()); CPPUNIT_ASSERT((*i)->attributeExists(CKA_ID)); CPPUNIT_ASSERT((*i)->getAttribute(CKA_ID).isByteStringAttribute()); if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[0]) { present4[0] = true; } if ((*i)->getAttribute(CKA_ID).getByteStringValue() == id[2]) { present4[1] = true; } } for (int j = 0; j < 2; j++) { CPPUNIT_ASSERT(present4[j] == true); } // Release the test token delete testToken; } void OSTokenTests::testClearToken() { // Create a new token ByteString label = "40414243"; // ABCD ByteString serial = "0102030405060708"; #ifndef _WIN32 OSToken* newToken = OSToken::createToken("./testdir", "newToken", label, serial); #else OSToken* newToken = OSToken::createToken(".\\testdir", "newToken", label, serial); #endif CPPUNIT_ASSERT(newToken != NULL); // Check the flags CK_ULONG flags; CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED)); // Set the SO PIN ByteString soPIN = "3132333435363738"; // 12345678 CPPUNIT_ASSERT(newToken->setSOPIN(soPIN)); // Set the user PIN ByteString userPIN = "31323334"; // 1234 CPPUNIT_ASSERT(newToken->setUserPIN(userPIN)); CPPUNIT_ASSERT(newToken->getTokenFlags(flags)); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); delete newToken; // Now reopen the newly created token #ifndef _WIN32 OSToken reopenedToken("./testdir/newToken"); #else OSToken reopenedToken(".\\testdir\\newToken"); #endif CPPUNIT_ASSERT(reopenedToken.isValid()); // Retrieve the flags, user PIN and so PIN ByteString retrievedSOPIN, retrievedUserPIN; CPPUNIT_ASSERT(reopenedToken.getSOPIN(retrievedSOPIN)); CPPUNIT_ASSERT(reopenedToken.getUserPIN(retrievedUserPIN)); CPPUNIT_ASSERT(reopenedToken.getTokenFlags(flags)); CPPUNIT_ASSERT(retrievedSOPIN == soPIN); CPPUNIT_ASSERT(retrievedUserPIN == userPIN); CPPUNIT_ASSERT(flags == (CKF_RNG | CKF_LOGIN_REQUIRED | CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_USER_PIN_INITIALIZED)); // Now clear the token CPPUNIT_ASSERT(reopenedToken.clearToken()); CPPUNIT_ASSERT(!reopenedToken.isValid()); // Try to open it once more #ifndef _WIN32 OSToken clearedToken("./testdir/newToken"); #else OSToken clearedToken(".\\testdir\\newToken"); #endif CPPUNIT_ASSERT(!clearedToken.isValid()); } softhsm-2.0.0/src/lib/object_store/test/UUIDTests.cpp0000664000175000017500000000412412533040716017414 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** UUIDTests.cpp Contains test cases to test the UUID implementation *****************************************************************************/ #include #include #include #include "UUIDTests.h" #include "UUID.h" CPPUNIT_TEST_SUITE_REGISTRATION(UUIDTests); void UUIDTests::setUp() { } void UUIDTests::tearDown() { } void UUIDTests::testUUID() { std::string uuid1 = UUID::newUUID(); std::string uuid2 = UUID::newUUID(); std::string uuid3 = UUID::newUUID(); CPPUNIT_ASSERT((uuid1.size() == 36) && (uuid2.size() == 36) && (uuid3.size() == 36)); CPPUNIT_ASSERT(uuid1.compare(uuid2)); CPPUNIT_ASSERT(uuid1.compare(uuid3)); CPPUNIT_ASSERT(uuid2.compare(uuid3)); } softhsm-2.0.0/src/lib/object_store/test/UUIDTests.h0000664000175000017500000000355312533040716017066 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** UUIDTests.h Contains test cases to test the UUID implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_UUIDTESTS_H #define _SOFTHSM_V2_UUIDTESTS_H #include class UUIDTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(UUIDTests); CPPUNIT_TEST(testUUID); CPPUNIT_TEST_SUITE_END(); public: void testUUID(); void setUp(); void tearDown(); private: }; #endif // !_SOFTHSM_V2_UUIDTESTS_H softhsm-2.0.0/src/lib/object_store/OSToken.h0000664000175000017500000001102612533040716015632 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSToken.h The token class; a token is stored in a directory containing several files. Each object is stored in a separate file and a token object is present that has the token specific attributes *****************************************************************************/ #ifndef _SOFTHSM_V2_OSTOKEN_H #define _SOFTHSM_V2_OSTOKEN_H #include "config.h" #include "ObjectStoreToken.h" #include "OSAttribute.h" #include "ObjectFile.h" #include "Directory.h" #include "Generation.h" #include "UUID.h" #include "MutexFactory.h" #include "cryptoki.h" #include #include #include #include class OSToken : public ObjectStoreToken { public: // Constructor OSToken(const std::string inTokenPath); // Create a new token static OSToken* createToken(const std::string basePath, const std::string tokenDir, const ByteString& label, const ByteString& serial); // Access an existing token static OSToken* accessToken(const std::string &basePath, const std::string &tokenDir); // Constructor for new tokens OSToken(const std::string tokenPath, const ByteString& label, const ByteString& serialNumber); // Set the SO PIN virtual bool setSOPIN(const ByteString& soPINBlob); // Get the SO PIN virtual bool getSOPIN(ByteString& soPINBlob); // Set the user PIN virtual bool setUserPIN(ByteString userPINBlob); // Get the user PIN virtual bool getUserPIN(ByteString& userPINBlob); // Get the token flags virtual bool getTokenFlags(CK_ULONG& flags); // Set the token flags virtual bool setTokenFlags(const CK_ULONG flags); // Retrieve the token label virtual bool getTokenLabel(ByteString& label); // Retrieve the token serial virtual bool getTokenSerial(ByteString& serial); // Retrieve objects virtual std::set getObjects(); // Insert objects into the given set virtual void getObjects(std::set &inObjects); // Create a new object virtual OSObject* createObject(); // Delete an object virtual bool deleteObject(OSObject* object); // Destructor virtual ~OSToken(); // Checks if the token is consistent virtual bool isValid(); // Invalidate the token (for instance if it is deleted) virtual void invalidate(); // Delete the token virtual bool clearToken(); private: // ObjectFile instances can call the index() function friend class ObjectFile; // Index the token bool index(bool isFirstTime = false); // Is the token consistent and valid? bool valid; // The token path std::string tokenPath; // The current objects of the token std::set objects; // All the objects ever associated with this token // // This set is kept to be able to clean up when the token // instance is discarded; in case the contents of a token // change, some objects may disappear but we cannot simply // delete them since they may still be referenced from an // object outside of this class. std::set allObjects; // The current list of files std::set currentFiles; // The token object ObjectFile* tokenObject; // Generation control Generation* gen; // The directory object for this token Directory* tokenDir; // For thread safeness Mutex* tokenMutex; }; #endif // !_SOFTHSM_V2_OSTOKEN_H softhsm-2.0.0/src/lib/object_store/DBObject.cpp0000664000175000017500000007711412533040716016271 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBObject.h This class represents object records in a database *****************************************************************************/ #include "config.h" #include "DBObject.h" #include "OSPathSep.h" #include "DB.h" #include "OSAttributes.h" #include #include #include #include #include // Create an object that can access a record, but don't do anything yet. DBObject::DBObject(DB::Connection *connection, ObjectStoreToken *token) : _mutex(MutexFactory::i()->getMutex()), _connection(connection), _token(token), _objectId(0), _transaction(NULL) { } DBObject::DBObject(DB::Connection *connection, ObjectStoreToken *token, long long objectId) : _mutex(MutexFactory::i()->getMutex()), _connection(connection), _token(token), _objectId(objectId), _transaction(NULL) { } // Destructor DBObject::~DBObject() { for (std::map::iterator it = _attributes.begin(); it!=_attributes.end(); ++it) { delete it->second; it->second = NULL; } if (_transaction) { for (std::map::iterator it = _transaction->begin(); it!=_transaction->end(); ++it) { delete it->second; it->second = NULL; } delete _transaction; } MutexFactory::i()->recycleMutex(_mutex); } void DBObject::dropConnection() { MutexLocker lock(_mutex); _connection = NULL; } // create tables to support storage of attributes for the DBObject bool DBObject::createTables() { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } // Create the tables inside the database DB::Statement cr_object = _connection->prepare("create table object (id integer primary key autoincrement);"); if (!_connection->execute(cr_object)) { ERROR_MSG("Failed to create \"object\" table"); return false; } // attribute_text DB::Statement cr_attr_text = _connection->prepare( "create table attribute_text (" "value text," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_text)) { ERROR_MSG("Failed to create \"attribute_text\" table"); return false; } // attribute_integer DB::Statement cr_attr_integer = _connection->prepare( "create table attribute_integer (" "value integer," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_integer)) { ERROR_MSG("Failed to create \"attribute_integer\" table"); return false; } // attribute_binary DB::Statement cr_attr_binary = _connection->prepare( "create table attribute_binary (" "value blob," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_binary)) { ERROR_MSG("Failed to create \"attribute_binary\" table"); return false; } // attribute_array DB::Statement cr_attr_array = _connection->prepare( "create table attribute_array (" "value blob," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_array)) { ERROR_MSG("Failed to create \"attribute_array\" table"); return false; } // attribute_boolean DB::Statement cr_attr_boolean = _connection->prepare( "create table attribute_boolean (" "value boolean," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_boolean)) { ERROR_MSG("Failed to create \"attribute_boolean\" table"); return false; } // attribute_datetime DB::Statement cr_attr_datetime = _connection->prepare( "create table attribute_datetime (" "value datetime," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_datetime)) { ERROR_MSG("Failed to create \"attribute_datetime\" table"); return false; } // attribute_real DB::Statement cr_attr_real = _connection->prepare( "create table attribute_real (" "value real," "type integer," "object_id integer references object(id) on delete cascade," "id integer primary key autoincrement)" ); if (!_connection->execute(cr_attr_real)) { ERROR_MSG("Failed to create \"attribute_real\" table"); return false; } return true; } bool DBObject::dropTables() { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } // Create the tables inside the database DB::Statement dr_object = _connection->prepare("drop table object"); if (!_connection->execute(dr_object)) { ERROR_MSG("Failed to drop \"object\" table"); return false; } // attribute_text DB::Statement dr_attr_text = _connection->prepare("drop table attribute_text"); if (!_connection->execute(dr_attr_text)) { ERROR_MSG("Failed to drop \"attribute_text\" table"); return false; } // attribute_integer DB::Statement dr_attr_integer = _connection->prepare("drop table attribute_integer"); if (!_connection->execute(dr_attr_integer)) { ERROR_MSG("Failed to drop \"attribute_integer\" table"); return false; } // attribute_binary DB::Statement dr_attr_binary = _connection->prepare("drop table attribute_binary"); if (!_connection->execute(dr_attr_binary)) { ERROR_MSG("Failed to drop \"attribute_binary\" table"); return false; } // attribute_array DB::Statement dr_attr_array = _connection->prepare("drop table attribute_array"); if (!_connection->execute(dr_attr_array)) { ERROR_MSG("Failed to drop \"attribute_array\" table"); return false; } // attribute_boolean DB::Statement dr_attr_boolean = _connection->prepare("drop table attribute_boolean"); if (!_connection->execute(dr_attr_boolean)) { ERROR_MSG("Failed to drop \"attribute_boolean\" table"); return false; } // attribute_datetime DB::Statement dr_attr_datetime = _connection->prepare("drop table attribute_datetime"); if (!_connection->execute(dr_attr_datetime)) { ERROR_MSG("Failed to drop \"attribute_datetime\" table"); return false; } // attribute_real DB::Statement dr_attr_real = _connection->prepare("drop table attribute_real"); if (!_connection->execute(dr_attr_real)) { ERROR_MSG("Failed to drop \"attribute_real\" table"); return false; } return true; } bool DBObject::find(long long objectId) { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } if (objectId == 0) { ERROR_MSG("Invalid object_id 0 passed to find"); return false; } // find the object in the database for the given object_id DB::Statement statement = _connection->prepare( "select id from object where id=%lld", objectId); if (!statement.isValid()) { ERROR_MSG("Preparing object selection statement failed"); return false; } DB::Result result = _connection->perform(statement); if (result.getLongLong(1) != objectId) { ERROR_MSG("Failed to find object with id %lld",objectId); return false; } _objectId = objectId; return true; } bool DBObject::insert() { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } DB::Statement statement = _connection->prepare("insert into object default values"); if (!_connection->execute(statement)) { ERROR_MSG("Failed to insert a new object"); return false; } _objectId = _connection->lastInsertRowId(); return _objectId != 0; } bool DBObject::remove() { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } DB::Statement statement = _connection->prepare("delete from object where id=%lld",_objectId); if (!_connection->execute(statement)) { ERROR_MSG("Failed to remove an existing object"); return false; } _objectId = 0; return true; } long long DBObject::objectId() { MutexLocker lock(_mutex); return _objectId; } static bool isModifiable(CK_ATTRIBUTE_TYPE type) { switch (type) { case CKA_LABEL: case CKA_TRUSTED: case CKA_ID: case CKA_ISSUER: case CKA_SERIAL_NUMBER: case CKA_START_DATE: case CKA_END_DATE: case CKA_DERIVE: case CKA_SUBJECT: case CKA_ENCRYPT: case CKA_VERIFY: case CKA_VERIFY_RECOVER: case CKA_WRAP: case CKA_SENSITIVE: case CKA_DECRYPT: case CKA_SIGN: case CKA_SIGN_RECOVER: case CKA_UNWRAP: case CKA_EXTRACTABLE: case CKA_OS_TOKENFLAGS: case CKA_OS_SOPIN: case CKA_OS_USERPIN: return true; default: return false; } } enum AttributeKind { akUnknown, akBoolean, akInteger, akBinary, akArray }; static AttributeKind attributeKind(CK_ATTRIBUTE_TYPE type) { switch (type) { case CKA_CLASS: return akInteger; case CKA_TOKEN: return akBoolean; case CKA_PRIVATE: return akBoolean; case CKA_LABEL: return akBinary; case CKA_APPLICATION: return akBinary; case CKA_VALUE: return akBinary; case CKA_OBJECT_ID: return akBinary; case CKA_CERTIFICATE_TYPE: return akInteger; case CKA_ISSUER: return akBinary; case CKA_SERIAL_NUMBER: return akBinary; case CKA_AC_ISSUER: return akBinary; case CKA_OWNER: return akBinary; case CKA_ATTR_TYPES: return akBinary; case CKA_TRUSTED: return akBoolean; case CKA_CERTIFICATE_CATEGORY: return akInteger; case CKA_JAVA_MIDP_SECURITY_DOMAIN: return akInteger; case CKA_URL: return akBinary; case CKA_HASH_OF_SUBJECT_PUBLIC_KEY: return akBinary; case CKA_HASH_OF_ISSUER_PUBLIC_KEY: return akBinary; case CKA_NAME_HASH_ALGORITHM: return akInteger; case CKA_CHECK_VALUE: return akBinary; case CKA_KEY_TYPE: return akInteger; case CKA_SUBJECT: return akBinary; case CKA_ID: return akBinary; case CKA_SENSITIVE: return akBoolean; case CKA_ENCRYPT: return akBoolean; case CKA_DECRYPT: return akBoolean; case CKA_WRAP: return akBoolean; case CKA_UNWRAP: return akBoolean; case CKA_SIGN: return akBoolean; case CKA_SIGN_RECOVER: return akBoolean; case CKA_VERIFY: return akBoolean; case CKA_VERIFY_RECOVER: return akBoolean; case CKA_DERIVE: return akBoolean; case CKA_START_DATE: return akBinary; case CKA_END_DATE: return akBinary; case CKA_MODULUS: return akBinary; case CKA_MODULUS_BITS: return akInteger; case CKA_PUBLIC_EXPONENT: return akBinary; case CKA_PRIVATE_EXPONENT: return akBinary; case CKA_PRIME_1: return akBinary; case CKA_PRIME_2: return akBinary; case CKA_EXPONENT_1: return akBinary; case CKA_EXPONENT_2: return akBinary; case CKA_COEFFICIENT: return akBinary; case CKA_PRIME: return akBinary; case CKA_SUBPRIME: return akBinary; case CKA_BASE: return akBinary; case CKA_PRIME_BITS: return akInteger; case CKA_SUBPRIME_BITS: return akInteger; case CKA_VALUE_BITS: return akInteger; case CKA_VALUE_LEN: return akInteger; case CKA_EXTRACTABLE: return akBoolean; case CKA_LOCAL: return akBoolean; case CKA_NEVER_EXTRACTABLE: return akBoolean; case CKA_ALWAYS_SENSITIVE: return akBoolean; case CKA_KEY_GEN_MECHANISM: return akInteger; case CKA_MODIFIABLE: return akBoolean; case CKA_COPYABLE: return akBoolean; case CKA_ECDSA_PARAMS: return akBinary; case CKA_EC_POINT: return akBinary; case CKA_SECONDARY_AUTH: return akBoolean; case CKA_AUTH_PIN_FLAGS: return akInteger; case CKA_ALWAYS_AUTHENTICATE: return akBoolean; case CKA_WRAP_WITH_TRUSTED: return akBoolean; /* case CKA_OTP_FORMAT: case CKA_OTP_LENGTH: case CKA_OTP_TIME_INTERVAL: case CKA_OTP_USER_FRIENDLY_MODE: case CKA_OTP_CHALLENGE_REQUIREMENT: case CKA_OTP_TIME_REQUIREMENT: case CKA_OTP_COUNTER_REQUIREMENT: case CKA_OTP_PIN_REQUIREMENT: case CKA_OTP_COUNTER: case CKA_OTP_TIME: case CKA_OTP_USER_IDENTIFIER: case CKA_OTP_SERVICE_IDENTIFIER: case CKA_OTP_SERVICE_LOGO: case CKA_OTP_SERVICE_LOGO_TYPE: */ case CKA_GOSTR3410_PARAMS: return akBinary; case CKA_GOSTR3411_PARAMS: return akBinary; case CKA_GOST28147_PARAMS: return akBinary; /* case CKA_HW_FEATURE_TYPE: case CKA_RESET_ON_INIT: case CKA_HAS_RESET: case CKA_PIXEL_X: case CKA_PIXEL_Y: case CKA_RESOLUTION: case CKA_CHAR_ROWS: case CKA_CHAR_COLUMNS: case CKA_COLOR: case CKA_BITS_PER_PIXEL: case CKA_CHAR_SETS: case CKA_ENCODING_METHODS: case CKA_MIME_TYPES: case CKA_MECHANISM_TYPE: case CKA_REQUIRED_CMS_ATTRIBUTES: case CKA_DEFAULT_CMS_ATTRIBUTES: case CKA_SUPPORTED_CMS_ATTRIBUTES: */ case CKA_WRAP_TEMPLATE: return akArray; case CKA_UNWRAP_TEMPLATE: return akArray; case CKA_DERIVE_TEMPLATE: return akArray; case CKA_ALLOWED_MECHANISMS: return akArray; case CKA_OS_TOKENLABEL: return akBinary; case CKA_OS_TOKENSERIAL: return akBinary; case CKA_OS_TOKENFLAGS: return akInteger; case CKA_OS_SOPIN: return akBinary; case CKA_OS_USERPIN: return akBinary; default: return akUnknown; } } static bool decodeArray(std::map& array, const unsigned char *binary, size_t size) { for (size_t pos = 0; pos < size; ) { // finished? if (pos == size) break; CK_ATTRIBUTE_TYPE attrType; if (pos + sizeof(attrType) > size) { goto overrun; } memcpy(&attrType, binary + pos, sizeof(attrType)); pos += sizeof(attrType); AttributeKind attrKind; if (pos + sizeof(AttributeKind) > size) { goto overrun; } memcpy(&attrKind, binary + pos, sizeof(attrKind)); pos += sizeof(attrKind); // Verify using attributeKind()? switch (attrKind) { case akBoolean: { bool value; if (pos + sizeof(value) > size) { goto overrun; } memcpy(&value, binary + pos, sizeof(value)); pos += sizeof(value); array.insert(std::pair (attrType, value)); } break; case akInteger: { unsigned long value; if (pos + sizeof(value) > size) { goto overrun; } memcpy(&value, binary + pos, sizeof(value)); pos += sizeof(value); array.insert(std::pair (attrType, value)); } break; case akBinary: { ByteString value; unsigned long len; if (pos + sizeof(len) > size) { goto overrun; } memcpy(&len, binary + pos, sizeof(len)); pos += sizeof(len); if (pos + len > size) { goto overrun; } value.resize(len); memcpy(&value[0], binary + pos, len); pos += len; array.insert(std::pair (attrType, value)); } break; default: ERROR_MSG("unsupported attribute kind in array"); return false; } } return true; overrun: ERROR_MSG("array template overrun"); return false; } static bool encodeArray(ByteString& value, const std::map& attributes) { for (std::map::const_iterator i = attributes.begin(); i != attributes.end(); ++i) { CK_ATTRIBUTE_TYPE attrType = i->first; value += ByteString((unsigned char*) &attrType, sizeof(attrType)); OSAttribute attr = i->second; if (attr.isBooleanAttribute()) { AttributeKind attrKind = akBoolean; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); bool val = attr.getBooleanValue(); value += ByteString((unsigned char*) &val, sizeof(val)); } else if (attr.isUnsignedLongAttribute()) { AttributeKind attrKind = akInteger; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); unsigned long val = attr.getUnsignedLongValue(); value += ByteString((unsigned char*) &val, sizeof(val)); } else if (attr.isByteStringAttribute()) { AttributeKind attrKind = akBinary; value += ByteString((unsigned char*) &attrKind, sizeof(attrKind)); ByteString val = attr.getByteStringValue(); unsigned long len = val.size(); value += ByteString((unsigned char*) &len, sizeof(len)); value += val; } else { ERROR_MSG("unsupported attribute kind for array"); return false; } } return true; } OSAttribute *DBObject::accessAttribute(CK_ATTRIBUTE_TYPE type) { switch (attributeKind(type)) { case akUnknown: return NULL; case akBoolean: { // try to find the attribute in the boolean attribute table DB::Statement statement = _connection->prepare( "select value from attribute_boolean where type=%lu and object_id=%lld", type, _objectId); if (!statement.isValid()) { return NULL; } DB::Result result = _connection->perform(statement); if (!result.isValid()) { return NULL; } // Store the attribute in the transaction when it is active. std::map *attrs = &_attributes; if (_transaction) attrs = _transaction; bool value = result.getInt(1) != 0; std::map::iterator it = attrs->find(type); OSAttribute *attr; if (it != attrs->end()) { if (it->second != NULL) { delete it->second; } it->second = new OSAttribute(value); attr = it->second; } else { attr = new OSAttribute(value); (*attrs)[type] = attr; } return attr; } case akInteger: { // try to find the attribute in the integer attribute table DB::Statement statement = _connection->prepare( "select value from attribute_integer where type=%lu and object_id=%lld", type, _objectId); if (!statement.isValid()) { return NULL; } DB::Result result = _connection->perform(statement); if (!result.isValid()) { return NULL; } // Store the attribute in the transaction when it is active. std::map *attrs = &_attributes; if (_transaction) attrs = _transaction; unsigned long value = result.getULongLong(1); std::map::iterator it = attrs->find(type); OSAttribute *attr; if (it != attrs->end()) { if (it->second != NULL) { delete it->second; } it->second = new OSAttribute(value); attr = it->second; } else { attr = new OSAttribute(value); (*attrs)[type] = attr; } return attr; } case akBinary: { // try to find the attribute in the binary attribute table DB::Statement statement = _connection->prepare( "select value from attribute_binary where type=%lu and object_id=%lld", type, _objectId); if (!statement.isValid()) { return NULL; } DB::Result result = _connection->perform(statement); if (!result.isValid()) { return NULL; } // Store the attribute in the transaction when it is active. std::map *attrs = &_attributes; if (_transaction) attrs = _transaction; const unsigned char *value = result.getBinary(1); size_t size = result.getFieldLength(1); std::map::iterator it = attrs->find(type); OSAttribute *attr; if (it != attrs->end()) { if (it->second != NULL) { delete it->second; } it->second = new OSAttribute(ByteString(value,size)); attr = it->second; } else { attr = new OSAttribute(ByteString(value,size)); (*attrs)[type] = attr; return attr; } return attr; } case akArray: { // try to find the attribute in the array attribute table DB::Statement statement = _connection->prepare( "select value from attribute_array where type=%lu and object_id=%lld", type, _objectId); if (!statement.isValid()) { return NULL; } DB::Result result = _connection->perform(statement); if (!result.isValid()) { return NULL; } // Store the attribute in the transaction when it is active. std::map *attrs = &_attributes; if (_transaction) attrs = _transaction; const unsigned char *binary = result.getBinary(1); size_t size = result.getFieldLength(1); std::map::iterator it = attrs->find(type); OSAttribute *attr; if (it != attrs->end()) { std::map value; if (!decodeArray(value,binary,size)) { return NULL; } if (it->second != NULL) { delete it->second; } it->second = new OSAttribute(value); attr = it->second; } else { std::map value; if (!decodeArray(value,binary,size)) { return NULL; } attr = new OSAttribute(value); (*attrs)[type] = attr; return attr; } return attr; } } return NULL; } // Retrieve the specified attribute for internal use // Calling function must lock the mutex OSAttribute* DBObject::getAttributeDB(CK_ATTRIBUTE_TYPE type) { if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return NULL; } if (_objectId == 0) { ERROR_MSG("Cannot read from invalid object."); return NULL; } // If a transaction is in progress, we can just return the attribute from the transaction. if (_transaction) { std::map::iterator it = _transaction->find(type); if (it != _transaction->end()) return it->second; } // If the attribute exists and is non-modifiable then return a previously retrieved attribute value. if (!isModifiable(type)) { std::map::iterator it = _attributes.find(type); if (it != _attributes.end()) { return it->second; } } return accessAttribute(type); } // Check if the specified attribute exists bool DBObject::attributeExists(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(_mutex); return getAttributeDB(type) != NULL; } // Retrieve the specified attribute OSAttribute DBObject::getAttribute(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(_mutex); OSAttribute* attr = getAttributeDB(type); if (attr == NULL) return OSAttribute((unsigned long)0); return *attr; } bool DBObject::getBooleanValue(CK_ATTRIBUTE_TYPE type, bool val) { MutexLocker lock(_mutex); OSAttribute* attr = getAttributeDB(type); if (attr == NULL) return val; if (attr->isBooleanAttribute()) { return attr->getBooleanValue(); } else { ERROR_MSG("The attribute is not a boolean: 0x%08X", type); return val; } } unsigned long DBObject::getUnsignedLongValue(CK_ATTRIBUTE_TYPE type, unsigned long val) { MutexLocker lock(_mutex); OSAttribute* attr = getAttributeDB(type); if (attr == NULL) return val; if (attr->isUnsignedLongAttribute()) { return attr->getUnsignedLongValue(); } else { ERROR_MSG("The attribute is not an unsigned long: 0x%08X", type); return val; } } ByteString DBObject::getByteStringValue(CK_ATTRIBUTE_TYPE type) { MutexLocker lock(_mutex); ByteString val; OSAttribute* attr = getAttributeDB(type); if (attr == NULL) return val; if (attr->isByteStringAttribute()) { return attr->getByteStringValue(); } else { ERROR_MSG("The attribute is not a byte string: 0x%08X", type); return val; } } CK_ATTRIBUTE_TYPE DBObject::nextAttributeType(CK_ATTRIBUTE_TYPE) { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } if (_objectId == 0) { ERROR_MSG("Cannot get next attribute for invalid object."); return false; } // FIXME: implement for C_CopyObject return CKA_CLASS; } // Set the specified attribute bool DBObject::setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute) { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } if (_objectId == 0) { ERROR_MSG("Cannot update invalid object."); return false; } // Retrieve and existing attribute if it exists or NULL if it doesn't OSAttribute *attr = getAttributeDB(type); // Update an existing attribute... if (attr) { DB::Statement statement; bool bindByteString = true; if (attr->isBooleanAttribute()) { // update boolean attribute statement = _connection->prepare( "update attribute_boolean set value=%d where type=%lu and object_id=%lld", attribute.getBooleanValue() ? 1 : 0, type, _objectId); bindByteString = false; } else if (attr->isUnsignedLongAttribute()) { // update integer attribute statement = _connection->prepare( "update attribute_integer set value=%lld where type=%lu and object_id=%lld", static_cast(attribute.getUnsignedLongValue()), type, _objectId); bindByteString = false; } else if (attr->isByteStringAttribute()) { // update binary attribute statement = _connection->prepare( "update attribute_binary set value=? where type=%lu and object_id=%lld", type, _objectId); //bindByteString = true; } else if (attr->isArrayAttribute()) { // update array attribute ByteString value; if (!encodeArray(value, attribute.getArrayValue())) { return false; } statement = _connection->prepare( "update attribute_array set value=? where type=%lu and object_id=%lld", type, _objectId); DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT); bindByteString = false; } if (bindByteString) { DB::Bindings(statement).bindBlob(1, attribute.getByteStringValue().const_byte_str(), attribute.getByteStringValue().size(), SQLITE_STATIC); } // Statement is valid when a prepared statement has been attached to it. if (statement.isValid()) { if (!_connection->execute(statement)) { ERROR_MSG("Failed to update attribute %lu for object %lld",type,_objectId); return false; } if (_transaction) { std::map::iterator it = _transaction->find(type); if (it != _transaction->end()) *it->second = attribute; else (*_transaction)[type] = new OSAttribute(attribute); } else *attr = attribute; return true; } } DB::Statement statement; // Insert the attribute, because it is currently unknown if (attribute.isBooleanAttribute()) { // Could not update it, so we need to insert it. statement = _connection->prepare( "insert into attribute_boolean (value,type,object_id) values (%d,%lu,%lld)", attribute.getBooleanValue() ? 1 : 0, type, _objectId); } else if (attribute.isUnsignedLongAttribute()) { // Could not update it, so we need to insert it. statement = _connection->prepare( "insert into attribute_integer (value,type,object_id) values (%lld,%lu,%lld)", static_cast(attribute.getUnsignedLongValue()), type, _objectId); } else if (attribute.isByteStringAttribute()) { // Could not update it, so we need to insert it. statement = _connection->prepare( "insert into attribute_binary (value,type,object_id) values (?,%lu,%lld)", type, _objectId); DB::Bindings(statement).bindBlob(1, attribute.getByteStringValue().const_byte_str(), attribute.getByteStringValue().size(), SQLITE_STATIC); } else if (attribute.isArrayAttribute()) { // Could not update it, so we need to insert it. ByteString value; if (!encodeArray(value, attribute.getArrayValue())) { return false; } statement = _connection->prepare( "insert into attribute_array (value,type,object_id) values (?,%lu,%lld)", type, _objectId); DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT); } // Statement is valid when a prepared statement has been attached to it. if (statement.isValid()) { if (!_connection->execute(statement)) { ERROR_MSG("Failed to insert attribute %lu for object %lld",type,_objectId); return false; } if (_transaction) (*_transaction)[type] = new OSAttribute(attribute); else _attributes[type] = new OSAttribute(attribute); return true; } return false; } // The validity state of the object bool DBObject::isValid() { MutexLocker lock(_mutex); return _objectId != 0 && _connection != NULL; } // Start an attribute set transaction; this method is used when - for // example - a key is generated and all its attributes need to be // persisted in one go. // // N.B.: Starting a transaction locks the object! bool DBObject::startTransaction(Access access) { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } if (_transaction) { ERROR_MSG("Transaction is already active."); return false; } _transaction = new std::map; if (_transaction == NULL) { ERROR_MSG("Not enough memory to start transaction."); return false; } if (_connection->inTransaction()) { ERROR_MSG("Transaction in database is already active."); return false; } // Ask the connection to start the transaction. if (access == ReadWrite) return _connection->beginTransactionRW(); else return _connection->beginTransactionRO(); } // Commit an attribute transaction bool DBObject::commitTransaction() { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } if (_transaction == NULL) { ERROR_MSG("No transaction active."); return false; } if (!_connection->commitTransaction()) { return false; } // Copy the values from the internally stored transaction to the _attributes field. for (std::map::iterator it = _transaction->begin(); it!=_transaction->end(); ++it) { std::map::iterator attr_it = _attributes.find(it->first); if (attr_it == _attributes.end()) { _attributes[it->first] = it->second; } else { *attr_it->second = *it->second; delete it->second; } it->second = NULL; } delete _transaction; _transaction = NULL; return true; } // Abort an attribute transaction; loads back the previous version of the object from disk bool DBObject::abortTransaction() { MutexLocker lock(_mutex); if (_connection == NULL) { ERROR_MSG("Object is not connected to the database."); return false; } // Forget the atributes that were set during the transaction. if (_transaction) { for (std::map::iterator it = _transaction->begin(); it!=_transaction->end(); ++it) { delete it->second; it->second = NULL; } delete _transaction; _transaction = NULL; } return _connection->rollbackTransaction(); } // Destroy the object; WARNING: pointers to the object become invalid after this call bool DBObject::destroyObject() { // NOTE: Do not lock _mutex, because _token will call us back and cause a deadlock. // There is no need to lock anyway as _token is a non-mutable pointer, so no race // conditions possible. if (_token == NULL) { ERROR_MSG("Cannot destroy an object that is not associated with a token"); return false; } return _token->deleteObject(this); } softhsm-2.0.0/src/lib/object_store/DB.h0000664000175000017500000001363412533040716014604 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DB.h Specifies classes to access the Token Database *****************************************************************************/ #ifndef _SOFTHSM_V2_DB_H #define _SOFTHSM_V2_DB_H #include "config.h" #include #include namespace DB { // Log an error to the error handler that has been setup using a call to setLogErrorHandler declared below. void logError(const std::string &format, ...); // The ap parameter has already been started with va_start. // So the handler only has to pass this on to a vprintf function // to actually print it. typedef int (*LogErrorHandler)(const char *format, va_list ap); // Set an alternative for vprintf to log the actual errors. // Set to NULL to disable logging al together. LogErrorHandler setLogErrorHandler(LogErrorHandler handler); // Set the log error handler back to the default value that logs to stdout. void resetLogErrorHandler(); // Forward declaration of the handle class used by Statement, Binding and Result. class Handle; // Responsible for holding on to a prepared statement. // After a prepared statement has been used it can be reused when the same query is performed again. class Statement { public: Statement(); Statement(sqlite3_stmt *statement); Statement(const Statement &statement); Statement &operator=(const Statement &statement); virtual ~Statement(); bool isValid(); // Something we'd like to check during testing. int refcount(); // Reset a prepared statement bool reset(); // Perform a single step of the prepared statement. enum ReturnCode { ReturnCodeRow, ReturnCodeDone, ReturnCodeError }; ReturnCode step(); Handle *handle() const; protected: Handle *_handle; }; // Responsible for allowing parameters to be bound to statements. // On a statement that has been performed or executed you first // need to call reset() before new parameters can be bound. class Bindings : public Statement { public: Bindings(); Bindings(const Statement &statement); // To clear all existing bindings call this method. bool clear(); // Bind a value to a parameter in a prepared statement bool bindBlob(int index, const void *value, int n, void(*destruct)(void*)); bool bindDouble(int index, double value); bool bindInt(int index, int value); bool bindInt64(int index, long long value ); //bool bindNull(int index); bool bindText(int index, const char *value, int n, void(*destruct)(void*)); //bool bindZeroBlob(int index, int n); }; // Responsible for providing access to the result set of a query. // Used for queries that actually provide a result set. // A result that is returned will be positioned at the first row. class Result : public Statement { public: Result(); Result(const Statement &statement); bool fieldIsNull(unsigned int fieldidx); time_t getDatetime(unsigned int fieldidx); unsigned char getUChar(unsigned int fieldidx); float getFloat(unsigned int fieldidx); double getDouble(unsigned int fieldidx); int getInt(unsigned int fieldidx); unsigned int getUInt(unsigned int fieldidx); long long getLongLong(unsigned int fieldidx); unsigned long long getULongLong(unsigned int fieldidx); const char *getString(unsigned int fieldidx); const unsigned char *getBinary(unsigned int fieldidx); size_t getFieldLength(unsigned int fieldidx); // Position the result on the first row again. bool firstRow(); // Position the result on the next row. bool nextRow(); }; // Responsible for connection to the database and for managing prepared statements. class Connection { public: static Connection *Create(const std::string &dbdir, const std::string &dbname); virtual ~Connection(); // value that was passed into dbdir when this connection was created. const std::string &dbdir(); // concatenation of dbdir and dbname const std::string &dbpath(); Statement prepare(const std::string &format, ...); Result perform(Statement &statement); bool execute(Statement &statement); bool connect(const char *connectionLabel = NULL); void close(); bool tableExists(const std::string &tablename); long long lastInsertRowId(); bool inTransaction(); bool beginTransactionRO(); bool endTransactionRO(); bool beginTransactionRW(); bool commitTransaction(); bool rollbackTransaction(); // Set the busy timeout that the database layer will wait for a database lock to become available. bool setBusyTimeout(int ms); private: std::string _dbdir; std::string _dbpath; sqlite3 *_db; Connection(const std::string &dbdir, const std::string &dbname); // disable evil constructors Connection(const Connection &); void operator=(const Connection&); }; } #endif // !_SOFTHSM_V2_DB_H softhsm-2.0.0/src/lib/object_store/Generation.cpp0000664000175000017500000001056012533040716016740 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Generation.cpp Helper for generation number handling. *****************************************************************************/ #include "config.h" #include "log.h" #include "Generation.h" // Factory Generation* Generation::create(const std::string path, bool isToken /* = false */) { Generation* gen = new Generation(path, isToken); if ((gen != NULL) && isToken && (gen->genMutex == NULL)) { delete gen; return NULL; } return gen; } // Destructor Generation::~Generation() { if (isToken) { MutexFactory::i()->recycleMutex(genMutex); } } // Synchronize from locked disk file bool Generation::sync(File &objectFile) { if (isToken) { ERROR_MSG("Generation sync() called for a token"); return false; } unsigned long onDisk; if (!objectFile.readULong(onDisk)) { if (objectFile.isEOF()) { onDisk = 0; } else { return false; } } currentValue = onDisk; return objectFile.seek(0L); } // Check if the target was updated bool Generation::wasUpdated() { if (isToken) { MutexLocker lock(genMutex); File genFile(path); if (!genFile.isValid()) { return true; } unsigned long onDisk; if (!genFile.readULong(onDisk)) { return true; } return (onDisk != currentValue); } else { File objectFile(path); if (!objectFile.isValid()) { return true; } unsigned long onDisk; if (!objectFile.readULong(onDisk)) { return (!objectFile.isEOF()); } return (onDisk != currentValue); } } // Update void Generation::update() { pendingUpdate = true; } // Commit void Generation::commit() { if (isToken) { MutexLocker lock(genMutex); File genFile(path, true, true, true, false); if (!genFile.isValid()) { return; } genFile.lock(); if (genFile.isEmpty()) { currentValue++; if (currentValue == 0) { currentValue++; } pendingUpdate = false; (void) genFile.writeULong(currentValue); genFile.unlock(); return; } unsigned long onDisk; bool bOK = true; bOK = bOK && genFile.readULong(onDisk); bOK = bOK && genFile.seek(0L); if (pendingUpdate) { onDisk++; if (onDisk == 0) { onDisk++; } } bOK = bOK && genFile.writeULong(onDisk); if (bOK) { currentValue = onDisk; pendingUpdate = false; } genFile.unlock(); } } // Set the current value when read from disk void Generation::set(unsigned long onDisk) { currentValue = onDisk; } // Return new value unsigned long Generation::get() { pendingUpdate = false; currentValue++; if (currentValue == 0) { currentValue = 1; } return currentValue; } // Rollback (called when the new value failed to be written) void Generation::rollback() { pendingUpdate = true; if (currentValue != 1) { currentValue--; } } // Constructor Generation::Generation(const std::string inPath, bool inIsToken) { path = inPath; isToken = inIsToken; pendingUpdate = false; currentValue = 0; genMutex = NULL; if (isToken) { genMutex = MutexFactory::i()->getMutex(); if (genMutex != NULL) { commit(); } } } softhsm-2.0.0/src/lib/object_store/OSAttribute.cpp0000664000175000017500000000737412533040716017063 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSAttribute.cpp This class represents the object store view on an object's attribute *****************************************************************************/ #include "config.h" #include "OSAttribute.h" // Copy constructor OSAttribute::OSAttribute(const OSAttribute& in) { attributeType = in.attributeType; boolValue = in.boolValue; ulongValue = in.ulongValue; byteStrValue = in.byteStrValue; arrayValue = in.arrayValue; } // Constructor for a boolean type attribute OSAttribute::OSAttribute(const bool value) { boolValue = value; attributeType = BOOL; ulongValue = 0; } // Constructor for an unsigned long type attribute OSAttribute::OSAttribute(const unsigned long value) { ulongValue = value; attributeType = ULONG; boolValue = false; } // Constructor for a byte string type attribute OSAttribute::OSAttribute(const ByteString& value) { byteStrValue = value; attributeType = BYTESTR; boolValue = false; ulongValue = 0; } // Constructor for an array type attribute OSAttribute::OSAttribute(const std::map& value) { arrayValue = value; attributeType = ARRAY; boolValue = false; ulongValue = 0; } // Check the attribute type bool OSAttribute::isBooleanAttribute() const { return (attributeType == BOOL); } bool OSAttribute::isUnsignedLongAttribute() const { return (attributeType == ULONG); } bool OSAttribute::isByteStringAttribute() const { return (attributeType == BYTESTR); } bool OSAttribute::isArrayAttribute() const { return (attributeType == ARRAY); } // Retrieve the attribute value bool OSAttribute::getBooleanValue() const { return boolValue; } unsigned long OSAttribute::getUnsignedLongValue() const { return ulongValue; } const ByteString& OSAttribute::getByteStringValue() const { return byteStrValue; } const std::map& OSAttribute::getArrayValue() const { return arrayValue; } // Helper for template (aka array) matching bool OSAttribute::peekValue(ByteString& value) const { switch (attributeType) { case BOOL: value.resize(sizeof(boolValue)); memcpy(&value[0], &boolValue, value.size()); return true; case ULONG: value.resize(sizeof(ulongValue)); memcpy(&value[0], &ulongValue, value.size()); return true; case BYTESTR: value.resize(byteStrValue.size()); memcpy(&value[0], byteStrValue.const_byte_str(), value.size()); return true; default: return false; } } softhsm-2.0.0/src/lib/object_store/OSToken.cpp0000664000175000017500000003352112533040716016171 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSToken.cpp The token class; a token is stored in a directory containing several files. Each object is stored in a separate file and a token object is present that has the token specific attributes *****************************************************************************/ #include "config.h" #include "log.h" #include "OSAttributes.h" #include "OSAttribute.h" #include "ObjectFile.h" #include "Directory.h" #include "Generation.h" #include "UUID.h" #include "cryptoki.h" #include "OSToken.h" #include "OSPathSep.h" #include #include #include #include #include #include // Constructor OSToken::OSToken(const std::string inTokenPath) { tokenPath = inTokenPath; tokenDir = new Directory(tokenPath); gen = Generation::create(tokenPath + OS_PATHSEP + "generation", true); tokenObject = new ObjectFile(this, tokenPath + OS_PATHSEP + "token.object", tokenPath + OS_PATHSEP + "token.lock"); tokenMutex = MutexFactory::i()->getMutex(); valid = (gen != NULL) && (tokenMutex != NULL) && tokenDir->isValid() && tokenObject->valid; DEBUG_MSG("Opened token %s", tokenPath.c_str()); index(true); } // Create a new token /*static*/ OSToken* OSToken::createToken(const std::string basePath, const std::string tokenDir, const ByteString& label, const ByteString& serial) { Directory baseDir(basePath); if (!baseDir.isValid()) { return NULL; } // Create the token directory if (!baseDir.mkdir(tokenDir)) { return NULL; } // Create the token object ObjectFile tokenObject(NULL, basePath + OS_PATHSEP + tokenDir + OS_PATHSEP + "token.object", basePath + OS_PATHSEP + tokenDir + OS_PATHSEP + "token.lock", true); if (!tokenObject.valid) { baseDir.rmdir(tokenDir); return NULL; } // Set the initial attributes CK_ULONG flags = CKF_RNG | CKF_LOGIN_REQUIRED | // FIXME: check CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED; OSAttribute tokenLabel(label); OSAttribute tokenSerial(serial); OSAttribute tokenFlags(flags); if (!tokenObject.setAttribute(CKA_OS_TOKENLABEL, tokenLabel) || !tokenObject.setAttribute(CKA_OS_TOKENSERIAL, tokenSerial) || !tokenObject.setAttribute(CKA_OS_TOKENFLAGS, tokenFlags)) { baseDir.remove(tokenDir + OS_PATHSEP + "token.object"); baseDir.remove(tokenDir + OS_PATHSEP + "token.lock"); baseDir.rmdir(tokenDir); return NULL; } DEBUG_MSG("Created new token %s", tokenDir.c_str()); return new OSToken(basePath + OS_PATHSEP + tokenDir); } // Access an existing token /*static*/ OSToken *OSToken::accessToken(const std::string &basePath, const std::string &tokenDir) { return new OSToken(basePath + OS_PATHSEP + tokenDir); } // Destructor OSToken::~OSToken() { // Clean up std::set cleanUp = allObjects; allObjects.clear(); for (std::set::iterator i = cleanUp.begin(); i != cleanUp.end(); i++) { delete *i; } delete tokenDir; if (gen != NULL) delete gen; MutexFactory::i()->recycleMutex(tokenMutex); delete tokenObject; } // Set the SO PIN bool OSToken::setSOPIN(const ByteString& soPINBlob) { if (!valid) return false; OSAttribute soPIN(soPINBlob); CK_ULONG flags; if (tokenObject->setAttribute(CKA_OS_SOPIN, soPIN) && getTokenFlags(flags)) { flags &= ~CKF_SO_PIN_COUNT_LOW; flags &= ~CKF_SO_PIN_FINAL_TRY; flags &= ~CKF_SO_PIN_LOCKED; flags &= ~CKF_SO_PIN_TO_BE_CHANGED; return setTokenFlags(flags); } return false; } // Get the SO PIN bool OSToken::getSOPIN(ByteString& soPINBlob) { if (!valid || !tokenObject->isValid()) { return false; } if (tokenObject->attributeExists(CKA_OS_SOPIN)) { soPINBlob = tokenObject->getAttribute(CKA_OS_SOPIN).getByteStringValue(); return true; } else { return false; } } // Set the user PIN bool OSToken::setUserPIN(ByteString userPINBlob) { if (!valid) return false; OSAttribute userPIN(userPINBlob); CK_ULONG flags; if (tokenObject->setAttribute(CKA_OS_USERPIN, userPIN) && getTokenFlags(flags)) { flags |= CKF_USER_PIN_INITIALIZED; flags &= ~CKF_USER_PIN_COUNT_LOW; flags &= ~CKF_USER_PIN_FINAL_TRY; flags &= ~CKF_USER_PIN_LOCKED; flags &= ~CKF_USER_PIN_TO_BE_CHANGED; return setTokenFlags(flags); } return false; } // Get the user PIN bool OSToken::getUserPIN(ByteString& userPINBlob) { if (!valid || !tokenObject->isValid()) { return false; } if (tokenObject->attributeExists(CKA_OS_USERPIN)) { userPINBlob = tokenObject->getAttribute(CKA_OS_USERPIN).getByteStringValue(); return true; } else { return false; } } // Retrieve the token label bool OSToken::getTokenLabel(ByteString& label) { if (!valid || !tokenObject->isValid()) { return false; } if (tokenObject->attributeExists(CKA_OS_TOKENLABEL)) { label = tokenObject->getAttribute(CKA_OS_TOKENLABEL).getByteStringValue(); return true; } else { return false; } } // Retrieve the token serial bool OSToken::getTokenSerial(ByteString& serial) { if (!valid || !tokenObject->isValid()) { return false; } if (tokenObject->attributeExists(CKA_OS_TOKENSERIAL)) { serial = tokenObject->getAttribute(CKA_OS_TOKENSERIAL).getByteStringValue(); return true; } else { return false; } } // Get the token flags bool OSToken::getTokenFlags(CK_ULONG& flags) { if (!valid || !tokenObject->isValid()) { return false; } if (tokenObject->attributeExists(CKA_OS_TOKENFLAGS)) { flags = tokenObject->getAttribute(CKA_OS_TOKENFLAGS).getUnsignedLongValue(); // Check if the user PIN is initialised if (tokenObject->attributeExists(CKA_OS_USERPIN)) { flags |= CKF_USER_PIN_INITIALIZED; } return true; } else { return false; } } // Set the token flags bool OSToken::setTokenFlags(const CK_ULONG flags) { if (!valid) return false; OSAttribute tokenFlags(flags); return tokenObject->setAttribute(CKA_OS_TOKENFLAGS, tokenFlags); } // Retrieve objects std::set OSToken::getObjects() { index(); // Make sure that no other thread is in the process of changing // the object list when we return it MutexLocker lock(tokenMutex); return objects; } void OSToken::getObjects(std::set &inObjects) { index(); // Make sure that no other thread is in the process of changing // the object list when we return it MutexLocker lock(tokenMutex); inObjects.insert(objects.begin(),objects.end()); } // Create a new object OSObject* OSToken::createObject() { if (!valid) return NULL; // Generate a name for the object std::string objectUUID = UUID::newUUID(); std::string objectPath = tokenPath + OS_PATHSEP + objectUUID + ".object"; std::string lockPath = tokenPath + OS_PATHSEP + objectUUID + ".lock"; // Create the new object file ObjectFile* newObject = new ObjectFile(this, objectPath, lockPath, true); if (!newObject->valid) { ERROR_MSG("Failed to create new object %s", objectPath.c_str()); delete newObject; return NULL; } // Now add it to the set of objects MutexLocker lock(tokenMutex); objects.insert(newObject); allObjects.insert(newObject); currentFiles.insert(newObject->getFilename()); DEBUG_MSG("(0x%08X) Created new object %s (0x%08X)", this, objectPath.c_str(), newObject); gen->update(); gen->commit(); return newObject; } // Delete an object bool OSToken::deleteObject(OSObject* object) { if (!valid) return false; if (objects.find(object) == objects.end()) { ERROR_MSG("Cannot delete non-existent object 0x%08X", object); return false; } MutexLocker lock(tokenMutex); ObjectFile* fileObject = dynamic_cast(object); if (fileObject == NULL) { ERROR_MSG("Object type not compatible with this token class 0x%08X", object); return false; } // Invalidate the object instance fileObject->invalidate(); // Retrieve the filename of the object std::string objectFilename = fileObject->getFilename(); // Attempt to delete the file if (!tokenDir->remove(objectFilename)) { ERROR_MSG("Failed to delete object file %s", objectFilename.c_str()); return false; } // Retrieve the filename of the lock std::string lockFilename = fileObject->getLockname(); // Attempt to delete the lock if (!tokenDir->remove(lockFilename)) { ERROR_MSG("Failed to delete lock file %s", lockFilename.c_str()); return false; } objects.erase(object); DEBUG_MSG("Deleted object %s", objectFilename.c_str()); gen->update(); gen->commit(); return true; } // Checks if the token is consistent bool OSToken::isValid() { return valid; } // Invalidate the token (for instance if it is deleted) void OSToken::invalidate() { valid = false; } // Delete the token bool OSToken::clearToken() { MutexLocker lock(tokenMutex); // Invalidate the token invalidate(); // First, clear out all objects objects.clear(); // Now, delete all files in the token directory if (!tokenDir->refresh()) { return false; } std::vector tokenFiles = tokenDir->getFiles(); for (std::vector::iterator i = tokenFiles.begin(); i != tokenFiles.end(); i++) { if (!tokenDir->remove(*i)) { ERROR_MSG("Failed to remove %s from token directory %s", i->c_str(), tokenPath.c_str()); return false; } } // Now remove the token directory if (!tokenDir->rmdir("")) { ERROR_MSG("Failed to remove the token directory %s", tokenPath.c_str()); return false; } DEBUG_MSG("Token instance %s was succesfully cleared", tokenPath.c_str()); return true; } // Index the token bool OSToken::index(bool isFirstTime /* = false */) { // Check if re-indexing is required if (!isFirstTime && (!valid || !gen->wasUpdated())) { return true; } // Check the integrity if (!tokenDir->refresh() || !tokenObject->valid) { valid = false; return false; } DEBUG_MSG("Token %s has changed", tokenPath.c_str()); // Retrieve the directory listing std::vector tokenFiles = tokenDir->getFiles(); // Filter out the objects std::set newSet; for (std::vector::iterator i = tokenFiles.begin(); i != tokenFiles.end(); i++) { if ((i->size() > 7) && (!(i->substr(i->size() - 7).compare(".object"))) && (i->compare("token.object"))) { newSet.insert(*i); } else { DEBUG_MSG("Ignored file %s", i->c_str()); } } // Compute the changes compared to the last list of files std::set addedFiles; std::set removedFiles; // No access to object mutable fields before MutexLocker lock(tokenMutex); if (!isFirstTime) { // First compute which files were added for (std::set::iterator i = newSet.begin(); i != newSet.end(); i++) { if (currentFiles.find(*i) == currentFiles.end()) { addedFiles.insert(*i); } } // Now compute which files were removed for (std::set::iterator i = currentFiles.begin(); i != currentFiles.end(); i++) { if (newSet.find(*i) == newSet.end()) { removedFiles.insert(*i); } } } else { addedFiles = newSet; } currentFiles = newSet; DEBUG_MSG("%d objects were added and %d objects were removed", addedFiles.size(), removedFiles.size()); DEBUG_MSG("Current directory set contains %d objects", currentFiles.size()); // Now update the set of objects // Add new objects for (std::set::iterator i = addedFiles.begin(); i != addedFiles.end(); i++) { if ((i->find_last_of('.') == std::string::npos) || (i->substr(i->find_last_of('.')) != ".object")) { continue; } std::string lockName(*i); lockName.replace(lockName.find_last_of('.'), std::string::npos, ".lock"); // Create a new token object for the added file ObjectFile* newObject = new ObjectFile(this, tokenPath + OS_PATHSEP + *i, tokenPath + OS_PATHSEP + lockName); DEBUG_MSG("(0x%08X) New object %s (0x%08X) added", this, newObject->getFilename().c_str(), newObject); objects.insert(newObject); allObjects.insert(newObject); } // Remove deleted objects std::set newObjects; for (std::set::iterator i = objects.begin(); i != objects.end(); i++) { ObjectFile* fileObject = dynamic_cast((*i)); if (fileObject == NULL) { ERROR_MSG("Object type not compatible with this token class 0x%08X", (*i)); return false; } DEBUG_MSG("Processing %s (0x%08X)", fileObject->getFilename().c_str(), *i); if (removedFiles.find(fileObject->getFilename()) == removedFiles.end()) { DEBUG_MSG("Adding object %s", fileObject->getFilename().c_str()); // This object gets to stay in the set newObjects.insert(*i); } else { fileObject->invalidate(); } } // Set the new objects objects = newObjects; DEBUG_MSG("The token now contains %d objects", objects.size()); return true; } softhsm-2.0.0/src/lib/object_store/Makefile.in0000664000175000017500000006234212552216620016213 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__append_1 = DB.cpp \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBObject.cpp \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBToken.cpp subdir = src/lib/object_store DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_objectstore_la_LIBADD = am__libsofthsm_objectstore_la_SOURCES_DIST = ObjectStore.cpp UUID.cpp \ Directory.cpp File.cpp Generation.cpp OSAttribute.cpp \ OSToken.cpp ObjectFile.cpp SessionObject.cpp \ SessionObjectStore.cpp FindOperation.cpp ObjectStoreToken.cpp \ DB.cpp DBObject.cpp DBToken.cpp @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@am__objects_1 = DB.lo DBObject.lo \ @BUILD_OBJECTSTORE_BACKEND_DB_TRUE@ DBToken.lo am_libsofthsm_objectstore_la_OBJECTS = ObjectStore.lo UUID.lo \ Directory.lo File.lo Generation.lo OSAttribute.lo OSToken.lo \ ObjectFile.lo SessionObject.lo SessionObjectStore.lo \ FindOperation.lo ObjectStoreToken.lo $(am__objects_1) libsofthsm_objectstore_la_OBJECTS = \ $(am_libsofthsm_objectstore_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = libsofthsm_objectstore_la_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX \ $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=link $(CXXLD) \ $(AM_CXXFLAGS) $(CXXFLAGS) \ $(libsofthsm_objectstore_la_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_objectstore_la_SOURCES) DIST_SOURCES = $(am__libsofthsm_objectstore_la_SOURCES_DIST) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../crypto \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/../common \ -I$(srcdir)/.. \ @SQLITE3_INCLUDES@ noinst_LTLIBRARIES = libsofthsm_objectstore.la libsofthsm_objectstore_la_SOURCES = ObjectStore.cpp UUID.cpp \ Directory.cpp File.cpp Generation.cpp OSAttribute.cpp \ OSToken.cpp ObjectFile.cpp SessionObject.cpp \ SessionObjectStore.cpp FindOperation.cpp ObjectStoreToken.cpp \ $(am__append_1) libsofthsm_objectstore_la_LDFLAGS = @SQLITE3_LIBS@ SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/object_store/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/object_store/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_objectstore.la: $(libsofthsm_objectstore_la_OBJECTS) $(libsofthsm_objectstore_la_DEPENDENCIES) $(EXTRA_libsofthsm_objectstore_la_DEPENDENCIES) $(AM_V_CXXLD)$(libsofthsm_objectstore_la_LINK) $(libsofthsm_objectstore_la_OBJECTS) $(libsofthsm_objectstore_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DB.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DBObject.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DBToken.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Directory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/File.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/FindOperation.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/Generation.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSAttribute.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSToken.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ObjectFile.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ObjectStore.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ObjectStoreToken.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionObject.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SessionObjectStore.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/UUID.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/object_store/ObjectStoreToken.h0000664000175000017500000000647412533040716017547 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectStoreToken.h The object store abstract token base class; *****************************************************************************/ #ifndef _SOFTHSM_V2_OBJECTSTORETOKEN_H #define _SOFTHSM_V2_OBJECTSTORETOKEN_H #include "config.h" #include "OSObject.h" #include #include class ObjectStoreToken { public: // Select the type of backend to use for storing token objects. static bool selectBackend(const std::string& backend); // Create a new token static ObjectStoreToken* createToken(const std::string basePath, const std::string tokenDir, const ByteString& label, const ByteString& serial); // Access an existing token static ObjectStoreToken* accessToken(const std::string &basePath, const std::string &tokenDir); // Set the SO PIN virtual bool setSOPIN(const ByteString& soPINBlob) = 0; // Get the SO PIN virtual bool getSOPIN(ByteString& soPINBlob) = 0; // Set the user PIN virtual bool setUserPIN(ByteString userPINBlob) = 0; // Get the user PIN virtual bool getUserPIN(ByteString& userPINBlob) = 0; // Get the token flags virtual bool getTokenFlags(CK_ULONG& flags) = 0; // Set the token flags virtual bool setTokenFlags(const CK_ULONG flags) = 0; // Retrieve the token label virtual bool getTokenLabel(ByteString& label) = 0; // Retrieve the token serial virtual bool getTokenSerial(ByteString& serial) = 0; // Retrieve objects virtual std::set getObjects() = 0; // Insert objects into the given set virtual void getObjects(std::set &objects) = 0; // Create a new object virtual OSObject* createObject() = 0; // Delete an object virtual bool deleteObject(OSObject* object) = 0; // Destructor virtual ~ObjectStoreToken() {}; // Checks if the token is consistent virtual bool isValid() = 0; // Invalidate the token (for instance if it is deleted) virtual void invalidate() = 0; // Delete the token virtual bool clearToken() = 0; }; #endif // !_SOFTHSM_V2_OBJECTSTORETOKEN_H softhsm-2.0.0/src/lib/object_store/FindOperation.h0000664000175000017500000000475212533040716017061 00000000000000/* * Copyright (c) 2012 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** FindOperation.h This class represents the find operation that can be used to collect objects that match the attributes contained in a given template. *****************************************************************************/ #ifndef _SOFTHSM_V2_FINDOPERATION_H #define _SOFTHSM_V2_FINDOPERATION_H #include "config.h" #include #include "OSObject.h" class FindOperation { public: // Factory method creates a new find operation static FindOperation* create(); // Hand this operation back to the factory for recycling. void recycle(); // Add the objects from thet set that match the attributes in the given template to the find operation. void setHandles(const std::set &handles); // Retrieve handles CK_ULONG retrieveHandles(CK_OBJECT_HANDLE_PTR phObject, CK_ULONG ulCount); // Erase handles from the handles set. CK_ULONG eraseHandles(CK_ULONG ulIndex, CK_ULONG ulCount); protected: // Use a protected constructor to force creation via factory method. FindOperation(); std::set _handles; }; #endif // _SOFTHSM_V2_FINDOPERATION_H softhsm-2.0.0/src/lib/object_store/SessionObjectStore.h0000664000175000017500000000646712533040716020114 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SessionObjectStore.h The token class; a token is stored in a directory containing several files. Each object is stored in a separate file and a token object is present that has the token specific attributes *****************************************************************************/ #ifndef _SOFTHSM_V2_SESSIONOBJECTSTORE_H #define _SOFTHSM_V2_SESSIONOBJECTSTORE_H #include "config.h" #include "OSAttribute.h" #include "SessionObject.h" #include "MutexFactory.h" #include "cryptoki.h" #include #include #include #include #include class SessionObjectStore { public: // Constructor SessionObjectStore(); // Retrieve objects std::set getObjects(); // Insert the session objects for the given slotID into the given OSObject set void getObjects(CK_SLOT_ID slotID, std::set &inObjects); // Create a new object SessionObject* createObject(CK_SLOT_ID slotID, CK_SESSION_HANDLE hSession, bool isPrivate = false); // Delete an object bool deleteObject(SessionObject* object); // Indicate that a session has been closed; invalidates all objects // associated with this session. void sessionClosed(CK_SESSION_HANDLE hSession); // Indicate that for a token all sessions have been closed. // Invalidates all objects associated with the token. void allSessionsClosed(CK_SLOT_ID slotID); // Indicate that a token has been logged out; invalidates all private // objects associated with this token. void tokenLoggedOut(CK_SLOT_ID slotID); // Destructor virtual ~SessionObjectStore(); // Clears the store; should be called when all sessions are closed void clearStore(); private: // The current objects in the store std::set objects; // All the objects ever kept in the store std::set allObjects; // The current list of files std::set currentFiles; // For thread safeness Mutex* storeMutex; }; #endif // !_SOFTHSM_V2_SESSIONOBJECTSTORE_H softhsm-2.0.0/src/lib/object_store/UUID.cpp0000664000175000017500000000431212533040716015411 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** UUID.cpp UUID generation helper functions *****************************************************************************/ #include "config.h" #include "UUID.h" #include "CryptoFactory.h" #include "RNG.h" #include #include #include #include // Generate a new UUID string std::string UUID::newUUID() { RNG* rng = CryptoFactory::i()->getRNG(); ByteString uuid; if (!rng->generateRandom(uuid, 16)) { ERROR_MSG("Fatal, could not generate random UUID"); throw -1; } // Convert it to a string char uuidStr[37]; sprintf(uuidStr, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7], uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]); return std::string(uuidStr); } softhsm-2.0.0/src/lib/object_store/ObjectStore.cpp0000664000175000017500000001121512533040716017066 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ObjectStore.h The object store manages the separate tokens that the SoftHSM supports. Each token is organised as a directory containing files that are contain the token's objects. The object store is initialised with a root directory from which it enumerates the tokens. *****************************************************************************/ #include "config.h" #include "log.h" #include "ObjectStore.h" #include "Directory.h" #include "ObjectStoreToken.h" #include "OSPathSep.h" #include "UUID.h" #include // Constructor ObjectStore::ObjectStore(std::string inStorePath) { storePath = inStorePath; valid = false; storeMutex = MutexFactory::i()->getMutex(); MutexLocker lock(storeMutex); // Find all tokens in the specified path Directory storeDir(storePath); if (!storeDir.isValid()) { ERROR_MSG("Failed to enumerate object store in %s", storePath.c_str()); return; } // Assume that all subdirectories are tokens std::vector dirs = storeDir.getSubDirs(); for (std::vector::iterator i = dirs.begin(); i != dirs.end(); i++) { // Create a token instance ObjectStoreToken* token = ObjectStoreToken::accessToken(storePath, *i); if (!token->isValid()) { ERROR_MSG("Failed to open token %s", i->c_str()); delete token; continue; } tokens.push_back(token); allTokens.push_back(token); } valid = true; } // Destructor ObjectStore::~ObjectStore() { { MutexLocker lock(storeMutex); // Clean up tokens.clear(); for (std::vector::iterator i = allTokens.begin(); i != allTokens.end(); i++) { delete *i; } } MutexFactory::i()->recycleMutex(storeMutex); } // Check if the object store is valid bool ObjectStore::isValid() { return valid; } // Return the number of tokens that is present size_t ObjectStore::getTokenCount() { MutexLocker lock(storeMutex); return tokens.size(); } // Return a pointer to the n-th token (counting starts at 0) ObjectStoreToken* ObjectStore::getToken(size_t whichToken) { MutexLocker lock(storeMutex); if (whichToken >= tokens.size()) { return NULL; } return tokens[whichToken]; } // Create a new token ObjectStoreToken* ObjectStore::newToken(const ByteString& label) { MutexLocker lock(storeMutex); // Generate a UUID for the token std::string tokenUUID = UUID::newUUID(); // Convert the UUID to a serial number std::string serialNumber = tokenUUID.substr(19, 4) + tokenUUID.substr(24); ByteString serial((const unsigned char*) serialNumber.c_str(), serialNumber.size()); // Create the token ObjectStoreToken* newToken = ObjectStoreToken::createToken(storePath, tokenUUID, label, serial); if (newToken != NULL) { tokens.push_back(newToken); allTokens.push_back(newToken); } return newToken; } // Destroy a token bool ObjectStore::destroyToken(ObjectStoreToken *token) { MutexLocker lock(storeMutex); // Find the token for (std::vector::iterator i = tokens.begin(); i != tokens.end(); i++) { if (*i == token) { // Found the token, now destroy the token if (!token->clearToken()) { ERROR_MSG("Failed to clear token instance"); return false; } // And remove it from the vector tokens.erase(i); return true; } } ERROR_MSG("Could not find the token instance to destroy"); return false; } softhsm-2.0.0/src/lib/object_store/OSAttributes.h0000664000175000017500000000416212533040716016703 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSAttributes.h Specifies vendor defined attributes for use in internal object store files *****************************************************************************/ #ifndef _SOFTHSM_V2_OSATTRIBUTES_H #define _SOFTHSM_V2_OSATTRIBUTES_H #include "config.h" #include "cryptoki.h" // Define vendor tag; presumably the one below is reasonably unique #define CKA_VENDOR_SOFTHSM (CKA_VENDOR_DEFINED + 0x5348) // 'SH' // Vendor defined attribute types for the token file #define CKA_OS_TOKENLABEL (CKA_VENDOR_SOFTHSM + 1) #define CKA_OS_TOKENSERIAL (CKA_VENDOR_SOFTHSM + 2) #define CKA_OS_TOKENFLAGS (CKA_VENDOR_SOFTHSM + 3) #define CKA_OS_SOPIN (CKA_VENDOR_SOFTHSM + 4) #define CKA_OS_USERPIN (CKA_VENDOR_SOFTHSM + 5) #endif // !_SOFTHSM_V2_OSATTRIBUTES_H softhsm-2.0.0/src/lib/object_store/DBToken.cpp0000664000175000017500000005341112533040716016135 00000000000000/* * Copyright (c) 2013 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DBToken.cpp The token class; a token is stored in a directory containing a single database file. Each object is stored in multiple tables with every attribute base type stored in a different table. *****************************************************************************/ #include "config.h" #include "log.h" #include "OSAttributes.h" #include "OSAttribute.h" #include "OSPathSep.h" #include "cryptoki.h" #include "DBToken.h" #include "DBObject.h" #include "DB.h" #include "Directory.h" #include #include #include #include #include #include #include #include const char * const DBTOKEN_FILE = "sqlite3.db"; const long long DBTOKEN_OBJECT_TOKENINFO = 1; // Constructor for creating a new token. DBToken::DBToken(const std::string &baseDir, const std::string &tokenName, const ByteString &label, const ByteString &serial) : _connection(NULL), _tokenMutex(NULL) { std::string tokenDir = baseDir + OS_PATHSEP + tokenName; std::string tokenPath = tokenDir + OS_PATHSEP + DBTOKEN_FILE; // Refuse to open an already existing database. FILE *f = fopen(tokenPath.c_str(),"r"); if (f) { fclose(f); ERROR_MSG("Refusing to overwrite and existing database at \"%s\"", tokenPath.c_str()); return; } // First create the directory for the token, we expect basePath to already exist if (mkdir(tokenDir.c_str(), S_IFDIR | S_IRWXU)) { // Allow the directory to exists already. if (errno != EEXIST) { ERROR_MSG("Unable to create directory \"%s\"", tokenDir.c_str()); return; } } // Create _connection = DB::Connection::Create(tokenDir, DBTOKEN_FILE); if (_connection == NULL) { ERROR_MSG("Failed to create a database connection for \"%s\"", tokenPath.c_str()); return; } if (!_connection->connect()) { delete _connection; _connection = NULL; ERROR_MSG("Failed to connect to the database at \"%s\"", tokenPath.c_str()); // Now remove the token directory if (remove(tokenDir.c_str())) { ERROR_MSG("Failed to remove the token directory \"%s\"", tokenDir.c_str()); } return; } // Create a DBObject for the established connection to the database. DBObject tokenObject(_connection); // First create the tables that support storage of object attributes and then insert the object containing // the token info into the database. if (!tokenObject.createTables() || !tokenObject.insert() || tokenObject.objectId()!=DBTOKEN_OBJECT_TOKENINFO) { tokenObject.dropConnection(); _connection->close(); delete _connection; _connection = NULL; ERROR_MSG("Failed to create tables for storing objects in database at \"%s\"", tokenPath.c_str()); return; } // Set the initial attributes CK_ULONG flags = CKF_RNG | CKF_LOGIN_REQUIRED | // FIXME: check CKF_RESTORE_KEY_NOT_NEEDED | CKF_TOKEN_INITIALIZED | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED; OSAttribute tokenLabel(label); OSAttribute tokenSerial(serial); OSAttribute tokenFlags(flags); if (!tokenObject.setAttribute(CKA_OS_TOKENLABEL, tokenLabel) || !tokenObject.setAttribute(CKA_OS_TOKENSERIAL, tokenSerial) || !tokenObject.setAttribute(CKA_OS_TOKENFLAGS, tokenFlags)) { _connection->close(); delete _connection; _connection = NULL; // Now remove the token file if (remove(tokenPath.c_str())) { ERROR_MSG("Failed to remove the token file at \"%s\"", tokenPath.c_str()); } // Now remove the token directory if (remove(tokenDir.c_str())) { ERROR_MSG("Failed to remove the token directory at \"%s\"", tokenDir.c_str()); } return; } _tokenMutex = MutexFactory::i()->getMutex(); // Success! } // Constructor for accessing an existing token. DBToken::DBToken(const std::string &baseDir, const std::string &tokenName) : _connection(NULL), _tokenMutex(NULL) { std::string tokenDir = baseDir + OS_PATHSEP + tokenName; std::string tokenPath = tokenDir + OS_PATHSEP + DBTOKEN_FILE; // Refuse to open an already existing database. FILE *f = fopen(tokenPath.c_str(),"r"); if (f == NULL) { ERROR_MSG("Refusing to open a non-existant database at \"%s\"", tokenPath.c_str()); return; } fclose(f); // Create a database connection. _connection = DB::Connection::Create(tokenDir, DBTOKEN_FILE); if (_connection == NULL) { ERROR_MSG("Failed to create a database connection for \"%s\"", tokenPath.c_str()); return; } if (!_connection->connect()) { delete _connection; _connection = NULL; ERROR_MSG("Failed to connect to the database at \"%s\"", tokenPath.c_str()); return; } // Find the DBObject for the established connection to the database. DBObject tokenObject(_connection); // First find the token obect that indicates the token is properly initialized. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { tokenObject.dropConnection(); _connection->close(); delete _connection; _connection = NULL; ERROR_MSG("Failed to open token object in the token database at \"%s\"", tokenPath.c_str()); return; } _tokenMutex = MutexFactory::i()->getMutex(); // Success! } DBToken *DBToken::createToken(const std::string basePath, const std::string tokenDir, const ByteString &label, const ByteString &serial) { Directory baseDir(basePath); if (!baseDir.isValid()) { return NULL; } // Create the token directory if (!baseDir.mkdir(tokenDir)) { return NULL; } DBToken *token = new DBToken(basePath, tokenDir, label, serial); if (!token->isValid()) { baseDir.rmdir(tokenDir); delete token; return NULL; } DEBUG_MSG("Created new token %s", tokenDir.c_str()); return token; } DBToken *DBToken::accessToken(const std::string &basePath, const std::string &tokenDir) { return new DBToken(basePath, tokenDir); } // Destructor DBToken::~DBToken() { if (_tokenMutex) { MutexFactory::i()->recycleMutex(_tokenMutex); _tokenMutex = NULL; } std::map cleanUp = _allObjects; _allObjects.clear(); for (std::map::iterator i = cleanUp.begin(); i != cleanUp.end(); ++i) { delete i->second; } if (_connection) { delete _connection; _connection = NULL; } } // Set the SO PIN bool DBToken::setSOPIN(const ByteString& soPINBlob) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadWrite)) { ERROR_MSG("Unable to start a transaction for updating the SOPIN and TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } OSAttribute soPIN(soPINBlob); if (!tokenObject.setAttribute(CKA_OS_SOPIN, soPIN)) { ERROR_MSG("Error while setting SOPIN in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_TOKENFLAGS)) { ERROR_MSG("Error while getting TOKENFLAGS from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } // Retrieve flags from the database and reset flags related to tries and expiration of the SOPIN. CK_ULONG flags = tokenObject.getAttribute(CKA_OS_TOKENFLAGS).getUnsignedLongValue() & ~(CKF_SO_PIN_COUNT_LOW | CKF_SO_PIN_FINAL_TRY | CKF_SO_PIN_LOCKED | CKF_SO_PIN_TO_BE_CHANGED); OSAttribute changedTokenFlags(flags); if (!tokenObject.setAttribute(CKA_OS_TOKENFLAGS, changedTokenFlags)) { ERROR_MSG("Error while setting TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.commitTransaction()) { ERROR_MSG("Error while committing SOPIN and TOKENFLAGS changes to token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } return true; } // Get the SO PIN bool DBToken::getSOPIN(ByteString& soPINBlob) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadOnly)) { ERROR_MSG("Unable to start a transaction for getting the SOPIN from token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_SOPIN)) { ERROR_MSG("Error while getting SOPIN from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } tokenObject.commitTransaction(); soPINBlob = tokenObject.getAttribute(CKA_OS_SOPIN).getByteStringValue(); return true; } // Set the user PIN bool DBToken::setUserPIN(ByteString userPINBlob) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadWrite)) { ERROR_MSG("Unable to start a transaction for updating the USERPIN and TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } OSAttribute userPIN(userPINBlob); if (!tokenObject.setAttribute(CKA_OS_USERPIN, userPIN)) { ERROR_MSG("Error while setting USERPIN in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_TOKENFLAGS)) { ERROR_MSG("Error while getting TOKENFLAGS from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } // Retrieve flags from the database and reset flags related to tries and expiration of the SOPIN. CK_ULONG flags = tokenObject.getAttribute(CKA_OS_TOKENFLAGS).getUnsignedLongValue() | (CKF_USER_PIN_INITIALIZED & ~(CKF_USER_PIN_COUNT_LOW | CKF_USER_PIN_FINAL_TRY | CKF_USER_PIN_LOCKED | CKF_USER_PIN_TO_BE_CHANGED)); OSAttribute changedTokenFlags(flags); if (!tokenObject.setAttribute(CKA_OS_TOKENFLAGS, changedTokenFlags)) { ERROR_MSG("Error while setting TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.commitTransaction()) { ERROR_MSG("Error while committing USERPIN and TOKENFLAGS changes to token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } return true; } // Get the user PIN bool DBToken::getUserPIN(ByteString& userPINBlob) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadOnly)) { ERROR_MSG("Unable to start a transaction for getting the USERPIN from token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_USERPIN)) { ERROR_MSG("Error while getting USERPIN from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } tokenObject.commitTransaction(); userPINBlob = tokenObject.getAttribute(CKA_OS_USERPIN).getByteStringValue(); return true; } // Retrieve the token label bool DBToken::getTokenLabel(ByteString& label) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadOnly)) { ERROR_MSG("Unable to start a transaction for getting the TOKENLABEL from token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_TOKENLABEL)) { ERROR_MSG("Error while getting TOKENLABEL from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } tokenObject.commitTransaction(); label = tokenObject.getAttribute(CKA_OS_TOKENLABEL).getByteStringValue(); return true; } // Retrieve the token serial bool DBToken::getTokenSerial(ByteString& serial) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadOnly)) { ERROR_MSG("Unable to start a transaction for getting the TOKENSERIAL from token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_TOKENSERIAL)) { ERROR_MSG("Error while getting TOKENSERIAL from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } tokenObject.commitTransaction(); serial = tokenObject.getAttribute(CKA_OS_TOKENSERIAL).getByteStringValue(); return true; } // Get the token flags bool DBToken::getTokenFlags(CK_ULONG& flags) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadOnly)) { ERROR_MSG("Unable to start a transaction for updating the SOPIN and TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.attributeExists(CKA_OS_TOKENFLAGS)) { ERROR_MSG("Error while getting TOKENFLAGS from token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } tokenObject.commitTransaction(); flags = tokenObject.getAttribute(CKA_OS_TOKENFLAGS).getUnsignedLongValue(); return true; } // Set the token flags bool DBToken::setTokenFlags(const CK_ULONG flags) { if (_connection == NULL) return false; // Create a DBObject for the established connection to the token object in the database DBObject tokenObject(_connection); if (!tokenObject.startTransaction(DBObject::ReadWrite)) { ERROR_MSG("Unable to start a transaction for setting the TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); return false; } // First find the token object in the database. if (!tokenObject.find(DBTOKEN_OBJECT_TOKENINFO)) { ERROR_MSG("Token object not found in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } OSAttribute tokenFlags(flags); if (!tokenObject.setAttribute(CKA_OS_TOKENFLAGS, tokenFlags)) { ERROR_MSG("Error while setting TOKENFLAGS in token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } if (!tokenObject.commitTransaction()) { ERROR_MSG("Error while committing TOKENFLAGS changes to token database at \"%s\"", _connection->dbpath().c_str()); tokenObject.abortTransaction(); return false; } return true; } // Retrieve objects std::set DBToken::getObjects() { std::set objects; getObjects(objects); return objects; } void DBToken::getObjects(std::set &objects) { if (_connection == NULL) return; if (!_connection->beginTransactionRO()) return; DB::Statement statement = _connection->prepare("select id from object limit -1 offset 1"); DB::Result result = _connection->perform(statement); if (result.isValid()) { do { long long objectId = result.getLongLong(1); { MutexLocker lock(_tokenMutex); std::map::iterator it = _allObjects.find(objectId); if (it == _allObjects.end()) { DBObject *object = new DBObject(_connection, this, objectId); _allObjects[objectId] = object; objects.insert(object); } else { objects.insert(it->second); } } } while (result.nextRow()); } _connection->endTransactionRO(); } // Create a new object OSObject *DBToken::createObject() { if (_connection == NULL) return NULL; DBObject *newObject = new DBObject(_connection, this); if (newObject == NULL) { ERROR_MSG("Failed to create an object: out of memory"); return NULL; } if (!newObject->startTransaction(DBObject::ReadWrite)) { delete newObject; ERROR_MSG("Unable to start a transaction in token database at \"%s\"", _connection->dbpath().c_str()); return NULL; } if (!newObject->insert()) { newObject->abortTransaction(); delete newObject; ERROR_MSG("Unable to insert an object into token database at \"%s\"", _connection->dbpath().c_str()); return NULL; } if (!newObject->isValid()) { newObject->abortTransaction(); delete newObject; ERROR_MSG("Object that was inserted in not valid"); return NULL; } if (!newObject->commitTransaction()) { newObject->abortTransaction(); delete newObject; ERROR_MSG("Unable to commit a created object to token database at \"%s\"", _connection->dbpath().c_str()); return NULL; } // Now add the new object to the list of existing objects. { MutexLocker lock(_tokenMutex); _allObjects[newObject->objectId()] = newObject; } return newObject; } bool DBToken::deleteObject(OSObject *object) { if (_connection == NULL) return false; if (object == NULL) { ERROR_MSG("Object passed in as a parameter is NULL"); return false; } if (!object->startTransaction(DBObject::ReadWrite)) { ERROR_MSG("Unable to start a transaction for deleting an object in token database at \"%s\"", _connection->dbpath().c_str()); return false; } if (!static_cast(object)->remove()) { ERROR_MSG("Error while deleting an existing object from the token database at \"%s\"", _connection->dbpath().c_str()); object->abortTransaction(); return false; } if (!object->commitTransaction()) { ERROR_MSG("Error while committing the deletion of an existing object in token database at \"%s\"", _connection->dbpath().c_str()); object->abortTransaction(); return false; } return true; } // Checks if the token is consistent bool DBToken::isValid() { return _connection != NULL && _connection->tableExists("object"); } // Invalidate the token (for instance if it is deleted) void DBToken::invalidate() { } // Delete the token. bool DBToken::clearToken() { if (_connection == NULL) return false; std::string tokenDir = _connection->dbdir(); std::string tokenPath = _connection->dbpath(); if (!DBObject(_connection).dropTables()) { ERROR_MSG("Failed to drop all tables in the token database at \"%s\"", tokenPath.c_str()); return false; } _connection->close(); delete _connection; _connection = NULL; // Remove all files from the token directory, even ones not placed there by us. Directory dir(tokenDir); std::vector tokenFiles = dir.getFiles(); for (std::vector::iterator i = tokenFiles.begin(); i != tokenFiles.end(); i++) { if (!dir.remove(*i)) { ERROR_MSG("Failed to remove \"%s\" from token directory \"%s\"", i->c_str(), tokenDir.c_str()); return false; } } // Now remove the token directory if (!dir.rmdir("")) { ERROR_MSG("Failed to remove the token directory \"%s\"", tokenDir.c_str()); return false; } DEBUG_MSG("Token instance %s was succesfully cleared", tokenDir.c_str()); return true; } softhsm-2.0.0/src/lib/object_store/Directory.cpp0000664000175000017500000001360412533040716016613 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** Directory.cpp Helper functions for accessing directories. *****************************************************************************/ #include "config.h" #include "Directory.h" #include "OSPathSep.h" #include "log.h" #include #include #ifndef _WIN32 #include #include #else #include #include #endif #include #include #include #include // Constructor Directory::Directory(std::string inPath) { path = inPath; dirMutex = MutexFactory::i()->getMutex(); valid = (dirMutex != NULL) && refresh(); } // Destructor Directory::~Directory() { MutexFactory::i()->recycleMutex(dirMutex); } // Check if the directory is valid bool Directory::isValid() { return valid; } // Return a list of all files in a directory std::vector Directory::getFiles() { // Make sure that no other thread is in the process of changing // the file list when we return it MutexLocker lock(dirMutex); return files; } // Return a list of all subdirectories in a directory std::vector Directory::getSubDirs() { // Make sure that no other thread is in the process of changing // the subdirectory list when we return it MutexLocker lock(dirMutex); return subDirs; } // Refresh the directory listing bool Directory::refresh() { // Prevent concurrent call until valid is reset MutexLocker lock(dirMutex); // Reset the state valid = false; subDirs.clear(); files.clear(); #ifndef _WIN32 // Enumerate the directory DIR* dir = opendir(path.c_str()); if (dir == NULL) { DEBUG_MSG("Failed to open directory %s", path.c_str()); return false; } // Enumerate the directory struct dirent* entry = NULL; while ((entry = readdir(dir)) != NULL) { bool pushed = false; // Check if this is the . or .. entry if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) { continue; } // Convert the name of the entry to a C++ string std::string name(entry->d_name); #if defined(_DIRENT_HAVE_D_TYPE) && defined(_BSD_SOURCE) // Determine the type of the entry switch(entry->d_type) { case DT_DIR: // This is a directory subDirs.push_back(name); pushed = true; break; case DT_REG: // This is a regular file files.push_back(name); pushed = true; break; default: break; } #endif if (!pushed) { // The entry type has to be determined using lstat struct stat entryStatus; std::string fullPath = path + OS_PATHSEP + name; if (!lstat(fullPath.c_str(), &entryStatus)) { if (S_ISDIR(entryStatus.st_mode)) { subDirs.push_back(name); } else if (S_ISREG(entryStatus.st_mode)) { files.push_back(name); } else { DEBUG_MSG("File not used %s", name.c_str()); } } } } // Close the directory closedir(dir); #else // Enumerate the directory std::string pattern; intptr_t h; struct _finddata_t fi; if ((path.back() == '/') || (path.back() == '\\')) pattern = path + "*"; else pattern = path + "/*"; memset(&fi, 0, sizeof(fi)); h = _findfirst(pattern.c_str(), &fi); if (h == -1) { // empty directory if (errno == ENOENT) goto finished; DEBUG_MSG("Failed to open directory %s", path.c_str()); return false; } // scan files & subdirs do { // Check if this is the . or .. entry if (!strcmp(fi.name, ".") || !strcmp(fi.name, "..")) continue; if ((fi.attrib & _A_SUBDIR) == 0) files.push_back(fi.name); else subDirs.push_back(fi.name); memset(&fi, 0, sizeof(fi)); } while (_findnext(h, &fi) == 0); (void) _findclose(h); finished: #endif valid = true; return true; } // Create a new subdirectory bool Directory::mkdir(std::string name) { std::string fullPath = path + OS_PATHSEP + name; #ifndef _WIN32 return (!::mkdir(fullPath.c_str(), S_IFDIR | S_IRWXU) && refresh()); #else return (!_mkdir(fullPath.c_str()) && refresh()); #endif } // Delete a subdirectory in the directory bool Directory::rmdir(std::string name, bool doRefresh /* = false */) { std::string fullPath; if (name.empty()) fullPath = path; else fullPath = path + OS_PATHSEP + name; #ifndef _WIN32 if (::rmdir(fullPath.c_str()) != 0) return false; #else if (_rmdir(fullPath.c_str()) != 0) return false; #endif if (doRefresh) return refresh(); return true; } // Delete a file in the directory bool Directory::remove(std::string name) { std::string fullPath = path + OS_PATHSEP + name; #ifndef _WIN32 return (!::remove(fullPath.c_str()) && refresh()); #else return (!_unlink(fullPath.c_str()) && refresh()); #endif } softhsm-2.0.0/src/lib/crypto/0000775000175000017500000000000012552220146013053 500000000000000softhsm-2.0.0/src/lib/crypto/BotanRNG.cpp0000664000175000017500000000467412533040716015126 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BOTANRNG.cpp Botan random number generator class *****************************************************************************/ #include "config.h" #include "BotanRNG.h" #include #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) #include #else #include #endif // Base constructor BotanRNG::BotanRNG() { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) rng = &Botan::global_state().global_rng(); #else rng = new Botan::AutoSeeded_RNG(); #endif } // Destructor BotanRNG::~BotanRNG() { #if BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,11,14) delete rng; #endif } // Generate random data bool BotanRNG::generateRandom(ByteString& data, const size_t len) { data.wipe(len); if (len > 0) rng->randomize(&data[0], len); return true; } // Seed the random pool void BotanRNG::seed(ByteString& seedData) { rng->add_entropy(seedData.byte_str(), seedData.size()); rng->reseed(seedData.size()); } // Get the RNG Botan::RandomNumberGenerator* BotanRNG::getRNG() { return rng; } softhsm-2.0.0/src/lib/crypto/BotanMacAlgorithm.h0000664000175000017500000000475112533040716016510 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanMacAlgorithm.h Botan MAC algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANMACALGORITHM_H #define _SOFTHSM_V2_BOTANMACALGORITHM_H #include #include "config.h" #include "SymmetricKey.h" #include "MacAlgorithm.h" #include class BotanMacAlgorithm : public MacAlgorithm { public: // Constructor BotanMacAlgorithm(); // Destructor virtual ~BotanMacAlgorithm(); // Signing functions virtual bool signInit(const SymmetricKey* key); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(const SymmetricKey* key); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(ByteString& signature); // Return the MAC size virtual size_t getMacSize() const = 0; protected: // Return the right hash for the operation virtual std::string getHash() const = 0; private: // The current context Botan::HMAC* hmac; }; #endif // !_SOFTHSM_V2_BOTANMACALGORITHM_H softhsm-2.0.0/src/lib/crypto/OSSLRSAKeyPair.h0000664000175000017500000000440212533040716015561 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSAKeyPair.h OpenSSL RSA key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLRSAKEYPAIR_H #define _SOFTHSM_V2_OSSLRSAKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "OSSLRSAPublicKey.h" #include "OSSLRSAPrivateKey.h" class OSSLRSAKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(OSSLRSAPublicKey& publicKey); // Set the private key void setPrivateKey(OSSLRSAPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key OSSLRSAPublicKey pubKey; // The private key OSSLRSAPrivateKey privKey; }; #endif // !_SOFTHSM_V2_OSSLRSAKEYPAIR_H softhsm-2.0.0/src/lib/crypto/AsymmetricAlgorithm.h0000664000175000017500000001334412533040716017137 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymmetricAlgorithm.h Base class for asymmetric algorithm classes *****************************************************************************/ #ifndef _SOFTHSM_V2_ASYMMETRICALGORITHM_H #define _SOFTHSM_V2_ASYMMETRICALGORITHM_H #include "config.h" #include "AsymmetricKeyPair.h" #include "AsymmetricParameters.h" #include "HashAlgorithm.h" #include "PublicKey.h" #include "PrivateKey.h" #include "RNG.h" #include "SymmetricKey.h" struct AsymAlgo { enum Type { Unknown, RSA, DSA, DH, ECDH, ECDSA, GOST }; }; struct AsymMech { enum Type { Unknown, RSA, RSA_MD5_PKCS, RSA_PKCS, RSA_PKCS_OAEP, RSA_SHA1_PKCS, RSA_SHA224_PKCS, RSA_SHA256_PKCS, RSA_SHA384_PKCS, RSA_SHA512_PKCS, RSA_SHA1_PKCS_PSS, RSA_SHA224_PKCS_PSS, RSA_SHA256_PKCS_PSS, RSA_SHA384_PKCS_PSS, RSA_SHA512_PKCS_PSS, RSA_SSL, DSA, DSA_SHA1, DSA_SHA224, DSA_SHA256, DSA_SHA384, DSA_SHA512, ECDSA, GOST, GOST_GOST }; }; struct AsymRSAMGF { enum Type { Unknown, MGF1_SHA1, MGF1_SHA224, MGF1_SHA256, MGF1_SHA384, MGF1_SHA512 }; }; struct RSA_PKCS_PSS_PARAMS { HashAlgo::Type hashAlg; AsymRSAMGF::Type mgf; size_t sLen; }; class AsymmetricAlgorithm { public: // Base constructors AsymmetricAlgorithm(); // Destructor virtual ~AsymmetricAlgorithm() { } // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding) = 0; // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding) = 0; // Wrap/Unwrap keys bool wrapKey(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); bool unwrapKey(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL) = 0; virtual unsigned long getMinKeySize() = 0; virtual unsigned long getMaxKeySize() = 0; virtual bool generateParameters(AsymmetricParameters** ppParams, void* parameters = NULL, RNG* rng = NULL); virtual bool deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) = 0; virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) = 0; virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) = 0; virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey() = 0; virtual PrivateKey* newPrivateKey() = 0; virtual AsymmetricParameters* newParameters(); // Key recycling -- override these functions in a derived class if you need to perform specific cleanup virtual void recycleKeyPair(AsymmetricKeyPair* toRecycle); virtual void recycleParameters(AsymmetricParameters* toRecycle); virtual void recyclePublicKey(PublicKey* toRecycle); virtual void recyclePrivateKey(PrivateKey* toRecycle); virtual void recycleSymmetricKey(SymmetricKey* toRecycle); protected: PublicKey* currentPublicKey; PrivateKey* currentPrivateKey; AsymMech::Type currentMechanism; AsymMech::Type currentPadding; private: enum { NONE, SIGN, VERIFY } currentOperation; bool isWrappingMech(AsymMech::Type padding); }; #endif // !_SOFTHSM_V2_ASYMMETRICALGORITHM_H softhsm-2.0.0/src/lib/crypto/BotanECDSAPublicKey.cpp0000664000175000017500000000724112533040716017120 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSAPublicKey.cpp Botan ECDSA public key class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDSAPublicKey.h" #include "BotanUtil.h" #include // Constructors BotanECDSAPublicKey::BotanECDSAPublicKey() { eckey = NULL; } BotanECDSAPublicKey::BotanECDSAPublicKey(const Botan::ECDSA_PublicKey* inECKEY) { eckey = NULL; setFromBotan(inECKEY); } // Destructor BotanECDSAPublicKey::~BotanECDSAPublicKey() { delete eckey; } // The type /*static*/ const char* BotanECDSAPublicKey::type = "Botan ECDSA Public Key"; // Get the base point order length unsigned long BotanECDSAPublicKey::getOrderLength() const { try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); return group.get_order().bytes(); } catch (...) { ERROR_MSG("Can't get EC group for order length"); return 0; } } // Set from Botan representation void BotanECDSAPublicKey::setFromBotan(const Botan::ECDSA_PublicKey* inECKEY) { ByteString inEC = BotanUtil::ecGroup2ByteString(inECKEY->domain()); setEC(inEC); ByteString inQ = BotanUtil::ecPoint2ByteString(inECKEY->public_point()); setQ(inQ); } // Check if the key is of the given type bool BotanECDSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the ECDSA public key components void BotanECDSAPublicKey::setEC(const ByteString& inEC) { ECPublicKey::setEC(inEC); if (eckey) { delete eckey; eckey = NULL; } } void BotanECDSAPublicKey::setQ(const ByteString& inQ) { ECPublicKey::setQ(inQ); if (eckey) { delete eckey; eckey = NULL; } } // Retrieve the Botan representation of the key Botan::ECDSA_PublicKey* BotanECDSAPublicKey::getBotanKey() { if (!eckey) { createBotanKey(); } return eckey; } // Create the Botan representation of the key void BotanECDSAPublicKey::createBotanKey() { if (ec.size() != 0 && q.size() != 0) { if (eckey) { delete eckey; eckey = NULL; } try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); Botan::PointGFp point = BotanUtil::byteString2ECPoint(q, group); eckey = new Botan::ECDSA_PublicKey(group, point); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } #endif softhsm-2.0.0/src/lib/crypto/DSAPrivateKey.cpp0000664000175000017500000000642112533040716016117 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSAPrivateKey.cpp DSA private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "DSAPrivateKey.h" #include // Set the type /*static*/ const char* DSAPrivateKey::type = "Abstract DSA private key"; // Check if the key is of the given type bool DSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long DSAPrivateKey::getBitLength() const { return getP().bits(); } // Get the output length unsigned long DSAPrivateKey::getOutputLength() const { return getQ().size() * 2; } // Setters for the DSA private key components void DSAPrivateKey::setX(const ByteString& inX) { x = inX; } // Setters for the DSA domain parameters void DSAPrivateKey::setP(const ByteString& inP) { p = inP; } void DSAPrivateKey::setQ(const ByteString& inQ) { q = inQ; } void DSAPrivateKey::setG(const ByteString& inG) { g = inG; } // Getters for the DSA private key components const ByteString& DSAPrivateKey::getX() const { return x; } // Getters for the DSA domain parameters const ByteString& DSAPrivateKey::getP() const { return p; } const ByteString& DSAPrivateKey::getQ() const { return q; } const ByteString& DSAPrivateKey::getG() const { return g; } // Serialisation ByteString DSAPrivateKey::serialise() const { return p.serialise() + q.serialise() + g.serialise() + x.serialise(); } bool DSAPrivateKey::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); ByteString dG = ByteString::chainDeserialise(serialised); ByteString dX = ByteString::chainDeserialise(serialised); if ((dP.size() == 0) || (dQ.size() == 0) || (dG.size() == 0) || (dX.size() == 0)) { return false; } setP(dP); setQ(dQ); setG(dG); setX(dX); return true; } softhsm-2.0.0/src/lib/crypto/OSSLECPrivateKey.cpp0000664000175000017500000001143012533040716016474 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECPrivateKey.cpp OpenSSL EC private key class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "OSSLECPrivateKey.h" #include "OSSLUtil.h" #include #include // Constructors OSSLECPrivateKey::OSSLECPrivateKey() { eckey = EC_KEY_new(); // For PKCS#8 encoding EC_KEY_set_enc_flags(eckey, EC_PKEY_NO_PUBKEY); } OSSLECPrivateKey::OSSLECPrivateKey(const EC_KEY* inECKEY) { eckey = EC_KEY_new(); // For PKCS#8 encoding EC_KEY_set_enc_flags(eckey, EC_PKEY_NO_PUBKEY); setFromOSSL(inECKEY); } // Destructor OSSLECPrivateKey::~OSSLECPrivateKey() { EC_KEY_free(eckey); } // The type /*static*/ const char* OSSLECPrivateKey::type = "OpenSSL EC Private Key"; // Get the base point order length unsigned long OSSLECPrivateKey::getOrderLength() const { const EC_GROUP* grp = EC_KEY_get0_group(eckey); if (grp != NULL) { BIGNUM* order = BN_new(); if (order == NULL) return 0; if (!EC_GROUP_get_order(grp, order, NULL)) { BN_clear_free(order); return 0; } unsigned long len = BN_num_bytes(order); BN_clear_free(order); return len; } return 0; } // Set from OpenSSL representation void OSSLECPrivateKey::setFromOSSL(const EC_KEY* inECKEY) { const EC_GROUP* grp = EC_KEY_get0_group(inECKEY); if (grp != NULL) { ByteString inEC = OSSL::grp2ByteString(grp); setEC(inEC); } const BIGNUM* pk = EC_KEY_get0_private_key(inECKEY); if (pk != NULL) { ByteString inD = OSSL::bn2ByteString(pk); setD(inD); } } // Check if the key is of the given type bool OSSLECPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the EC private key components void OSSLECPrivateKey::setD(const ByteString& inD) { ECPrivateKey::setD(inD); BIGNUM* pk = OSSL::byteString2bn(inD); EC_KEY_set_private_key(eckey, pk); BN_clear_free(pk); } // Setters for the EC public key components void OSSLECPrivateKey::setEC(const ByteString& inEC) { ECPrivateKey::setEC(inEC); EC_GROUP* grp = OSSL::byteString2grp(inEC); EC_KEY_set_group(eckey, grp); EC_GROUP_free(grp); } // Encode into PKCS#8 DER ByteString OSSLECPrivateKey::PKCS8Encode() { ByteString der; if (eckey == NULL) return der; EVP_PKEY* pkey = EVP_PKEY_new(); if (pkey == NULL) return der; if (!EVP_PKEY_set1_EC_KEY(pkey, eckey)) { EVP_PKEY_free(pkey); return der; } PKCS8_PRIV_KEY_INFO* p8inf = EVP_PKEY2PKCS8(pkey); EVP_PKEY_free(pkey); if (p8inf == NULL) return der; int len = i2d_PKCS8_PRIV_KEY_INFO(p8inf, NULL); if (len < 0) { PKCS8_PRIV_KEY_INFO_free(p8inf); return der; } der.resize(len); unsigned char* priv = &der[0]; int len2 = i2d_PKCS8_PRIV_KEY_INFO(p8inf, &priv); PKCS8_PRIV_KEY_INFO_free(p8inf); if (len2 != len) der.wipe(); return der; } // Decode from PKCS#8 BER bool OSSLECPrivateKey::PKCS8Decode(const ByteString& ber) { int len = ber.size(); if (len <= 0) return false; const unsigned char* priv = ber.const_byte_str(); PKCS8_PRIV_KEY_INFO* p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &priv, len); if (p8 == NULL) return false; EVP_PKEY* pkey = EVP_PKCS82PKEY(p8); PKCS8_PRIV_KEY_INFO_free(p8); if (pkey == NULL) return false; EC_KEY* key = EVP_PKEY_get1_EC_KEY(pkey); EVP_PKEY_free(pkey); if (key == NULL) return false; setFromOSSL(key); EC_KEY_free(key); return true; } // Retrieve the OpenSSL representation of the key EC_KEY* OSSLECPrivateKey::getOSSLKey() { return eckey; } #endif softhsm-2.0.0/src/lib/crypto/HashAlgorithm.h0000664000175000017500000000422112533040716015677 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HashAlgorithm.h Base class for hash algorithm classes *****************************************************************************/ #ifndef _SOFTHSM_V2_HASHALGORITHM_H #define _SOFTHSM_V2_HASHALGORITHM_H #include "config.h" #include "ByteString.h" struct HashAlgo { enum Type { Unknown, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, GOST }; }; class HashAlgorithm { public: // Base constructors HashAlgorithm(); // Destructor virtual ~HashAlgorithm() { } // Hashing functions virtual bool hashInit(); virtual bool hashUpdate(const ByteString& data); virtual bool hashFinal(ByteString& hashedData); virtual int getHashSize() = 0; protected: // The current operation enum { NONE, HASHING } currentOperation; }; #endif // !_SOFTHSM_V2_HASHALGORITHM_H softhsm-2.0.0/src/lib/crypto/BotanUtil.h0000664000175000017500000000516012533040716015051 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanUtil.h Botan convenience functions *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANUTIL_H #define _SOFTHSM_V2_BOTANUTIL_H #include "config.h" #include "ByteString.h" #include #if defined(WITH_ECC) || defined(WITH_GOST) #include #endif namespace BotanUtil { // Convert a Botan BigInt to a ByteString ByteString bigInt2ByteString(const Botan::BigInt& bigInt); ByteString bigInt2ByteStringPrefix(const Botan::BigInt& bigInt, size_t size); // Convert a ByteString to a Botan BigInt Botan::BigInt byteString2bigInt(const ByteString& byteString); #if defined(WITH_ECC) || defined(WITH_GOST) // Convert a Botan EC group to a ByteString ByteString ecGroup2ByteString(const Botan::EC_Group& ecGroup); // Convert a ByteString to a Botan EC group Botan::EC_Group byteString2ECGroup(const ByteString& byteString); // Convert a Botan EC point to a ByteString ByteString ecPoint2ByteString(const Botan::PointGFp& ecPoint); // Convert a ByteString to a Botan EC point in the given EC group Botan::PointGFp byteString2ECPoint(const ByteString& byteString, const Botan::EC_Group& ecGroup); #endif } #endif // !_SOFTHSM_V2_BOTANUTIL_H softhsm-2.0.0/src/lib/crypto/OSSLDHPrivateKey.cpp0000664000175000017500000001104412533040716016501 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDHPrivateKey.cpp OpenSSL Diffie-Hellman private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDHPrivateKey.h" #include "OSSLUtil.h" #include #include #include // Constructors OSSLDHPrivateKey::OSSLDHPrivateKey() { dh = DH_new(); // Use the OpenSSL implementation and not any engine DH_set_method(dh, DH_get_default_method()); } OSSLDHPrivateKey::OSSLDHPrivateKey(const DH* inDH) { dh = DH_new(); // Use the OpenSSL implementation and not any engine DH_set_method(dh, DH_OpenSSL()); setFromOSSL(inDH); } // Destructor OSSLDHPrivateKey::~OSSLDHPrivateKey() { DH_free(dh); } // The type /*static*/ const char* OSSLDHPrivateKey::type = "OpenSSL DH Private Key"; // Set from OpenSSL representation void OSSLDHPrivateKey::setFromOSSL(const DH* inDH) { if (inDH->p) { ByteString inP = OSSL::bn2ByteString(inDH->p); setP(inP); } if (inDH->g) { ByteString inG = OSSL::bn2ByteString(inDH->g); setG(inG); } if (inDH->priv_key) { ByteString inX = OSSL::bn2ByteString(inDH->priv_key); setX(inX); } } // Check if the key is of the given type bool OSSLDHPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DH private key components void OSSLDHPrivateKey::setX(const ByteString& inX) { DHPrivateKey::setX(inX); if (dh->priv_key) { BN_clear_free(dh->priv_key); dh->priv_key = NULL; } dh->priv_key = OSSL::byteString2bn(inX); } // Setters for the DH public key components void OSSLDHPrivateKey::setP(const ByteString& inP) { DHPrivateKey::setP(inP); if (dh->p) { BN_clear_free(dh->p); dh->p = NULL; } dh->p = OSSL::byteString2bn(inP); } void OSSLDHPrivateKey::setG(const ByteString& inG) { DHPrivateKey::setG(inG); if (dh->g) { BN_clear_free(dh->g); dh->g = NULL; } dh->g = OSSL::byteString2bn(inG); } // Encode into PKCS#8 DER ByteString OSSLDHPrivateKey::PKCS8Encode() { ByteString der; if (dh == NULL) return der; EVP_PKEY* pkey = EVP_PKEY_new(); if (pkey == NULL) return der; if (!EVP_PKEY_set1_DH(pkey, dh)) { EVP_PKEY_free(pkey); return der; } PKCS8_PRIV_KEY_INFO* p8inf = EVP_PKEY2PKCS8(pkey); EVP_PKEY_free(pkey); if (p8inf == NULL) return der; int len = i2d_PKCS8_PRIV_KEY_INFO(p8inf, NULL); if (len < 0) { PKCS8_PRIV_KEY_INFO_free(p8inf); return der; } der.resize(len); unsigned char* priv = &der[0]; int len2 = i2d_PKCS8_PRIV_KEY_INFO(p8inf, &priv); PKCS8_PRIV_KEY_INFO_free(p8inf); if (len2 != len) der.wipe(); return der; } // Decode from PKCS#8 BER bool OSSLDHPrivateKey::PKCS8Decode(const ByteString& ber) { int len = ber.size(); if (len <= 0) return false; const unsigned char* priv = ber.const_byte_str(); PKCS8_PRIV_KEY_INFO* p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &priv, len); if (p8 == NULL) return false; EVP_PKEY* pkey = EVP_PKCS82PKEY(p8); PKCS8_PRIV_KEY_INFO_free(p8); if (pkey == NULL) return false; DH* key = EVP_PKEY_get1_DH(pkey); EVP_PKEY_free(pkey); if (key == NULL) return false; setFromOSSL(key); DH_free(key); return true; } // Retrieve the OpenSSL representation of the key DH* OSSLDHPrivateKey::getOSSLKey() { return dh; } softhsm-2.0.0/src/lib/crypto/CryptoFactory.cpp0000664000175000017500000000633312533040716016316 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** CryptoFactory.cpp This class is a factory for all cryptographic algorithm implementations. It is an abstract base class for a factory that produces cryptographic library specific implementations of cryptographic algorithms. *****************************************************************************/ #include "config.h" #include "CryptoFactory.h" #if defined(WITH_OPENSSL) #include "OSSLCryptoFactory.h" // Return the one-and-only instance CryptoFactory* CryptoFactory::i() { return OSSLCryptoFactory::i(); } // This will destroy the one-and-only instance. void CryptoFactory::reset() { OSSLCryptoFactory::reset(); } #elif defined(WITH_BOTAN) #include "BotanCryptoFactory.h" // Return the one-and-only instance CryptoFactory* CryptoFactory::i() { return BotanCryptoFactory::i(); } // This will destroy the one-and-only instance. void CryptoFactory::reset() { BotanCryptoFactory::reset(); } #else #error "You must configure a cryptographic library to use" #endif // Recycle a symmetric algorithm instance -- override this function in the derived // class if you need to perform specific clean-up void CryptoFactory::recycleSymmetricAlgorithm(SymmetricAlgorithm* toRecycle) { delete toRecycle; } // Recycle an asymmetric algorithm instance -- override this function in the derived // class if you need to perform specific clean-up void CryptoFactory::recycleAsymmetricAlgorithm(AsymmetricAlgorithm* toRecycle) { delete toRecycle; } // Recycle a hash algorithm instance -- override this function in the derived // class if you need to perform specific clean-up void CryptoFactory::recycleHashAlgorithm(HashAlgorithm* toRecycle) { delete toRecycle; } // Recycle a MAC algorithm instance -- override this function in the derived // class if you need to perform specific clean-up void CryptoFactory::recycleMacAlgorithm(MacAlgorithm* toRecycle) { delete toRecycle; } softhsm-2.0.0/src/lib/crypto/BotanSHA384.h0000664000175000017500000000352712533040716015013 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA384.h Botan SHA384 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANSHA384_H #define _SOFTHSM_V2_BOTANSHA384_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanSHA384 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANSHA384_H softhsm-2.0.0/src/lib/crypto/BotanGOSTR3411.cpp0000664000175000017500000000342612533040716015701 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTR3411.cpp Botan GOST R 34.11-94 implementation *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "BotanGOSTR3411.h" #include int BotanGOSTR3411::getHashSize() { return 32; } Botan::HashFunction* BotanGOSTR3411::getHash() const { return new Botan::GOST_34_11(); } #endif softhsm-2.0.0/src/lib/crypto/DHPrivateKey.h0000664000175000017500000000512412533040716015447 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHPrivateKey.h Diffie-Hellman private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_DHPRIVATEKEY_H #define _SOFTHSM_V2_DHPRIVATEKEY_H #include "config.h" #include "PrivateKey.h" class DHPrivateKey : public PrivateKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Setters for the DH private key components virtual void setX(const ByteString& inX); // Setters for the DH public key components virtual void setP(const ByteString& inP); virtual void setG(const ByteString& inG); // Getters for the DH private key components virtual const ByteString& getX() const; // Getters for the DH public key components virtual const ByteString& getP() const; virtual const ByteString& getG() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Private components ByteString x; // Public components ByteString p,g; }; #endif // !_SOFTHSM_V2_DHPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/BotanECDH.h0000664000175000017500000000667212533040716014650 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDH.h Botan ECDH asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDH_H #define _SOFTHSM_V2_BOTANECDH_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class BotanECDH : public AsymmetricAlgorithm { public: // Destructor virtual ~BotanECDH() { } // Signing functions virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: }; #endif // !_SOFTHSM_V2_BOTANECDH_H softhsm-2.0.0/src/lib/crypto/BotanRSAPrivateKey.cpp0000664000175000017500000001500212533040716017114 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSAPrivateKey.cpp Botan RSA private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanRSAPrivateKey.h" #include "BotanUtil.h" #include "BotanRNG.h" #include "BotanCryptoFactory.h" #include #include #include #include #include #include // Constructors BotanRSAPrivateKey::BotanRSAPrivateKey() { rsa = NULL; } BotanRSAPrivateKey::BotanRSAPrivateKey(const Botan::RSA_PrivateKey* inRSA) { rsa = NULL; setFromBotan(inRSA); } // Destructor BotanRSAPrivateKey::~BotanRSAPrivateKey() { delete rsa; } // The type /*static*/ const char* BotanRSAPrivateKey::type = "Botan RSA Private Key"; // Set from Botan representation void BotanRSAPrivateKey::setFromBotan(const Botan::RSA_PrivateKey* inRSA) { ByteString inP = BotanUtil::bigInt2ByteString(inRSA->get_p()); setP(inP); ByteString inQ = BotanUtil::bigInt2ByteString(inRSA->get_q()); setQ(inQ); ByteString inDP1 = BotanUtil::bigInt2ByteString(inRSA->get_d1()); setDP1(inDP1); ByteString inDQ1 = BotanUtil::bigInt2ByteString(inRSA->get_d2()); setDQ1(inDQ1); ByteString inPQ = BotanUtil::bigInt2ByteString(inRSA->get_c()); setPQ(inPQ); ByteString inD = BotanUtil::bigInt2ByteString(inRSA->get_d()); setD(inD); ByteString inN = BotanUtil::bigInt2ByteString(inRSA->get_n()); setN(inN); ByteString inE = BotanUtil::bigInt2ByteString(inRSA->get_e()); setE(inE); } // Check if the key is of the given type bool BotanRSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the RSA private key components void BotanRSAPrivateKey::setP(const ByteString& inP) { RSAPrivateKey::setP(inP); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPrivateKey::setQ(const ByteString& inQ) { RSAPrivateKey::setQ(inQ); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPrivateKey::setPQ(const ByteString& inPQ) { RSAPrivateKey::setPQ(inPQ); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPrivateKey::setDP1(const ByteString& inDP1) { RSAPrivateKey::setDP1(inDP1); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPrivateKey::setDQ1(const ByteString& inDQ1) { RSAPrivateKey::setDQ1(inDQ1); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPrivateKey::setD(const ByteString& inD) { RSAPrivateKey::setD(inD); if (rsa) { delete rsa; rsa = NULL; } } // Setters for the RSA public key components void BotanRSAPrivateKey::setN(const ByteString& inN) { RSAPrivateKey::setN(inN); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPrivateKey::setE(const ByteString& inE) { RSAPrivateKey::setE(inE); if (rsa) { delete rsa; rsa = NULL; } } // Encode into PKCS#8 DER ByteString BotanRSAPrivateKey::PKCS8Encode() { ByteString der; createBotanKey(); if (rsa == NULL) return der; #if BOTAN_VERSION_MINOR == 11 const Botan::secure_vector ber = Botan::PKCS8::BER_encode(*rsa); #else const Botan::SecureVector ber = Botan::PKCS8::BER_encode(*rsa); #endif der.resize(ber.size()); memcpy(&der[0], &ber[0], ber.size()); return der; } // Decode from PKCS#8 BER bool BotanRSAPrivateKey::PKCS8Decode(const ByteString& ber) { Botan::DataSource_Memory source(ber.const_byte_str(), ber.size()); if (source.end_of_data()) return false; #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector keydata; #else Botan::SecureVector keydata; #endif Botan::AlgorithmIdentifier alg_id; Botan::RSA_PrivateKey* key = NULL; try { Botan::BER_Decoder(source) .start_cons(Botan::SEQUENCE) .decode_and_check(0, "Unknown PKCS #8 version number") .decode(alg_id) .decode(keydata, Botan::OCTET_STRING) .discard_remaining() .end_cons(); if (keydata.empty()) throw Botan::Decoding_Error("PKCS #8 private key decoding failed"); if (Botan::OIDS::lookup(alg_id.oid).compare("RSA")) { ERROR_MSG("Decoded private key not RSA"); return false; } BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); key = new Botan::RSA_PrivateKey(alg_id, keydata, *rng->getRNG()); if (key == NULL) return false; setFromBotan(key); delete key; } catch (std::exception& e) { ERROR_MSG("Decode failed on %s", e.what()); return false; } return true; } // Retrieve the Botan representation of the key Botan::RSA_PrivateKey* BotanRSAPrivateKey::getBotanKey() { if (!rsa) { createBotanKey(); } return rsa; } // Create the Botan representation of the key void BotanRSAPrivateKey::createBotanKey() { // d and n is not needed, they can be calculated if (p.size() != 0 && q.size() != 0 && e.size() != 0) { if (rsa) { delete rsa; rsa = NULL; } try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); rsa = new Botan::RSA_PrivateKey(*rng->getRNG(), BotanUtil::byteString2bigInt(p), BotanUtil::byteString2bigInt(q), BotanUtil::byteString2bigInt(e), BotanUtil::byteString2bigInt(d), BotanUtil::byteString2bigInt(n)); } catch (...) { ERROR_MSG("Could not create the Botan private key"); } } } softhsm-2.0.0/src/lib/crypto/BotanDHPublicKey.cpp0000664000175000017500000000673312533040716016601 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDHPublicKey.cpp Botan Diffie-Hellman public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDHPublicKey.h" #include "BotanUtil.h" #include // Constructors BotanDHPublicKey::BotanDHPublicKey() { dh = NULL; } BotanDHPublicKey::BotanDHPublicKey(const Botan::DH_PublicKey* inDH) { dh = NULL; setFromBotan(inDH); } // Destructor BotanDHPublicKey::~BotanDHPublicKey() { delete dh; } // The type /*static*/ const char* BotanDHPublicKey::type = "Botan DH Public Key"; // Set from Botan representation void BotanDHPublicKey::setFromBotan(const Botan::DH_PublicKey* inDH) { ByteString inP = BotanUtil::bigInt2ByteString(inDH->group_p()); setP(inP); ByteString inG = BotanUtil::bigInt2ByteString(inDH->group_g()); setG(inG); ByteString inY = BotanUtil::bigInt2ByteString(inDH->get_y()); setY(inY); } // Check if the key is of the given type bool BotanDHPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DH public key components void BotanDHPublicKey::setP(const ByteString& inP) { DHPublicKey::setP(inP); if (dh) { delete dh; dh = NULL; } } void BotanDHPublicKey::setG(const ByteString& inG) { DHPublicKey::setG(inG); if (dh) { delete dh; dh = NULL; } } void BotanDHPublicKey::setY(const ByteString& inY) { DHPublicKey::setY(inY); if (dh) { delete dh; dh = NULL; } } // Retrieve the Botan representation of the key Botan::DH_PublicKey* BotanDHPublicKey::getBotanKey() { if (!dh) { createBotanKey(); } return dh; } // Create the Botan representation of the key void BotanDHPublicKey::createBotanKey() { // We actually do not need to check q, since it can be set zero if (p.size() != 0 && y.size() != 0) { if (dh) { delete dh; dh = NULL; } try { dh = new Botan::DH_PublicKey(Botan::DL_Group(BotanUtil::byteString2bigInt(p), BotanUtil::byteString2bigInt(g)), BotanUtil::byteString2bigInt(y)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } softhsm-2.0.0/src/lib/crypto/OSSLSHA256.h0000664000175000017500000000346312533040716014525 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA256.h OpenSSL SHA256 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLSHA256_H #define _SOFTHSM_V2_OSSLSHA256_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLSHA256 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLSHA256_H softhsm-2.0.0/src/lib/crypto/BotanRSA.cpp0000664000175000017500000006337412533040716015127 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSA.cpp Botan RSA asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanRSA.h" #include "BotanRNG.h" #include "CryptoFactory.h" #include "BotanCryptoFactory.h" #include "RSAParameters.h" #include "BotanRSAKeyPair.h" #include #include #include // Constructor BotanRSA::BotanRSA() { signer = NULL; verifier = NULL; } // Destructor BotanRSA::~BotanRSA() { delete signer; delete verifier; } // Signing functions bool BotanRSA::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { std::string emsa = ""; switch (mechanism) { case AsymMech::RSA: emsa = "Raw"; break; case AsymMech::RSA_PKCS: emsa = "EMSA3(Raw)"; break; default: // Call default implementation return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen); } // Check if the private key is the right type if (!privateKey->isOfType(BotanRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } BotanRSAPrivateKey* pk = (BotanRSAPrivateKey*) privateKey; Botan::RSA_PrivateKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan private key"); return false; } try { signer = new Botan::PK_Signer(*botanKey, emsa); // Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster. } catch (...) { ERROR_MSG("Could not create the signer token"); return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 std::vector signResult; #else Botan::SecureVector signResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); signResult = signer->sign_message(dataToSign.const_byte_str(), dataToSign.size(), *rng->getRNG()); } catch (std::exception& e) { ERROR_MSG("Could not sign the data: %s", e.what()); delete signer; signer = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete signer; signer = NULL; return true; } bool BotanRSA::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!privateKey->isOfType(BotanRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } std::string emsa; std::ostringstream request; size_t sLen; switch (mechanism) { case AsymMech::RSA_MD5_PKCS: emsa = "EMSA3(MD5)"; break; case AsymMech::RSA_SHA1_PKCS: emsa = "EMSA3(SHA-160)"; break; case AsymMech::RSA_SHA224_PKCS: emsa = "EMSA3(SHA-224)"; break; case AsymMech::RSA_SHA256_PKCS: emsa = "EMSA3(SHA-256)"; break; case AsymMech::RSA_SHA384_PKCS: emsa = "EMSA3(SHA-384)"; break; case AsymMech::RSA_SHA512_PKCS: emsa = "EMSA3(SHA-512)"; break; case AsymMech::RSA_SHA1_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA1 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA1) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-20)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } request << "EMSA4(SHA-160,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA224_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA224 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA224) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-28)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } request << "EMSA4(SHA-224,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA256_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA256 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA256) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-32)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } request << "EMSA4(SHA-256,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA384_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA384 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA384) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-48)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } request << "EMSA4(SHA-384,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA512_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA512 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA512) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-64)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } request << "EMSA4(SHA-512,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SSL: emsa = "EMSA3(Parallel(MD5,SHA-160))"; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } BotanRSAPrivateKey* pk = (BotanRSAPrivateKey*) currentPrivateKey; Botan::RSA_PrivateKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan private key"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } try { signer = new Botan::PK_Signer(*botanKey, emsa); // Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster. } catch (...) { ERROR_MSG("Could not create the signer token"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool BotanRSA::signUpdate(const ByteString& dataToSign) { if (!AsymmetricAlgorithm::signUpdate(dataToSign)) { return false; } try { if (dataToSign.size() != 0) { signer->update(dataToSign.const_byte_str(), dataToSign.size()); } } catch (...) { ERROR_MSG("Could not add data to signer token"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); delete signer; signer = NULL; return false; } return true; } bool BotanRSA::signFinal(ByteString& signature) { if (!AsymmetricAlgorithm::signFinal(signature)) { return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 std::vector signResult; #else Botan::SecureVector signResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); signResult = signer->signature(*rng->getRNG()); } catch (...) { ERROR_MSG("Could not sign the data"); delete signer; signer = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete signer; signer = NULL; return true; } // Verification functions bool BotanRSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { std::string emsa = ""; switch (mechanism) { case AsymMech::RSA: emsa = "Raw"; break; case AsymMech::RSA_PKCS: emsa = "EMSA3(Raw)"; break; default: // Call the generic function return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen); } // Check if the public key is the right type if (!publicKey->isOfType(BotanRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } BotanRSAPublicKey* pk = (BotanRSAPublicKey*) publicKey; Botan::RSA_PublicKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan public key"); return false; } try { verifier = new Botan::PK_Verifier(*botanKey, emsa); } catch (...) { ERROR_MSG("Could not create the verifier token"); return false; } // Perform the verify operation bool verResult; try { verResult = verifier->verify_message(originalData.const_byte_str(), originalData.size(), signature.const_byte_str(), signature.size()); } catch (...) { ERROR_MSG("Could not check the signature"); delete verifier; verifier = NULL; return false; } delete verifier; verifier = NULL; return verResult; } bool BotanRSA::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen)) { return false; } // Check if the public key is the right type if (!publicKey->isOfType(BotanRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } std::string emsa; std::ostringstream request; size_t sLen; switch (mechanism) { case AsymMech::RSA_MD5_PKCS: emsa = "EMSA3(MD5)"; break; case AsymMech::RSA_SHA1_PKCS: emsa = "EMSA3(SHA-160)"; break; case AsymMech::RSA_SHA224_PKCS: emsa = "EMSA3(SHA-224)"; break; case AsymMech::RSA_SHA256_PKCS: emsa = "EMSA3(SHA-256)"; break; case AsymMech::RSA_SHA384_PKCS: emsa = "EMSA3(SHA-384)"; break; case AsymMech::RSA_SHA512_PKCS: emsa = "EMSA3(SHA-512)"; break; case AsymMech::RSA_SHA1_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA1 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA1) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-20)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } request << "EMSA4(SHA-160,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA224_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA224 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA224) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-28)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } request << "EMSA4(SHA-224,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA256_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA256 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA256) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-32)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } request << "EMSA4(SHA-256,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA384_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA384 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA384) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-48)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } request << "EMSA4(SHA-384,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SHA512_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA512 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA512) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-64)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } request << "EMSA4(SHA-512,MGF1," << sLen << ")"; emsa = request.str(); break; case AsymMech::RSA_SSL: emsa = "EMSA3(Parallel(MD5,SHA-160))"; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } BotanRSAPublicKey* pk = (BotanRSAPublicKey*) currentPublicKey; Botan::RSA_PublicKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan public key"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } try { verifier = new Botan::PK_Verifier(*botanKey, emsa); } catch (...) { ERROR_MSG("Could not create the verifier token"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool BotanRSA::verifyUpdate(const ByteString& originalData) { if (!AsymmetricAlgorithm::verifyUpdate(originalData)) { return false; } try { if (originalData.size() != 0) { verifier->update(originalData.const_byte_str(), originalData.size()); } } catch (...) { ERROR_MSG("Could not add data to the verifier token"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); delete verifier; verifier = NULL; return false; } return true; } bool BotanRSA::verifyFinal(const ByteString& signature) { if (!AsymmetricAlgorithm::verifyFinal(signature)) { return false; } // Perform the verify operation bool verResult; try { verResult = verifier->check_signature(signature.const_byte_str(), signature.size()); } catch (...) { ERROR_MSG("Could not check the signature"); delete verifier; verifier = NULL; return false; } delete verifier; verifier = NULL; return verResult; } // Encryption functions bool BotanRSA::encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding) { // Check if the public key is the right type if (!publicKey->isOfType(BotanRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } std::string eme; switch (padding) { case AsymMech::RSA_PKCS: eme = "PKCS1v15"; break; case AsymMech::RSA_PKCS_OAEP: eme = "EME1(SHA-160)"; break; case AsymMech::RSA: eme = "Raw"; break; default: ERROR_MSG("Invalid padding mechanism supplied (%i)", padding); return false; } BotanRSAPublicKey* pk = (BotanRSAPublicKey*) publicKey; Botan::RSA_PublicKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan public key"); return false; } Botan::PK_Encryptor_EME* encryptor = NULL; try { encryptor = new Botan::PK_Encryptor_EME(*botanKey, eme); } catch (...) { ERROR_MSG("Could not create the encryptor token"); return false; } // Perform the encryption operation #if BOTAN_VERSION_MINOR == 11 std::vector encResult; #else Botan::SecureVector encResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); encResult = encryptor->encrypt(data.const_byte_str(), data.size(), *rng->getRNG()); } catch (...) { ERROR_MSG("Could not encrypt the data"); delete encryptor; return false; } // Return the result encryptedData.resize(encResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&encryptedData[0], encResult.data(), encResult.size()); #else memcpy(&encryptedData[0], encResult.begin(), encResult.size()); #endif delete encryptor; return true; } // Decryption functions bool BotanRSA::decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding) { // Check if the private key is the right type if (!privateKey->isOfType(BotanRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } std::string eme; switch (padding) { case AsymMech::RSA_PKCS: eme = "PKCS1v15"; break; case AsymMech::RSA_PKCS_OAEP: eme = "EME1(SHA-160)"; break; case AsymMech::RSA: eme = "Raw"; break; default: ERROR_MSG("Invalid padding mechanism supplied (%i)", padding); return false; } BotanRSAPrivateKey* pk = (BotanRSAPrivateKey*) privateKey; Botan::RSA_PrivateKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan private key"); return false; } Botan::PK_Decryptor_EME* decryptor = NULL; try { decryptor = new Botan::PK_Decryptor_EME(*botanKey, eme); } catch (...) { ERROR_MSG("Could not create the decryptor token"); return false; } // Perform the decryption operation #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector decResult; #else Botan::SecureVector decResult; #endif try { decResult = decryptor->decrypt(encryptedData.const_byte_str(), encryptedData.size()); } catch (...) { ERROR_MSG("Could not decrypt the data"); delete decryptor; return false; } // Return the result if (padding == AsymMech::RSA) { // We compensate that Botan removes leading zeros int modSize = pk->getN().size(); int decSize = decResult.size(); data.resize(modSize); #if BOTAN_VERSION_MINOR == 11 memcpy(&data[0] + modSize - decSize, decResult.data(), decSize); #else memcpy(&data[0] + modSize - decSize, decResult.begin(), decSize); #endif } else { data.resize(decResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&data[0], decResult.data(), decResult.size()); #else memcpy(&data[0], decResult.begin(), decResult.size()); #endif } delete decryptor; return true; } // Key factory bool BotanRSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(RSAParameters::type)) { ERROR_MSG("Invalid parameters supplied for RSA key generation"); return false; } RSAParameters* params = (RSAParameters*) parameters; if (params->getBitLength() < getMinKeySize() || params->getBitLength() > getMaxKeySize()) { ERROR_MSG("This RSA key size (%lu) is not supported", params->getBitLength()); return false; } // Retrieve the desired public exponent unsigned long e = params->getE().long_val(); // Check the public exponent if ((e == 0) || (e % 2 != 1)) { ERROR_MSG("Invalid RSA public exponent %d", e); return false; } // Create an asymmetric key-pair object to return BotanRSAKeyPair* kp = new BotanRSAKeyPair(); // Generate the key-pair Botan::RSA_PrivateKey* rsa = NULL; try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); rsa = new Botan::RSA_PrivateKey(*rng->getRNG(), params->getBitLength(), e); } catch (std::exception& ex) { ERROR_MSG("RSA key generation failed: %s", ex.what()); delete kp; return false; } ((BotanRSAPublicKey*) kp->getPublicKey())->setFromBotan(rsa); ((BotanRSAPrivateKey*) kp->getPrivateKey())->setFromBotan(rsa); *ppKeyPair = kp; // Release the key delete rsa; return true; } unsigned long BotanRSA::getMinKeySize() { return 1024; } unsigned long BotanRSA::getMaxKeySize() { return 4096; } bool BotanRSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); BotanRSAKeyPair* kp = new BotanRSAKeyPair(); bool rv = true; if (!((RSAPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((RSAPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool BotanRSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanRSAPublicKey* pub = new BotanRSAPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool BotanRSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanRSAPrivateKey* priv = new BotanRSAPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* BotanRSA::newPublicKey() { return (PublicKey*) new BotanRSAPublicKey(); } PrivateKey* BotanRSA::newPrivateKey() { return (PrivateKey*) new BotanRSAPrivateKey(); } AsymmetricParameters* BotanRSA::newParameters() { return (AsymmetricParameters*) new RSAParameters(); } bool BotanRSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } RSAParameters* params = new RSAParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } softhsm-2.0.0/src/lib/crypto/MacAlgorithm.h0000664000175000017500000000523512533040716015522 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** MacAlgorithm.h Base class for MAC algorithm classes *****************************************************************************/ #ifndef _SOFTHSM_V2_MACALGORITHM_H #define _SOFTHSM_V2_MACALGORITHM_H #include #include "config.h" #include "SymmetricKey.h" #include "RNG.h" struct MacAlgo { enum Type { Unknown, HMAC_MD5, HMAC_SHA1, HMAC_SHA224, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512, HMAC_GOST }; }; class MacAlgorithm { public: // Base constructors MacAlgorithm(); // Destructor virtual ~MacAlgorithm() { } // Signing functions virtual bool signInit(const SymmetricKey* key); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(const SymmetricKey* key); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(ByteString& signature); // Key virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual void recycleKey(SymmetricKey* toRecycle); // Return the MAC size virtual size_t getMacSize() const = 0; protected: // The current key const SymmetricKey* currentKey; private: // The current operation enum { NONE, SIGN, VERIFY } currentOperation; }; #endif // !_SOFTHSM_V2_MACALGORITHM_H softhsm-2.0.0/src/lib/crypto/OSSLDES.h0000664000175000017500000000442312533040716014265 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDES.h OpenSSL AES implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDES_H #define _SOFTHSM_V2_OSSLDES_H #include #include #include "config.h" #include "OSSLEVPSymmetricAlgorithm.h" class OSSLDES : public OSSLEVPSymmetricAlgorithm { public: // Destructor virtual ~OSSLDES() { } // Wrap/Unwrap keys virtual bool wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); virtual bool unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); // Generate key virtual bool generateKey(SymmetricKey& key, RNG* rng = NULL); // Return the block size virtual size_t getBlockSize() const; protected: // Return the right EVP cipher for the operation virtual const EVP_CIPHER* getCipher() const; }; #endif // !_SOFTHSM_V2_OSSLDES_H softhsm-2.0.0/src/lib/crypto/OSSLDSA.h0000664000175000017500000000753212533040716014265 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSA.h OpenSSL DSA asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDSA_H #define _SOFTHSM_V2_OSSLDSA_H #include "config.h" #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include class OSSLDSA : public AsymmetricAlgorithm { public: // Constructor OSSLDSA(); // Destructor virtual ~OSSLDSA(); // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool generateParameters(AsymmetricParameters** ppParams, void* parameters = NULL, RNG* rng = NULL); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: HashAlgorithm* pCurrentHash; }; #endif // !_SOFTHSM_V2_OSSLDSA_H softhsm-2.0.0/src/lib/crypto/RSAPrivateKey.cpp0000664000175000017500000001033012533040716016127 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSAPrivateKey.cpp RSA private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "RSAPrivateKey.h" #include // Set the type /*static*/ const char* RSAPrivateKey::type = "Abstract RSA private key"; // Check if the key is of the given type bool RSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long RSAPrivateKey::getBitLength() const { return getN().bits(); } // Get the output length unsigned long RSAPrivateKey::getOutputLength() const { // Also handle odd number of bits (bits % 8 != 0) return (getBitLength() + 7) / 8; } // Setters for the RSA private key components void RSAPrivateKey::setP(const ByteString& inP) { p = inP; } void RSAPrivateKey::setQ(const ByteString& inQ) { q = inQ; } void RSAPrivateKey::setPQ(const ByteString& inPQ) { pq = inPQ; } void RSAPrivateKey::setDP1(const ByteString& inDP1) { dp1 = inDP1; } void RSAPrivateKey::setDQ1(const ByteString& inDQ1) { dq1 = inDQ1; } void RSAPrivateKey::setD(const ByteString& inD) { d = inD; } // Setters for the RSA public key components void RSAPrivateKey::setN(const ByteString& inN) { n = inN; } void RSAPrivateKey::setE(const ByteString& inE) { e = inE; } // Getters for the RSA private key components const ByteString& RSAPrivateKey::getP() const { return p; } const ByteString& RSAPrivateKey::getQ() const { return q; } const ByteString& RSAPrivateKey::getPQ() const { return pq; } const ByteString& RSAPrivateKey::getDP1() const { return dp1; } const ByteString& RSAPrivateKey::getDQ1() const { return dq1; } const ByteString& RSAPrivateKey::getD() const { return d; } // Getters for the RSA public key components const ByteString& RSAPrivateKey::getN() const { return n; } const ByteString& RSAPrivateKey::getE() const { return e; } // Serialisation ByteString RSAPrivateKey::serialise() const { return p.serialise() + q.serialise() + pq.serialise() + dp1.serialise() + dq1.serialise() + d.serialise() + n.serialise() + e.serialise(); } bool RSAPrivateKey::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); ByteString dPQ = ByteString::chainDeserialise(serialised); ByteString dDP1 = ByteString::chainDeserialise(serialised); ByteString dDQ1 = ByteString::chainDeserialise(serialised); ByteString dD = ByteString::chainDeserialise(serialised); ByteString dN = ByteString::chainDeserialise(serialised); ByteString dE = ByteString::chainDeserialise(serialised); if ((dD.size() == 0) || (dN.size() == 0) || (dE.size() == 0)) { return false; } setP(dP); setQ(dQ); setPQ(dPQ); setDP1(dDP1); setDQ1(dDQ1); setD(dD); setN(dN); setE(dE); return true; } softhsm-2.0.0/src/lib/crypto/DHParameters.cpp0000664000175000017500000000562112533040716016024 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHParameters.cpp Diffie-Hellman parameters (only used for key generation) *****************************************************************************/ #include "config.h" #include "log.h" #include "DHParameters.h" #include // The type /*static*/ const char* DHParameters::type = "Generic DH parameters"; // Set the public prime p void DHParameters::setP(const ByteString& inP) { p = inP; } // Set the generator g void DHParameters::setG(const ByteString& inG) { g = inG; } // Set the optional bit length void DHParameters::setXBitLength(const size_t inBitLen) { bitLen = inBitLen; } // Get the public prime p const ByteString& DHParameters::getP() const { return p; } // Get the generator g const ByteString& DHParameters::getG() const { return g; } // Get the optional bit length size_t DHParameters::getXBitLength() const { return bitLen; } // Are the parameters of the given type? bool DHParameters::areOfType(const char* inType) { return (strcmp(type, inType) == 0); } // Serialisation ByteString DHParameters::serialise() const { ByteString len(bitLen); return p.serialise() + g.serialise() + len.serialise(); } bool DHParameters::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dG = ByteString::chainDeserialise(serialised); ByteString dLen = ByteString::chainDeserialise(serialised); if ((dP.size() == 0) || (dG.size() == 0) || (dLen.size() == 0)) { return false; } setP(dP); setG(dG); setXBitLength(dLen.long_val()); return true; } softhsm-2.0.0/src/lib/crypto/BotanSHA1.cpp0000664000175000017500000000333112533040716015161 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA1.cpp Botan SHA1 implementation *****************************************************************************/ #include "config.h" #include "BotanSHA1.h" #include int BotanSHA1::getHashSize() { return 20; } Botan::HashFunction* BotanSHA1::getHash() const { return new Botan::SHA_160(); } softhsm-2.0.0/src/lib/crypto/OSSLGOSTPrivateKey.cpp0000664000175000017500000001151112533040736016763 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTPrivateKey.cpp OpenSSL GOST R 34.10-2001 private key class *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "OSSLGOSTPrivateKey.h" #include "OSSLUtil.h" #include #include // DER of a private key const unsigned char dummyKey[] = { 0x30, 0x45, 0x02, 0x01, 0x00, 0x30, 0x1c, 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x13, 0x30, 0x12, 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x23, 0x01, 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x1e, 0x01, 0x04, 0x22, 0x02, 0x20, 0x1b, 0x3f, 0x94, 0xf7, 0x1a, 0x5f, 0x2f, 0xe7, 0xe5, 0x74, 0x0b, 0x8c, 0xd4, 0xb7, 0x18, 0xdd, 0x65, 0x68, 0x26, 0xd1, 0x54, 0xfb, 0x77, 0xba, 0x63, 0x72, 0xd9, 0xf0, 0x63, 0x87, 0xe0, 0xd6 }; // Constructors OSSLGOSTPrivateKey::OSSLGOSTPrivateKey() { pkey = EVP_PKEY_new(); } OSSLGOSTPrivateKey::OSSLGOSTPrivateKey(const EVP_PKEY* inPKEY) { OSSLGOSTPrivateKey(); setFromOSSL(inPKEY); } // Destructor OSSLGOSTPrivateKey::~OSSLGOSTPrivateKey() { EVP_PKEY_free(pkey); } // The type /*static*/ const char* OSSLGOSTPrivateKey::type = "OpenSSL GOST Private Key"; // Get the output length unsigned long OSSLGOSTPrivateKey::getOutputLength() const { return 64; } // Set from OpenSSL representation void OSSLGOSTPrivateKey::setFromOSSL(const EVP_PKEY* pkey) { const EC_KEY* eckey = (const EC_KEY*) EVP_PKEY_get0((EVP_PKEY*) pkey); const BIGNUM* priv = EC_KEY_get0_private_key(eckey); setD(OSSL::bn2ByteString(priv)); ByteString inEC; int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(eckey)); inEC.resize(i2d_ASN1_OBJECT(OBJ_nid2obj(nid), NULL)); unsigned char *p = &inEC[0]; i2d_ASN1_OBJECT(OBJ_nid2obj(nid), &p); setEC(inEC); } // Check if the key is of the given type bool OSSLGOSTPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the GOST private key components void OSSLGOSTPrivateKey::setD(const ByteString& inD) { GOSTPrivateKey::setD(inD); EC_KEY* inEC = (EC_KEY*) EVP_PKEY_get0((EVP_PKEY*) pkey); if (inEC == NULL) { const unsigned char* p = dummyKey; if (d2i_PrivateKey(NID_id_GostR3410_2001, &pkey, &p, (long) sizeof(dummyKey)) == NULL) { ERROR_MSG("d2i_PrivateKey failed"); return; } inEC = (EC_KEY*) EVP_PKEY_get0((EVP_PKEY*) pkey); } const BIGNUM* priv = OSSL::byteString2bn(inD); if (EC_KEY_set_private_key(inEC, priv) <= 0) { ERROR_MSG("EC_KEY_set_private_key failed"); return; } BN_clear_free((BIGNUM*)priv); #ifdef notyet if (gost2001_compute_public(inEC) <= 0) ERROR_MSG("gost2001_compute_public failed"); #endif } // Setters for the GOST public key components void OSSLGOSTPrivateKey::setEC(const ByteString& inEC) { GOSTPrivateKey::setEC(inEC); } // Retrieve the OpenSSL representation of the key EVP_PKEY* OSSLGOSTPrivateKey::getOSSLKey() { return pkey; } // Serialisation ByteString OSSLGOSTPrivateKey::serialise() const { return ec.serialise() + d.serialise(); } bool OSSLGOSTPrivateKey::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); ByteString dD = ByteString::chainDeserialise(serialised); if ((dEC.size() == 0) || (dD.size() == 0)) { return false; } setEC(dEC); setD(dD); return true; } // Encode into PKCS#8 DER ByteString OSSLGOSTPrivateKey::PKCS8Encode() { ByteString der; // TODO return der; } // Decode from PKCS#8 BER bool OSSLGOSTPrivateKey::PKCS8Decode(const ByteString& /*ber*/) { return false; } #endif softhsm-2.0.0/src/lib/crypto/OSSLEVPHashAlgorithm.h0000664000175000017500000000432112533040716016754 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLEVPHashAlgorithm.h Base class for OpenSSL hash algorithm classes *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLEVPHASHALGORITHM_H #define _SOFTHSM_V2_OSSLEVPHASHALGORITHM_H #include "config.h" #include "HashAlgorithm.h" #include class OSSLEVPHashAlgorithm : public HashAlgorithm { public: // Base constructors OSSLEVPHashAlgorithm() : HashAlgorithm() { EVP_MD_CTX_init(&curCTX); } // Destructor ~OSSLEVPHashAlgorithm(); // Hashing functions virtual bool hashInit(); virtual bool hashUpdate(const ByteString& data); virtual bool hashFinal(ByteString& hashedData); virtual int getHashSize() = 0; protected: virtual const EVP_MD* getEVPHash() const = 0; private: // Current hashing context EVP_MD_CTX curCTX; }; #endif // !_SOFTHSM_V2_OSSLEVPHASHALGORITHM_H softhsm-2.0.0/src/lib/crypto/OSSLGOSTPrivateKey.h0000664000175000017500000000537412533040716016440 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTPrivateKey.h OpenSSL GOST R 34.10-2001 private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLGOSTPRIVATEKEY_H #define _SOFTHSM_V2_OSSLGOSTPRIVATEKEY_H #include "config.h" #include "GOSTPrivateKey.h" #include class OSSLGOSTPrivateKey : public GOSTPrivateKey { public: // Constructors OSSLGOSTPrivateKey(); OSSLGOSTPrivateKey(const EVP_PKEY* inPKEY); // Destructor virtual ~OSSLGOSTPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the output length virtual unsigned long getOutputLength() const; // Setters for the GOST private key components virtual void setD(const ByteString& inD); // Setters for the GOST public key components virtual void setEC(const ByteString& inEC); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from OpenSSL representation virtual void setFromOSSL(const EVP_PKEY* pkey); // Retrieve the OpenSSL representation of the key EVP_PKEY* getOSSLKey(); private: // The internal OpenSSL representation EVP_PKEY* pkey; }; #endif // !_SOFTHSM_V2_OSSLGOSTPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/BotanHashAlgorithm.cpp0000664000175000017500000000560512533040716017225 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanHashAlgorithm.cpp Base class for Botan hash algorithm classes *****************************************************************************/ #include "config.h" #include "BotanHashAlgorithm.h" #include // Base constructor BotanHashAlgorithm::BotanHashAlgorithm() { hash = NULL; } // Destructor BotanHashAlgorithm::~BotanHashAlgorithm() { delete hash; } // Hashing functions bool BotanHashAlgorithm::hashInit() { if (!HashAlgorithm::hashInit()) { return false; } // Initialize digesting try { if (hash == NULL) { hash = getHash(); } else { hash->clear(); } } catch (...) { ERROR_MSG("Failed to initialize the digesting token"); ByteString dummy; HashAlgorithm::hashFinal(dummy); return false; } return true; } bool BotanHashAlgorithm::hashUpdate(const ByteString& data) { if (!HashAlgorithm::hashUpdate(data)) { return false; } // Continue digesting try { if (data.size() != 0) { hash->update(data.const_byte_str(), data.size()); } } catch (...) { ERROR_MSG("Failed to buffer data"); ByteString dummy; HashAlgorithm::hashFinal(dummy); return false; } return true; } bool BotanHashAlgorithm::hashFinal(ByteString& hashedData) { if (!HashAlgorithm::hashFinal(hashedData)) { return false; } // Resize hashedData.resize(hash->output_length()); // Read the digest try { hash->final(&hashedData[0]); } catch (...) { ERROR_MSG("Failed to digest the data"); return false; } return true; } softhsm-2.0.0/src/lib/crypto/OSSLSHA1.cpp0000664000175000017500000000324512533040716014702 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA1.h OpenSSL SHA1 implementation *****************************************************************************/ #include "config.h" #include "OSSLSHA1.h" #include int OSSLSHA1::getHashSize() { return 20; } const EVP_MD* OSSLSHA1::getEVPHash() const { return EVP_sha1(); } softhsm-2.0.0/src/lib/crypto/BotanCryptoFactory.h0000664000175000017500000000644212533040716016750 00000000000000/* * Copyright (c) 2010 SURFnet bv * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanCryptoFactory.h This is a Botan based cryptographic algorithm factory *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANCRYPTOFACTORY_H #define _SOFTHSM_V2_BOTANCRYPTOFACTORY_H #ifdef HAVE_PTHREAD_H #include #endif #include "config.h" #include "CryptoFactory.h" #include "SymmetricAlgorithm.h" #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include "MacAlgorithm.h" #include "RNG.h" #include "MutexFactory.h" #include #include #include class BotanCryptoFactory : public CryptoFactory { public: // Return the one-and-only instance static BotanCryptoFactory* i(); // This will destroy the one-and-only instance. static void reset(); // Create a concrete instance of a symmetric algorithm SymmetricAlgorithm* getSymmetricAlgorithm(SymAlgo::Type algorithm); // Create a concrete instance of an asymmetric algorithm AsymmetricAlgorithm* getAsymmetricAlgorithm(AsymAlgo::Type algorithm); // Create a concrete instance of a hash algorithm HashAlgorithm* getHashAlgorithm(HashAlgo::Type algorithm); // Create a concrete instance of a MAC algorithm MacAlgorithm* getMacAlgorithm(MacAlgo::Type algorithm); // Get the global RNG (may be an unique RNG per thread) RNG* getRNG(RNGImpl::Type name = RNGImpl::Default); // Destructor ~BotanCryptoFactory(); private: // Constructor BotanCryptoFactory(); // The one-and-only instance #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif // Thread specific RNG #ifdef HAVE_PTHREAD_H std::map rngs; #elif _WIN32 std::map rngs; #endif Mutex* rngsMutex; #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) bool wasInitialized; #endif }; #endif // !_SOFTHSM_V2_BOTANCRYPTOFACTORY_H softhsm-2.0.0/src/lib/crypto/OSSLDES.cpp0000664000175000017500000001004412533040716014614 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDES.cpp OpenSSL (3)DES implementation *****************************************************************************/ #include "config.h" #include "OSSLDES.h" #include #include "odd.h" bool OSSLDES::wrapKey(const SymmetricKey* /*key*/, const SymWrap::Type /*mode*/, const ByteString& /*in*/, ByteString& /*out*/) { ERROR_MSG("DES does not support key wrapping"); return false; } bool OSSLDES::unwrapKey(const SymmetricKey* /*key*/, const SymWrap::Type /*mode*/, const ByteString& /*in*/, ByteString& /*out*/) { ERROR_MSG("DES does not support key unwrapping"); return false; } const EVP_CIPHER* OSSLDES::getCipher() const { if (currentKey == NULL) return NULL; // Check currentKey bit length; 3DES only supports 56-bit, 112-bit or 168-bit keys if ( #ifndef WITH_FIPS (currentKey->getBitLen() != 56) && #endif (currentKey->getBitLen() != 112) && (currentKey->getBitLen() != 168)) { ERROR_MSG("Invalid DES currentKey length (%d bits)", currentKey->getBitLen()); return NULL; } // People shouldn't really be using 56-bit DES keys, generate a warning if (currentKey->getBitLen() == 56) { DEBUG_MSG("CAUTION: use of 56-bit DES keys is not recommended!"); } // Determine the cipher mode if (currentCipherMode == SymMode::CBC) { switch(currentKey->getBitLen()) { case 56: return EVP_des_cbc(); case 112: return EVP_des_ede_cbc(); case 168: return EVP_des_ede3_cbc(); }; } else if (currentCipherMode == SymMode::ECB) { switch(currentKey->getBitLen()) { case 56: return EVP_des_ecb(); case 112: return EVP_des_ede_ecb(); case 168: return EVP_des_ede3_ecb(); }; } else if (currentCipherMode == SymMode::OFB) { switch(currentKey->getBitLen()) { case 56: return EVP_des_ofb(); case 112: return EVP_des_ede_ofb(); case 168: return EVP_des_ede3_ofb(); }; } else if (currentCipherMode == SymMode::CFB) { switch(currentKey->getBitLen()) { case 56: return EVP_des_cfb(); case 112: return EVP_des_ede_cfb(); case 168: return EVP_des_ede3_cfb(); }; } ERROR_MSG("Invalid DES cipher mode %i", currentCipherMode); return NULL; } bool OSSLDES::generateKey(SymmetricKey& key, RNG* rng /* = NULL */) { if (rng == NULL) { return false; } if (key.getBitLen() == 0) { return false; } ByteString keyBits; // don't count parity bit if (!rng->generateRandom(keyBits, key.getBitLen()/7)) { return false; } // fix the odd parity size_t i; for (i = 0; i < keyBits.size(); i++) { keyBits[i] = odd_parity[keyBits[i]]; } return key.setKeyBits(keyBits); } size_t OSSLDES::getBlockSize() const { // The block size is 64 bits return 64 >> 3; } softhsm-2.0.0/src/lib/crypto/BotanECDSAPublicKey.h0000664000175000017500000000516112533040716016564 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSAPublicKey.h Botan ECDSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDSAPUBLICKEY_H #define _SOFTHSM_V2_BOTANECDSAPUBLICKEY_H #include "config.h" #include "ECPublicKey.h" #include class BotanECDSAPublicKey : public ECPublicKey { public: // Constructors BotanECDSAPublicKey(); BotanECDSAPublicKey(const Botan::ECDSA_PublicKey* inECKEY); // Destructor virtual ~BotanECDSAPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the ECDSA public key components virtual void setEC(const ByteString& inEC); virtual void setQ(const ByteString& inQ); // Set from Botan representation virtual void setFromBotan(const Botan::ECDSA_PublicKey* inECKEY); // Retrieve the Botan representation of the key Botan::ECDSA_PublicKey* getBotanKey(); private: // The internal Botan representation Botan::ECDSA_PublicKey* eckey; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANECDSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLECPublicKey.cpp0000664000175000017500000000667512533040716016317 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECPublicKey.cpp OpenSSL Elliptic Curve public key class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "OSSLECPublicKey.h" #include "OSSLUtil.h" #include #include // Constructors OSSLECPublicKey::OSSLECPublicKey() { eckey = EC_KEY_new(); } OSSLECPublicKey::OSSLECPublicKey(const EC_KEY* inECKEY) { eckey = EC_KEY_new(); setFromOSSL(inECKEY); } // Destructor OSSLECPublicKey::~OSSLECPublicKey() { EC_KEY_free(eckey); } // The type /*static*/ const char* OSSLECPublicKey::type = "OpenSSL EC Public Key"; // Get the base point order length unsigned long OSSLECPublicKey::getOrderLength() const { const EC_GROUP* grp = EC_KEY_get0_group(eckey); if (grp != NULL) { BIGNUM* order = BN_new(); if (order == NULL) return 0; if (!EC_GROUP_get_order(grp, order, NULL)) { BN_clear_free(order); return 0; } unsigned long len = BN_num_bytes(order); BN_clear_free(order); return len; } return 0; } // Set from OpenSSL representation void OSSLECPublicKey::setFromOSSL(const EC_KEY* inECKEY) { const EC_GROUP* grp = EC_KEY_get0_group(inECKEY); if (grp != NULL) { ByteString inEC = OSSL::grp2ByteString(grp); setEC(inEC); } const EC_POINT* pub = EC_KEY_get0_public_key(inECKEY); if (pub != NULL && grp != NULL) { ByteString inQ = OSSL::pt2ByteString(pub, grp); setQ(inQ); } } // Check if the key is of the given type bool OSSLECPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the EC public key components void OSSLECPublicKey::setEC(const ByteString& inEC) { ECPublicKey::setEC(inEC); EC_GROUP* grp = OSSL::byteString2grp(inEC); EC_KEY_set_group(eckey, grp); EC_GROUP_free(grp); } void OSSLECPublicKey::setQ(const ByteString& inQ) { ECPublicKey::setQ(inQ); EC_POINT* pub = OSSL::byteString2pt(inQ, EC_KEY_get0_group(eckey)); EC_KEY_set_public_key(eckey, pub); EC_POINT_free(pub); } // Retrieve the OpenSSL representation of the key EC_KEY* OSSLECPublicKey::getOSSLKey() { return eckey; } #endif softhsm-2.0.0/src/lib/crypto/OSSLDHPublicKey.cpp0000664000175000017500000000642612533040716016315 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDHPublicKey.cpp OpenSSL Diffie-Hellman public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDHPublicKey.h" #include "OSSLUtil.h" #include #include // Constructors OSSLDHPublicKey::OSSLDHPublicKey() { dh = DH_new(); // Use the OpenSSL implementation and not any engine DH_set_method(dh, DH_get_default_method()); } OSSLDHPublicKey::OSSLDHPublicKey(const DH* inDH) { dh = DH_new(); // Use the OpenSSL implementation and not any engine DH_set_method(dh, DH_OpenSSL()); setFromOSSL(inDH); } // Destructor OSSLDHPublicKey::~OSSLDHPublicKey() { DH_free(dh); } // The type /*static*/ const char* OSSLDHPublicKey::type = "OpenSSL DH Public Key"; // Set from OpenSSL representation void OSSLDHPublicKey::setFromOSSL(const DH* inDH) { if (inDH->p) { ByteString inP = OSSL::bn2ByteString(inDH->p); setP(inP); } if (inDH->g) { ByteString inG = OSSL::bn2ByteString(inDH->g); setG(inG); } if (inDH->pub_key) { ByteString inY = OSSL::bn2ByteString(inDH->pub_key); setY(inY); } } // Check if the key is of the given type bool OSSLDHPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DH public key components void OSSLDHPublicKey::setP(const ByteString& inP) { DHPublicKey::setP(inP); if (dh->p) { BN_clear_free(dh->p); dh->p = NULL; } dh->p = OSSL::byteString2bn(inP); } void OSSLDHPublicKey::setG(const ByteString& inG) { DHPublicKey::setG(inG); if (dh->g) { BN_clear_free(dh->g); dh->g = NULL; } dh->g = OSSL::byteString2bn(inG); } void OSSLDHPublicKey::setY(const ByteString& inY) { DHPublicKey::setY(inY); if (dh->pub_key) { BN_clear_free(dh->pub_key); dh->pub_key = NULL; } dh->pub_key = OSSL::byteString2bn(inY); } // Retrieve the OpenSSL representation of the key DH* OSSLDHPublicKey::getOSSLKey() { return dh; } softhsm-2.0.0/src/lib/crypto/BotanDSAPrivateKey.h0000664000175000017500000000542712533040716016555 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSAPrivateKey.h Botan DSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDSAPRIVATEKEY_H #define _SOFTHSM_V2_BOTANDSAPRIVATEKEY_H #include "config.h" #include "DSAPrivateKey.h" #include class BotanDSAPrivateKey : public DSAPrivateKey { public: // Constructors BotanDSAPrivateKey(); BotanDSAPrivateKey(const Botan::DSA_PrivateKey* inDSA); // Destructor virtual ~BotanDSAPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DSA private key components virtual void setX(const ByteString& inX); // Setters for the DSA domain parameters virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setG(const ByteString& inG); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from Botan representation virtual void setFromBotan(const Botan::DSA_PrivateKey* inDSA); // Retrieve the Botan representation of the key Botan::DSA_PrivateKey* getBotanKey(); private: // The internal Botan representation Botan::DSA_PrivateKey* dsa; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANDSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/ECPublicKey.h0000664000175000017500000000471712533040716015256 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECPublicKey.h Elliptic Curve public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_ECPUBLICKEY_H #define _SOFTHSM_V2_ECPUBLICKEY_H #include "config.h" #include "PublicKey.h" class ECPublicKey : public PublicKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Get the base point order length virtual unsigned long getOrderLength() const = 0; // Setters for the EC public key components virtual void setEC(const ByteString& inEc); virtual void setQ(const ByteString& inQ); // Getters for the EC public key components virtual const ByteString& getEC() const; virtual const ByteString& getQ() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Public components ByteString ec,q; }; #endif // !_SOFTHSM_V2_ECPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLGOST.h0000664000175000017500000000741412533040716014431 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOST.h OpenSSL GOST R 34.10-2001 asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLGOST_H #define _SOFTHSM_V2_OSSLGOST_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class OSSLGOST : public AsymmetricAlgorithm { public: // Constructor OSSLGOST() : AsymmetricAlgorithm() { EVP_MD_CTX_init(&curCTX); } // Destructor ~OSSLGOST(); // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: EVP_MD_CTX curCTX; }; #endif // !_SOFTHSM_V2_OSSLGOST_H softhsm-2.0.0/src/lib/crypto/BotanDSAPublicKey.cpp0000664000175000017500000000742212533040716016711 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSAPublicKey.cpp Botan DSA public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDSAPublicKey.h" #include "BotanUtil.h" #include // Constructors BotanDSAPublicKey::BotanDSAPublicKey() { dsa = NULL; } BotanDSAPublicKey::BotanDSAPublicKey(const Botan::DSA_PublicKey* inDSA) { dsa = NULL; setFromBotan(inDSA); } // Destructor BotanDSAPublicKey::~BotanDSAPublicKey() { delete dsa; } // The type /*static*/ const char* BotanDSAPublicKey::type = "Botan DSA Public Key"; // Set from Botan representation void BotanDSAPublicKey::setFromBotan(const Botan::DSA_PublicKey* inDSA) { ByteString inP = BotanUtil::bigInt2ByteString(inDSA->group_p()); setP(inP); ByteString inQ = BotanUtil::bigInt2ByteString(inDSA->group_q()); setQ(inQ); ByteString inG = BotanUtil::bigInt2ByteString(inDSA->group_g()); setG(inG); ByteString inY = BotanUtil::bigInt2ByteString(inDSA->get_y()); setY(inY); } // Check if the key is of the given type bool BotanDSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DSA public key components void BotanDSAPublicKey::setP(const ByteString& inP) { DSAPublicKey::setP(inP); if (dsa) { delete dsa; dsa = NULL; } } void BotanDSAPublicKey::setQ(const ByteString& inQ) { DSAPublicKey::setQ(inQ); if (dsa) { delete dsa; dsa = NULL; } } void BotanDSAPublicKey::setG(const ByteString& inG) { DSAPublicKey::setG(inG); if (dsa) { delete dsa; dsa = NULL; } } void BotanDSAPublicKey::setY(const ByteString& inY) { DSAPublicKey::setY(inY); if (dsa) { delete dsa; dsa = NULL; } } // Retrieve the Botan representation of the key Botan::DSA_PublicKey* BotanDSAPublicKey::getBotanKey() { if (!dsa) { createBotanKey(); } return dsa; } // Create the Botan representation of the key void BotanDSAPublicKey::createBotanKey() { // We actually do not need to check q, since it can be set zero if (p.size() != 0 && g.size() != 0 && y.size() != 0) { if (dsa) { delete dsa; dsa = NULL; } try { dsa = new Botan::DSA_PublicKey(Botan::DL_Group(BotanUtil::byteString2bigInt(p), BotanUtil::byteString2bigInt(q), BotanUtil::byteString2bigInt(g)), BotanUtil::byteString2bigInt(y)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } softhsm-2.0.0/src/lib/crypto/Makefile.am0000664000175000017500000000555612533040716015044 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../common \ -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/.. \ @CRYPTO_INCLUDES@ noinst_LTLIBRARIES = libsofthsm_crypto.la libsofthsm_crypto_la_SOURCES = AsymmetricAlgorithm.cpp \ AsymmetricKeyPair.cpp \ CryptoFactory.cpp \ DESKey.cpp \ DHParameters.cpp \ DHPublicKey.cpp \ DHPrivateKey.cpp \ DSAParameters.cpp \ DSAPublicKey.cpp \ DSAPrivateKey.cpp \ ECParameters.cpp \ ECPublicKey.cpp \ ECPrivateKey.cpp \ GOSTPublicKey.cpp \ GOSTPrivateKey.cpp \ HashAlgorithm.cpp \ MacAlgorithm.cpp \ RSAParameters.cpp \ RSAPrivateKey.cpp \ RSAPublicKey.cpp \ SymmetricAlgorithm.cpp \ SymmetricKey.cpp libsofthsm_crypto_la_LIBADD = @CRYPTO_LIBS@ SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h $(srcdir)/*.cpp # Compile with support of OpenSSL if WITH_OPENSSL libsofthsm_crypto_la_SOURCES += OSSLAES.cpp \ OSSLCryptoFactory.cpp \ OSSLDES.cpp \ OSSLDH.cpp \ OSSLDHKeyPair.cpp \ OSSLDHPrivateKey.cpp \ OSSLDHPublicKey.cpp \ OSSLDSA.cpp \ OSSLDSAKeyPair.cpp \ OSSLDSAPrivateKey.cpp \ OSSLDSAPublicKey.cpp \ OSSLECDH.cpp \ OSSLECDSA.cpp \ OSSLECKeyPair.cpp \ OSSLECPrivateKey.cpp \ OSSLECPublicKey.cpp \ OSSLEVPHashAlgorithm.cpp \ OSSLEVPMacAlgorithm.cpp \ OSSLEVPSymmetricAlgorithm.cpp \ OSSLGOST.cpp \ OSSLGOSTKeyPair.cpp \ OSSLGOSTPrivateKey.cpp \ OSSLGOSTPublicKey.cpp \ OSSLGOSTR3411.cpp \ OSSLHMAC.cpp \ OSSLMD5.cpp \ OSSLRNG.cpp \ OSSLRSA.cpp \ OSSLRSAKeyPair.cpp \ OSSLRSAPrivateKey.cpp \ OSSLRSAPublicKey.cpp \ OSSLSHA1.cpp \ OSSLSHA224.cpp \ OSSLSHA256.cpp \ OSSLSHA384.cpp \ OSSLSHA512.cpp \ OSSLUtil.cpp endif # Compile with support of Botan if WITH_BOTAN libsofthsm_crypto_la_SOURCES += BotanAES.cpp \ BotanCryptoFactory.cpp \ BotanDES.cpp \ BotanDH.cpp \ BotanDHKeyPair.cpp \ BotanDHPrivateKey.cpp \ BotanDHPublicKey.cpp \ BotanDSA.cpp \ BotanDSAKeyPair.cpp \ BotanDSAPrivateKey.cpp \ BotanDSAPublicKey.cpp \ BotanECDH.cpp \ BotanECDHKeyPair.cpp \ BotanECDHPrivateKey.cpp \ BotanECDHPublicKey.cpp \ BotanECDSA.cpp \ BotanECDSAKeyPair.cpp \ BotanECDSAPrivateKey.cpp \ BotanECDSAPublicKey.cpp \ BotanGOST.cpp \ BotanGOSTKeyPair.cpp \ BotanGOSTPrivateKey.cpp \ BotanGOSTPublicKey.cpp \ BotanGOSTR3411.cpp \ BotanHashAlgorithm.cpp \ BotanHMAC.cpp \ BotanMacAlgorithm.cpp \ BotanMD5.cpp \ BotanRNG.cpp \ BotanRSA.cpp \ BotanRSAKeyPair.cpp \ BotanRSAPrivateKey.cpp \ BotanRSAPublicKey.cpp \ BotanSHA1.cpp \ BotanSHA224.cpp \ BotanSHA256.cpp \ BotanSHA384.cpp \ BotanSHA512.cpp \ BotanSymmetricAlgorithm.cpp \ BotanUtil.cpp endif softhsm-2.0.0/src/lib/crypto/BotanDH.h0000664000175000017500000000704512533040716014433 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDH.h Botan Diffie-Hellman asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDH_H #define _SOFTHSM_V2_BOTANDH_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class BotanDH : public AsymmetricAlgorithm { public: // Destructor virtual ~BotanDH() { } // Signing functions virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool generateParameters(AsymmetricParameters** ppParams, void* parameters = NULL, RNG* rng = NULL); virtual bool deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: }; #endif // !_SOFTHSM_V2_BOTANDH_H softhsm-2.0.0/src/lib/crypto/OSSLEVPMacAlgorithm.cpp0000664000175000017500000001113112533040716017121 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ // TODO: Store context in securely allocated memory /***************************************************************************** OSSLEVPMacAlgorithm.cpp OpenSSL MAC algorithm implementation *****************************************************************************/ #include "config.h" #include "OSSLEVPMacAlgorithm.h" // Destructor OSSLEVPMacAlgorithm::~OSSLEVPMacAlgorithm() { HMAC_CTX_cleanup(&curCTX); } // Signing functions bool OSSLEVPMacAlgorithm::signInit(const SymmetricKey* key) { // Call the superclass initialiser if (!MacAlgorithm::signInit(key)) { return false; } // Initialize the context HMAC_CTX_init(&curCTX); // Initialize EVP signing if (!HMAC_Init(&curCTX, key->getKeyBits().const_byte_str(), key->getKeyBits().size(), getEVPHash())) { ERROR_MSG("HMAC_Init failed"); HMAC_CTX_cleanup(&curCTX); ByteString dummy; MacAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLEVPMacAlgorithm::signUpdate(const ByteString& dataToSign) { if (!MacAlgorithm::signUpdate(dataToSign)) { return false; } // The GOST implementation in OpenSSL will segfault if we update with zero length. if (dataToSign.size() == 0) return true; if (!HMAC_Update(&curCTX, dataToSign.const_byte_str(), dataToSign.size())) { ERROR_MSG("HMAC_Update failed"); HMAC_CTX_cleanup(&curCTX); ByteString dummy; MacAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLEVPMacAlgorithm::signFinal(ByteString& signature) { if (!MacAlgorithm::signFinal(signature)) { return false; } signature.resize(EVP_MD_size(getEVPHash())); unsigned int outLen = signature.size(); if (!HMAC_Final(&curCTX, &signature[0], &outLen)) { ERROR_MSG("HMAC_Final failed"); HMAC_CTX_cleanup(&curCTX); return false; } signature.resize(outLen); HMAC_CTX_cleanup(&curCTX); return true; } // Verification functions bool OSSLEVPMacAlgorithm::verifyInit(const SymmetricKey* key) { // Call the superclass initialiser if (!MacAlgorithm::verifyInit(key)) { return false; } // Initialize the context HMAC_CTX_init(&curCTX); // Initialize EVP signing if (!HMAC_Init(&curCTX, key->getKeyBits().const_byte_str(), key->getKeyBits().size(), getEVPHash())) { ERROR_MSG("HMAC_Init failed"); HMAC_CTX_cleanup(&curCTX); ByteString dummy; MacAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLEVPMacAlgorithm::verifyUpdate(const ByteString& originalData) { if (!MacAlgorithm::verifyUpdate(originalData)) { return false; } // The GOST implementation in OpenSSL will segfault if we update with zero length. if (originalData.size() == 0) return true; if (!HMAC_Update(&curCTX, originalData.const_byte_str(), originalData.size())) { ERROR_MSG("HMAC_Update failed"); HMAC_CTX_cleanup(&curCTX); ByteString dummy; MacAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLEVPMacAlgorithm::verifyFinal(ByteString& signature) { if (!MacAlgorithm::verifyFinal(signature)) { return false; } ByteString macResult; unsigned int outLen = EVP_MD_size(getEVPHash()); macResult.resize(outLen); if (!HMAC_Final(&curCTX, &macResult[0], &outLen)) { ERROR_MSG("HMAC_Final failed"); HMAC_CTX_cleanup(&curCTX); return false; } HMAC_CTX_cleanup(&curCTX); return macResult == signature; } softhsm-2.0.0/src/lib/crypto/GOSTPublicKey.cpp0000664000175000017500000000451212533040716016067 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** GOSTPublicKey.cpp GOST R 34.10-2001 public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "GOSTPublicKey.h" #include // Set the type /*static*/ const char* GOSTPublicKey::type = "Abstract GOST public key"; // Check if the key is of the given type bool GOSTPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long GOSTPublicKey::getBitLength() const { return getQ().size() * 8; } // Setters for the GOST public key components void GOSTPublicKey::setQ(const ByteString& inQ) { q = inQ; } // Setters for the GOST public key components void GOSTPublicKey::setEC(const ByteString& inEC) { ec = inEC; } // Getters for the GOST public key components const ByteString& GOSTPublicKey::getQ() const { return q; } // Getters for the GOST public key components const ByteString& GOSTPublicKey::getEC() const { return ec; } softhsm-2.0.0/src/lib/crypto/ECParameters.h0000664000175000017500000000421612533040716015464 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECParameters.h Elliptic Curve parameters (only used for key generation) *****************************************************************************/ #ifndef _SOFTHSM_V2_ECPARAMETERS_H #define _SOFTHSM_V2_ECPARAMETERS_H #include "config.h" #include "ByteString.h" #include "AsymmetricParameters.h" class ECParameters : public AsymmetricParameters { public: // The type static const char* type; // Set the curve OID ec void setEC(const ByteString& inEC); // Get the curve OID ec const ByteString& getEC() const; // Are the parameters of the given type? virtual bool areOfType(const char* inType); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); private: ByteString ec; }; #endif // !_SOFTHSM_V2_ECPARAMETERS_H softhsm-2.0.0/src/lib/crypto/OSSLEVPMacAlgorithm.h0000664000175000017500000000505612533040716016577 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLEVPMacAlgorithm.h OpenSSL MAC algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLEVPMACALGORITHM_H #define _SOFTHSM_V2_OSSLEVPMACALGORITHM_H #include #include "config.h" #include "SymmetricKey.h" #include "MacAlgorithm.h" #include #include class OSSLEVPMacAlgorithm : public MacAlgorithm { public: // Constructor OSSLEVPMacAlgorithm() { HMAC_CTX_init(&curCTX); }; // Destructor ~OSSLEVPMacAlgorithm(); // Signing functions virtual bool signInit(const SymmetricKey* key); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(const SymmetricKey* key); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(ByteString& signature); // Return the MAC size virtual size_t getMacSize() const = 0; protected: // Return the right hash for the operation virtual const EVP_MD* getEVPHash() const = 0; private: // The current context HMAC_CTX curCTX; }; #endif // !_SOFTHSM_V2_OSSLEVPMACALGORITHM_H softhsm-2.0.0/src/lib/crypto/OSSLECDH.h0000664000175000017500000000662412533040716014362 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECDH.h OpenSSL ECDH asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLECDH_H #define _SOFTHSM_V2_OSSLECDH_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class OSSLECDH : public AsymmetricAlgorithm { public: // Destructor virtual ~OSSLECDH() { } // Signing functions virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: }; #endif // !_SOFTHSM_V2_OSSLECDH_H softhsm-2.0.0/src/lib/crypto/BotanRSAPublicKey.h0000664000175000017500000000471212533040716016373 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSAPublicKey.h Botan RSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANRSAPUBLICKEY_H #define _SOFTHSM_V2_BOTANRSAPUBLICKEY_H #include "config.h" #include "RSAPublicKey.h" #include class BotanRSAPublicKey : public RSAPublicKey { public: // Constructors BotanRSAPublicKey(); BotanRSAPublicKey(const Botan::RSA_PublicKey* inRSA); // Destructor virtual ~BotanRSAPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the RSA public key components virtual void setN(const ByteString& inN); virtual void setE(const ByteString& inE); // Set from Botan representation virtual void setFromBotan(const Botan::RSA_PublicKey* inRSA); // Retrieve the Botan representation of the key Botan::RSA_PublicKey* getBotanKey(); private: // The internal Botan representation Botan::RSA_PublicKey* rsa; void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANRSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanRNG.h0000664000175000017500000000412412533040716014561 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRNG.h Botan random number generator class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANRNG_H #define _SOFTHSM_V2_BOTANRNG_H #include "config.h" #include "ByteString.h" #include "RNG.h" #include "botan/rng.h" class BotanRNG : public RNG { public: // Base constructor BotanRNG(); // Destructor virtual ~BotanRNG(); // Generate random data virtual bool generateRandom(ByteString& data, const size_t len); // Seed the random pool virtual void seed(ByteString& seedData); // Get RNG Botan::RandomNumberGenerator* getRNG(); private: // The RNG Botan::RandomNumberGenerator* rng; }; #endif // !_SOFTHSM_V2_BOTANRNG_H softhsm-2.0.0/src/lib/crypto/BotanDSAKeyPair.h0000664000175000017500000000445512533040716016036 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSAKeyPair.h Botan DSA key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDSAKEYPAIR_H #define _SOFTHSM_V2_BOTANDSAKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "BotanDSAPublicKey.h" #include "BotanDSAPrivateKey.h" class BotanDSAKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(BotanDSAPublicKey& publicKey); // Set the private key void setPrivateKey(BotanDSAPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key BotanDSAPublicKey pubKey; // The private key BotanDSAPrivateKey privKey; }; #endif // !_SOFTHSM_V2_BOTANDSAKEYPAIR_H softhsm-2.0.0/src/lib/crypto/OSSLRSAKeyPair.cpp0000664000175000017500000000417012533040716016116 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSAKeyPair.cpp OpenSSL RSA key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLRSAKeyPair.h" // Set the public key void OSSLRSAKeyPair::setPublicKey(OSSLRSAPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void OSSLRSAKeyPair::setPrivateKey(OSSLRSAPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* OSSLRSAKeyPair::getPublicKey() { return &pubKey; } const PublicKey* OSSLRSAKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* OSSLRSAKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* OSSLRSAKeyPair::getConstPrivateKey() const { return &privKey; } softhsm-2.0.0/src/lib/crypto/OSSLDSAKeyPair.cpp0000664000175000017500000000417012533040716016100 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSAKeyPair.cpp OpenSSL DSA key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDSAKeyPair.h" // Set the public key void OSSLDSAKeyPair::setPublicKey(OSSLDSAPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void OSSLDSAKeyPair::setPrivateKey(OSSLDSAPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* OSSLDSAKeyPair::getPublicKey() { return &pubKey; } const PublicKey* OSSLDSAKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* OSSLDSAKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* OSSLDSAKeyPair::getConstPrivateKey() const { return &privKey; } softhsm-2.0.0/src/lib/crypto/BotanSHA1.h0000664000175000017500000000351312533040716014630 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA1.h Botan SHA1 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANSHA1_H #define _SOFTHSM_V2_BOTANSHA1_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanSHA1 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANSHA1_H softhsm-2.0.0/src/lib/crypto/PrivateKey.h0000664000175000017500000000446412533040716015241 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** PrivateKey.h Base class for private key classes *****************************************************************************/ #ifndef _SOFTHSM_V2_PRIVATEKEY_H #define _SOFTHSM_V2_PRIVATEKEY_H #include "config.h" #include "ByteString.h" #include "Serialisable.h" #include class PrivateKey : public Serialisable { public: // Base constructors PrivateKey() { } PrivateKey(const PrivateKey& in); // Destructor virtual ~PrivateKey() { } // Check if the private key is of the given type virtual bool isOfType(const char* inType) = 0; // Get the bit length virtual unsigned long getBitLength() const = 0; // Get the output length virtual unsigned long getOutputLength() const = 0; // Serialisation virtual ByteString serialise() const = 0; // Encode into PKCS#8 DER virtual ByteString PKCS8Encode() = 0; // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber) = 0; }; #endif // !_SOFTHSM_V2_PRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/PublicKey.h0000664000175000017500000000417512533040716015044 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** PublicKey.h Base class for public key classes *****************************************************************************/ #ifndef _SOFTHSM_V2_PUBLICKEY_H #define _SOFTHSM_V2_PUBLICKEY_H #include "config.h" #include "ByteString.h" #include "Serialisable.h" class PublicKey : public Serialisable { public: // Base constructors PublicKey() { } PublicKey(const PublicKey& /*in*/) { } // Destructor virtual ~PublicKey() { } // Check if it is of the given type virtual bool isOfType(const char* inType) = 0; // Get the bit length virtual unsigned long getBitLength() const = 0; // Get the output length virtual unsigned long getOutputLength() const = 0; // Serialisation virtual ByteString serialise() const = 0; }; #endif // !_SOFTHSM_V2_PUBLICKEY_H softhsm-2.0.0/src/lib/crypto/DHPublicKey.cpp0000664000175000017500000000565712533040716015621 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHPublicKey.cpp Diffie-Hellman public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "DHPublicKey.h" #include // Set the type /*static*/ const char* DHPublicKey::type = "Abstract DH public key"; // Check if the key is of the given type bool DHPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long DHPublicKey::getBitLength() const { return getP().bits(); } // Get the output length unsigned long DHPublicKey::getOutputLength() const { return getP().size(); } // Setters for the DH public key components void DHPublicKey::setP(const ByteString& inP) { p = inP; } void DHPublicKey::setG(const ByteString& inG) { g = inG; } void DHPublicKey::setY(const ByteString& inY) { y = inY; } // Getters for the DH public key components const ByteString& DHPublicKey::getP() const { return p; } const ByteString& DHPublicKey::getG() const { return g; } const ByteString& DHPublicKey::getY() const { return y; } // Serialisation ByteString DHPublicKey::serialise() const { return p.serialise() + g.serialise() + y.serialise(); } bool DHPublicKey::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dG = ByteString::chainDeserialise(serialised); ByteString dY = ByteString::chainDeserialise(serialised); if ((dP.size() == 0) || (dG.size() == 0) || (dY.size() == 0)) { return false; } setP(dP); setG(dG); setY(dY); return true; } softhsm-2.0.0/src/lib/crypto/BotanECDSA.h0000664000175000017500000000744512533040716014763 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSA.h Botan ECDSA asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDSA_H #define _SOFTHSM_V2_BOTANECDSA_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class BotanECDSA : public AsymmetricAlgorithm { public: // Constructor BotanECDSA(); // Destructor virtual ~BotanECDSA(); // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: Botan::PK_Signer* signer; Botan::PK_Verifier* verifier; }; #endif // !_SOFTHSM_V2_BOTANECDSA_H softhsm-2.0.0/src/lib/crypto/OSSLECPrivateKey.h0000664000175000017500000000522112533040716016142 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECPrivateKey.h OpenSSL Elliptic Curve private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLECPRIVATEKEY_H #define _SOFTHSM_V2_OSSLECPRIVATEKEY_H #include "config.h" #include "ECPrivateKey.h" #include #include class OSSLECPrivateKey : public ECPrivateKey { public: // Constructors OSSLECPrivateKey(); OSSLECPrivateKey(const EC_KEY* inECKEY); // Destructor virtual ~OSSLECPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the EC private key components virtual void setD(const ByteString& inD); // Setters for the EC public key components virtual void setEC(const ByteString& inEC); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from OpenSSL representation virtual void setFromOSSL(const EC_KEY* inECKEY); // Retrieve the OpenSSL representation of the key EC_KEY* getOSSLKey(); private: // The internal OpenSSL representation EC_KEY* eckey; }; #endif // !_SOFTHSM_V2_OSSLECPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/CryptoFactory.h0000664000175000017500000000727012533040716015764 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** CryptoFactory.h This class is a factory for all cryptographic algorithm implementations. It is an abstract base class for a factory that produces cryptographic library specific implementations of cryptographic algorithms. *****************************************************************************/ #ifndef _SOFTHSM_V2_CRYPTOFACTORY_H #define _SOFTHSM_V2_CRYPTOFACTORY_H #include "config.h" #include "SymmetricAlgorithm.h" #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include "MacAlgorithm.h" #include "RNG.h" class CryptoFactory { public: // Return the one-and-only instance static CryptoFactory* i(); // This will destroy the one-and-only instance. static void reset(); #ifdef WITH_FIPS // Return the FIPS 140-2 selftest status virtual bool getFipsSelfTestStatus() const = 0; #endif // Create a concrete instance of a symmetric algorithm virtual SymmetricAlgorithm* getSymmetricAlgorithm(SymAlgo::Type algorithm) = 0; // Recycle a symmetric algorithm instance -- override this function in the derived // class if you need to perform specific clean-up virtual void recycleSymmetricAlgorithm(SymmetricAlgorithm* toRecycle); // Create a concrete instance of an asymmetric algorithm virtual AsymmetricAlgorithm* getAsymmetricAlgorithm(AsymAlgo::Type algorithm) = 0; // Recycle an asymmetric algorithm instance -- override this function in the derived // class if you need to perform specific clean-up virtual void recycleAsymmetricAlgorithm(AsymmetricAlgorithm* toRecycle); // Create a concrete instance of a hash algorithm virtual HashAlgorithm* getHashAlgorithm(HashAlgo::Type algorithm) = 0; // Recycle a hash algorithm instance -- override this function in the derived // class if you need to perform specific clean-up virtual void recycleHashAlgorithm(HashAlgorithm* toRecycle); // Create a concrete instance of a MAC algorithm virtual MacAlgorithm* getMacAlgorithm(MacAlgo::Type algorithm) = 0; // Recycle a MAC algorithm instance -- override this function in the derived // class if you need to perform specific clean-up virtual void recycleMacAlgorithm(MacAlgorithm* toRecycle); // Get the global RNG (may be an unique RNG per thread) virtual RNG* getRNG(RNGImpl::Type name = RNGImpl::Default) = 0; // Destructor virtual ~CryptoFactory() { } private: }; #endif // !_SOFTHSM_V2_CRYPTOFACTORY_H softhsm-2.0.0/src/lib/crypto/SymmetricAlgorithm.h0000664000175000017500000000723112533040716016774 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SymmetricAlgorithm.h Base class for symmetric algorithm classes *****************************************************************************/ #ifndef _SOFTHSM_V2_SYMMETRICALGORITHM_H #define _SOFTHSM_V2_SYMMETRICALGORITHM_H #include #include "config.h" #include "SymmetricKey.h" #include "RNG.h" struct SymAlgo { enum Type { Unknown, AES, DES, DES3 }; }; struct SymMode { enum Type { Unknown, CBC, CFB, ECB, OFB }; }; struct SymWrap { enum Type { Unknown, AES_KEYWRAP, AES_KEYWRAP_PAD }; }; class SymmetricAlgorithm { public: // Base constructors SymmetricAlgorithm(); // Destructor virtual ~SymmetricAlgorithm() { } // Encryption functions virtual bool encryptInit(const SymmetricKey* key, const SymMode::Type mode = SymMode::CBC, const ByteString& IV = ByteString(), bool padding = true); virtual bool encryptUpdate(const ByteString& data, ByteString& encryptedData); virtual bool encryptFinal(ByteString& encryptedData); // Decryption functions virtual bool decryptInit(const SymmetricKey* key, const SymMode::Type mode = SymMode::CBC, const ByteString& IV = ByteString(), bool padding = true); virtual bool decryptUpdate(const ByteString& encryptedData, ByteString& data); virtual bool decryptFinal(ByteString& data); // Wrap/Unwrap keys virtual bool wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out) = 0; virtual bool unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out) = 0; // Key factory virtual void recycleKey(SymmetricKey* toRecycle); virtual bool generateKey(SymmetricKey& key, RNG* rng = NULL); virtual bool reconstructKey(SymmetricKey& key, const ByteString& serialisedData); // Return cipher information virtual size_t getBlockSize() const = 0; virtual SymMode::Type getCipherMode(); virtual bool getPaddingMode(); virtual unsigned long getBufferSize(); protected: // The current key const SymmetricKey* currentKey; // The current cipher mode SymMode::Type currentCipherMode; // The current padding bool currentPaddingMode; // The current operation enum { NONE, ENCRYPT, DECRYPT } currentOperation; // The current number of bytes in buffer unsigned long currentBufferSize; }; #endif // !_SOFTHSM_V2_SYMMETRICALGORITHM_H softhsm-2.0.0/src/lib/crypto/BotanDHPrivateKey.cpp0000664000175000017500000001661012533040716016770 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDHPrivateKey.cpp Botan Diffie-Hellman private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDHPrivateKey.h" #include "BotanCryptoFactory.h" #include "BotanRNG.h" #include "BotanUtil.h" #include #include #include #include #include #if BOTAN_VERSION_MINOR == 11 std::vector BotanDH_PrivateKey::public_value() const { return impl->public_value(); } #else Botan::MemoryVector BotanDH_PrivateKey::public_value() const { return impl->public_value(); } #endif // Redefine of DH_PrivateKey constructor with the correct format #if BOTAN_VERSION_MINOR == 11 BotanDH_PrivateKey::BotanDH_PrivateKey( const Botan::AlgorithmIdentifier& alg_id, const Botan::secure_vector& key_bits, Botan::RandomNumberGenerator& rng) : Botan::DL_Scheme_PrivateKey(alg_id, key_bits, Botan::DL_Group::PKCS3_DH_PARAMETERS) { impl = new Botan::DH_PrivateKey(rng, group, x); } #else BotanDH_PrivateKey::BotanDH_PrivateKey( const Botan::AlgorithmIdentifier& alg_id, const Botan::MemoryRegion& key_bits, Botan::RandomNumberGenerator& rng) : Botan::DL_Scheme_PrivateKey(alg_id, key_bits, Botan::DL_Group::PKCS3_DH_PARAMETERS) { impl = new Botan::DH_PrivateKey(rng, group, x); } #endif BotanDH_PrivateKey::BotanDH_PrivateKey(Botan::RandomNumberGenerator& rng, const Botan::DL_Group& grp, const Botan::BigInt& x_arg) { impl = new Botan::DH_PrivateKey(rng, grp, x_arg); group = grp; x = x_arg; y = impl->get_y(); } BotanDH_PrivateKey::~BotanDH_PrivateKey() { delete impl; } // Constructors BotanDHPrivateKey::BotanDHPrivateKey() { dh = NULL; } BotanDHPrivateKey::BotanDHPrivateKey(const BotanDH_PrivateKey* inDH) { dh = NULL; setFromBotan(inDH); } // Destructor BotanDHPrivateKey::~BotanDHPrivateKey() { delete dh; } // The type /*static*/ const char* BotanDHPrivateKey::type = "Botan DH Private Key"; // Set from Botan representation void BotanDHPrivateKey::setFromBotan(const BotanDH_PrivateKey* inDH) { ByteString inP = BotanUtil::bigInt2ByteString(inDH->impl->group_p()); setP(inP); ByteString inG = BotanUtil::bigInt2ByteString(inDH->impl->group_g()); setG(inG); ByteString inX = BotanUtil::bigInt2ByteString(inDH->impl->get_x()); setX(inX); } // Check if the key is of the given type bool BotanDHPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DH private key components void BotanDHPrivateKey::setX(const ByteString& inX) { DHPrivateKey::setX(inX); if (dh) { delete dh; dh = NULL; } } // Setters for the DH public key components void BotanDHPrivateKey::setP(const ByteString& inP) { DHPrivateKey::setP(inP); if (dh) { delete dh; dh = NULL; } } void BotanDHPrivateKey::setG(const ByteString& inG) { DHPrivateKey::setG(inG); if (dh) { delete dh; dh = NULL; } } // Encode into PKCS#8 DER ByteString BotanDHPrivateKey::PKCS8Encode() { ByteString der; createBotanKey(); if (dh == NULL) return der; // Force PKCS3_DH_PARAMETERS for p, g and no q. const size_t PKCS8_VERSION = 0; #if BOTAN_VERSION_MINOR == 11 const std::vector parameters = dh->impl->get_domain().DER_encode(Botan::DL_Group::PKCS3_DH_PARAMETERS); const Botan::AlgorithmIdentifier alg_id(dh->impl->get_oid(), parameters); const Botan::secure_vector ber = Botan::DER_Encoder() .start_cons(Botan::SEQUENCE) .encode(PKCS8_VERSION) .encode(alg_id) .encode(dh->impl->pkcs8_private_key(), Botan::OCTET_STRING) .end_cons() .get_contents(); #else const Botan::MemoryVector parameters = dh->impl->get_domain().DER_encode(Botan::DL_Group::PKCS3_DH_PARAMETERS); const Botan::AlgorithmIdentifier alg_id(dh->impl->get_oid(), parameters); const Botan::SecureVector ber = Botan::DER_Encoder() .start_cons(Botan::SEQUENCE) .encode(PKCS8_VERSION) .encode(alg_id) .encode(dh->impl->pkcs8_private_key(), Botan::OCTET_STRING) .end_cons() .get_contents(); #endif der.resize(ber.size()); memcpy(&der[0], &ber[0], ber.size()); return der; } // Decode from PKCS#8 BER bool BotanDHPrivateKey::PKCS8Decode(const ByteString& ber) { Botan::DataSource_Memory source(ber.const_byte_str(), ber.size()); if (source.end_of_data()) return false; #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector keydata; #else Botan::SecureVector keydata; #endif Botan::AlgorithmIdentifier alg_id; BotanDH_PrivateKey* key = NULL; try { Botan::BER_Decoder(source) .start_cons(Botan::SEQUENCE) .decode_and_check(0, "Unknown PKCS #8 version number") .decode(alg_id) .decode(keydata, Botan::OCTET_STRING) .discard_remaining() .end_cons(); if (keydata.empty()) throw Botan::Decoding_Error("PKCS #8 private key decoding failed"); if (Botan::OIDS::lookup(alg_id.oid).compare("DH")) { ERROR_MSG("Decoded private key not DH"); return false; } BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); key = new BotanDH_PrivateKey(alg_id, keydata, *rng->getRNG()); if (key == NULL) return false; setFromBotan(key); delete key; } catch (std::exception& e) { ERROR_MSG("Decode failed on %s", e.what()); return false; } return true; } // Retrieve the Botan representation of the key BotanDH_PrivateKey* BotanDHPrivateKey::getBotanKey() { if (!dh) { createBotanKey(); } return dh; } // Create the Botan representation of the key void BotanDHPrivateKey::createBotanKey() { // y is not needed if (p.size() != 0 && g.size() != 0 && x.size() != 0) { if (dh) { delete dh; dh = NULL; } try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); dh = new BotanDH_PrivateKey(*rng->getRNG(), Botan::DL_Group(BotanUtil::byteString2bigInt(p), BotanUtil::byteString2bigInt(g)), BotanUtil::byteString2bigInt(x)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } softhsm-2.0.0/src/lib/crypto/OSSLHMAC.cpp0000664000175000017500000000511712533040716014716 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLHMAC.cpp OpenSSL HMAC implementation *****************************************************************************/ #include "config.h" #include "OSSLHMAC.h" #ifdef WITH_GOST #include "OSSLCryptoFactory.h" #endif const EVP_MD* OSSLHMACMD5::getEVPHash() const { return EVP_md5(); } size_t OSSLHMACMD5::getMacSize() const { return 16; } const EVP_MD* OSSLHMACSHA1::getEVPHash() const { return EVP_sha1(); } size_t OSSLHMACSHA1::getMacSize() const { return 20; } const EVP_MD* OSSLHMACSHA224::getEVPHash() const { return EVP_sha224(); } size_t OSSLHMACSHA224::getMacSize() const { return 28; } const EVP_MD* OSSLHMACSHA256::getEVPHash() const { return EVP_sha256(); } size_t OSSLHMACSHA256::getMacSize() const { return 32; } const EVP_MD* OSSLHMACSHA384::getEVPHash() const { return EVP_sha384(); } size_t OSSLHMACSHA384::getMacSize() const { return 48; } const EVP_MD* OSSLHMACSHA512::getEVPHash() const { return EVP_sha512(); } size_t OSSLHMACSHA512::getMacSize() const { return 64; } #ifdef WITH_GOST const EVP_MD* OSSLHMACGOSTR3411::getEVPHash() const { return OSSLCryptoFactory::i()->EVP_GOST_34_11; } size_t OSSLHMACGOSTR3411::getMacSize() const { return 32; } #endif softhsm-2.0.0/src/lib/crypto/BotanECDHKeyPair.cpp0000664000175000017500000000430312533040716016455 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDHKeyPair.cpp Botan ECDH key-pair class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDHKeyPair.h" // Set the public key void BotanECDHKeyPair::setPublicKey(BotanECDHPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void BotanECDHKeyPair::setPrivateKey(BotanECDHPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* BotanECDHKeyPair::getPublicKey() { return &pubKey; } const PublicKey* BotanECDHKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* BotanECDHKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* BotanECDHKeyPair::getConstPrivateKey() const { return &privKey; } #endif softhsm-2.0.0/src/lib/crypto/BotanSHA512.h0000664000175000017500000000352712533040716015004 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA512.h Botan SHA512 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANSHA512_H #define _SOFTHSM_V2_BOTANSHA512_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanSHA512 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANSHA512_H softhsm-2.0.0/src/lib/crypto/OSSLRSAPrivateKey.cpp0000664000175000017500000001371312533040716016640 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSAPrivateKey.cpp OpenSSL RSA private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLRSAPrivateKey.h" #include "OSSLUtil.h" #include #include #include // Constructors OSSLRSAPrivateKey::OSSLRSAPrivateKey() { rsa = RSA_new(); // Use the OpenSSL implementation and not any engine RSA_set_method(rsa, RSA_get_default_method()); } OSSLRSAPrivateKey::OSSLRSAPrivateKey(const RSA* inRSA) { rsa = RSA_new(); // Use the OpenSSL implementation and not any engine RSA_set_method(rsa, RSA_PKCS1_SSLeay()); setFromOSSL(inRSA); } // Destructor OSSLRSAPrivateKey::~OSSLRSAPrivateKey() { RSA_free(rsa); } // The type /*static*/ const char* OSSLRSAPrivateKey::type = "OpenSSL RSA Private Key"; // Set from OpenSSL representation void OSSLRSAPrivateKey::setFromOSSL(const RSA* inRSA) { if (inRSA->p) { ByteString inP = OSSL::bn2ByteString(inRSA->p); setP(inP); } if (inRSA->q) { ByteString inQ = OSSL::bn2ByteString(inRSA->q); setQ(inQ); } if (inRSA->dmp1) { ByteString inDP1 = OSSL::bn2ByteString(inRSA->dmp1); setDP1(inDP1); } if (inRSA->dmq1) { ByteString inDQ1 = OSSL::bn2ByteString(inRSA->dmq1); setDQ1(inDQ1); } if (inRSA->iqmp) { ByteString inPQ = OSSL::bn2ByteString(inRSA->iqmp); setPQ(inPQ); } if (inRSA->d) { ByteString inD = OSSL::bn2ByteString(inRSA->d); setD(inD); } if (inRSA->n) { ByteString inN = OSSL::bn2ByteString(inRSA->n); setN(inN); } if (inRSA->e) { ByteString inE = OSSL::bn2ByteString(inRSA->e); setE(inE); } } // Check if the key is of the given type bool OSSLRSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the RSA private key components void OSSLRSAPrivateKey::setP(const ByteString& inP) { RSAPrivateKey::setP(inP); if (rsa->p) { BN_clear_free(rsa->p); rsa->p = NULL; } rsa->p = OSSL::byteString2bn(inP); } void OSSLRSAPrivateKey::setQ(const ByteString& inQ) { RSAPrivateKey::setQ(inQ); if (rsa->q) { BN_clear_free(rsa->q); rsa->q = NULL; } rsa->q = OSSL::byteString2bn(inQ); } void OSSLRSAPrivateKey::setPQ(const ByteString& inPQ) { RSAPrivateKey::setPQ(inPQ); if (rsa->iqmp) { BN_clear_free(rsa->iqmp); rsa->iqmp = NULL; } rsa->iqmp = OSSL::byteString2bn(inPQ); } void OSSLRSAPrivateKey::setDP1(const ByteString& inDP1) { RSAPrivateKey::setDP1(inDP1); if (rsa->dmp1) { BN_clear_free(rsa->dmp1); rsa->dmp1 = NULL; } rsa->dmp1 = OSSL::byteString2bn(inDP1); } void OSSLRSAPrivateKey::setDQ1(const ByteString& inDQ1) { RSAPrivateKey::setDQ1(inDQ1); if (rsa->dmq1) { BN_clear_free(rsa->dmq1); rsa->dmq1 = NULL; } rsa->dmq1 = OSSL::byteString2bn(inDQ1); } void OSSLRSAPrivateKey::setD(const ByteString& inD) { RSAPrivateKey::setD(inD); if (rsa->d) { BN_clear_free(rsa->d); rsa->d = NULL; } rsa->d = OSSL::byteString2bn(inD); } // Setters for the RSA public key components void OSSLRSAPrivateKey::setN(const ByteString& inN) { RSAPrivateKey::setN(inN); if (rsa->n) { BN_clear_free(rsa->n); rsa->n = NULL; } rsa->n = OSSL::byteString2bn(inN); } void OSSLRSAPrivateKey::setE(const ByteString& inE) { RSAPrivateKey::setE(inE); if (rsa->e) { BN_clear_free(rsa->e); rsa->e = NULL; } rsa->e = OSSL::byteString2bn(inE); } // Encode into PKCS#8 DER ByteString OSSLRSAPrivateKey::PKCS8Encode() { ByteString der; if (rsa == NULL) return der; EVP_PKEY* pkey = EVP_PKEY_new(); if (pkey == NULL) return der; if (!EVP_PKEY_set1_RSA(pkey, rsa)) { EVP_PKEY_free(pkey); return der; } PKCS8_PRIV_KEY_INFO* p8inf = EVP_PKEY2PKCS8(pkey); EVP_PKEY_free(pkey); if (p8inf == NULL) return der; int len = i2d_PKCS8_PRIV_KEY_INFO(p8inf, NULL); if (len < 0) { PKCS8_PRIV_KEY_INFO_free(p8inf); return der; } der.resize(len); unsigned char* priv = &der[0]; int len2 = i2d_PKCS8_PRIV_KEY_INFO(p8inf, &priv); PKCS8_PRIV_KEY_INFO_free(p8inf); if (len2 != len) der.wipe(); return der; } // Decode from PKCS#8 BER bool OSSLRSAPrivateKey::PKCS8Decode(const ByteString& ber) { int len = ber.size(); if (len <= 0) return false; const unsigned char* priv = ber.const_byte_str(); PKCS8_PRIV_KEY_INFO* p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &priv, len); if (p8 == NULL) return false; EVP_PKEY* pkey = EVP_PKCS82PKEY(p8); PKCS8_PRIV_KEY_INFO_free(p8); if (pkey == NULL) return false; RSA* key = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); if (key == NULL) return false; setFromOSSL(key); RSA_free(key); return true; } // Retrieve the OpenSSL representation of the key RSA* OSSLRSAPrivateKey::getOSSLKey() { return rsa; } softhsm-2.0.0/src/lib/crypto/OSSLEVPSymmetricAlgorithm.cpp0000664000175000017500000002030012533040716020373 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ // TODO: Store EVP context in securely allocated memory /***************************************************************************** OSSLEVPSymmetricAlgorithm.cpp OpenSSL symmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "OSSLEVPSymmetricAlgorithm.h" #include "salloc.h" // Constructor OSSLEVPSymmetricAlgorithm::OSSLEVPSymmetricAlgorithm() { pCurCTX = NULL; } // Destructor OSSLEVPSymmetricAlgorithm::~OSSLEVPSymmetricAlgorithm() { if (pCurCTX != NULL) { sfree(pCurCTX); } } // Encryption functions bool OSSLEVPSymmetricAlgorithm::encryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode::CBC */, const ByteString& IV /* = ByteString()*/, bool padding /* = true */) { // Call the superclass initialiser if (!SymmetricAlgorithm::encryptInit(key, mode, IV, padding)) { return false; } // Check the IV if ((IV.size() > 0) && (IV.size() != getBlockSize())) { ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize()); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } ByteString iv; if (IV.size() > 0) { iv = IV; } else { iv.wipe(getBlockSize()); } // Determine the cipher class const EVP_CIPHER* cipher = getCipher(); if (cipher == NULL) { ERROR_MSG("Failed to initialise EVP encrypt operation"); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } // Allocate the EVP context pCurCTX = (EVP_CIPHER_CTX*) salloc(sizeof(EVP_CIPHER_CTX)); if (pCurCTX == NULL) { ERROR_MSG("Failed to allocate space for EVP_CIPHER_CTX"); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } int rv = EVP_EncryptInit(pCurCTX, cipher, (unsigned char*) currentKey->getKeyBits().const_byte_str(), iv.byte_str()); if (!rv) { ERROR_MSG("Failed to initialise EVP encrypt operation"); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } EVP_CIPHER_CTX_set_padding(pCurCTX, padding ? 1 : 0); return true; } bool OSSLEVPSymmetricAlgorithm::encryptUpdate(const ByteString& data, ByteString& encryptedData) { if (!SymmetricAlgorithm::encryptUpdate(data, encryptedData)) { if (pCurCTX != NULL) { EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; } return false; } if (data.size() == 0) { encryptedData.resize(0); return true; } // Prepare the output block encryptedData.resize(data.size() + getBlockSize() - 1); int outLen = encryptedData.size(); if (!EVP_EncryptUpdate(pCurCTX, &encryptedData[0], &outLen, (unsigned char*) data.const_byte_str(), data.size())) { ERROR_MSG("EVP_EncryptUpdate failed"); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } // Resize the output block encryptedData.resize(outLen); currentBufferSize -= outLen; return true; } bool OSSLEVPSymmetricAlgorithm::encryptFinal(ByteString& encryptedData) { if (!SymmetricAlgorithm::encryptFinal(encryptedData)) { if (pCurCTX != NULL) { EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; } return false; } // Prepare the output block encryptedData.resize(getBlockSize()); int outLen = encryptedData.size(); if (!EVP_EncryptFinal(pCurCTX, &encryptedData[0], &outLen)) { ERROR_MSG("EVP_EncryptFinal failed"); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; return false; } // Resize the output block encryptedData.resize(outLen); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; return true; } // Decryption functions bool OSSLEVPSymmetricAlgorithm::decryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode::CBC */, const ByteString& IV /* = ByteString() */, bool padding /* = true */) { // Call the superclass initialiser if (!SymmetricAlgorithm::decryptInit(key, mode, IV, padding)) { return false; } // Check the IV if ((IV.size() > 0) && (IV.size() != getBlockSize())) { ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize()); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } ByteString iv; if (IV.size() > 0) { iv = IV; } else { iv.wipe(getBlockSize()); } // Determine the cipher class const EVP_CIPHER* cipher = getCipher(); if (cipher == NULL) { ERROR_MSG("Failed to initialise EVP decrypt operation"); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } // Allocate the EVP context pCurCTX = (EVP_CIPHER_CTX*) salloc(sizeof(EVP_CIPHER_CTX)); if (pCurCTX == NULL) { ERROR_MSG("Failed to allocate space for EVP_CIPHER_CTX"); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } int rv = EVP_DecryptInit(pCurCTX, cipher, (unsigned char*) currentKey->getKeyBits().const_byte_str(), iv.byte_str()); if (!rv) { ERROR_MSG("Failed to initialise EVP decrypt operation"); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } EVP_CIPHER_CTX_set_padding(pCurCTX, padding ? 1 : 0); return true; } bool OSSLEVPSymmetricAlgorithm::decryptUpdate(const ByteString& encryptedData, ByteString& data) { if (!SymmetricAlgorithm::decryptUpdate(encryptedData, data)) { if (pCurCTX != NULL) { EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; } return false; } // Prepare the output block data.resize(encryptedData.size() + getBlockSize() - 1); int outLen = data.size(); DEBUG_MSG("Decrypting %d bytes into buffer of %d bytes", encryptedData.size(), data.size()); if (!EVP_DecryptUpdate(pCurCTX, &data[0], &outLen, (unsigned char*) encryptedData.const_byte_str(), encryptedData.size())) { ERROR_MSG("EVP_DecryptUpdate failed"); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } DEBUG_MSG("Decrypt returned %d bytes of data", outLen); // Resize the output block data.resize(outLen); currentBufferSize -= outLen; return true; } bool OSSLEVPSymmetricAlgorithm::decryptFinal(ByteString& data) { if (!SymmetricAlgorithm::decryptFinal(data)) { if (pCurCTX != NULL) { EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; } return false; } // Prepare the output block data.resize(getBlockSize()); int outLen = data.size(); int rv; if (!(rv = EVP_DecryptFinal(pCurCTX, &data[0], &outLen))) { ERROR_MSG("EVP_DecryptFinal failed (0x%08X)", rv); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; return false; } // Resize the output block data.resize(outLen); EVP_CIPHER_CTX_cleanup(pCurCTX); sfree(pCurCTX); pCurCTX = NULL; return true; } softhsm-2.0.0/src/lib/crypto/OSSLCryptoFactory.cpp0000664000175000017500000002103012533040716017006 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLCryptoFactory.cpp This is an OpenSSL based cryptographic algorithm factory *****************************************************************************/ #include "config.h" #include "MutexFactory.h" #include "OSSLCryptoFactory.h" #include "OSSLRNG.h" #include "OSSLAES.h" #include "OSSLDES.h" #include "OSSLMD5.h" #include "OSSLSHA1.h" #include "OSSLSHA224.h" #include "OSSLSHA256.h" #include "OSSLSHA384.h" #include "OSSLSHA512.h" #include "OSSLHMAC.h" #include "OSSLRSA.h" #include "OSSLDSA.h" #include "OSSLDH.h" #ifdef WITH_ECC #include "OSSLECDH.h" #include "OSSLECDSA.h" #endif #ifdef WITH_GOST #include "OSSLGOSTR3411.h" #include "OSSLGOST.h" #endif #ifdef HAVE_PTHREAD_H #include #endif #include #include #include #include #include #ifdef WITH_GOST #include #endif // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr OSSLCryptoFactory::instance(nullptr); #else std::auto_ptr OSSLCryptoFactory::instance(NULL); #endif #ifdef WITH_FIPS // Initialise the FIPS 140-2 selftest status bool OSSLCryptoFactory::FipsSelfTestStatus = false; #endif // Thread ID callback #ifdef HAVE_PTHREAD_H static unsigned long id_callback() { return (unsigned long) pthread_self(); } #endif static unsigned nlocks; static Mutex** locks; // Mutex callback void lock_callback(int mode, int n, const char* file, int line) { if ((unsigned) n >= nlocks) { ERROR_MSG("out of range [0..%u[ lock %d at %s:%d", nlocks, n, file, line); return; } Mutex* mtx = locks[(unsigned) n]; if (mode & CRYPTO_LOCK) { mtx->lock(); } else { mtx->unlock(); } } // Constructor OSSLCryptoFactory::OSSLCryptoFactory() { // Multi-thread support nlocks = CRYPTO_num_locks(); locks = new Mutex*[nlocks]; for (unsigned i = 0; i < nlocks; i++) { locks[i] = MutexFactory::i()->getMutex(); } #ifdef HAVE_PTHREAD_H CRYPTO_set_id_callback(id_callback); #endif CRYPTO_set_locking_callback(lock_callback); #ifdef WITH_FIPS // Already in FIPS mode on reenter (avoiding selftests) if (!FIPS_mode()) { FipsSelfTestStatus = false; if (!FIPS_mode_set(1)) { ERROR_MSG("can't enter into FIPS mode"); return; } } else { // Undo RAND_cleanup() RAND_init_fips(); } FipsSelfTestStatus = true; #endif // Initialise OpenSSL OpenSSL_add_all_algorithms(); // Initialise the one-and-only RNG rng = new OSSLRNG(); #ifdef WITH_GOST // Load engines ENGINE_load_builtin_engines(); // Initialise the GOST engine eg = ENGINE_by_id("gost"); if (eg == NULL) { ERROR_MSG("can't get the GOST engine"); return; } if (ENGINE_init(eg) <= 0) { ENGINE_free(eg); eg = NULL; ERROR_MSG("can't initialize the GOST engine"); return; } // better than digest_gost EVP_GOST_34_11 = ENGINE_get_digest(eg, NID_id_GostR3411_94); if (EVP_GOST_34_11 == NULL) { ERROR_MSG("can't get the GOST digest"); goto err; } // from the openssl.cnf if (ENGINE_register_pkey_asn1_meths(eg) <= 0) { ERROR_MSG("can't register ASN.1 for the GOST engine"); goto err; } if (ENGINE_ctrl_cmd_string(eg, "CRYPT_PARAMS", "id-Gost28147-89-CryptoPro-A-ParamSet", 0) <= 0) { ERROR_MSG("can't set params of the GOST engine"); goto err; } return; err: ENGINE_finish(eg); ENGINE_free(eg); eg = NULL; return; #endif } // Destructor OSSLCryptoFactory::~OSSLCryptoFactory() { #ifdef WITH_GOST // Finish the GOST engine if (eg != NULL) { ENGINE_finish(eg); ENGINE_free(eg); eg = NULL; } ENGINE_cleanup(); #endif // Destroy the one-and-only RNG delete rng; // Clean up OpenSSL ERR_remove_state(0); RAND_cleanup(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_free_strings(); // Recycle locks CRYPTO_set_locking_callback(NULL); for (unsigned i = 0; i < nlocks; i++) { MutexFactory::i()->recycleMutex(locks[i]); } delete[] locks; } // Return the one-and-only instance OSSLCryptoFactory* OSSLCryptoFactory::i() { if (!instance.get()) { instance.reset(new OSSLCryptoFactory()); } return instance.get(); } // This will destroy the one-and-only instance. void OSSLCryptoFactory::reset() { instance.reset(); } #ifdef WITH_FIPS bool OSSLCryptoFactory::getFipsSelfTestStatus() const { return FipsSelfTestStatus; } #endif // Create a concrete instance of a symmetric algorithm SymmetricAlgorithm* OSSLCryptoFactory::getSymmetricAlgorithm(SymAlgo::Type algorithm) { switch (algorithm) { case SymAlgo::AES: return new OSSLAES(); case SymAlgo::DES: case SymAlgo::DES3: return new OSSLDES(); default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Create a concrete instance of an asymmetric algorithm AsymmetricAlgorithm* OSSLCryptoFactory::getAsymmetricAlgorithm(AsymAlgo::Type algorithm) { switch (algorithm) { case AsymAlgo::RSA: return new OSSLRSA(); case AsymAlgo::DSA: return new OSSLDSA(); case AsymAlgo::DH: return new OSSLDH(); #ifdef WITH_ECC case AsymAlgo::ECDH: return new OSSLECDH(); case AsymAlgo::ECDSA: return new OSSLECDSA(); #endif #ifdef WITH_GOST case AsymAlgo::GOST: return new OSSLGOST(); #endif default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Create a concrete instance of a hash algorithm HashAlgorithm* OSSLCryptoFactory::getHashAlgorithm(HashAlgo::Type algorithm) { switch (algorithm) { case HashAlgo::MD5: return new OSSLMD5(); case HashAlgo::SHA1: return new OSSLSHA1(); case HashAlgo::SHA224: return new OSSLSHA224(); case HashAlgo::SHA256: return new OSSLSHA256(); case HashAlgo::SHA384: return new OSSLSHA384(); case HashAlgo::SHA512: return new OSSLSHA512(); #ifdef WITH_GOST case HashAlgo::GOST: return new OSSLGOSTR3411(); #endif default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Create a concrete instance of a MAC algorithm MacAlgorithm* OSSLCryptoFactory::getMacAlgorithm(MacAlgo::Type algorithm) { switch (algorithm) { case MacAlgo::HMAC_MD5: return new OSSLHMACMD5(); case MacAlgo::HMAC_SHA1: return new OSSLHMACSHA1(); case MacAlgo::HMAC_SHA224: return new OSSLHMACSHA224(); case MacAlgo::HMAC_SHA256: return new OSSLHMACSHA256(); case MacAlgo::HMAC_SHA384: return new OSSLHMACSHA384(); case MacAlgo::HMAC_SHA512: return new OSSLHMACSHA512(); #ifdef WITH_GOST case MacAlgo::HMAC_GOST: return new OSSLHMACGOSTR3411(); #endif default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Get the global RNG (may be an unique RNG per thread) RNG* OSSLCryptoFactory::getRNG(RNGImpl::Type name /* = RNGImpl::Default */) { if (name == RNGImpl::Default) { return rng; } else { // No RNG implementation is available ERROR_MSG("Unknown RNG '%i'", name); return NULL; } } softhsm-2.0.0/src/lib/crypto/BotanMD5.h0000664000175000017500000000350512533040716014522 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanMD5.h Botan MD5 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANMD5_H #define _SOFTHSM_V2_BOTANMD5_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanMD5 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANMD5_H softhsm-2.0.0/src/lib/crypto/BotanSHA256.h0000664000175000017500000000352712533040716015011 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA256.h Botan SHA256 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANSHA256_H #define _SOFTHSM_V2_BOTANSHA256_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanSHA256 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANSHA256_H softhsm-2.0.0/src/lib/crypto/BotanSHA224.h0000664000175000017500000000352712533040716015004 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA224.h Botan SHA224 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANSHA224_H #define _SOFTHSM_V2_BOTANSHA224_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanSHA224 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANSHA224_H softhsm-2.0.0/src/lib/crypto/OSSLDSAPrivateKey.cpp0000664000175000017500000001154212533040716016620 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSAPrivateKey.cpp OpenSSL DSA private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDSAPrivateKey.h" #include "OSSLUtil.h" #include #include #include // Constructors OSSLDSAPrivateKey::OSSLDSAPrivateKey() { dsa = DSA_new(); // Use the OpenSSL implementation and not any engine DSA_set_method(dsa, DSA_get_default_method()); } OSSLDSAPrivateKey::OSSLDSAPrivateKey(const DSA* inDSA) { dsa = DSA_new(); // Use the OpenSSL implementation and not any engine DSA_set_method(dsa, DSA_OpenSSL()); setFromOSSL(inDSA); } // Destructor OSSLDSAPrivateKey::~OSSLDSAPrivateKey() { DSA_free(dsa); } // The type /*static*/ const char* OSSLDSAPrivateKey::type = "OpenSSL DSA Private Key"; // Set from OpenSSL representation void OSSLDSAPrivateKey::setFromOSSL(const DSA* inDSA) { if (inDSA->p) { ByteString inP = OSSL::bn2ByteString(inDSA->p); setP(inP); } if (inDSA->q) { ByteString inQ = OSSL::bn2ByteString(inDSA->q); setQ(inQ); } if (inDSA->g) { ByteString inG = OSSL::bn2ByteString(inDSA->g); setG(inG); } if (inDSA->priv_key) { ByteString inX = OSSL::bn2ByteString(inDSA->priv_key); setX(inX); } } // Check if the key is of the given type bool OSSLDSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DSA private key components void OSSLDSAPrivateKey::setX(const ByteString& inX) { DSAPrivateKey::setX(inX); if (dsa->priv_key) { BN_clear_free(dsa->priv_key); dsa->priv_key = NULL; } dsa->priv_key = OSSL::byteString2bn(inX); } // Setters for the DSA domain parameters void OSSLDSAPrivateKey::setP(const ByteString& inP) { DSAPrivateKey::setP(inP); if (dsa->p) { BN_clear_free(dsa->p); dsa->p = NULL; } dsa->p = OSSL::byteString2bn(inP); } void OSSLDSAPrivateKey::setQ(const ByteString& inQ) { DSAPrivateKey::setQ(inQ); if (dsa->q) { BN_clear_free(dsa->q); dsa->q = NULL; } dsa->q = OSSL::byteString2bn(inQ); } void OSSLDSAPrivateKey::setG(const ByteString& inG) { DSAPrivateKey::setG(inG); if (dsa->g) { BN_clear_free(dsa->g); dsa->g = NULL; } dsa->g = OSSL::byteString2bn(inG); } // Encode into PKCS#8 DER ByteString OSSLDSAPrivateKey::PKCS8Encode() { ByteString der; if (dsa == NULL) return der; EVP_PKEY* pkey = EVP_PKEY_new(); if (pkey == NULL) return der; if (!EVP_PKEY_set1_DSA(pkey, dsa)) { EVP_PKEY_free(pkey); return der; } PKCS8_PRIV_KEY_INFO* p8inf = EVP_PKEY2PKCS8(pkey); EVP_PKEY_free(pkey); if (p8inf == NULL) return der; int len = i2d_PKCS8_PRIV_KEY_INFO(p8inf, NULL); if (len < 0) { PKCS8_PRIV_KEY_INFO_free(p8inf); return der; } der.resize(len); unsigned char* priv = &der[0]; int len2 = i2d_PKCS8_PRIV_KEY_INFO(p8inf, &priv); PKCS8_PRIV_KEY_INFO_free(p8inf); if (len2 != len) der.wipe(); return der; } // Decode from PKCS#8 BER bool OSSLDSAPrivateKey::PKCS8Decode(const ByteString& ber) { int len = ber.size(); if (len <= 0) return false; const unsigned char* priv = ber.const_byte_str(); PKCS8_PRIV_KEY_INFO* p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &priv, len); if (p8 == NULL) return false; EVP_PKEY* pkey = EVP_PKCS82PKEY(p8); PKCS8_PRIV_KEY_INFO_free(p8); if (pkey == NULL) return false; DSA* key = EVP_PKEY_get1_DSA(pkey); EVP_PKEY_free(pkey); if (key == NULL) return false; setFromOSSL(key); DSA_free(key); return true; } // Retrieve the OpenSSL representation of the key DSA* OSSLDSAPrivateKey::getOSSLKey() { return dsa; } softhsm-2.0.0/src/lib/crypto/OSSLGOSTKeyPair.cpp0000664000175000017500000000424712533040716016252 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTKeyPair.cpp OpenSSL GOST R 34.10-2001 key-pair class *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "OSSLGOSTKeyPair.h" // Set the public key void OSSLGOSTKeyPair::setPublicKey(OSSLGOSTPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void OSSLGOSTKeyPair::setPrivateKey(OSSLGOSTPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* OSSLGOSTKeyPair::getPublicKey() { return &pubKey; } const PublicKey* OSSLGOSTKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* OSSLGOSTKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* OSSLGOSTKeyPair::getConstPrivateKey() const { return &privKey; } #endif softhsm-2.0.0/src/lib/crypto/BotanMacAlgorithm.cpp0000664000175000017500000001342112533040716017035 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ // TODO: Store context in securely allocated memory /***************************************************************************** BotanMacAlgorithm.cpp Botan MAC algorithm implementation *****************************************************************************/ #include "config.h" #include "BotanMacAlgorithm.h" #include "salloc.h" #include #include // Constructor BotanMacAlgorithm::BotanMacAlgorithm() { hmac = NULL; } // Destructor BotanMacAlgorithm::~BotanMacAlgorithm() { delete hmac; hmac = NULL; } // Signing functions bool BotanMacAlgorithm::signInit(const SymmetricKey* key) { // Call the superclass initialiser if (!MacAlgorithm::signInit(key)) { return false; } // Determine the hash name std::string hashName = getHash(); if (hashName == "") { ERROR_MSG("Invalid sign hmac hash"); ByteString dummy; MacAlgorithm::signFinal(dummy); return false; } // Allocate the context try { hmac = new Botan::HMAC(Botan::get_hash(hashName)); hmac->set_key(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); } catch (...) { ERROR_MSG("Failed to create the sign hmac token"); ByteString dummy; MacAlgorithm::signFinal(dummy); delete hmac; hmac = NULL; return false; } return true; } bool BotanMacAlgorithm::signUpdate(const ByteString& dataToSign) { if (!MacAlgorithm::signUpdate(dataToSign)) { delete hmac; hmac = NULL; return false; } try { if (dataToSign.size() != 0) { hmac->update(dataToSign.const_byte_str(), dataToSign.size()); } } catch (...) { ERROR_MSG("Failed to update the sign hmac token"); ByteString dummy; MacAlgorithm::signFinal(dummy); delete hmac; hmac = NULL; return false; } return true; } bool BotanMacAlgorithm::signFinal(ByteString& signature) { if (!MacAlgorithm::signFinal(signature)) { return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector signResult; #else Botan::SecureVector signResult; #endif try { signResult = hmac->final(); } catch (...) { ERROR_MSG("Could not sign the data"); delete hmac; hmac = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete hmac; hmac = NULL; return true; } // Verification functions bool BotanMacAlgorithm::verifyInit(const SymmetricKey* key) { // Call the superclass initialiser if (!MacAlgorithm::verifyInit(key)) { return false; } // Determine the hash name std::string hashName = getHash(); if (hashName == "") { ERROR_MSG("Invalid verify hmac hash"); ByteString dummy; MacAlgorithm::verifyFinal(dummy); return false; } // Allocate the context try { hmac = new Botan::HMAC(Botan::get_hash(hashName)); hmac->set_key(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); } catch (...) { ERROR_MSG("Failed to create the verify hmac token"); ByteString dummy; MacAlgorithm::verifyFinal(dummy); delete hmac; hmac = NULL; return false; } return true; } bool BotanMacAlgorithm::verifyUpdate(const ByteString& originalData) { if (!MacAlgorithm::verifyUpdate(originalData)) { delete hmac; hmac = NULL; return false; } try { if (originalData.size() != 0) { hmac->update(originalData.const_byte_str(), originalData.size()); } } catch (...) { ERROR_MSG("Failed to update the verify hmac token"); ByteString dummy; MacAlgorithm::verifyFinal(dummy); delete hmac; hmac = NULL; return false; } return true; } bool BotanMacAlgorithm::verifyFinal(ByteString& signature) { if (!MacAlgorithm::verifyFinal(signature)) { return false; } // Perform the verify operation #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector macResult; #else Botan::SecureVector macResult; #endif try { macResult = hmac->final(); } catch (...) { ERROR_MSG("Failed to verify the data"); delete hmac; hmac = NULL; return false; } if (macResult.size() != signature.size()) { ERROR_MSG("Bad verify result size"); delete hmac; hmac = NULL; return false; } delete hmac; hmac = NULL; #if BOTAN_VERSION_MINOR == 11 return memcmp(&signature[0], macResult.data(), macResult.size()) == 0; #else return memcmp(&signature[0], macResult.begin(), macResult.size()) == 0; #endif } softhsm-2.0.0/src/lib/crypto/OSSLRNG.h0000664000175000017500000000355012533040716014300 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRNG.h OpenSSL random number generator class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLRNG_H #define _SOFTHSM_V2_OSSLRNG_H #include "config.h" #include "ByteString.h" #include "RNG.h" class OSSLRNG : public RNG { public: // Generate random data virtual bool generateRandom(ByteString& data, const size_t len); // Seed the random pool virtual void seed(ByteString& seedData); private: }; #endif // !_SOFTHSM_V2_OSSLRNG_H softhsm-2.0.0/src/lib/crypto/BotanHashAlgorithm.h0000664000175000017500000000427612533040716016675 00000000000000/* * Copyright (c) .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanHashAlgorithm.h Base class for Botan hash algorithm classes *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANHASHALGORITHM_H #define _SOFTHSM_V2_BOTANHASHALGORITHM_H #include "config.h" #include "HashAlgorithm.h" #include class BotanHashAlgorithm : public HashAlgorithm { public: // Base constructor BotanHashAlgorithm(); // Destructor virtual ~BotanHashAlgorithm(); // Hashing functions virtual bool hashInit(); virtual bool hashUpdate(const ByteString& data); virtual bool hashFinal(ByteString& hashedData); virtual int getHashSize() = 0; protected: virtual Botan::HashFunction* getHash() const = 0; private: // Current hashing context Botan::HashFunction *hash; }; #endif // !_SOFTHSM_V2_BOTANHASHALGORITHM_H softhsm-2.0.0/src/lib/crypto/AESKey.h0000664000175000017500000000342012533040716014226 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AESKey.h AES key symmetric key class *****************************************************************************/ #ifndef _SOFTHSM_V2_AESKEY_H #define _SOFTHSM_V2_AESKEY_H #include "config.h" #include "ByteString.h" #include "SymmetricKey.h" class AESKey : public SymmetricKey { public: // Base constructor AESKey(size_t inBitLen = 0) : SymmetricKey(inBitLen) { } }; #endif // !SOFTHSM_V2_AESKEY_H softhsm-2.0.0/src/lib/crypto/OSSLSHA512.h0000664000175000017500000000346312533040716014520 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA512.h OpenSSL SHA512 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLSHA512_H #define _SOFTHSM_V2_OSSLSHA512_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLSHA512 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLSHA512_H softhsm-2.0.0/src/lib/crypto/OSSLDSA.cpp0000664000175000017500000003515212533040716014617 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSA.cpp OpenSSL DSA asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDSA.h" #include "CryptoFactory.h" #include "DSAParameters.h" #include "OSSLDSAKeyPair.h" #include "OSSLUtil.h" #include #include #include #include // Constructor OSSLDSA::OSSLDSA() { pCurrentHash = NULL; } // Destructor OSSLDSA::~OSSLDSA() { if (pCurrentHash != NULL) { delete pCurrentHash; } } // Signing functions bool OSSLDSA::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (mechanism == AsymMech::DSA) { // Separate implementation for DSA signing without hash computation // Check if the private key is the right type if (!privateKey->isOfType(OSSLDSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } OSSLDSAPrivateKey* pk = (OSSLDSAPrivateKey*) privateKey; DSA* dsa = pk->getOSSLKey(); // Perform the signature operation unsigned int sigLen = pk->getOutputLength(); signature.resize(sigLen); memset(&signature[0], 0, sigLen); int dLen = dataToSign.size(); DSA_SIG* sig = DSA_do_sign(dataToSign.const_byte_str(), dLen, dsa); if (sig == NULL) return false; // Store the 2 values with padding BN_bn2bin(sig->r, &signature[sigLen / 2 - BN_num_bytes(sig->r)]); BN_bn2bin(sig->s, &signature[sigLen - BN_num_bytes(sig->s)]); DSA_SIG_free(sig); return true; } else { // Call default implementation return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen); } } bool OSSLDSA::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!privateKey->isOfType(OSSLDSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } HashAlgo::Type hash = HashAlgo::Unknown; switch (mechanism) { case AsymMech::DSA_SHA1: hash = HashAlgo::SHA1; break; case AsymMech::DSA_SHA224: hash = HashAlgo::SHA224; break; case AsymMech::DSA_SHA256: hash = HashAlgo::SHA256; break; case AsymMech::DSA_SHA384: hash = HashAlgo::SHA384; break; case AsymMech::DSA_SHA512: hash = HashAlgo::SHA512; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } pCurrentHash = CryptoFactory::i()->getHashAlgorithm(hash); if (pCurrentHash == NULL) { ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } if (!pCurrentHash->hashInit()) { delete pCurrentHash; pCurrentHash = NULL; ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLDSA::signUpdate(const ByteString& dataToSign) { if (!AsymmetricAlgorithm::signUpdate(dataToSign)) { return false; } if (!pCurrentHash->hashUpdate(dataToSign)) { delete pCurrentHash; pCurrentHash = NULL; ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLDSA::signFinal(ByteString& signature) { // Save necessary state before calling super class signFinal OSSLDSAPrivateKey* pk = (OSSLDSAPrivateKey*) currentPrivateKey; if (!AsymmetricAlgorithm::signFinal(signature)) { return false; } ByteString hash; bool bFirstResult = pCurrentHash->hashFinal(hash); delete pCurrentHash; pCurrentHash = NULL; if (!bFirstResult) { return false; } DSA* dsa = pk->getOSSLKey(); // Perform the signature operation unsigned int sigLen = pk->getOutputLength(); signature.resize(sigLen); memset(&signature[0], 0, sigLen); DSA_SIG* sig = DSA_do_sign(&hash[0], hash.size(), dsa); if (sig == NULL) return false; // Store the 2 values with padding BN_bn2bin(sig->r, &signature[sigLen / 2 - BN_num_bytes(sig->r)]); BN_bn2bin(sig->s, &signature[sigLen - BN_num_bytes(sig->s)]); DSA_SIG_free(sig); return true; } // Verification functions bool OSSLDSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (mechanism == AsymMech::DSA) { // Separate implementation for DSA verification without hash computation // Check if the private key is the right type if (!publicKey->isOfType(OSSLDSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // Perform the verify operation OSSLDSAPublicKey* pk = (OSSLDSAPublicKey*) publicKey; unsigned int sigLen = pk->getOutputLength(); if (signature.size() != sigLen) return false; DSA_SIG* sig = DSA_SIG_new(); if (sig == NULL) return false; const unsigned char *s = signature.const_byte_str(); sig->r = BN_bin2bn(s, sigLen / 2, NULL); sig->s = BN_bin2bn(s + sigLen / 2, sigLen / 2, NULL); if (sig->r == NULL || sig->s == NULL) { DSA_SIG_free(sig); return false; } int dLen = originalData.size(); int ret = DSA_do_verify(originalData.const_byte_str(), dLen, sig, pk->getOSSLKey()); if (ret != 1) { if (ret < 0) ERROR_MSG("DSA verify failed (0x%08X)", ERR_get_error()); DSA_SIG_free(sig); return false; } DSA_SIG_free(sig); return true; } else { // Call the generic function return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen); } } bool OSSLDSA::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!publicKey->isOfType(OSSLDSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } HashAlgo::Type hash = HashAlgo::Unknown; switch (mechanism) { case AsymMech::DSA_SHA1: hash = HashAlgo::SHA1; break; case AsymMech::DSA_SHA224: hash = HashAlgo::SHA224; break; case AsymMech::DSA_SHA256: hash = HashAlgo::SHA256; break; case AsymMech::DSA_SHA384: hash = HashAlgo::SHA384; break; case AsymMech::DSA_SHA512: hash = HashAlgo::SHA512; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } pCurrentHash = CryptoFactory::i()->getHashAlgorithm(hash); if (pCurrentHash == NULL) { ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } if (!pCurrentHash->hashInit()) { delete pCurrentHash; pCurrentHash = NULL; ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLDSA::verifyUpdate(const ByteString& originalData) { if (!AsymmetricAlgorithm::verifyUpdate(originalData)) { return false; } if (!pCurrentHash->hashUpdate(originalData)) { delete pCurrentHash; pCurrentHash = NULL; ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLDSA::verifyFinal(const ByteString& signature) { // Save necessary state before calling super class verifyFinal OSSLDSAPublicKey* pk = (OSSLDSAPublicKey*) currentPublicKey; if (!AsymmetricAlgorithm::verifyFinal(signature)) { return false; } ByteString hash; bool bFirstResult = pCurrentHash->hashFinal(hash); delete pCurrentHash; pCurrentHash = NULL; if (!bFirstResult) { return false; } // Perform the verify operation unsigned int sigLen = pk->getOutputLength(); if (signature.size() != sigLen) return false; DSA_SIG* sig = DSA_SIG_new(); if (sig == NULL) return false; const unsigned char *s = signature.const_byte_str(); sig->r = BN_bin2bn(s, sigLen / 2, NULL); sig->s = BN_bin2bn(s + sigLen / 2, sigLen / 2, NULL); if (sig->r == NULL || sig->s == NULL) { DSA_SIG_free(sig); return false; } int ret = DSA_do_verify(&hash[0], hash.size(), sig, pk->getOSSLKey()); if (ret != 1) { if (ret < 0) ERROR_MSG("DSA verify failed (0x%08X)", ERR_get_error()); DSA_SIG_free(sig); return false; } DSA_SIG_free(sig); return true; } // Encryption functions bool OSSLDSA::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DSA does not support encryption"); return false; } // Decryption functions bool OSSLDSA::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DSA does not support decryption"); return false; } // Key factory bool OSSLDSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(DSAParameters::type)) { ERROR_MSG("Invalid parameters supplied for DSA key generation"); return false; } DSAParameters* params = (DSAParameters*) parameters; // Generate the key-pair DSA* dsa = DSA_new(); if (dsa == NULL) { ERROR_MSG("Failed to instantiate OpenSSL DSA object"); return false; } // Use the OpenSSL implementation and not any engine DSA_set_method(dsa, DSA_get_default_method()); dsa->p = OSSL::byteString2bn(params->getP()); dsa->q = OSSL::byteString2bn(params->getQ()); dsa->g = OSSL::byteString2bn(params->getG()); if (DSA_generate_key(dsa) != 1) { ERROR_MSG("DSA key generation failed (0x%08X)", ERR_get_error()); DSA_free(dsa); return false; } // Create an asymmetric key-pair object to return OSSLDSAKeyPair* kp = new OSSLDSAKeyPair(); ((OSSLDSAPublicKey*) kp->getPublicKey())->setFromOSSL(dsa); ((OSSLDSAPrivateKey*) kp->getPrivateKey())->setFromOSSL(dsa); *ppKeyPair = kp; // Release the key DSA_free(dsa); return true; } unsigned long OSSLDSA::getMinKeySize() { #ifdef WITH_FIPS // OPENSSL_DSA_FIPS_MIN_MODULUS_BITS is 1024 return 1024; #else return 512; #endif } unsigned long OSSLDSA::getMaxKeySize() { return OPENSSL_DSA_MAX_MODULUS_BITS; } bool OSSLDSA::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/) { if ((ppParams == NULL) || (parameters == NULL)) { return false; } size_t bitLen = (size_t) parameters; if (bitLen < getMinKeySize() || bitLen > getMaxKeySize()) { ERROR_MSG("This DSA key size is not supported"); return false; } DSA* dsa = DSA_generate_parameters(bitLen, NULL, 0, NULL, NULL, NULL, NULL); if (dsa == NULL) { ERROR_MSG("Failed to generate %d bit DSA parameters", bitLen); return false; } // Store the DSA parameters DSAParameters* params = new DSAParameters(); ByteString p = OSSL::bn2ByteString(dsa->p); params->setP(p); ByteString q = OSSL::bn2ByteString(dsa->q); params->setQ(q); ByteString g = OSSL::bn2ByteString(dsa->g); params->setG(g); *ppParams = params; DSA_free(dsa); return true; } bool OSSLDSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); OSSLDSAKeyPair* kp = new OSSLDSAKeyPair(); bool rv = true; if (!((DSAPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((DSAPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool OSSLDSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLDSAPublicKey* pub = new OSSLDSAPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool OSSLDSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLDSAPrivateKey* priv = new OSSLDSAPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* OSSLDSA::newPublicKey() { return (PublicKey*) new OSSLDSAPublicKey(); } PrivateKey* OSSLDSA::newPrivateKey() { return (PrivateKey*) new OSSLDSAPrivateKey(); } AsymmetricParameters* OSSLDSA::newParameters() { return (AsymmetricParameters*) new DSAParameters(); } bool OSSLDSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } DSAParameters* params = new DSAParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } softhsm-2.0.0/src/lib/crypto/BotanSHA256.cpp0000664000175000017500000000334412533040716015341 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA256.cpp Botan SHA256 implementation *****************************************************************************/ #include "config.h" #include "BotanSHA256.h" #include int BotanSHA256::getHashSize() { return 32; } Botan::HashFunction* BotanSHA256::getHash() const { return new Botan::SHA_256(); } softhsm-2.0.0/src/lib/crypto/OSSLSHA224.h0000664000175000017500000000346312533040716014520 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA224.h OpenSSL SHA224 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLSHA224_H #define _SOFTHSM_V2_OSSLSHA224_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLSHA224 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLSHA224_H softhsm-2.0.0/src/lib/crypto/OSSLRSA.h0000664000175000017500000000743012533040716014300 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSA.h OpenSSL RSA asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLRSA_H #define _SOFTHSM_V2_OSSLRSA_H #include "config.h" #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include class OSSLRSA : public AsymmetricAlgorithm { public: // Constructor OSSLRSA(); // Destructor virtual ~OSSLRSA(); // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: HashAlgorithm* pCurrentHash; HashAlgorithm* pSecondHash; size_t sLen; }; #endif // !_SOFTHSM_V2_OSSLRSA_H softhsm-2.0.0/src/lib/crypto/BotanSymmetricAlgorithm.cpp0000664000175000017500000002070712533040716020316 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ // TODO: Store context in securely allocated memory /***************************************************************************** BotanSymmetricAlgorithm.cpp Botan symmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "BotanSymmetricAlgorithm.h" #include "salloc.h" #include #include #include #include #if BOTAN_VERSION_CODE >= BOTAN_VERSION_CODE_FOR(1,11,14) #include #endif // Constructor BotanSymmetricAlgorithm::BotanSymmetricAlgorithm() { cryption = NULL; } // Destructor BotanSymmetricAlgorithm::~BotanSymmetricAlgorithm() { delete cryption; cryption = NULL; } // Encryption functions bool BotanSymmetricAlgorithm::encryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode:CBC */, const ByteString& IV /* = ByteString()*/, bool padding /* = true */) { // Call the superclass initialiser if (!SymmetricAlgorithm::encryptInit(key, mode, IV, padding)) { return false; } // Check the IV if ((IV.size() > 0) && (IV.size() != getBlockSize())) { ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize()); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } ByteString iv; if (IV.size() > 0) { iv = IV; } else { iv.wipe(getBlockSize()); } // Determine the cipher std::string cipherName = getCipher(); if (cipherName == "") { ERROR_MSG("Invalid encryption cipher"); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); return false; } // Allocate the context try { Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); if (mode == SymMode::ECB) { cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, Botan::ENCRYPTION)); } else { Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size()); cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, botanIV, Botan::ENCRYPTION)); } cryption->start_msg(); } catch (...) { ERROR_MSG("Failed to create the encryption token"); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); delete cryption; cryption = NULL; return false; } return true; } bool BotanSymmetricAlgorithm::encryptUpdate(const ByteString& data, ByteString& encryptedData) { if (!SymmetricAlgorithm::encryptUpdate(data, encryptedData)) { delete cryption; cryption = NULL; return false; } // Write data try { if (data.size() > 0) cryption->write(data.const_byte_str(), data.size()); } catch (...) { ERROR_MSG("Failed to write to the encryption token"); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); delete cryption; cryption = NULL; return false; } // Read data int bytesRead = 0; try { size_t outLen = cryption->remaining(); encryptedData.resize(outLen); if (outLen > 0) bytesRead = cryption->read(&encryptedData[0], outLen); } catch (...) { ERROR_MSG("Failed to encrypt the data"); ByteString dummy; SymmetricAlgorithm::encryptFinal(dummy); delete cryption; cryption = NULL; return false; } // Resize the output block encryptedData.resize(bytesRead); currentBufferSize -= bytesRead; return true; } bool BotanSymmetricAlgorithm::encryptFinal(ByteString& encryptedData) { if (!SymmetricAlgorithm::encryptFinal(encryptedData)) { delete cryption; cryption = NULL; return false; } // Read data int bytesRead = 0; try { cryption->end_msg(); size_t outLen = cryption->remaining(); encryptedData.resize(outLen); if (outLen > 0) bytesRead = cryption->read(&encryptedData[0], outLen); } catch (...) { ERROR_MSG("Failed to encrypt the data"); delete cryption; cryption = NULL; return false; } // Clean up delete cryption; cryption = NULL; // Resize the output block encryptedData.resize(bytesRead); return true; } // Decryption functions bool BotanSymmetricAlgorithm::decryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode::CBC */, const ByteString& IV /* = ByteString() */, bool padding /* = true */) { // Call the superclass initialiser if (!SymmetricAlgorithm::decryptInit(key, mode, IV, padding)) { return false; } // Check the IV if ((IV.size() > 0) && (IV.size() != getBlockSize())) { ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize()); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } ByteString iv; if (IV.size() > 0) { iv = IV; } else { iv.wipe(getBlockSize()); } // Determine the cipher class std::string cipherName = getCipher(); if (cipherName == "") { ERROR_MSG("Invalid decryption cipher"); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); return false; } // Allocate the context try { Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); if (mode == SymMode::ECB) { cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, Botan::DECRYPTION)); } else { Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size()); cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, botanIV, Botan::DECRYPTION)); } cryption->start_msg(); } catch (...) { ERROR_MSG("Failed to create the decryption token"); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); delete cryption; cryption = NULL; return false; } return true; } bool BotanSymmetricAlgorithm::decryptUpdate(const ByteString& encryptedData, ByteString& data) { if (!SymmetricAlgorithm::decryptUpdate(encryptedData, data)) { delete cryption; cryption = NULL; return false; } // Write data try { if (encryptedData.size() > 0) cryption->write(encryptedData.const_byte_str(), encryptedData.size()); } catch (...) { ERROR_MSG("Failed to write to the decryption token"); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); delete cryption; cryption = NULL; return false; } // Read data int bytesRead = 0; try { size_t outLen = cryption->remaining(); data.resize(outLen); if (outLen > 0) bytesRead = cryption->read(&data[0], outLen); } catch (...) { ERROR_MSG("Failed to decrypt the data"); ByteString dummy; SymmetricAlgorithm::decryptFinal(dummy); delete cryption; cryption = NULL; return false; } // Resize the output block data.resize(bytesRead); currentBufferSize -= bytesRead; return true; } bool BotanSymmetricAlgorithm::decryptFinal(ByteString& data) { if (!SymmetricAlgorithm::decryptFinal(data)) { delete cryption; cryption = NULL; return false; } // Read data int bytesRead = 0; try { cryption->end_msg(); size_t outLen = cryption->remaining(); data.resize(outLen); if (outLen > 0) bytesRead = cryption->read(&data[0], outLen); } catch (...) { ERROR_MSG("Failed to decrypt the data"); delete cryption; cryption = NULL; return false; } // Clean up delete cryption; cryption = NULL; // Resize the output block data.resize(bytesRead); return true; } softhsm-2.0.0/src/lib/crypto/BotanRSAPrivateKey.h0000664000175000017500000000564112533040716016571 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSAPrivateKey.h Botan RSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANRSAPRIVATEKEY_H #define _SOFTHSM_V2_BOTANRSAPRIVATEKEY_H #include "config.h" #include "RSAPrivateKey.h" #include class BotanRSAPrivateKey : public RSAPrivateKey { public: // Constructors BotanRSAPrivateKey(); BotanRSAPrivateKey(const Botan::RSA_PrivateKey* inRSA); // Destructor virtual ~BotanRSAPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the RSA private key components virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setPQ(const ByteString& inPQ); virtual void setDP1(const ByteString& inDP1); virtual void setDQ1(const ByteString& inDQ1); virtual void setD(const ByteString& inD); // Setters for the RSA public key components virtual void setN(const ByteString& inN); virtual void setE(const ByteString& inE); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from Botan representation virtual void setFromBotan(const Botan::RSA_PrivateKey* inRSA); // Retrieve the Botan representation of the key Botan::RSA_PrivateKey* getBotanKey(); private: // The internal Botan representation Botan::RSA_PrivateKey* rsa; void createBotanKey(); }; #endif // !_SOFTHSM_V2_OSSLRSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/BotanECDSAKeyPair.cpp0000664000175000017500000000431612533040716016575 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSAKeyPair.cpp Botan ECDSA key-pair class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDSAKeyPair.h" // Set the public key void BotanECDSAKeyPair::setPublicKey(BotanECDSAPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void BotanECDSAKeyPair::setPrivateKey(BotanECDSAPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* BotanECDSAKeyPair::getPublicKey() { return &pubKey; } const PublicKey* BotanECDSAKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* BotanECDSAKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* BotanECDSAKeyPair::getConstPrivateKey() const { return &privKey; } #endif softhsm-2.0.0/src/lib/crypto/OSSLECKeyPair.cpp0000664000175000017500000000421712533040716015762 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECKeyPair.cpp OpenSSL Elliptic Curve key-pair class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "OSSLECKeyPair.h" // Set the public key void OSSLECKeyPair::setPublicKey(OSSLECPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void OSSLECKeyPair::setPrivateKey(OSSLECPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* OSSLECKeyPair::getPublicKey() { return &pubKey; } const PublicKey* OSSLECKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* OSSLECKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* OSSLECKeyPair::getConstPrivateKey() const { return &privKey; } #endif softhsm-2.0.0/src/lib/crypto/OSSLRSAPublicKey.h0000664000175000017500000000451312533040716016107 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSAPublicKey.h OpenSSL RSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLRSAPUBLICKEY_H #define _SOFTHSM_V2_OSSLRSAPUBLICKEY_H #include "config.h" #include "RSAPublicKey.h" #include class OSSLRSAPublicKey : public RSAPublicKey { public: // Constructors OSSLRSAPublicKey(); OSSLRSAPublicKey(const RSA* inRSA); // Destructor virtual ~OSSLRSAPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the RSA public key components virtual void setN(const ByteString& inN); virtual void setE(const ByteString& inE); // Set from OpenSSL representation virtual void setFromOSSL(const RSA* inRSA); // Retrieve the OpenSSL representation of the key RSA* getOSSLKey(); private: // The internal OpenSSL representation RSA* rsa; }; #endif // !_SOFTHSM_V2_OSSLRSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanDSAPublicKey.h0000664000175000017500000000511712533040716016355 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSAPublicKey.h Botan DSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDSAPUBLICKEY_H #define _SOFTHSM_V2_BOTANDSAPUBLICKEY_H #include "config.h" #include "DSAPublicKey.h" #include class BotanDSAPublicKey : public DSAPublicKey { public: // Constructors BotanDSAPublicKey(); BotanDSAPublicKey(const Botan::DSA_PublicKey* inDSA); // Destructor virtual ~BotanDSAPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DSA public key components virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setG(const ByteString& inG); virtual void setY(const ByteString& inY); // Set from Botan representation virtual void setFromBotan(const Botan::DSA_PublicKey* inDSA); // Retrieve the Botan representation of the key Botan::DSA_PublicKey* getBotanKey(); private: // The internal Botan representation Botan::DSA_PublicKey* dsa; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANDSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/SymmetricAlgorithm.cpp0000664000175000017500000001042112533040716017322 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SymmetricAlgorithm.cpp Base class for symmetric algorithm classes *****************************************************************************/ #include "SymmetricAlgorithm.h" #include #include SymmetricAlgorithm::SymmetricAlgorithm() { currentKey = NULL; currentCipherMode = SymMode::Unknown; currentPaddingMode = true; currentOperation = NONE; currentBufferSize = 0; } bool SymmetricAlgorithm::encryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode::CBC */, const ByteString& /*IV = ByteString() */, bool padding /* = true */) { if ((key == NULL) || (currentOperation != NONE)) { return false; } currentKey = key; currentCipherMode = mode; currentPaddingMode = padding; currentOperation = ENCRYPT; currentBufferSize = 0; return true; } bool SymmetricAlgorithm::encryptUpdate(const ByteString& data, ByteString& /*encryptedData*/) { if (currentOperation != ENCRYPT) { return false; } currentBufferSize += data.size(); return true; } bool SymmetricAlgorithm::encryptFinal(ByteString& /*encryptedData*/) { if (currentOperation != ENCRYPT) { return false; } currentKey = NULL; currentCipherMode = SymMode::Unknown; currentPaddingMode = true; currentOperation = NONE; currentBufferSize = 0; return true; } bool SymmetricAlgorithm::decryptInit(const SymmetricKey* key, const SymMode::Type mode /* = SymMode::CBC */, const ByteString& /*IV = ByteString() */, bool padding /* = true */) { if ((key == NULL) || (currentOperation != NONE)) { return false; } currentKey = key; currentCipherMode = mode; currentPaddingMode = padding; currentOperation = DECRYPT; currentBufferSize = 0; return true; } bool SymmetricAlgorithm::decryptUpdate(const ByteString& encryptedData, ByteString& /*data*/) { if (currentOperation != DECRYPT) { return false; } currentBufferSize += encryptedData.size(); return true; } bool SymmetricAlgorithm::decryptFinal(ByteString& /*data*/) { if (currentOperation != DECRYPT) { return false; } currentKey = NULL; currentCipherMode = SymMode::Unknown; currentPaddingMode = true; currentOperation = NONE; currentBufferSize = 0; return true; } // Key factory void SymmetricAlgorithm::recycleKey(SymmetricKey* toRecycle) { delete toRecycle; } bool SymmetricAlgorithm::generateKey(SymmetricKey& key, RNG* rng /* = NULL */) { if (rng == NULL) { return false; } if (key.getBitLen() == 0) { return false; } ByteString keyBits; if (!rng->generateRandom(keyBits, key.getBitLen()/8)) { return false; } return key.setKeyBits(keyBits); } bool SymmetricAlgorithm::reconstructKey(SymmetricKey& key, const ByteString& serialisedData) { return key.setKeyBits(serialisedData); } SymMode::Type SymmetricAlgorithm::getCipherMode() { return currentCipherMode; } bool SymmetricAlgorithm::getPaddingMode() { return currentPaddingMode; } unsigned long SymmetricAlgorithm::getBufferSize() { return currentBufferSize; } softhsm-2.0.0/src/lib/crypto/OSSLRSAPrivateKey.h0000664000175000017500000000543712533040716016311 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSAPrivateKey.h OpenSSL RSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLRSAPRIVATEKEY_H #define _SOFTHSM_V2_OSSLRSAPRIVATEKEY_H #include "config.h" #include "RSAPrivateKey.h" #include class OSSLRSAPrivateKey : public RSAPrivateKey { public: // Constructors OSSLRSAPrivateKey(); OSSLRSAPrivateKey(const RSA* inRSA); // Destructor virtual ~OSSLRSAPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the RSA private key components virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setPQ(const ByteString& inPQ); virtual void setDP1(const ByteString& inDP1); virtual void setDQ1(const ByteString& inDQ1); virtual void setD(const ByteString& inD); // Setters for the RSA public key components virtual void setN(const ByteString& inN); virtual void setE(const ByteString& inE); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from OpenSSL representation virtual void setFromOSSL(const RSA* inRSA); // Retrieve the OpenSSL representation of the key RSA* getOSSLKey(); private: // The internal OpenSSL representation RSA* rsa; }; #endif // !_SOFTHSM_V2_OSSLRSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLCryptoFactory.h0000664000175000017500000000657512533040716016474 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLCryptoFactory.h This is an OpenSSL based cryptographic algorithm factory *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLCRYPTOFACTORY_H #define _SOFTHSM_V2_OSSLCRYPTOFACTORY_H #include "config.h" #include "CryptoFactory.h" #include "SymmetricAlgorithm.h" #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include "MacAlgorithm.h" #include "RNG.h" #include #ifdef WITH_GOST #include #include #endif class OSSLCryptoFactory : public CryptoFactory { public: // Return the one-and-only instance static OSSLCryptoFactory* i(); // This will destroy the one-and-only instance. static void reset(); #ifdef WITH_FIPS // Return the FIPS 140-2 selftest status virtual bool getFipsSelfTestStatus() const; #endif // Create a concrete instance of a symmetric algorithm virtual SymmetricAlgorithm* getSymmetricAlgorithm(SymAlgo::Type algorithm); // Create a concrete instance of an asymmetric algorithm virtual AsymmetricAlgorithm* getAsymmetricAlgorithm(AsymAlgo::Type algorithm); // Create a concrete instance of a hash algorithm virtual HashAlgorithm* getHashAlgorithm(HashAlgo::Type algorithm); // Create a concrete instance of a MAC algorithm virtual MacAlgorithm* getMacAlgorithm(MacAlgo::Type algorithm); // Get the global RNG (may be an unique RNG per thread) virtual RNG* getRNG(RNGImpl::Type name = RNGImpl::Default); // Destructor virtual ~OSSLCryptoFactory(); #ifdef WITH_GOST // The EVP_MD for GOST R 34.11-94 const EVP_MD *EVP_GOST_34_11; #endif private: // Constructor OSSLCryptoFactory(); // The one-and-only instance #ifdef HAVE_CXX11 static std::unique_ptr instance; #else static std::auto_ptr instance; #endif #ifdef WITH_FIPS // The FIPS 140-2 selftest status static bool FipsSelfTestStatus; #endif // The one-and-only RNG instance RNG* rng; #ifdef WITH_GOST // The GOST engine ENGINE *eg; #endif }; #endif // !_SOFTHSM_V2_OSSLCRYPTOFACTORY_H softhsm-2.0.0/src/lib/crypto/BotanAES.cpp0000664000175000017500000002121712533040716015100 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanAES.cpp Botan AES implementation *****************************************************************************/ #include "config.h" #include "BotanAES.h" #include #include #include #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) #include #endif // Wrap/Unwrap keys bool BotanAES::wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out) { // Check key bit length; AES only supports 128, 192 or 256 bit keys if ((key->getBitLen() != 128) && (key->getBitLen() != 192) && (key->getBitLen() != 256)) { ERROR_MSG("Invalid AES key length (%d bits)", key->getBitLen()); return false; } // Determine the wrapping mode if (mode == SymWrap::AES_KEYWRAP) { // RFC 3394 AES key wrap if (in.size() < 16) { ERROR_MSG("key data to wrap too small"); return false; } if ((in.size() % 8) != 0) { ERROR_MSG("key data to wrap not aligned"); return false; } #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector data(in.size()); memcpy(data.data(), in.const_byte_str(), in.size()); Botan::secure_vector wrapped; #else Botan::MemoryVector data(in.size()); memcpy(data.begin(), in.const_byte_str(), in.size()); Botan::SecureVector wrapped; #endif Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory(); try { wrapped = Botan::rfc3394_keywrap(data, botanKey, af); } #else try { wrapped = Botan::rfc3394_keywrap(data, botanKey); } #endif catch (...) { ERROR_MSG("AES key wrap failed"); return false; } out.resize(wrapped.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&out[0], wrapped.data(), out.size()); #else memcpy(&out[0], wrapped.begin(), out.size()); #endif return true; } #ifdef HAVE_AES_KEY_WRAP_PAD else if (mode == SymWrap::AES_KEYWRAP_PAD) { // RFC 5649 AES key wrap with pad #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector data(in.size()); memcpy(data.data(), in.const_byte_str(), in.size()); Botan::secure_vector wrapped; #else Botan::MemoryVector data(in.size()); memcpy(data.begin(), in.const_byte_str(), in.size()); Botan::SecureVector wrapped; #endif Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory(); try { wrapped = Botan::rfc5649_keywrap(data, botanKey, af); } #else try { wrapped = Botan::rfc5649_keywrap(data, botanKey); } #endif catch (...) { ERROR_MSG("AES key wrap failed"); return false; } out.resize(wrapped.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&out[0], wrapped.data(), out.size()); #else memcpy(&out[0], wrapped.begin(), out.size()); #endif return true; } #endif else { ERROR_MSG("unknown AES key wrap mode %i", mode); return false; } } bool BotanAES::unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out) { // Check key bit length; AES only supports 128, 192 or 256 bit keys if ((key->getBitLen() != 128) && (key->getBitLen() != 192) && (key->getBitLen() != 256)) { ERROR_MSG("Invalid AES key length (%d bits)", key->getBitLen()); return false; } // Determine the unwrapping mode if (mode == SymWrap::AES_KEYWRAP) { // RFC 3394 AES key wrap if (in.size() < 24) { ERROR_MSG("key data to unwrap too small"); return false; } if ((in.size() % 8) != 0) { ERROR_MSG("key data to unwrap not aligned"); return false; } #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector wrapped(in.size()); memcpy(wrapped.data(), in.const_byte_str(), in.size()); Botan::secure_vector unwrapped; #else Botan::MemoryVector wrapped(in.size()); memcpy(wrapped.begin(), in.const_byte_str(), in.size()); Botan::SecureVector unwrapped; #endif Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory(); try { unwrapped = Botan::rfc3394_keyunwrap(wrapped, botanKey, af); } #else try { unwrapped = Botan::rfc3394_keyunwrap(wrapped, botanKey); } #endif catch (...) { ERROR_MSG("AES key unwrap failed"); return false; } out.resize(unwrapped.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&out[0], unwrapped.data(), out.size()); #else memcpy(&out[0], unwrapped.begin(), out.size()); #endif return true; } #ifdef HAVE_AES_KEY_WRAP_PAD else if (mode == SymWrap::AES_KEYWRAP_PAD) { // RFC 5649 AES key wrap with wrap if (in.size() < 16) { ERROR_MSG("key data to unwrap too small"); return false; } if ((in.size() % 8) != 0) { ERROR_MSG("key data to unwrap not aligned"); return false; } #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector wrapped(in.size()); memcpy(wrapped.data(), in.const_byte_str(), in.size()); Botan::secure_vector unwrapped; #else Botan::MemoryVector wrapped(in.size()); memcpy(wrapped.begin(), in.const_byte_str(), in.size()); Botan::SecureVector unwrapped; #endif Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size()); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory(); try { unwrapped = Botan::rfc5649_keyunwrap(wrapped, botanKey, af); } #else try { unwrapped = Botan::rfc5649_keyunwrap(wrapped, botanKey); } #endif catch (...) { ERROR_MSG("AES key unwrap failed"); return false; } out.resize(unwrapped.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&out[0], unwrapped.data(), out.size()); #else memcpy(&out[0], unwrapped.begin(), out.size()); #endif return true; } #endif else { ERROR_MSG("unknown AES key wrap mode %i", mode); return false; } } std::string BotanAES::getCipher() const { std::string algo; std::string mode; std::string padding; if (currentKey == NULL) return ""; // Check currentKey bit length; AES only supports 128, 192 or 256 bit keys switch (currentKey->getBitLen()) { case 128: algo = "AES-128"; break; case 192: algo = "AES-192"; break; case 256: algo = "AES-256"; break; default: ERROR_MSG("Invalid AES currentKey length (%d bits)", currentKey->getBitLen()); return ""; } // Determine the cipher mode switch (currentCipherMode) { case SymMode::CBC: mode = "CBC"; break; case SymMode::ECB: mode = "ECB"; break; default: ERROR_MSG("Invalid AES cipher mode %i", currentCipherMode); return ""; } // Check padding mode if (currentPaddingMode) { padding = "PKCS7"; } else { padding = "NoPadding"; } return algo + "/" + mode + "/" + padding; } size_t BotanAES::getBlockSize() const { // The block size is 128 bits return 128 >> 3; } softhsm-2.0.0/src/lib/crypto/BotanECDHPublicKey.cpp0000664000175000017500000000721212533040716017002 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDHPublicKey.cpp Botan ECDH public key class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDHPublicKey.h" #include "BotanUtil.h" #include // Constructors BotanECDHPublicKey::BotanECDHPublicKey() { eckey = NULL; } BotanECDHPublicKey::BotanECDHPublicKey(const Botan::ECDH_PublicKey* inECKEY) { eckey = NULL; setFromBotan(inECKEY); } // Destructor BotanECDHPublicKey::~BotanECDHPublicKey() { delete eckey; } // The type /*static*/ const char* BotanECDHPublicKey::type = "Botan ECDH Public Key"; // Get the base point order length unsigned long BotanECDHPublicKey::getOrderLength() const { try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); return group.get_order().bytes(); } catch (...) { ERROR_MSG("Can't get EC group for order length"); return 0; } } // Set from Botan representation void BotanECDHPublicKey::setFromBotan(const Botan::ECDH_PublicKey* inECKEY) { ByteString inEC = BotanUtil::ecGroup2ByteString(inECKEY->domain()); setEC(inEC); ByteString inQ = BotanUtil::ecPoint2ByteString(inECKEY->public_point()); setQ(inQ); } // Check if the key is of the given type bool BotanECDHPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the ECDH public key components void BotanECDHPublicKey::setEC(const ByteString& inEC) { ECPublicKey::setEC(inEC); if (eckey) { delete eckey; eckey = NULL; } } void BotanECDHPublicKey::setQ(const ByteString& inQ) { ECPublicKey::setQ(inQ); if (eckey) { delete eckey; eckey = NULL; } } // Retrieve the Botan representation of the key Botan::ECDH_PublicKey* BotanECDHPublicKey::getBotanKey() { if (!eckey) { createBotanKey(); } return eckey; } // Create the Botan representation of the key void BotanECDHPublicKey::createBotanKey() { if (ec.size() != 0 && q.size() != 0) { if (eckey) { delete eckey; eckey = NULL; } try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); Botan::PointGFp point = BotanUtil::byteString2ECPoint(q, group); eckey = new Botan::ECDH_PublicKey(group, point); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } #endif softhsm-2.0.0/src/lib/crypto/OSSLGOSTPublicKey.h0000664000175000017500000000506212533040716016236 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTPublicKey.h OpenSSL GOST R 34.10-2001 public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLGOSTPUBLICKEY_H #define _SOFTHSM_V2_OSSLGOSTPUBLICKEY_H #include "config.h" #include "GOSTPublicKey.h" #include class OSSLGOSTPublicKey : public GOSTPublicKey { public: // Constructors OSSLGOSTPublicKey(); OSSLGOSTPublicKey(const EVP_PKEY* inPKEY); // Destructor virtual ~OSSLGOSTPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the output length virtual unsigned long getOutputLength() const; // Setters for the GOST public key components virtual void setEC(const ByteString& inEC); virtual void setQ(const ByteString& inQ); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); // Set from OpenSSL representation virtual void setFromOSSL(const EVP_PKEY* pkey); // Retrieve the OpenSSL representation of the key EVP_PKEY* getOSSLKey(); private: // The internal OpenSSL representation EVP_PKEY* pkey; }; #endif // !_SOFTHSM_V2_OSSLDSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanDHPublicKey.h0000664000175000017500000000503412533040716016237 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDHPublicKey.h Botan Diffie-Hellman public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDHPUBLICKEY_H #define _SOFTHSM_V2_BOTANDHPUBLICKEY_H #include "config.h" #include "DHPublicKey.h" #include class BotanDHPublicKey : public DHPublicKey { public: // Constructors BotanDHPublicKey(); BotanDHPublicKey(const Botan::DH_PublicKey* inDH); // Destructor virtual ~BotanDHPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DH public key components virtual void setP(const ByteString& inP); virtual void setG(const ByteString& inG); virtual void setY(const ByteString& inY); // Set from Botan representation virtual void setFromBotan(const Botan::DH_PublicKey* inDH); // Retrieve the Botan representation of the key Botan::DH_PublicKey* getBotanKey(); private: // The internal Botan representation Botan::DH_PublicKey* dh; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANDHPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLRSA.cpp0000664000175000017500000007637012533040716014644 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSA.cpp OpenSSL RSA asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLRSA.h" #include "CryptoFactory.h" #include "RSAParameters.h" #include "OSSLRSAKeyPair.h" #include #include #include #include // Constructor OSSLRSA::OSSLRSA() { pCurrentHash = NULL; pSecondHash = NULL; sLen = 0; } // Destructor OSSLRSA::~OSSLRSA() { if (pCurrentHash != NULL) { delete pCurrentHash; } if (pSecondHash != NULL) { delete pSecondHash; } } // Signing functions bool OSSLRSA::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (mechanism == AsymMech::RSA_PKCS) { // Separate implementation for RSA PKCS #1 signing without hash computation // Check if the private key is the right type if (!privateKey->isOfType(OSSLRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // In case of PKCS #1 signing the length of the input data may not exceed 40% of the // modulus size OSSLRSAPrivateKey* osslKey = (OSSLRSAPrivateKey*) privateKey; size_t allowedLen = osslKey->getN().size() - 11; if (dataToSign.size() > allowedLen) { ERROR_MSG("Data to sign exceeds maximum for PKCS #1 signature"); return false; } // Perform the signature operation signature.resize(osslKey->getN().size()); RSA* rsa = osslKey->getOSSLKey(); if (!RSA_blinding_on(rsa, NULL)) { ERROR_MSG("Failed to turn on blinding for OpenSSL RSA key"); return false; } int sigLen = RSA_private_encrypt(dataToSign.size(), (unsigned char*) dataToSign.const_byte_str(), &signature[0], rsa, RSA_PKCS1_PADDING); RSA_blinding_off(rsa); if (sigLen == -1) { ERROR_MSG("An error occurred while performing a PKCS #1 signature"); return false; } signature.resize(sigLen); return true; } else if (mechanism == AsymMech::RSA) { // Separate implementation for raw RSA signing // Check if the private key is the right type if (!privateKey->isOfType(OSSLRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // In case of raw RSA, the length of the input data must match the length of the modulus OSSLRSAPrivateKey* osslKey = (OSSLRSAPrivateKey*) privateKey; if (dataToSign.size() != osslKey->getN().size()) { ERROR_MSG("Size of data to sign does not match the modulus size"); return false; } // Perform the signature operation signature.resize(osslKey->getN().size()); RSA* rsa = osslKey->getOSSLKey(); if (!RSA_blinding_on(rsa, NULL)) { ERROR_MSG("Failed to turn on blinding for OpenSSL RSA key"); return false; } int sigLen = RSA_private_encrypt(dataToSign.size(), (unsigned char*) dataToSign.const_byte_str(), &signature[0], rsa, RSA_NO_PADDING); RSA_blinding_off(rsa); if (sigLen == -1) { ERROR_MSG("An error occurred while performing a raw RSA signature"); return false; } signature.resize(sigLen); return true; } else { // Call default implementation return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen); } } bool OSSLRSA::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!privateKey->isOfType(OSSLRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } HashAlgo::Type hash1 = HashAlgo::Unknown; HashAlgo::Type hash2 = HashAlgo::Unknown; switch (mechanism) { case AsymMech::RSA_MD5_PKCS: hash1 = HashAlgo::MD5; break; case AsymMech::RSA_SHA1_PKCS: hash1 = HashAlgo::SHA1; break; case AsymMech::RSA_SHA224_PKCS: hash1 = HashAlgo::SHA224; break; case AsymMech::RSA_SHA256_PKCS: hash1 = HashAlgo::SHA256; break; case AsymMech::RSA_SHA384_PKCS: hash1 = HashAlgo::SHA384; break; case AsymMech::RSA_SHA512_PKCS: hash1 = HashAlgo::SHA512; break; case AsymMech::RSA_SHA1_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA1 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA1) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-20)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } hash1 = HashAlgo::SHA1; break; case AsymMech::RSA_SHA224_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA224 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA224) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-28)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } hash1 = HashAlgo::SHA224; break; case AsymMech::RSA_SHA256_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA256 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA256) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-32)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } hash1 = HashAlgo::SHA256; break; case AsymMech::RSA_SHA384_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA384 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA384) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-48)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } hash1 = HashAlgo::SHA384; break; case AsymMech::RSA_SHA512_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA512 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA512) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((privateKey->getBitLength()+6)/8-2-64)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, privateKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } hash1 = HashAlgo::SHA512; break; case AsymMech::RSA_SSL: hash1 = HashAlgo::MD5; hash2 = HashAlgo::SHA1; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } pCurrentHash = CryptoFactory::i()->getHashAlgorithm(hash1); if (pCurrentHash == NULL || !pCurrentHash->hashInit()) { if (pCurrentHash != NULL) { delete pCurrentHash; pCurrentHash = NULL; } ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } if (hash2 != HashAlgo::Unknown) { pSecondHash = CryptoFactory::i()->getHashAlgorithm(hash2); if (pSecondHash == NULL || !pSecondHash->hashInit()) { delete pCurrentHash; pCurrentHash = NULL; if (pSecondHash != NULL) { delete pSecondHash; pSecondHash = NULL; } ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } } return true; } bool OSSLRSA::signUpdate(const ByteString& dataToSign) { if (!AsymmetricAlgorithm::signUpdate(dataToSign)) { return false; } if (!pCurrentHash->hashUpdate(dataToSign)) { delete pCurrentHash; pCurrentHash = NULL; ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } if ((pSecondHash != NULL) && !pSecondHash->hashUpdate(dataToSign)) { delete pCurrentHash; pCurrentHash = NULL; delete pSecondHash; pSecondHash = NULL; ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLRSA::signFinal(ByteString& signature) { // Save necessary state before calling super class signFinal OSSLRSAPrivateKey* pk = (OSSLRSAPrivateKey*) currentPrivateKey; AsymMech::Type mechanism = currentMechanism; if (!AsymmetricAlgorithm::signFinal(signature)) { return false; } ByteString firstHash, secondHash; bool bFirstResult = pCurrentHash->hashFinal(firstHash); bool bSecondResult = (pSecondHash != NULL) ? pSecondHash->hashFinal(secondHash) : true; delete pCurrentHash; pCurrentHash = NULL; if (pSecondHash != NULL) { delete pSecondHash; pSecondHash = NULL; } if (!bFirstResult || !bSecondResult) { return false; } ByteString digest = firstHash + secondHash; // Resize the data block for the signature to the modulus size of the key signature.resize(pk->getN().size()); // Determine the signature NID type int type = 0; bool isPSS = false; const EVP_MD* hash = NULL; switch (mechanism) { case AsymMech::RSA_MD5_PKCS: type = NID_md5; break; case AsymMech::RSA_SHA1_PKCS: type = NID_sha1; break; case AsymMech::RSA_SHA224_PKCS: type = NID_sha224; break; case AsymMech::RSA_SHA256_PKCS: type = NID_sha256; break; case AsymMech::RSA_SHA384_PKCS: type = NID_sha384; break; case AsymMech::RSA_SHA512_PKCS: type = NID_sha512; break; case AsymMech::RSA_SHA1_PKCS_PSS: isPSS = true; hash = EVP_sha1(); break; case AsymMech::RSA_SHA224_PKCS_PSS: isPSS = true; hash = EVP_sha224(); break; case AsymMech::RSA_SHA256_PKCS_PSS: isPSS = true; hash = EVP_sha256(); break; case AsymMech::RSA_SHA384_PKCS_PSS: isPSS = true; hash = EVP_sha384(); break; case AsymMech::RSA_SHA512_PKCS_PSS: isPSS = true; hash = EVP_sha512(); break; case AsymMech::RSA_SSL: type = NID_md5_sha1; break; default: break; } // Perform the signature operation unsigned int sigLen = signature.size(); RSA* rsa = pk->getOSSLKey(); if (!RSA_blinding_on(rsa, NULL)) { ERROR_MSG("Failed to turn blinding on for OpenSSL RSA key"); return false; } bool rv; if (isPSS) { ByteString em; em.resize(pk->getN().size()); rv = (RSA_padding_add_PKCS1_PSS(pk->getOSSLKey(), &em[0], &digest[0], hash, sLen) == 1); if (!rv) { ERROR_MSG("RSA PSS padding failed (0x%08X)", ERR_get_error()); } else { int result = RSA_private_encrypt(em.size(), &em[0], &signature[0], pk->getOSSLKey(), RSA_NO_PADDING); if (result >= 0) { sigLen = result; rv = true; } else { rv = false; ERROR_MSG("RSA private encrypt failed (0x%08X)", ERR_get_error()); } } } else { rv = (RSA_sign(type, &digest[0], digest.size(), &signature[0], &sigLen, pk->getOSSLKey()) == 1); } RSA_blinding_off(rsa); signature.resize(sigLen); return rv; } // Verification functions bool OSSLRSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (mechanism == AsymMech::RSA_PKCS) { // Specific implementation for PKCS #1 only verification; originalData is assumed to contain // a digestInfo structure and verification is performed by comparing originalData to the data // recovered from the signature // Check if the public key is the right type if (!publicKey->isOfType(OSSLRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // Perform the RSA public key operation OSSLRSAPublicKey* osslKey = (OSSLRSAPublicKey*) publicKey; ByteString recoveredData; recoveredData.resize(osslKey->getN().size()); RSA* rsa = osslKey->getOSSLKey(); int retLen = RSA_public_decrypt(signature.size(), (unsigned char*) signature.const_byte_str(), &recoveredData[0], rsa, RSA_PKCS1_PADDING); if (retLen == -1) { ERROR_MSG("Public key operation failed"); return false; } recoveredData.resize(retLen); return (originalData == recoveredData); } else if (mechanism == AsymMech::RSA) { // Specific implementation for raw RSA verifiction; originalData is assumed to contain the // full input data used to compute the signature and verification is performed by comparing // originalData to the data recovered from the signature // Check if the public key is the right type if (!publicKey->isOfType(OSSLRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // Perform the RSA public key operation OSSLRSAPublicKey* osslKey = (OSSLRSAPublicKey*) publicKey; ByteString recoveredData; recoveredData.resize(osslKey->getN().size()); RSA* rsa = osslKey->getOSSLKey(); int retLen = RSA_public_decrypt(signature.size(), (unsigned char*) signature.const_byte_str(), &recoveredData[0], rsa, RSA_NO_PADDING); if (retLen == -1) { ERROR_MSG("Public key operation failed"); return false; } recoveredData.resize(retLen); return (originalData == recoveredData); } else { // Call the generic function return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen); } } bool OSSLRSA::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen)) { return false; } // Check if the public key is the right type if (!publicKey->isOfType(OSSLRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } HashAlgo::Type hash1 = HashAlgo::Unknown; HashAlgo::Type hash2 = HashAlgo::Unknown; switch (mechanism) { case AsymMech::RSA_MD5_PKCS: hash1 = HashAlgo::MD5; break; case AsymMech::RSA_SHA1_PKCS: hash1 = HashAlgo::SHA1; break; case AsymMech::RSA_SHA224_PKCS: hash1 = HashAlgo::SHA224; break; case AsymMech::RSA_SHA256_PKCS: hash1 = HashAlgo::SHA256; break; case AsymMech::RSA_SHA384_PKCS: hash1 = HashAlgo::SHA384; break; case AsymMech::RSA_SHA512_PKCS: hash1 = HashAlgo::SHA512; break; case AsymMech::RSA_SHA1_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA1 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA1) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-20)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } hash1 = HashAlgo::SHA1; break; case AsymMech::RSA_SHA224_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA224 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA224) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-28)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } hash1 = HashAlgo::SHA224; break; case AsymMech::RSA_SHA256_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA256 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA256) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-32)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } hash1 = HashAlgo::SHA256; break; case AsymMech::RSA_SHA384_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA384 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA384) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-48)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } hash1 = HashAlgo::SHA384; break; case AsymMech::RSA_SHA512_PKCS_PSS: if (param == NULL || paramLen != sizeof(RSA_PKCS_PSS_PARAMS) || ((RSA_PKCS_PSS_PARAMS*) param)->hashAlg != HashAlgo::SHA512 || ((RSA_PKCS_PSS_PARAMS*) param)->mgf != AsymRSAMGF::MGF1_SHA512) { ERROR_MSG("Invalid parameters"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } sLen = ((RSA_PKCS_PSS_PARAMS*) param)->sLen; if (sLen > ((publicKey->getBitLength()+6)/8-2-64)) { ERROR_MSG("sLen (%lu) is too large for current key size (%lu)", (unsigned long)sLen, publicKey->getBitLength()); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } hash1 = HashAlgo::SHA512; break; case AsymMech::RSA_SSL: hash1 = HashAlgo::MD5; hash2 = HashAlgo::SHA1; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } pCurrentHash = CryptoFactory::i()->getHashAlgorithm(hash1); if (pCurrentHash == NULL || !pCurrentHash->hashInit()) { if (pCurrentHash != NULL) { delete pCurrentHash; pCurrentHash = NULL; } ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } if (hash2 != HashAlgo::Unknown) { pSecondHash = CryptoFactory::i()->getHashAlgorithm(hash2); if (pSecondHash == NULL || !pSecondHash->hashInit()) { delete pCurrentHash; pCurrentHash = NULL; if (pSecondHash != NULL) { delete pSecondHash; pSecondHash = NULL; } ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } } return true; } bool OSSLRSA::verifyUpdate(const ByteString& originalData) { if (!AsymmetricAlgorithm::verifyUpdate(originalData)) { return false; } if (!pCurrentHash->hashUpdate(originalData)) { delete pCurrentHash; pCurrentHash = NULL; ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } if ((pSecondHash != NULL) && !pSecondHash->hashUpdate(originalData)) { delete pCurrentHash; pCurrentHash = NULL; delete pSecondHash; pSecondHash = NULL; ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLRSA::verifyFinal(const ByteString& signature) { // Save necessary state before calling super class verifyFinal OSSLRSAPublicKey* pk = (OSSLRSAPublicKey*) currentPublicKey; AsymMech::Type mechanism = currentMechanism; if (!AsymmetricAlgorithm::verifyFinal(signature)) { return false; } ByteString firstHash, secondHash; bool bFirstResult = pCurrentHash->hashFinal(firstHash); bool bSecondResult = (pSecondHash != NULL) ? pSecondHash->hashFinal(secondHash) : true; delete pCurrentHash; pCurrentHash = NULL; if (pSecondHash != NULL) { delete pSecondHash; pSecondHash = NULL; } if (!bFirstResult || !bSecondResult) { return false; } ByteString digest = firstHash + secondHash; // Determine the signature NID type int type = 0; bool isPSS = false; const EVP_MD* hash = NULL; switch (mechanism) { case AsymMech::RSA_MD5_PKCS: type = NID_md5; break; case AsymMech::RSA_SHA1_PKCS: type = NID_sha1; break; case AsymMech::RSA_SHA224_PKCS: type = NID_sha224; break; case AsymMech::RSA_SHA256_PKCS: type = NID_sha256; break; case AsymMech::RSA_SHA384_PKCS: type = NID_sha384; break; case AsymMech::RSA_SHA512_PKCS: type = NID_sha512; break; case AsymMech::RSA_SHA1_PKCS_PSS: isPSS = true; hash = EVP_sha1(); break; case AsymMech::RSA_SHA224_PKCS_PSS: isPSS = true; hash = EVP_sha224(); break; case AsymMech::RSA_SHA256_PKCS_PSS: isPSS = true; hash = EVP_sha256(); break; case AsymMech::RSA_SHA384_PKCS_PSS: isPSS = true; hash = EVP_sha384(); break; case AsymMech::RSA_SHA512_PKCS_PSS: isPSS = true; hash = EVP_sha512(); break; case AsymMech::RSA_SSL: type = NID_md5_sha1; break; default: break; } // Perform the verify operation bool rv; if (isPSS) { ByteString plain; plain.resize(pk->getN().size()); int result = RSA_public_decrypt(signature.size(), (unsigned char*) signature.const_byte_str(), &plain[0], pk->getOSSLKey(), RSA_NO_PADDING); if (result < 0) { rv = false; ERROR_MSG("RSA public decrypt failed (0x%08X)", ERR_get_error()); } else { plain.resize(result); result = RSA_verify_PKCS1_PSS(pk->getOSSLKey(), &digest[0], hash, &plain[0], sLen); if (result == 1) { rv = true; } else { rv = false; ERROR_MSG("RSA PSS verify failed (0x%08X)", ERR_get_error()); } } } else { rv = (RSA_verify(type, &digest[0], digest.size(), (unsigned char*) signature.const_byte_str(), signature.size(), pk->getOSSLKey()) == 1); if (!rv) ERROR_MSG("RSA verify failed (0x%08X)", ERR_get_error()); } return rv; } // Encryption functions bool OSSLRSA::encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding) { // Check if the public key is the right type if (!publicKey->isOfType(OSSLRSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // Retrieve the OpenSSL key object RSA* rsa = ((OSSLRSAPublicKey*) publicKey)->getOSSLKey(); // Check the data and padding algorithm int osslPadding = 0; if (padding == AsymMech::RSA_PKCS) { // The size of the input data cannot be more than the modulus // length of the key - 11 if (data.size() > (size_t) (RSA_size(rsa) - 11)) { ERROR_MSG("Too much data supplied for RSA PKCS #1 encryption"); return false; } osslPadding = RSA_PKCS1_PADDING; } else if (padding == AsymMech::RSA_PKCS_OAEP) { // The size of the input data cannot be more than the modulus // length of the key - 41 if (data.size() > (size_t) (RSA_size(rsa) - 41)) { ERROR_MSG("Too much data supplied for RSA OAEP encryption"); return false; } osslPadding = RSA_PKCS1_OAEP_PADDING; } else if (padding == AsymMech::RSA) { // The size of the input data should be exactly equal to the modulus length if (data.size() != (size_t) RSA_size(rsa)) { ERROR_MSG("Incorrect amount of input data supplied for raw RSA encryption"); return false; } osslPadding = RSA_NO_PADDING; } else { ERROR_MSG("Invalid padding mechanism supplied (%i)", padding); return false; } // Perform the RSA operation encryptedData.resize(RSA_size(rsa)); if (RSA_public_encrypt(data.size(), (unsigned char*) data.const_byte_str(), &encryptedData[0], rsa, osslPadding) == -1) { ERROR_MSG("RSA public key encryption failed (0x%08X)", ERR_get_error()); return false; } return true; } // Decryption functions bool OSSLRSA::decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding) { // Check if the private key is the right type if (!privateKey->isOfType(OSSLRSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // Retrieve the OpenSSL key object RSA* rsa = ((OSSLRSAPrivateKey*) privateKey)->getOSSLKey(); // Check the input size if (encryptedData.size() != (size_t) RSA_size(rsa)) { ERROR_MSG("Invalid amount of input data supplied for RSA decryption"); return false; } // Determine the OpenSSL padding algorithm int osslPadding = 0; switch (padding) { case AsymMech::RSA_PKCS: osslPadding = RSA_PKCS1_PADDING; break; case AsymMech::RSA_PKCS_OAEP: osslPadding = RSA_PKCS1_OAEP_PADDING; break; case AsymMech::RSA: osslPadding = RSA_NO_PADDING; break; default: ERROR_MSG("Invalid padding mechanism supplied (%i)", padding); return false; } // Perform the RSA operation data.resize(RSA_size(rsa)); int decSize = RSA_private_decrypt(encryptedData.size(), (unsigned char*) encryptedData.const_byte_str(), &data[0], rsa, osslPadding); if (decSize == -1) { ERROR_MSG("RSA private key decryption failed (0x%08X)", ERR_get_error()); return false; } data.resize(decSize); return true; } // Key factory bool OSSLRSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(RSAParameters::type)) { ERROR_MSG("Invalid parameters supplied for RSA key generation"); return false; } RSAParameters* params = (RSAParameters*) parameters; if (params->getBitLength() < getMinKeySize() || params->getBitLength() > getMaxKeySize()) { ERROR_MSG("This RSA key size (%lu) is not supported", params->getBitLength()); return false; } if (params->getBitLength() < 1024) { WARNING_MSG("Using an RSA key size < 1024 bits is not recommended"); } // Retrieve the desired public exponent unsigned long e = params->getE().long_val(); // Check the public exponent if ((e == 0) || (e % 2 != 1)) { ERROR_MSG("Invalid RSA public exponent %d", e); return false; } // Generate the key-pair RSA* rsa = RSA_generate_key(params->getBitLength(), e, NULL, NULL); // Check if the key was successfully generated if (rsa == NULL) { ERROR_MSG("RSA key generation failed (0x%08X)", ERR_get_error()); return false; } // Create an asymmetric key-pair object to return OSSLRSAKeyPair* kp = new OSSLRSAKeyPair(); ((OSSLRSAPublicKey*) kp->getPublicKey())->setFromOSSL(rsa); ((OSSLRSAPrivateKey*) kp->getPrivateKey())->setFromOSSL(rsa); *ppKeyPair = kp; // Release the key RSA_free(rsa); return true; } unsigned long OSSLRSA::getMinKeySize() { #ifdef WITH_FIPS // OPENSSL_RSA_FIPS_MIN_MODULUS_BITS is 1024 return 1024; #else return 512; #endif } unsigned long OSSLRSA::getMaxKeySize() { return OPENSSL_RSA_MAX_MODULUS_BITS; } bool OSSLRSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); OSSLRSAKeyPair* kp = new OSSLRSAKeyPair(); bool rv = true; if (!((RSAPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((RSAPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool OSSLRSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLRSAPublicKey* pub = new OSSLRSAPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool OSSLRSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLRSAPrivateKey* priv = new OSSLRSAPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* OSSLRSA::newPublicKey() { return (PublicKey*) new OSSLRSAPublicKey(); } PrivateKey* OSSLRSA::newPrivateKey() { return (PrivateKey*) new OSSLRSAPrivateKey(); } AsymmetricParameters* OSSLRSA::newParameters() { return (AsymmetricParameters*) new RSAParameters(); } bool OSSLRSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } RSAParameters* params = new RSAParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } softhsm-2.0.0/src/lib/crypto/RSAPublicKey.cpp0000664000175000017500000000540112533040716015736 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSAPublicKey.cpp RSA public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "RSAPublicKey.h" #include // Set the type /*static*/ const char* RSAPublicKey::type = "Abstract RSA public key"; // Check if the key is of the given type bool RSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long RSAPublicKey::getBitLength() const { return getN().bits(); } // Get the output length unsigned long RSAPublicKey::getOutputLength() const { // Also handle odd number of bits (bits % 8 != 0) return (getBitLength() + 7) / 8; } // Setters for the RSA public key components void RSAPublicKey::setN(const ByteString& inN) { n = inN; } void RSAPublicKey::setE(const ByteString& inE) { e = inE; } // Getters for the RSA public key components const ByteString& RSAPublicKey::getN() const { return n; } const ByteString& RSAPublicKey::getE() const { return e; } // Serialisation ByteString RSAPublicKey::serialise() const { return n.serialise() + e.serialise(); } bool RSAPublicKey::deserialise(ByteString& serialised) { ByteString dN = ByteString::chainDeserialise(serialised); ByteString dE = ByteString::chainDeserialise(serialised); if ((dN.size() == 0) || (dE.size() == 0)) { return false; } setN(dN); setE(dE); return true; } softhsm-2.0.0/src/lib/crypto/OSSLDH.h0000664000175000017500000000677512533040716014161 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDH.h OpenSSL Diffie-Hellman asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDH_H #define _SOFTHSM_V2_OSSLDH_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class OSSLDH : public AsymmetricAlgorithm { public: // Destructor virtual ~OSSLDH() { } // Signing functions virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool generateParameters(AsymmetricParameters** ppParams, void* parameters = NULL, RNG* rng = NULL); virtual bool deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: }; #endif // !_SOFTHSM_V2_OSSLDH_H softhsm-2.0.0/src/lib/crypto/BotanSHA384.cpp0000664000175000017500000000334412533040716015343 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA384.cpp Botan SHA384 implementation *****************************************************************************/ #include "config.h" #include "BotanSHA384.h" #include int BotanSHA384::getHashSize() { return 48; } Botan::HashFunction* BotanSHA384::getHash() const { return new Botan::SHA_384(); } softhsm-2.0.0/src/lib/crypto/OSSLGOSTR3411.cpp0000664000175000017500000000342612533040716015416 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTR3411.h OpenSSL GOST R 34.11-94 implementation *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "OSSLGOSTR3411.h" #include "OSSLCryptoFactory.h" #include int OSSLGOSTR3411::getHashSize() { return 32; } const EVP_MD* OSSLGOSTR3411::getEVPHash() const { return OSSLCryptoFactory::i()->EVP_GOST_34_11; } #endif softhsm-2.0.0/src/lib/crypto/BotanDES.h0000664000175000017500000000443312533040716014551 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDES.h Botan (3)DES implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDES_H #define _SOFTHSM_V2_BOTANDES_H #include #include "config.h" #include "BotanSymmetricAlgorithm.h" class BotanDES : public BotanSymmetricAlgorithm { public: // Destructor virtual ~BotanDES() { } // Wrap/Unwrap keys virtual bool wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); virtual bool unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); // Generate key virtual bool generateKey(SymmetricKey& key, RNG* rng = NULL); // Return the block size virtual size_t getBlockSize() const; protected: // Return the right Botan cipher for the operation virtual std::string getCipher() const; }; #endif // !_SOFTHSM_V2_BOTANDES_H softhsm-2.0.0/src/lib/crypto/BotanRSAKeyPair.h0000664000175000017500000000445512533040716016054 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSAKeyPair.h Botan RSA key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANRSAKEYPAIR_H #define _SOFTHSM_V2_BOTANRSAKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "BotanRSAPublicKey.h" #include "BotanRSAPrivateKey.h" class BotanRSAKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(BotanRSAPublicKey& publicKey); // Set the private key void setPrivateKey(BotanRSAPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key BotanRSAPublicKey pubKey; // The private key BotanRSAPrivateKey privKey; }; #endif // !_SOFTHSM_V2_BOTANRSAKEYPAIR_H softhsm-2.0.0/src/lib/crypto/OSSLRNG.cpp0000664000175000017500000000355512533040716014640 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRNG.cpp OpenSSL random number generator class *****************************************************************************/ #include "config.h" #include "OSSLRNG.h" #include // Generate random data bool OSSLRNG::generateRandom(ByteString& data, const size_t len) { data.wipe(len); if (len == 0) return true; return RAND_bytes(&data[0], len) == 1; } // Seed the random pool void OSSLRNG::seed(ByteString& seedData) { RAND_seed(seedData.byte_str(), seedData.size()); } softhsm-2.0.0/src/lib/crypto/OSSLDSAPublicKey.h0000664000175000017500000000464112533040716016073 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSAPublicKey.h OpenSSL DSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDSAPUBLICKEY_H #define _SOFTHSM_V2_OSSLDSAPUBLICKEY_H #include "config.h" #include "DSAPublicKey.h" #include class OSSLDSAPublicKey : public DSAPublicKey { public: // Constructors OSSLDSAPublicKey(); OSSLDSAPublicKey(const DSA* inDSA); // Destructor virtual ~OSSLDSAPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DSA public key components virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setG(const ByteString& inG); virtual void setY(const ByteString& inY); // Set from OpenSSL representation virtual void setFromOSSL(const DSA* inDSA); // Retrieve the OpenSSL representation of the key DSA* getOSSLKey(); private: // The internal OpenSSL representation DSA* dsa; }; #endif // !_SOFTHSM_V2_OSSLDSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanGOSTPublicKey.h0000664000175000017500000000550412533040716016522 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTPublicKey.h Botan GOST R 34.11-2001 public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANGOSTPUBLICKEY_H #define _SOFTHSM_V2_BOTANGOSTPUBLICKEY_H #include "config.h" #include "GOSTPublicKey.h" #include class BotanGOSTPublicKey : public GOSTPublicKey { public: // Constructors BotanGOSTPublicKey(); BotanGOSTPublicKey(const Botan::GOST_3410_PublicKey* inECKEY); // Destructor virtual ~BotanGOSTPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the output length virtual unsigned long getOutputLength() const; // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the GOST public key components virtual void setEC(const ByteString& inEC); virtual void setQ(const ByteString& inQ); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); // Set from Botan representation virtual void setFromBotan(const Botan::GOST_3410_PublicKey* inECKEY); // Retrieve the Botan representation of the key Botan::GOST_3410_PublicKey* getBotanKey(); private: // The internal Botan representation Botan::GOST_3410_PublicKey* eckey; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANGOSTPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanECDHKeyPair.h0000664000175000017500000000447112533040716016130 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDHKeyPair.h Botan ECDH key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDHKEYPAIR_H #define _SOFTHSM_V2_BOTANECDHKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "BotanECDHPublicKey.h" #include "BotanECDHPrivateKey.h" class BotanECDHKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(BotanECDHPublicKey& publicKey); // Set the private key void setPrivateKey(BotanECDHPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key BotanECDHPublicKey pubKey; // The private key BotanECDHPrivateKey privKey; }; #endif // !_SOFTHSM_V2_BOTANECDHKEYPAIR_H softhsm-2.0.0/src/lib/crypto/OSSLDHPrivateKey.h0000664000175000017500000000506512533040716016154 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDHPrivateKey.h OpenSSL Diffie-Hellman private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDHPRIVATEKEY_H #define _SOFTHSM_V2_OSSLDHPRIVATEKEY_H #include "config.h" #include "DHPrivateKey.h" #include class OSSLDHPrivateKey : public DHPrivateKey { public: // Constructors OSSLDHPrivateKey(); OSSLDHPrivateKey(const DH* inDH); // Destructor virtual ~OSSLDHPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DH private key components virtual void setX(const ByteString& inX); // Setters for the DH public key components virtual void setP(const ByteString& inP); virtual void setG(const ByteString& inG); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from OpenSSL representation virtual void setFromOSSL(const DH* inDH); // Retrieve the OpenSSL representation of the key DH* getOSSLKey(); private: // The internal OpenSSL representation DH* dh; }; #endif // !_SOFTHSM_V2_OSSLDHPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/MacAlgorithm.cpp0000664000175000017500000000552712533040716016061 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** MacAlgorithm.cpp Base class for MAC algorithm classes *****************************************************************************/ #include "MacAlgorithm.h" #include #include MacAlgorithm::MacAlgorithm() { currentOperation = NONE; currentKey = NULL; } bool MacAlgorithm::signInit(const SymmetricKey* key) { if ((key == NULL) || (currentOperation != NONE)) { return false; } currentKey = key; currentOperation = SIGN; return true; } bool MacAlgorithm::signUpdate(const ByteString& /*dataToSign*/) { if (currentOperation != SIGN) { return false; } return true; } bool MacAlgorithm::signFinal(ByteString& /*signature*/) { if (currentOperation != SIGN) { return false; } currentOperation = NONE; currentKey = NULL; return true; } bool MacAlgorithm::verifyInit(const SymmetricKey* key) { if ((key == NULL) || (currentOperation != NONE)) { return false; } currentOperation = VERIFY; currentKey = key; return true; } bool MacAlgorithm::verifyUpdate(const ByteString& /*originalData*/) { if (currentOperation != VERIFY) { return false; } return true; } bool MacAlgorithm::verifyFinal(ByteString& /*signature*/) { if (currentOperation != VERIFY) { return false; } currentOperation = NONE; currentKey = NULL; return true; } unsigned long MacAlgorithm::getMinKeySize() { return 0; } unsigned long MacAlgorithm::getMaxKeySize() { return 0; } void MacAlgorithm::recycleKey(SymmetricKey* toRecycle) { delete toRecycle; } softhsm-2.0.0/src/lib/crypto/OSSLSHA512.cpp0000664000175000017500000000326112533040716015047 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA512.h OpenSSL SHA512 implementation *****************************************************************************/ #include "config.h" #include "OSSLSHA512.h" #include int OSSLSHA512::getHashSize() { return 64; } const EVP_MD* OSSLSHA512::getEVPHash() const { return EVP_sha512(); } softhsm-2.0.0/src/lib/crypto/BotanECDHPrivateKey.h0000664000175000017500000000545712533040716016654 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDHPrivateKey.h Botan ECDH private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDHPRIVATEKEY_H #define _SOFTHSM_V2_BOTANECDHPRIVATEKEY_H #include "config.h" #include "ECPrivateKey.h" #include class BotanECDHPrivateKey : public ECPrivateKey { public: // Constructors BotanECDHPrivateKey(); BotanECDHPrivateKey(const Botan::ECDH_PrivateKey* inECKEY); // Destructor virtual ~BotanECDHPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the ECDH private key components virtual void setD(const ByteString& inD); // Setters for the ECDH public key components virtual void setEC(const ByteString& inEC); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from Botan representation virtual void setFromBotan(const Botan::ECDH_PrivateKey* inECKEY); // Retrieve the Botan representation of the key Botan::ECDH_PrivateKey* getBotanKey(); private: // The internal Botan representation Botan::ECDH_PrivateKey* eckey; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANECDHPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLAES.cpp0000664000175000017500000001556612533040716014627 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLAES.cpp OpenSSL AES implementation *****************************************************************************/ #include "config.h" #include "OSSLAES.h" #include #include #include "salloc.h" // Wrap/Unwrap keys #ifdef HAVE_AES_KEY_WRAP bool OSSLAES::wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out) { // RFC 3394 input length checks do not apply to RFC 5649 mode with padding if (mode == SymWrap::AES_KEYWRAP && !checkLength(in.size(), 16, "wrap")) return false; return wrapUnwrapKey(key, mode, in, out, 1); } #else bool OSSLAES::wrapKey(const SymmetricKey* /*key*/, const SymWrap::Type /*mode*/, const ByteString& /*in*/, ByteString& /*out*/) { return false; } #endif #ifdef HAVE_AES_KEY_WRAP bool OSSLAES::unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out) { // RFC 3394 algorithm produce at least 3 blocks of data if ((mode == SymWrap::AES_KEYWRAP && !checkLength(in.size(), 24, "unwrap")) || // RFC 5649 algorithm produce at least 2 blocks of data (mode == SymWrap::AES_KEYWRAP_PAD && !checkLength(in.size(), 16, "unwrap"))) return false; return wrapUnwrapKey(key, mode, in, out, 0); } #else bool OSSLAES::unwrapKey(const SymmetricKey* /*key*/, const SymWrap::Type /*mode*/, const ByteString& /*in*/, ByteString& /*out*/) { return false; } #endif #ifdef HAVE_AES_KEY_WRAP // RFC 3394 wrapping and all unwrapping algorithms require aligned blocks bool OSSLAES::checkLength(const int insize, const int minsize, const char * const operation) const { if (insize < minsize) { ERROR_MSG("key data to %s too small", operation); return false; } if ((insize % 8) != 0) { ERROR_MSG("key data to %s not aligned", operation); return false; } return true; } const EVP_CIPHER* OSSLAES::getWrapCipher(const SymWrap::Type mode, const SymmetricKey* key) const { if (key == NULL) return NULL; // Check currentKey bit length; AES only supports 128, 192 or 256 bit keys if ((key->getBitLen() != 128) && (key->getBitLen() != 192) && (key->getBitLen() != 256)) { ERROR_MSG("Invalid AES key length (%d bits)", key->getBitLen()); return NULL; } // Determine the un/wrapping mode if (mode == SymWrap::AES_KEYWRAP) { // RFC 3394 AES key wrap switch(key->getBitLen()) { case 128: return EVP_aes_128_wrap(); case 192: return EVP_aes_192_wrap(); case 256: return EVP_aes_256_wrap(); }; } #ifdef HAVE_AES_KEY_WRAP_PAD else if (mode == SymWrap::AES_KEYWRAP_PAD) { // RFC 5649 AES key wrap with pad switch(key->getBitLen()) { case 128: return EVP_aes_128_wrap_pad(); case 192: return EVP_aes_192_wrap_pad(); case 256: return EVP_aes_256_wrap_pad(); }; } #endif ERROR_MSG("unknown AES key wrap mode %i", mode); return NULL; } // EVP wrapping/unwrapping // wrap = 1 -> wrapping // wrap = 0 -> unwrapping bool OSSLAES::wrapUnwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out, const int wrap) const { const char *prefix = ""; if (wrap == 0) prefix = "un"; // Determine the cipher method const EVP_CIPHER* cipher = getWrapCipher(mode, key); if (cipher == NULL) { ERROR_MSG("Failed to get EVP %swrap cipher", prefix); return false; } // Allocate the EVP context EVP_CIPHER_CTX* pWrapCTX = (EVP_CIPHER_CTX*) salloc(sizeof(EVP_CIPHER_CTX)); if (pWrapCTX == NULL) { ERROR_MSG("Failed to allocate space for EVP_CIPHER_CTX"); return false; } EVP_CIPHER_CTX_init(pWrapCTX); EVP_CIPHER_CTX_set_flags(pWrapCTX, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); int rv = EVP_CipherInit_ex(pWrapCTX, cipher, NULL, (unsigned char*) key->getKeyBits().const_byte_str(), NULL, wrap); if (rv) // Padding is handled by cipher mode separately rv = EVP_CIPHER_CTX_set_padding(pWrapCTX, 0); if (!rv) { ERROR_MSG("Failed to initialise EVP cipher %swrap operation", prefix); EVP_CIPHER_CTX_cleanup(pWrapCTX); sfree(pWrapCTX); return false; } // 1 input byte could be expanded to two AES blocks out.resize(in.size() + 2 * EVP_CIPHER_CTX_block_size(pWrapCTX) - 1); int outLen = 0; int curBlockLen = 0; rv = EVP_CipherUpdate(pWrapCTX, &out[0], &curBlockLen, in.const_byte_str(), in.size()); if (rv == 1) { outLen = curBlockLen; rv = EVP_CipherFinal_ex(pWrapCTX, &out[0], &curBlockLen); } if (rv != 1) { ERROR_MSG("Failed EVP %swrap operation", prefix); EVP_CIPHER_CTX_cleanup(pWrapCTX); sfree(pWrapCTX); return false; } outLen += curBlockLen; out.resize(outLen); return true; } #endif const EVP_CIPHER* OSSLAES::getCipher() const { if (currentKey == NULL) return NULL; // Check currentKey bit length; AES only supports 128, 192 or 256 bit keys if ((currentKey->getBitLen() != 128) && (currentKey->getBitLen() != 192) && (currentKey->getBitLen() != 256)) { ERROR_MSG("Invalid AES currentKey length (%d bits)", currentKey->getBitLen()); return NULL; } // Determine the cipher mode if (currentCipherMode == SymMode::CBC) { switch(currentKey->getBitLen()) { case 128: return EVP_aes_128_cbc(); case 192: return EVP_aes_192_cbc(); case 256: return EVP_aes_256_cbc(); }; } else if (currentCipherMode == SymMode::ECB) { switch(currentKey->getBitLen()) { case 128: return EVP_aes_128_ecb(); case 192: return EVP_aes_192_ecb(); case 256: return EVP_aes_256_ecb(); }; } ERROR_MSG("Invalid AES cipher mode %i", currentCipherMode); return NULL; } size_t OSSLAES::getBlockSize() const { // The block size is 128 bits return 128 >> 3; } softhsm-2.0.0/src/lib/crypto/BotanGOSTR3411.h0000664000175000017500000000355712533040716015353 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTR3411.h Botan GOST R 34.11-94 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANGOSTR3411_H #define _SOFTHSM_V2_BOTANGOSTR3411_H #include "config.h" #include "BotanHashAlgorithm.h" #include class BotanGOSTR3411 : public BotanHashAlgorithm { virtual int getHashSize(); protected: virtual Botan::HashFunction* getHash() const; }; #endif // !_SOFTHSM_V2_BOTANGOSTR3411_H softhsm-2.0.0/src/lib/crypto/OSSLDSAPrivateKey.h0000664000175000017500000000514512533040716016267 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSAPrivateKey.h OpenSSL DSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDSAPRIVATEKEY_H #define _SOFTHSM_V2_OSSLDSAPRIVATEKEY_H #include "config.h" #include "DSAPrivateKey.h" #include class OSSLDSAPrivateKey : public DSAPrivateKey { public: // Constructors OSSLDSAPrivateKey(); OSSLDSAPrivateKey(const DSA* inDSA); // Destructor virtual ~OSSLDSAPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DSA private key components virtual void setX(const ByteString& inX); // Setters for the DSA domain parameters virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setG(const ByteString& inG); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from OpenSSL representation virtual void setFromOSSL(const DSA* inDSA); // Retrieve the OpenSSL representation of the key DSA* getOSSLKey(); private: // The internal OpenSSL representation DSA* dsa; }; #endif // !_SOFTHSM_V2_OSSLDSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLAES.h0000664000175000017500000000477612533040716014275 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLAES.h OpenSSL AES implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLAES_H #define _SOFTHSM_V2_OSSLAES_H #include #include #include "config.h" #include "OSSLEVPSymmetricAlgorithm.h" class OSSLAES : public OSSLEVPSymmetricAlgorithm { public: // Destructor virtual ~OSSLAES() { } // Wrap/Unwrap keys virtual bool wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); virtual bool unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); // Return the block size virtual size_t getBlockSize() const; protected: // Return the right EVP cipher for the operation virtual const EVP_CIPHER* getCipher() const; const EVP_CIPHER* getWrapCipher(const SymWrap::Type mode, const SymmetricKey* key) const; bool wrapUnwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out, const int wrap) const; bool checkLength(const int insize, const int minsize, const char * const operation) const; }; #endif // !_SOFTHSM_V2_OSSLAES_H softhsm-2.0.0/src/lib/crypto/DSAPublicKey.h0000664000175000017500000000503312533040716015366 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSAPublicKey.h DSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_DSAPUBLICKEY_H #define _SOFTHSM_V2_DSAPUBLICKEY_H #include "config.h" #include "PublicKey.h" class DSAPublicKey : public PublicKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Setters for the DSA public key components virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setG(const ByteString& inG); virtual void setY(const ByteString& inY); // Getters for the DSA public key components virtual const ByteString& getP() const; virtual const ByteString& getQ() const; virtual const ByteString& getG() const; virtual const ByteString& getY() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Public components ByteString p,q,g,y; }; #endif // !_SOFTHSM_V2_DSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLGOSTR3411.h0000664000175000017500000000351312533040716015060 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTR3411.h OpenSSL GOST R 34.11-94 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLGOSTR3411_H #define _SOFTHSM_V2_OSSLGOSTR3411_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLGOSTR3411 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLGOSTR3411_H softhsm-2.0.0/src/lib/crypto/DHPublicKey.h0000664000175000017500000000471112533040716015254 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHPublicKey.h Diffie-Hellman public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_DHPUBLICKEY_H #define _SOFTHSM_V2_DHPUBLICKEY_H #include "config.h" #include "PublicKey.h" class DHPublicKey : public PublicKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Setters for the DH public key components virtual void setP(const ByteString& inP); virtual void setG(const ByteString& inG); virtual void setY(const ByteString& inY); // Getters for the DH public key components virtual const ByteString& getP() const; virtual const ByteString& getG() const; virtual const ByteString& getY() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Public components ByteString p,g,y; }; #endif // !_SOFTHSM_V2_DHPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLHMAC.h0000664000175000017500000000532712533040716014366 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLHMAC.h OpenSSL HMAC implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLHMAC_H #define _SOFTHSM_V2_OSSLHMAC_H #include "config.h" #include "OSSLEVPMacAlgorithm.h" #include class OSSLHMACMD5 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; class OSSLHMACSHA1 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; class OSSLHMACSHA224 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; class OSSLHMACSHA256 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; class OSSLHMACSHA384 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; class OSSLHMACSHA512 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; #ifdef WITH_GOST class OSSLHMACGOSTR3411 : public OSSLEVPMacAlgorithm { protected: virtual const EVP_MD* getEVPHash() const; virtual size_t getMacSize() const; }; #endif #endif // !_SOFTHSM_V2_OSSLHMAC_H softhsm-2.0.0/src/lib/crypto/OSSLGOST.cpp0000664000175000017500000003252312533040716014763 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOST.cpp OpenSSL GOST R 34.10-2001 asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "OSSLGOST.h" #include "OSSLCryptoFactory.h" #include "ECParameters.h" #include "OSSLGOSTKeyPair.h" #include "OSSLGOSTPrivateKey.h" #include "OSSLGOSTPublicKey.h" #include #include #include #include #include // Destructor OSSLGOST::~OSSLGOST() { EVP_MD_CTX_cleanup(&curCTX); } // Signing functions bool OSSLGOST::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (mechanism == AsymMech::GOST) { // Separate implementation for GOST signing without hash computation // Check if the private key is the right type if (!privateKey->isOfType(OSSLGOSTPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // In case of raw GOST, the length of the input data must be 32 bytes if (dataToSign.size() != 32) { ERROR_MSG("Size of data to sign is not 32 bytes"); return false; } // Perform the signature operation OSSLGOSTPrivateKey* osslKey = (OSSLGOSTPrivateKey*) privateKey; EVP_PKEY* pkey = osslKey->getOSSLKey(); size_t outLen; if (pkey == NULL) { ERROR_MSG("Could not get the OpenSSL private key"); return false; } signature.resize(EVP_PKEY_size(pkey)); outLen = signature.size(); EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pkey,NULL); if (ctx == NULL) { ERROR_MSG("EVP_PKEY_CTX_new failed"); return false; } if (EVP_PKEY_sign_init(ctx) <= 0) { ERROR_MSG("EVP_PKEY_sign_init failed"); EVP_PKEY_CTX_free(ctx); return false; } if (EVP_PKEY_sign(ctx, &signature[0], &outLen, dataToSign.const_byte_str(), dataToSign.size()) <= 0) { ERROR_MSG("An error occurred while performing a signature"); EVP_PKEY_CTX_free(ctx); return false; } signature.resize(outLen); EVP_PKEY_CTX_free(ctx); return true; } else { // Call default implementation return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen); } } bool OSSLGOST::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!privateKey->isOfType(OSSLGOSTPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } if (mechanism != AsymMech::GOST_GOST) { ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } EVP_MD_CTX_init(&curCTX); const EVP_MD* md = OSSLCryptoFactory::i()->EVP_GOST_34_11; if (!EVP_DigestInit_ex(&curCTX, md, NULL)) { ERROR_MSG("EVP_DigestInit_ex failed"); EVP_MD_CTX_cleanup(&curCTX); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLGOST::signUpdate(const ByteString& dataToSign) { if (!AsymmetricAlgorithm::signUpdate(dataToSign)) { return false; } if (!EVP_DigestUpdate(&curCTX, dataToSign.const_byte_str(), dataToSign.size())) { ERROR_MSG("EVP_DigestUpdate failed"); EVP_MD_CTX_cleanup(&curCTX); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool OSSLGOST::signFinal(ByteString& signature) { // Save necessary state before calling super class signFinal OSSLGOSTPrivateKey* pk = (OSSLGOSTPrivateKey*) currentPrivateKey; if (!AsymmetricAlgorithm::signFinal(signature)) { return false; } // Perform the signature operation EVP_PKEY* pkey = pk->getOSSLKey(); unsigned int outLen; if (pkey == NULL) { ERROR_MSG("Could not get the OpenSSL private key"); EVP_MD_CTX_cleanup(&curCTX); return false; } signature.resize(EVP_PKEY_size(pkey)); outLen = signature.size(); if (!EVP_SignFinal(&curCTX, &signature[0], &outLen, pkey)) { ERROR_MSG("EVP_SignFinal failed"); EVP_MD_CTX_cleanup(&curCTX); return false; } signature.resize(outLen); EVP_MD_CTX_cleanup(&curCTX); return true; } // Verification functions bool OSSLGOST::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (mechanism == AsymMech::GOST) { // Separate implementation for GOST verification without hash computation // Check if the private key is the right type if (!publicKey->isOfType(OSSLGOSTPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } // Perform the verification operation OSSLGOSTPublicKey* osslKey = (OSSLGOSTPublicKey*) publicKey; EVP_PKEY* pkey = osslKey->getOSSLKey(); if (pkey == NULL) { ERROR_MSG("Could not get the OpenSSL public key"); return false; } EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(pkey,NULL); if (ctx == NULL) { ERROR_MSG("EVP_PKEY_CTX_new failed"); return false; } if (EVP_PKEY_verify_init(ctx) <= 0) { ERROR_MSG("EVP_PKEY_verify_init failed"); EVP_PKEY_CTX_free(ctx); return false; } int ret = EVP_PKEY_verify(ctx, signature.const_byte_str(), signature.size(), originalData.const_byte_str(), originalData.size()); EVP_PKEY_CTX_free(ctx); if (ret != 1) { if (ret < 0) ERROR_MSG("GOST verify failed (0x%08X)", ERR_get_error()); return false; } return true; } else { // Call the generic function return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen); } } bool OSSLGOST::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen)) { return false; } // Check if the public key is the right type if (!publicKey->isOfType(OSSLGOSTPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } if (mechanism != AsymMech::GOST_GOST) { ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } EVP_MD_CTX_init(&curCTX); const EVP_MD* md = OSSLCryptoFactory::i()->EVP_GOST_34_11; if (!EVP_DigestInit_ex(&curCTX, md, NULL)) { ERROR_MSG("EVP_DigestInit_ex failed"); EVP_MD_CTX_cleanup(&curCTX); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLGOST::verifyUpdate(const ByteString& originalData) { if (!AsymmetricAlgorithm::verifyUpdate(originalData)) { return false; } if (!EVP_DigestUpdate(&curCTX, originalData.const_byte_str(), originalData.size())) { ERROR_MSG("EVP_DigestUpdate failed"); EVP_MD_CTX_cleanup(&curCTX); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool OSSLGOST::verifyFinal(const ByteString& signature) { // Save necessary state before calling super class verifyFinal OSSLGOSTPublicKey* pk = (OSSLGOSTPublicKey*) currentPublicKey; if (!AsymmetricAlgorithm::verifyFinal(signature)) { return false; } // Perform the verify operation EVP_PKEY *pkey = pk->getOSSLKey(); int ret; if (pkey == NULL) { ERROR_MSG("Could not get the OpenSSL public key"); EVP_MD_CTX_cleanup(&curCTX); return false; } ret = EVP_VerifyFinal(&curCTX, signature.const_byte_str(), signature.size(), pkey); EVP_MD_CTX_cleanup(&curCTX); if (ret != 1) { if (ret < 0) ERROR_MSG("GOST verify failed (0x%08X)", ERR_get_error()); return false; } return true; } // Encryption functions bool OSSLGOST::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("GOST does not support encryption"); return false; } // Decryption functions bool OSSLGOST::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("GOST does not support decryption"); return false; } // Key factory bool OSSLGOST::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(ECParameters::type)) { ERROR_MSG("Invalid parameters supplied for GOST key generation"); return false; } ECParameters* params = (ECParameters*) parameters; ByteString paramA = "06072a850302022301"; if (params->getEC() != paramA) { ERROR_MSG("unsupported parameters"); return false; } // Generate the key-pair EVP_PKEY_CTX* ctx = NULL; EVP_PKEY* pkey = NULL; OSSLGOSTKeyPair* kp; ctx = EVP_PKEY_CTX_new_id(NID_id_GostR3410_2001, NULL); if (ctx == NULL) { ERROR_MSG("EVP_PKEY_CTX_new_id failed"); goto err; } if (EVP_PKEY_keygen_init(ctx) <= 0) { ERROR_MSG("EVP_PKEY_keygen_init failed"); goto err; } if (EVP_PKEY_CTX_ctrl_str(ctx, "paramset", "A") <= 0) { ERROR_MSG("EVP_PKEY_CTX_ctrl_str failed"); goto err; } if (EVP_PKEY_keygen(ctx, &pkey) <= 0) { ERROR_MSG("EVP_PKEY_keygen failed"); goto err; } EVP_PKEY_CTX_free(ctx); ctx = NULL; // Create an asymmetric key-pair object to return kp = new OSSLGOSTKeyPair(); ((OSSLGOSTPublicKey*) kp->getPublicKey())->setFromOSSL(pkey); ((OSSLGOSTPrivateKey*) kp->getPrivateKey())->setFromOSSL(pkey); *ppKeyPair = kp; // Release the key EVP_PKEY_free(pkey); return true; err: if (ctx != NULL) EVP_PKEY_CTX_free(ctx); if (pkey != NULL) EVP_PKEY_free(pkey); return false; } unsigned long OSSLGOST::getMinKeySize() { return 0; } unsigned long OSSLGOST::getMaxKeySize() { return 0; } bool OSSLGOST::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); OSSLGOSTKeyPair* kp = new OSSLGOSTKeyPair(); bool rv = true; if (!((OSSLGOSTPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((OSSLGOSTPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool OSSLGOST::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLGOSTPublicKey* pub = new OSSLGOSTPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool OSSLGOST::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLGOSTPrivateKey* priv = new OSSLGOSTPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* OSSLGOST::newPublicKey() { return (PublicKey*) new OSSLGOSTPublicKey(); } PrivateKey* OSSLGOST::newPrivateKey() { return (PrivateKey*) new OSSLGOSTPrivateKey(); } AsymmetricParameters* OSSLGOST::newParameters() { return (AsymmetricParameters*) new ECParameters(); } bool OSSLGOST::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } ECParameters* params = new ECParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } #endif softhsm-2.0.0/src/lib/crypto/BotanECDHPublicKey.h0000664000175000017500000000514212533040716016447 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDHPublicKey.h Botan ECDH public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDHPUBLICKEY_H #define _SOFTHSM_V2_BOTANECDHPUBLICKEY_H #include "config.h" #include "ECPublicKey.h" #include class BotanECDHPublicKey : public ECPublicKey { public: // Constructors BotanECDHPublicKey(); BotanECDHPublicKey(const Botan::ECDH_PublicKey* inECKEY); // Destructor virtual ~BotanECDHPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the ECDH public key components virtual void setEC(const ByteString& inEC); virtual void setQ(const ByteString& inQ); // Set from Botan representation virtual void setFromBotan(const Botan::ECDH_PublicKey* inECKEY); // Retrieve the Botan representation of the key Botan::ECDH_PublicKey* getBotanKey(); private: // The internal Botan representation Botan::ECDH_PublicKey* eckey; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANECDHPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanGOSTPublicKey.cpp0000664000175000017500000001136112533040716017053 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTPublicKey.cpp Botan GOST R 34.10-2001 public key class *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "BotanGOSTPublicKey.h" #include "BotanUtil.h" #include // Constructors BotanGOSTPublicKey::BotanGOSTPublicKey() { eckey = NULL; } BotanGOSTPublicKey::BotanGOSTPublicKey(const Botan::GOST_3410_PublicKey* inECKEY) { BotanGOSTPublicKey(); setFromBotan(inECKEY); } // Destructor BotanGOSTPublicKey::~BotanGOSTPublicKey() { delete eckey; } // The type /*static*/ const char* BotanGOSTPublicKey::type = "Botan GOST Public Key"; // Get the base point order length unsigned long BotanGOSTPublicKey::getOrderLength() const { try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); return group.get_order().bytes(); } catch (...) { ERROR_MSG("Can't get EC group for order length"); return 0; } } // Get the output length unsigned long BotanGOSTPublicKey::getOutputLength() const { return getOrderLength() * 2; } // Set from Botan representation void BotanGOSTPublicKey::setFromBotan(const Botan::GOST_3410_PublicKey* inECKEY) { ByteString inEC = BotanUtil::ecGroup2ByteString(inECKEY->domain()); setEC(inEC); ByteString inQ = BotanUtil::ecPoint2ByteString(inECKEY->public_point()).substr(3); /* The points must be stored in little endian */ const size_t length = inQ.size() / 2; for (size_t i = 0; i < (length / 2); i++) { std::swap(inQ[i], inQ[length-1-i]); std::swap(inQ[length+i], inQ[2*length-1-i]); } setQ(inQ); } // Check if the key is of the given type bool BotanGOSTPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the GOST public key components void BotanGOSTPublicKey::setEC(const ByteString& inEC) { GOSTPublicKey::setEC(inEC); if (eckey) { delete eckey; eckey = NULL; } } void BotanGOSTPublicKey::setQ(const ByteString& inQ) { GOSTPublicKey::setQ(inQ); if (eckey) { delete eckey; eckey = NULL; } } // Serialisation ByteString BotanGOSTPublicKey::serialise() const { return ec.serialise() + q.serialise(); } bool BotanGOSTPublicKey::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); if ((dEC.size() == 0) || (dQ.size() == 0)) { return false; } setEC(dEC); setQ(dQ); return true; } // Retrieve the Botan representation of the key Botan::GOST_3410_PublicKey* BotanGOSTPublicKey::getBotanKey() { if (!eckey) { createBotanKey(); } return eckey; } // Create the Botan representation of the key void BotanGOSTPublicKey::createBotanKey() { if (ec.size() != 0 && q.size() != 0) { if (eckey) { delete eckey; eckey = NULL; } try { /* The points are stored in little endian */ ByteString bPoint = q; const size_t length = bPoint.size() / 2; for (size_t i = 0; i < (length / 2); i++) { std::swap(bPoint[i], bPoint[length-1-i]); std::swap(bPoint[length+i], bPoint[2*length-1-i]); } ByteString p = "044104" + bPoint; Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); Botan::PointGFp point = BotanUtil::byteString2ECPoint(p, group); eckey = new Botan::GOST_3410_PublicKey(group, point); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } #endif softhsm-2.0.0/src/lib/crypto/BotanECDH.cpp0000664000175000017500000001723312533040716015176 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDH.cpp Botan ECDH asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDH.h" #include "BotanRNG.h" #include "CryptoFactory.h" #include "BotanCryptoFactory.h" #include "ECParameters.h" #include "BotanECDHKeyPair.h" #include "BotanUtil.h" #include #include #include #include // Signing functions bool BotanECDH::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDH does not support signing"); return false; } bool BotanECDH::signUpdate(const ByteString& /*dataToSign*/) { ERROR_MSG("ECDH does not support signing"); return false; } bool BotanECDH::signFinal(ByteString& /*signature*/) { ERROR_MSG("ECDH does not support signing"); return false; } // Verification functions bool BotanECDH::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDH does not support verifying"); return false; } bool BotanECDH::verifyUpdate(const ByteString& /*originalData*/) { ERROR_MSG("ECDH does not support verifying"); return false; } bool BotanECDH::verifyFinal(const ByteString& /*signature*/) { ERROR_MSG("ECDH does not support verifying"); return false; } // Encryption functions bool BotanECDH::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDH does not support encryption"); return false; } // Decryption functions bool BotanECDH::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDH does not support decryption"); return false; } // Key factory bool BotanECDH::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(ECParameters::type)) { ERROR_MSG("Invalid parameters supplied for ECDH key generation"); return false; } ECParameters* params = (ECParameters*) parameters; // Generate the key-pair Botan::ECDH_PrivateKey* eckp = NULL; try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); eckp = new Botan::ECDH_PrivateKey(*rng->getRNG(), BotanUtil::byteString2ECGroup(params->getEC())); } catch (...) { ERROR_MSG("ECDH key generation failed"); return false; } // Create an asymmetric key-pair object to return BotanECDHKeyPair* kp = new BotanECDHKeyPair(); ((BotanECDHPublicKey*) kp->getPublicKey())->setFromBotan(eckp); ((BotanECDHPrivateKey*) kp->getPrivateKey())->setFromBotan(eckp); *ppKeyPair = kp; // Release the key delete eckp; return true; } bool BotanECDH::deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey) { // Check parameters if ((ppSymmetricKey == NULL) || (publicKey == NULL) || (privateKey == NULL)) { return false; } // Get keys Botan::ECDH_PublicKey* pub = ((BotanECDHPublicKey*) publicKey)->getBotanKey(); Botan::ECDH_PrivateKey* priv = ((BotanECDHPrivateKey*) privateKey)->getBotanKey(); if (pub == NULL || priv == NULL) { ERROR_MSG("Failed to get Botan ECDH keys"); return false; } // Derive the secret Botan::SymmetricKey sk; try { Botan::PK_Key_Agreement ka(*priv, "Raw"); sk = ka.derive_key(0, pub->public_value()); } catch (...) { ERROR_MSG("Botan ECDH key agreement failed"); return false; } ByteString secret; secret.resize(sk.length()); memcpy(&secret[0], sk.begin(), sk.length()); *ppSymmetricKey = new SymmetricKey(sk.length() * 8); if (*ppSymmetricKey == NULL) { ERROR_MSG("Can't create ECDH secret"); return false; } if (!(*ppSymmetricKey)->setKeyBits(secret)) { delete *ppSymmetricKey; *ppSymmetricKey = NULL; return false; } return true; } unsigned long BotanECDH::getMinKeySize() { // Smallest EC group is secp112r1 return 112; } unsigned long BotanECDH::getMaxKeySize() { // Biggest EC group is secp521r1 return 521; } bool BotanECDH::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); BotanECDHKeyPair* kp = new BotanECDHKeyPair(); bool rv = true; if (!((ECPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((ECPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool BotanECDH::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanECDHPublicKey* pub = new BotanECDHPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool BotanECDH::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanECDHPrivateKey* priv = new BotanECDHPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* BotanECDH::newPublicKey() { return (PublicKey*) new BotanECDHPublicKey(); } PrivateKey* BotanECDH::newPrivateKey() { return (PrivateKey*) new BotanECDHPrivateKey(); } AsymmetricParameters* BotanECDH::newParameters() { return (AsymmetricParameters*) new ECParameters(); } bool BotanECDH::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } ECParameters* params = new ECParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } #endif softhsm-2.0.0/src/lib/crypto/OSSLGOSTKeyPair.h0000664000175000017500000000443312533040716015714 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTKeyPair.h OpenSSL GOST R 34.10-2001 key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLGOSTKEYPAIR_H #define _SOFTHSM_V2_OSSLGOSTKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "OSSLGOSTPublicKey.h" #include "OSSLGOSTPrivateKey.h" class OSSLGOSTKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(OSSLGOSTPublicKey& publicKey); // Set the private key void setPrivateKey(OSSLGOSTPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key OSSLGOSTPublicKey pubKey; // The private key OSSLGOSTPrivateKey privKey; }; #endif // !_SOFTHSM_V2_OSSLGOSTKEYPAIR_H softhsm-2.0.0/src/lib/crypto/BotanRSAKeyPair.cpp0000664000175000017500000000424212533040716016401 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSAKeyPair.cpp Botan RSA key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanRSAKeyPair.h" // Set the public key void BotanRSAKeyPair::setPublicKey(BotanRSAPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void BotanRSAKeyPair::setPrivateKey(BotanRSAPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* BotanRSAKeyPair::getPublicKey() { return &pubKey; } const PublicKey* BotanRSAKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* BotanRSAKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* BotanRSAKeyPair::getConstPrivateKey() const { return &privKey; } softhsm-2.0.0/src/lib/crypto/OSSLDSAPublicKey.cpp0000664000175000017500000000711512533040716016425 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSAPublicKey.cpp OpenSSL DSA public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDSAPublicKey.h" #include "OSSLUtil.h" #include #include // Constructors OSSLDSAPublicKey::OSSLDSAPublicKey() { dsa = DSA_new(); // Use the OpenSSL implementation and not any engine DSA_set_method(dsa, DSA_get_default_method()); } OSSLDSAPublicKey::OSSLDSAPublicKey(const DSA* inDSA) { dsa = DSA_new(); // Use the OpenSSL implementation and not any engine DSA_set_method(dsa, DSA_OpenSSL()); setFromOSSL(inDSA); } // Destructor OSSLDSAPublicKey::~OSSLDSAPublicKey() { DSA_free(dsa); } // The type /*static*/ const char* OSSLDSAPublicKey::type = "OpenSSL DSA Public Key"; // Set from OpenSSL representation void OSSLDSAPublicKey::setFromOSSL(const DSA* inDSA) { if (inDSA->p) { ByteString inP = OSSL::bn2ByteString(inDSA->p); setP(inP); } if (inDSA->q) { ByteString inQ = OSSL::bn2ByteString(inDSA->q); setQ(inQ); } if (inDSA->g) { ByteString inG = OSSL::bn2ByteString(inDSA->g); setG(inG); } if (inDSA->pub_key) { ByteString inY = OSSL::bn2ByteString(inDSA->pub_key); setY(inY); } } // Check if the key is of the given type bool OSSLDSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DSA public key components void OSSLDSAPublicKey::setP(const ByteString& inP) { DSAPublicKey::setP(inP); if (dsa->p) { BN_clear_free(dsa->p); dsa->p = NULL; } dsa->p = OSSL::byteString2bn(inP); } void OSSLDSAPublicKey::setQ(const ByteString& inQ) { DSAPublicKey::setQ(inQ); if (dsa->q) { BN_clear_free(dsa->q); dsa->q = NULL; } dsa->q = OSSL::byteString2bn(inQ); } void OSSLDSAPublicKey::setG(const ByteString& inG) { DSAPublicKey::setG(inG); if (dsa->g) { BN_clear_free(dsa->g); dsa->g = NULL; } dsa->g = OSSL::byteString2bn(inG); } void OSSLDSAPublicKey::setY(const ByteString& inY) { DSAPublicKey::setY(inY); if (dsa->pub_key) { BN_clear_free(dsa->pub_key); dsa->pub_key = NULL; } dsa->pub_key = OSSL::byteString2bn(inY); } // Retrieve the OpenSSL representation of the key DSA* OSSLDSAPublicKey::getOSSLKey() { return dsa; } softhsm-2.0.0/src/lib/crypto/BotanDH.cpp0000664000175000017500000002131312533040716014760 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDH.cpp Botan Diffie-Hellman asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDH.h" #include "BotanRNG.h" #include "CryptoFactory.h" #include "BotanCryptoFactory.h" #include "DHParameters.h" #include "BotanDHKeyPair.h" #include "BotanUtil.h" #include #include #include #include // Signing functions bool BotanDH::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("DH does not support signing"); return false; } bool BotanDH::signUpdate(const ByteString& /*dataToSign*/) { ERROR_MSG("DH does not support signing"); return false; } bool BotanDH::signFinal(ByteString& /*signature*/) { ERROR_MSG("DH does not support signing"); return false; } // Verification functions bool BotanDH::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("DH does not support verifying"); return false; } bool BotanDH::verifyUpdate(const ByteString& /*originalData*/) { ERROR_MSG("DH does not support verifying"); return false; } bool BotanDH::verifyFinal(const ByteString& /*signature*/) { ERROR_MSG("DH does not support verifying"); return false; } // Encryption functions bool BotanDH::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DH does not support encryption"); return false; } // Decryption functions bool BotanDH::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DH does not support decryption"); return false; } // Key factory bool BotanDH::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(DHParameters::type)) { ERROR_MSG("Invalid parameters supplied for DH key generation"); return false; } DHParameters* params = (DHParameters*) parameters; // Generate the key-pair BotanDH_PrivateKey* dh = NULL; try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); // PKCS#3: 2^(l-1) <= x < 2^l Botan::BigInt x; if (params->getXBitLength() > 0) { x.randomize(*rng->getRNG(), params->getXBitLength()); } dh = new BotanDH_PrivateKey(*rng->getRNG(), Botan::DL_Group(BotanUtil::byteString2bigInt(params->getP()), BotanUtil::byteString2bigInt(params->getG())), x); } catch (std::exception& e) { ERROR_MSG("DH key generation failed with %s", e.what()); return false; } // Create an asymmetric key-pair object to return BotanDHKeyPair* kp = new BotanDHKeyPair(); ((BotanDHPublicKey*) kp->getPublicKey())->setFromBotan(dh); ((BotanDHPrivateKey*) kp->getPrivateKey())->setFromBotan(dh); *ppKeyPair = kp; // Release the key delete dh; return true; } bool BotanDH::deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey) { // Check parameters if ((ppSymmetricKey == NULL) || (publicKey == NULL) || (privateKey == NULL)) { return false; } // Get keys Botan::DH_PublicKey* pub = ((BotanDHPublicKey*) publicKey)->getBotanKey(); BotanDH_PrivateKey* priv = ((BotanDHPrivateKey*) privateKey)->getBotanKey(); if (pub == NULL || priv == NULL || priv->impl == NULL) { ERROR_MSG("Failed to get Botan DH keys"); return false; } // Derive the secret Botan::SymmetricKey sk; try { Botan::PK_Key_Agreement ka(*priv->impl, "Raw"); sk = ka.derive_key(0, pub->public_value()); } catch (std::exception& e) { ERROR_MSG("Botan DH key agreement failed: %s", e.what()); return false; } ByteString secret; secret.resize(sk.length()); memcpy(&secret[0], sk.begin(), sk.length()); *ppSymmetricKey = new SymmetricKey(sk.length() * 8); if (*ppSymmetricKey == NULL) { ERROR_MSG("Can't create DH secret"); return false; } if (!(*ppSymmetricKey)->setKeyBits(secret)) { delete *ppSymmetricKey; *ppSymmetricKey = NULL; return false; } return true; } unsigned long BotanDH::getMinKeySize() { return 512; } unsigned long BotanDH::getMaxKeySize() { return 4096; } bool BotanDH::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/) { if ((ppParams == NULL) || (parameters == NULL)) { return false; } size_t bitLen = (size_t) parameters; if (bitLen < getMinKeySize() || bitLen > getMaxKeySize()) { ERROR_MSG("This DH key size is not supported"); return false; } Botan::DL_Group* group = NULL; try { BotanRNG* brng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); group = new Botan::DL_Group(*brng->getRNG(), Botan::DL_Group::Strong, bitLen); } catch (...) { ERROR_MSG("Failed to generate %d bit DH parameters", bitLen); return false; } // Store the DH parameters DHParameters* params = new DHParameters(); ByteString p = BotanUtil::bigInt2ByteString(group->get_p()); params->setP(p); ByteString g = BotanUtil::bigInt2ByteString(group->get_g()); params->setG(g); *ppParams = params; delete group; return true; } bool BotanDH::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); BotanDHKeyPair* kp = new BotanDHKeyPair(); bool rv = true; if (!((DHPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((DHPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool BotanDH::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanDHPublicKey* pub = new BotanDHPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool BotanDH::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanDHPrivateKey* priv = new BotanDHPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* BotanDH::newPublicKey() { return (PublicKey*) new BotanDHPublicKey(); } PrivateKey* BotanDH::newPrivateKey() { return (PrivateKey*) new BotanDHPrivateKey(); } AsymmetricParameters* BotanDH::newParameters() { return (AsymmetricParameters*) new DHParameters(); } bool BotanDH::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } DHParameters* params = new DHParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } softhsm-2.0.0/src/lib/crypto/BotanECDSAPrivateKey.h0000664000175000017500000000547712533040716016772 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSAPrivateKey.h Botan ECDSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDSAPRIVATEKEY_H #define _SOFTHSM_V2_BOTANECDSAPRIVATEKEY_H #include "config.h" #include "ECPrivateKey.h" #include class BotanECDSAPrivateKey : public ECPrivateKey { public: // Constructors BotanECDSAPrivateKey(); BotanECDSAPrivateKey(const Botan::ECDSA_PrivateKey* inECKEY); // Destructor virtual ~BotanECDSAPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the ECDSA private key components virtual void setD(const ByteString& inD); // Setters for the ECDSA public key components virtual void setEC(const ByteString& inEC); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from Botan representation virtual void setFromBotan(const Botan::ECDSA_PrivateKey* inECKEY); // Retrieve the Botan representation of the key Botan::ECDSA_PrivateKey* getBotanKey(); private: // The internal Botan representation Botan::ECDSA_PrivateKey* eckey; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANECDSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLMD5.cpp0000664000175000017500000000323712533040716014574 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLMD5.h OpenSSL MD5 implementation *****************************************************************************/ #include "config.h" #include "OSSLMD5.h" #include int OSSLMD5::getHashSize() { return 16; } const EVP_MD* OSSLMD5::getEVPHash() const { return EVP_md5(); } softhsm-2.0.0/src/lib/crypto/BotanDHKeyPair.h0000664000175000017500000000445412533040716015721 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDHKeyPair.h Botan DiffieHellman key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDHKEYPAIR_H #define _SOFTHSM_V2_BOTANDHKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "BotanDHPublicKey.h" #include "BotanDHPrivateKey.h" class BotanDHKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(BotanDHPublicKey& publicKey); // Set the private key void setPrivateKey(BotanDHPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key BotanDHPublicKey pubKey; // The private key BotanDHPrivateKey privKey; }; #endif // !_SOFTHSM_V2_BOTANDHKEYPAIR_H softhsm-2.0.0/src/lib/crypto/test/0000775000175000017500000000000012552220147014033 500000000000000softhsm-2.0.0/src/lib/crypto/test/RNGTests.cpp0000664000175000017500000000515212533040716016134 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RNGTests.cpp Contains test cases to test the RNG class *****************************************************************************/ #include #include #include "RNGTests.h" #include "CryptoFactory.h" #include "RNG.h" #include "ent.h" #include CPPUNIT_TEST_SUITE_REGISTRATION(RNGTests); void RNGTests::setUp() { rng = NULL; rng = CryptoFactory::i()->getRNG(); // Check the RNG CPPUNIT_ASSERT(rng != NULL); } void RNGTests::tearDown() { fflush(stdout); } void RNGTests::testSimpleComparison() { ByteString a,b; CPPUNIT_ASSERT(rng->generateRandom(a, 256)); CPPUNIT_ASSERT(rng->generateRandom(b, 256)); CPPUNIT_ASSERT(a.size() == 256); CPPUNIT_ASSERT(b.size() == 256); CPPUNIT_ASSERT(a != b); } void RNGTests::testEnt() { ByteString a; double entropy, chiProbability, arithMean, montePi, serialCorrelation; // Generate 10MB of random data CPPUNIT_ASSERT(rng->generateRandom(a, 10*1024*1024)); // Perform entropy tests doEnt(a.byte_str(), a.size(), &entropy, &chiProbability, &arithMean, &montePi, &serialCorrelation); // Check entropy CPPUNIT_ASSERT(entropy >= 7.999); CPPUNIT_ASSERT((arithMean >= 127.4) && (arithMean <= 127.6)); CPPUNIT_ASSERT(serialCorrelation <= 0.001); } softhsm-2.0.0/src/lib/crypto/test/DSATests.cpp0000664000175000017500000003117012533040716016114 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSATests.cpp Contains test cases to test the RNG class *****************************************************************************/ #include #include #include #include "DSATests.h" #include "CryptoFactory.h" #include "RNG.h" #include "AsymmetricKeyPair.h" #include "AsymmetricAlgorithm.h" #include "DSAParameters.h" #include "DSAPublicKey.h" #include "DSAPrivateKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(DSATests); void DSATests::setUp() { dsa = NULL; dsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DSA); // Check the DSA object CPPUNIT_ASSERT(dsa != NULL); } void DSATests::tearDown() { if (dsa != NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(dsa); } fflush(stdout); } void DSATests::testKeyGeneration() { AsymmetricKeyPair* kp; // Key sizes to test std::vector keySizes; #ifndef WITH_FIPS keySizes.push_back(512); keySizes.push_back(768); keySizes.push_back(1024); keySizes.push_back(1536); #else keySizes.push_back(1024); #endif #ifndef WITH_BOTAN keySizes.push_back(2048); #endif for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { // Generate parameters DSAParameters* p; AsymmetricParameters** ap = (AsymmetricParameters**) &p; CPPUNIT_ASSERT(dsa->generateParameters(ap, (void*) *k)); // Generate key-pair CPPUNIT_ASSERT(dsa->generateKeyPair(&kp, p)); DSAPublicKey* pub = (DSAPublicKey*) kp->getPublicKey(); DSAPrivateKey* priv = (DSAPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getBitLength() == *k); CPPUNIT_ASSERT(priv->getBitLength() == *k); dsa->recycleParameters(p); dsa->recycleKeyPair(kp); } } void DSATests::testSerialisation() { // Generate 1024-bit parameters for testing DSAParameters* p; AsymmetricParameters** ap = (AsymmetricParameters**) &p; CPPUNIT_ASSERT(dsa->generateParameters(ap, (void*) 1024)); // Serialise the parameters ByteString serialisedParams = p->serialise(); // Deserialise the parameters AsymmetricParameters* dP; CPPUNIT_ASSERT(dsa->reconstructParameters(&dP, serialisedParams)); CPPUNIT_ASSERT(dP->areOfType(DSAParameters::type)); DSAParameters* ddP = (DSAParameters*) dP; CPPUNIT_ASSERT(p->getP() == ddP->getP()); CPPUNIT_ASSERT(p->getQ() == ddP->getQ()); CPPUNIT_ASSERT(p->getG() == ddP->getG()); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(dsa->generateKeyPair(&kp, dP)); // Serialise the key-pair ByteString serialisedKP = kp->serialise(); // Deserialise the key-pair AsymmetricKeyPair* dKP; CPPUNIT_ASSERT(dsa->reconstructKeyPair(&dKP, serialisedKP)); // Check the deserialised key-pair DSAPrivateKey* privKey = (DSAPrivateKey*) kp->getPrivateKey(); DSAPublicKey* pubKey = (DSAPublicKey*) kp->getPublicKey(); DSAPrivateKey* dPrivKey = (DSAPrivateKey*) dKP->getPrivateKey(); DSAPublicKey* dPubKey = (DSAPublicKey*) dKP->getPublicKey(); CPPUNIT_ASSERT(privKey->getP() == dPrivKey->getP()); CPPUNIT_ASSERT(privKey->getQ() == dPrivKey->getQ()); CPPUNIT_ASSERT(privKey->getG() == dPrivKey->getG()); CPPUNIT_ASSERT(privKey->getX() == dPrivKey->getX()); CPPUNIT_ASSERT(pubKey->getP() == dPubKey->getP()); CPPUNIT_ASSERT(pubKey->getQ() == dPubKey->getQ()); CPPUNIT_ASSERT(pubKey->getG() == dPubKey->getG()); CPPUNIT_ASSERT(pubKey->getY() == dPubKey->getY()); dsa->recycleParameters(p); dsa->recycleParameters(dP); dsa->recycleKeyPair(kp); dsa->recycleKeyPair(dKP); } void DSATests::testPKCS8() { // Generate 1024-bit parameters for testing AsymmetricParameters* p; CPPUNIT_ASSERT(dsa->generateParameters(&p, (void*) 1024)); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(dsa->generateKeyPair(&kp, p)); CPPUNIT_ASSERT(kp != NULL); DSAPrivateKey* priv = (DSAPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); DSAPrivateKey* dPriv = (DSAPrivateKey*) dsa->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getP() == dPriv->getP()); CPPUNIT_ASSERT(priv->getQ() == dPriv->getQ()); CPPUNIT_ASSERT(priv->getG() == dPriv->getG()); CPPUNIT_ASSERT(priv->getX() == dPriv->getX()); dsa->recycleParameters(p); dsa->recycleKeyPair(kp); dsa->recyclePrivateKey(dPriv); } void DSATests::testSigningVerifying() { AsymmetricKeyPair* kp; // Key sizes to test std::vector keySizes; #ifndef WITH_FIPS keySizes.push_back(512); keySizes.push_back(768); keySizes.push_back(1024); keySizes.push_back(1536); #else keySizes.push_back(1024); #endif #ifndef WITH_BOTAN keySizes.push_back(2048); #endif // Mechanisms to test std::vector mechanisms; mechanisms.push_back(AsymMech::DSA_SHA1); mechanisms.push_back(AsymMech::DSA_SHA224); mechanisms.push_back(AsymMech::DSA_SHA256); for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { // Generate parameters AsymmetricParameters* p; CPPUNIT_ASSERT(dsa->generateParameters(&p, (void*) *k)); // Generate key-pair CPPUNIT_ASSERT(dsa->generateKeyPair(&kp, p)); // Generate some data to sign ByteString dataToSign; RNG* rng = CryptoFactory::i()->getRNG(); CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567)); // Test mechanisms that perform internal hashing for (std::vector::iterator m = mechanisms.begin(); m != mechanisms.end(); m++) { ByteString blockSignature, singlePartSignature; // Sign the data in blocks CPPUNIT_ASSERT(dsa->signInit(kp->getPrivateKey(), *m)); CPPUNIT_ASSERT(dsa->signUpdate(dataToSign.substr(0, 134))); CPPUNIT_ASSERT(dsa->signUpdate(dataToSign.substr(134, 289))); CPPUNIT_ASSERT(dsa->signUpdate(dataToSign.substr(134 + 289))); CPPUNIT_ASSERT(dsa->signFinal(blockSignature)); // Sign the data in one pass CPPUNIT_ASSERT(dsa->sign(kp->getPrivateKey(), dataToSign, singlePartSignature, *m)); // Now perform multi-pass verification CPPUNIT_ASSERT(dsa->verifyInit(kp->getPublicKey(), *m)); CPPUNIT_ASSERT(dsa->verifyUpdate(dataToSign.substr(0, 125))); CPPUNIT_ASSERT(dsa->verifyUpdate(dataToSign.substr(125, 247))); CPPUNIT_ASSERT(dsa->verifyUpdate(dataToSign.substr(125 + 247))); CPPUNIT_ASSERT(dsa->verifyFinal(blockSignature)); // And single-pass verification CPPUNIT_ASSERT(dsa->verify(kp->getPublicKey(), dataToSign, singlePartSignature, *m)); } // Test mechanisms that do not perform internal hashing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, *k >= 2048 ? 32 : 20)); // Sign the data ByteString signature; CPPUNIT_ASSERT(dsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::DSA)); // Verify the signature CPPUNIT_ASSERT(dsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::DSA)); dsa->recycleKeyPair(kp); dsa->recycleParameters(p); } } void DSATests::testSignVerifyKnownVector() { DSAPublicKey* pubKey1 = (DSAPublicKey*) dsa->newPublicKey(); DSAPublicKey* pubKey2 = (DSAPublicKey*) dsa->newPublicKey(); DSAPrivateKey* privKey1 = (DSAPrivateKey*) dsa->newPrivateKey(); DSAPrivateKey* privKey2 = (DSAPrivateKey*) dsa->newPrivateKey(); // Reconstruct public and private key #1 ByteString p1 = "e0a67598cd1b763bc98c8abb333e5dda0cd3aa0e5e1fb5ba8a7b4eabc10ba338fae06dd4b90fda70d7cf0cb0c638be3341bec0af8a7330a3307ded2299a0ee606df035177a239c34a912c202aa5f83b9c4a7cf0235b5316bfc6efb9a248411258b30b839af172440f32563056cb67a861158ddd90e6a894c72a5bbef9e286c6b"; ByteString q1 = "e950511eab424b9a19a2aeb4e159b7844c589c4f"; ByteString g1 = "d29d5121b0423c2769ab21843e5a3240ff19cacc792264e3bb6be4f78edd1b15c4dff7f1d905431f0ab16790e1f773b5ce01c804e509066a9919f5195f4abc58189fd9ff987389cb5bedf21b4dab4f8b76a055ffe2770988fe2ec2de11ad92219f0b351869ac24da3d7ba87011a701ce8ee7bfe49486ed4527b7186ca4610a75"; ByteString x1 = "d0ec4e50bb290a42e9e355c73d8809345de2e139"; ByteString y1 = "25282217f5730501dd8dba3edfcf349aaffec20921128d70fac44110332201bba3f10986140cbb97c726938060473c8ec97b4731db004293b5e730363609df9780f8d883d8c4d41ded6a2f1e1bbbdc979e1b9d6d3c940301f4e978d65b19041fcf1e8b518f5c0576c770fe5a7a485d8329ee2914a2de1b5da4a6128ceab70f79"; pubKey1->setP(p1); pubKey1->setQ(q1); pubKey1->setG(g1); pubKey1->setY(y1); privKey1->setP(p1); privKey1->setQ(q1); privKey1->setG(g1); privKey1->setX(x1); // Test with key #1 ByteString data1 = "616263"; // "abc" ByteString goodSignature1 = "636155ac9a4633b4665d179f9e4117df68601f346c540b02d9d4852f89df8cfc99963204f4347704"; ByteString badSignature1 = "636155ac9a4633b4665d179f9e4117df68601f346c540b02d9d4852f89df8cfc99963204f4347705"; // Reconstruct public and private key #2 ByteString p2 = "f56c2a7d366e3ebdeaa1891fd2a0d099436438a673fed4d75f594959cffebca7be0fc72e4fe67d91d801cba0693ac4ed9e411b41d19e2fd1699c4390ad27d94c69c0b143f1dc88932cfe2310c886412047bd9b1c7a67f8a25909132627f51a0c866877e672e555342bdf9355347dbd43b47156b2c20bad9d2b071bc2fdcf9757f75c168c5d9fc43131be162a0756d1bdec2ca0eb0e3b018a8b38d3ef2487782aeb9fbf99d8b30499c55e4f61e5c7dcee2a2bb55bd7f75fcdf00e48f2e8356bdb59d86114028f67b8e07b127744778aff1cf1399a4d679d92fde7d941c5c85c5d7bff91ba69f9489d531d1ebfa727cfda651390f8021719fa9f7216ceb177bd75"; ByteString q2 = "c24ed361870b61e0d367f008f99f8a1f75525889c89db1b673c45af5867cb467"; ByteString g2 = "8dc6cc814cae4a1c05a3e186a6fe27eaba8cdb133fdce14a963a92e809790cba096eaa26140550c129fa2b98c16e84236aa33bf919cd6f587e048c52666576db6e925c6cbe9b9ec5c16020f9a44c9f1c8f7a8e611c1f6ec2513ea6aa0b8d0f72fed73ca37df240db57bbb27431d618697b9e771b0b301d5df05955425061a30dc6d33bb6d2a32bd0a75a0a71d2184f506372abf84a56aeeea8eb693bf29a640345fa1298a16e85421b2208d00068a5a42915f82cf0b858c8fa39d43d704b6927e0b2f916304e86fb6a1b487f07d8139e428bb096c6d67a76ec0b8d4ef274b8a2cf556d279ad267ccef5af477afed029f485b5597739f5d0240f67c2d948a6279"; ByteString x2 = "0caf2ef547ec49c4f3a6fe6df4223a174d01f2c115d49a6f73437c29a2a8458c"; ByteString y2 = "2828003d7c747199143c370fdd07a2861524514acc57f63f80c38c2087c6b795b62de1c224bf8d1d1424e60ce3f5ae3f76c754a2464af292286d873a7a30b7eacbbc75aafde7191d9157598cdb0b60e0c5aa3f6ebe425500c611957dbf5ed35490714a42811fdcdeb19af2ab30beadff2907931cee7f3b55532cffaeb371f84f01347630eb227a419b1f3f558bc8a509d64a765d8987d493b007c4412c297caf41566e26faee475137ec781a0dc088a26c8804a98c23140e7c936281864b99571ee95c416aa38ceebb41fdbff1eb1d1dc97b63ce1355257627c8b0fd840ddb20ed35be92f08c49aea5613957d7e5c7a6d5a5834b4cb069e0831753ecf65ba02b"; pubKey2->setP(p2); pubKey2->setQ(q2); pubKey2->setG(g2); pubKey2->setY(y2); privKey2->setP(p2); privKey2->setQ(q2); privKey2->setG(g2); privKey2->setX(x2); // Test with key #2 ByteString data2 = "616263"; // "abc" ByteString goodSignature2 = "315c875dcd4850e948b8ac42824e9483a32d5ba5abe0681b9b9448d444f2be3c89718d12e54a8d9ed066e4a55f7ed5a2229cd23b9a3cee78f83ed6aa61f6bcb9"; ByteString badSignature2 = "315c875dcd4850e948b8ac42824e9483a32d5ba5abe0681b9b9448d444f2be3c89718d12e54a8d9ed066e4a55f7ed5a2229cd23b9a3cee78f83ed6aa61f6bcb8"; CPPUNIT_ASSERT(dsa->verify(pubKey1, data1, goodSignature1, AsymMech::DSA_SHA1)); CPPUNIT_ASSERT(!dsa->verify(pubKey1, data1, badSignature1, AsymMech::DSA_SHA1)); CPPUNIT_ASSERT(dsa->verify(pubKey2, data2, goodSignature2, AsymMech::DSA_SHA256)); CPPUNIT_ASSERT(!dsa->verify(pubKey2, data2, badSignature2, AsymMech::DSA_SHA256)); dsa->recyclePublicKey(pubKey1); dsa->recyclePublicKey(pubKey2); dsa->recyclePrivateKey(privKey1); dsa->recyclePrivateKey(privKey2); } softhsm-2.0.0/src/lib/crypto/test/DHTests.cpp0000664000175000017500000001623412533040716016004 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHTests.cpp Contains test cases to test the DH class *****************************************************************************/ #include #include #include #include "DHTests.h" #include "CryptoFactory.h" #include "RNG.h" #include "AsymmetricKeyPair.h" #include "AsymmetricAlgorithm.h" #include "DHParameters.h" #include "DHPublicKey.h" #include "DHPrivateKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(DHTests); void DHTests::setUp() { dh = NULL; dh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::DH); // Check the DH object CPPUNIT_ASSERT(dh != NULL); } void DHTests::tearDown() { if (dh != NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(dh); } fflush(stdout); } void DHTests::testKeyGeneration() { AsymmetricKeyPair* kp; // Key sizes to test std::vector keySizes; #ifdef WITH_FIPS keySizes.push_back(1024); #else keySizes.push_back(512); //keySizes.push_back(768); //keySizes.push_back(1024); #endif for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { // Generate parameters DHParameters* p; AsymmetricParameters** ap = (AsymmetricParameters**) &p; CPPUNIT_ASSERT(dh->generateParameters(ap, (void*) *k)); // Generate key-pair CPPUNIT_ASSERT(dh->generateKeyPair(&kp, p)); DHPublicKey* pub = (DHPublicKey*) kp->getPublicKey(); DHPrivateKey* priv = (DHPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getBitLength() == *k); CPPUNIT_ASSERT(priv->getBitLength() == *k); dh->recycleKeyPair(kp); // Generate key-pair with a fixed private value length p->setXBitLength(128); CPPUNIT_ASSERT(dh->generateKeyPair(&kp, p)); priv = (DHPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv->getX().bits() == 128); dh->recycleParameters(p); dh->recycleKeyPair(kp); } } void DHTests::testSerialisation() { // Generate 1024-bit parameters for testing DHParameters* p; AsymmetricParameters** ap = (AsymmetricParameters**) &p; //CPPUNIT_ASSERT(dh->generateParameters(ap, (void*) 1024)); // changed for 512-bit for speed... #ifndef WITH_BOTAN CPPUNIT_ASSERT(dh->generateParameters(ap, (void*) 1024)); #else CPPUNIT_ASSERT(dh->generateParameters(ap, (void*) 512)); #endif // Set a fixed private value length p->setXBitLength(128); // Serialise the parameters ByteString serialisedParams = p->serialise(); // Deserialise the parameters AsymmetricParameters* dP; CPPUNIT_ASSERT(dh->reconstructParameters(&dP, serialisedParams)); CPPUNIT_ASSERT(dP->areOfType(DHParameters::type)); DHParameters* ddP = (DHParameters*) dP; CPPUNIT_ASSERT(p->getP() == ddP->getP()); CPPUNIT_ASSERT(p->getG() == ddP->getG()); CPPUNIT_ASSERT(p->getXBitLength() == ddP->getXBitLength()); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(dh->generateKeyPair(&kp, dP)); // Serialise the key-pair ByteString serialisedKP = kp->serialise(); // Deserialise the key-pair AsymmetricKeyPair* dKP; CPPUNIT_ASSERT(dh->reconstructKeyPair(&dKP, serialisedKP)); // Check the deserialised key-pair DHPrivateKey* privKey = (DHPrivateKey*) kp->getPrivateKey(); DHPublicKey* pubKey = (DHPublicKey*) kp->getPublicKey(); DHPrivateKey* dPrivKey = (DHPrivateKey*) dKP->getPrivateKey(); DHPublicKey* dPubKey = (DHPublicKey*) dKP->getPublicKey(); CPPUNIT_ASSERT(privKey->getP() == dPrivKey->getP()); CPPUNIT_ASSERT(privKey->getG() == dPrivKey->getG()); CPPUNIT_ASSERT(privKey->getX() == dPrivKey->getX()); CPPUNIT_ASSERT(pubKey->getP() == dPubKey->getP()); CPPUNIT_ASSERT(pubKey->getG() == dPubKey->getG()); CPPUNIT_ASSERT(pubKey->getY() == dPubKey->getY()); dh->recycleParameters(p); dh->recycleParameters(dP); dh->recycleKeyPair(kp); dh->recycleKeyPair(dKP); } void DHTests::testPKCS8() { // Generate 1024-bit parameters for testing AsymmetricParameters* p; //CPPUNIT_ASSERT(dh->generateParameters(&p, (void*) 1024)); // changed for 512-bit for speed... #ifndef WITH_BOTAN CPPUNIT_ASSERT(dh->generateParameters(&p, (void*) 1024)); #else CPPUNIT_ASSERT(dh->generateParameters(&p, (void*) 512)); #endif // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(dh->generateKeyPair(&kp, p)); CPPUNIT_ASSERT(kp != NULL); DHPrivateKey* priv = (DHPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); DHPrivateKey* dPriv = (DHPrivateKey*) dh->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getP() == dPriv->getP()); CPPUNIT_ASSERT(priv->getG() == dPriv->getG()); CPPUNIT_ASSERT(priv->getX() == dPriv->getX()); dh->recycleParameters(p); dh->recycleKeyPair(kp); dh->recyclePrivateKey(dPriv); } void DHTests::testDerivation() { AsymmetricKeyPair* kpa; AsymmetricKeyPair* kpb; // Key sizes to test std::vector keySizes; #ifdef WITH_FIPS keySizes.push_back(1024); #else keySizes.push_back(512); //keySizes.push_back(768); //keySizes.push_back(1024); #endif for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { // Generate parameters AsymmetricParameters* p; CPPUNIT_ASSERT(dh->generateParameters(&p, (void*) *k)); // Generate key-pairs CPPUNIT_ASSERT(dh->generateKeyPair(&kpa, p)); CPPUNIT_ASSERT(dh->generateKeyPair(&kpb, p)); // Derive secrets SymmetricKey* sa; CPPUNIT_ASSERT(dh->deriveKey(&sa, kpb->getPublicKey(), kpa->getPrivateKey())); SymmetricKey* sb; CPPUNIT_ASSERT(dh->deriveKey(&sb, kpa->getPublicKey(), kpb->getPrivateKey())); // Must be the same CPPUNIT_ASSERT(sa->getKeyBits() == sb->getKeyBits()); // Clean up dh->recycleSymmetricKey(sa); dh->recycleSymmetricKey(sb); dh->recycleKeyPair(kpa); dh->recycleKeyPair(kpb); dh->recycleParameters(p); } } void DHTests::testDeriveKnownVector() { // TODO } softhsm-2.0.0/src/lib/crypto/test/iso8859.c0000664000175000017500000000155612533040716015257 00000000000000/* This code was taken from http://www.fourmilab.ch/random/ where it states that: This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided “as is” without express or implied warranty. */ /* ISO 8859/1 Latin-1 alphabetic and upper and lower case bit vector tables. */ /* LINTLIBRARY */ unsigned char isoalpha[32] = { 0,0,0,0,0,0,0,0,127,255,255,224,127,255,255,224,0,0,0,0,0,0,0,0,255,255, 254,255,255,255,254,255 }; unsigned char isoupper[32] = { 0,0,0,0,0,0,0,0,127,255,255,224,0,0,0,0,0,0,0,0,0,0,0,0,255,255,254,254, 0,0,0,0 }; unsigned char isolower[32] = { 0,0,0,0,0,0,0,0,0,0,0,0,127,255,255,224,0,0,0,0,0,0,0,0,0,0,0,1,255,255, 254,255 }; softhsm-2.0.0/src/lib/crypto/test/RNGTests.h0000664000175000017500000000371112533040716015600 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RNGTests.h Contains test cases to test the RNG class *****************************************************************************/ #ifndef _SOFTHSM_V2_RNGTESTS_H #define _SOFTHSM_V2_RNGTESTS_H #include #include "RNG.h" class RNGTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RNGTests); CPPUNIT_TEST(testSimpleComparison); CPPUNIT_TEST(testEnt); CPPUNIT_TEST_SUITE_END(); public: void testSimpleComparison(); void testEnt(); void setUp(); void tearDown(); private: // RNG instance RNG* rng; }; #endif // !_SOFTHSM_V2_RNGTESTS_H softhsm-2.0.0/src/lib/crypto/test/HashTests.cpp0000664000175000017500000004760212533040716016377 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HashTests.cpp Contains test cases to test the hash implementations *****************************************************************************/ #include #include #include "HashTests.h" #include "CryptoFactory.h" #include #include "HashAlgorithm.h" #include "RNG.h" CPPUNIT_TEST_SUITE_REGISTRATION(HashTests); void HashTests::setUp() { hash = NULL; rng = NULL; } void HashTests::tearDown() { if (hash != NULL) { CryptoFactory::i()->recycleHashAlgorithm(hash); } fflush(stdout); } #ifndef WITH_FIPS void HashTests::testMD5() { char testData[4096] = "EDB39CC3CB5E8FD23A2182FAE8781F4E8E8534C8FE10BDC7ACDB34C4E22E4B60872E51AD092950771E475FB97B05D6203A0D1B3326D9678E44FB40787D8CF16BD3BBE4D4786F60BD8E9766EF1C30B22301FA8F7232358B3C5BE644342499622A5153B29D2E5F8F509771E8A5DE3B3737D30F2AB035262B8D83EC55F683E9B62BBB31E2E1F5E142A13ACB9701E1DE8752ACD492A943C2DB57CF4035BDA9D0519B86847CF74DB2F43CC23016D88EF44BA422710C00AEBB2ABDDED89D92E4BD132CEB87581644198B0D4AF82F3CE161ED03A4E189BE8276243243817F91159BDE294E61400041537618703754C609709846C3EDAE6922B498D24FDC6B9AE702A034BB3A2C6C230E58EE5759DC84AD0B960B111153F6D619E850E36833A26689B4718719EFF3A407B77B0BAD24A17E29B6A29E9125B4CF0DFFEB8D0B03D533ADA43D1F20CFFE0A067E0F6FFF28510148DD72AE33D8B72227523497B84082B682A480FA3B2FE42AAFF49883DAA4DC6826C9593D38002D73FA7AA91B41E828CC34FF12ECC1452B73709696A440CCDF3E6116DA36CB7A01C9E168C3518304721D2CDBC077F4D4B7E8D1A59F954872862F72AC12CB16E33BED8EC3CFD912E36BBF4DA86E31F5F45BE9294550965C7CBC03518AD7C5637A97F7470EDD6E359E82815230CE03AEE9512939A214D017719E5F6B2487E3B468D50DC8EA41EEE94360E77E0EAA9C27DFE2C28D63B7699406E2E6620FE23F96584EEA04034270A2A44096B70017CC2CB197CE8DA3B1924D8D2E86FB40FF59CCFC78B3A4F543068F08C3406DEF52413F95B2BE2AD5DA1ADBB7D95F2133F61AD5518A1BEA018E3C3C0C154EAE56B0B0F4A8818AE47DC618D138245192D055CE4EF8BD1A75030EABAFD66E45B204BA6B123FF54D78F51B6A7DB9B08BEE93E923F9DE553EC0BE4B8BE222998BC792002005ED66C0218902E7DDF6C6D5043A8A9790E438D5BDE37791CDC0DB6C974638884270D4F379DF845281C5F1F8A20978086A9444779D59423B6CEF8175E0BC2C517FA921EC66BE3F11ECEE078553F610D5B65FD293E37717C0CB323A2760646AD56C77A4B96940CF5AD1154A642043E40788C2D367123399FA6015422F5EFEC851EF558ACD4BC31EF3D3EF912241A586E54B97FAE083EE45FBBBED74BC9E3887795FC2EBC5354ACA358EC509F4AB8B2967488D5E5B77DD44EB72E66694A1F490ADEB2848918531B6FA7216C51CDB507598F1AA0985626482D3546BEF5CA3BB409934D11AECBAD47389F2CBCD85FB4DD1A8A6F4D0C28920671A31FFC14FC00FC51296A6182D5A05B16B33232798F0993C78BCC662932E2F57626D639DD00E39B206C1F8A15A19B5DCA9F8B015611AFA47A10A30527F552A22574E15E3577EAD9C7B89782F82D7082D747B50CEFD38C6F17D6269A696F518EE6EAFE1E1EA96FB4D"; char testResult[512] = "7299FE513582D71A3B9EA1E9F45F95FD"; // Get a MD5 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::MD5)) != NULL); ByteString b(testData); ByteString osslHash(testResult), shsmHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); // Now recreate the hash in a multiple part operation shsmHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } #endif void HashTests::testSHA1() { char testData[4096] = "0583243FDEDEBF8C9EA4017808B490A2581A5A06B8C2CCA4F2259B7FABDE4BECA9F80C3EFBFEC436CF5F252568CDF55C7D31002456F6FE711D404F9A274037E8D55EC6C55077E4900EEAF6524C44FBFCC1C5C1C6AF962CE22106610A7C8DE7D725BF924B81EA566B952C8723E0EAFA21EB2C6E6F5528A89FC24C478C0600CB4FD482FAFF8507284C5F1E8AEBA9CDBFB3E71D77B775DD7C09E65049423BBAA70499450AE3B46703A4A44AE281C1F0341EDF0473B079C44E0F9EFB4C3683ED706E480C901A16E77B52030A7E46E31991131AED9C98DCA1850A4BD6F35DBCF5A894A8843EE656EF0DC617D923EB38426855FAA2E77E70CE9A8AC81D0F14259A748F9227F732420CDAE5A1CFEA9B541F0B12ADD5D966EBF66613D7FBAF5FFCAC8D625CFA536DBCA8E54B01B237211656F165A8114CD157E82870BCCE6AE8AF5334105B4E50B0A4E4AE5D0A3CC5CD8FF85F7C4D20D2627694B168CB48DB81B5B78C620C7559B2043C268F5D7351256D41FE892ED8EF6F7B5DD8E193EDCD268C55C209DCD0E827FCF76D6951CEBD0065826FBF044ED5818FEE4ECB99973FDB6826BF92488652E804C40D07D4CE43FCB31481667EE637721B91FD38331A98A6E8969D5B1D0690CFA0B500D72BF2D42AD6471FE064496C91126EFCC46B8CD093BCBB70D21FDE1937A888CA08DF3068A858280ABEAF71608BC9229E8E5EFF1814C4887E3A26782A110F347560DAB6B07DB8D063E8343A3FCD99B34C3C3F649096339CA7D39DA6F7B2E489A9EE6CE01C923D45C50350AC57247838E323F1B2A284606E45D60938A6F492545C5EBA0C7396702C0F4E77F36AC9ECE7ADD32FA4EEF7B38F9FF3F8BFB4E05F1025AAB52FB1B4777A4FC4B881EFA484D04397DE4312B7EE2BCEAD0ABAC0513D9C1819F59996AB5E94D48C098634D9907A4CA41B5A900F7CC299937B089A52C221333BF6B35242CA8D552A9CAA3BB18944D5CCEF69E752FA74A8BA3DD58159BAE375944B26A636457C30C451A58984BD6F028C8CBD3ED893ECD2F1536AFF3A97DB92C0E2FC93B9CC3837FDF56E4E3065D10B15F9A5A8925A5F772E4521CDC885180ACE49D98719BCE6770604C11E6DF090C199A5BBF1D695E1D55E2C9E135E89AB26446F6FED3FBD7DFE58EB75CA61B2D3DA4974908C7183E62FDD79C233387C78EDFF8AAC412EA36AD929808023EF04B8C9B7F980CC3FFD50E7356F51FBDC3DE8551C4F5B283D41E861E5604155E81748BF017268D4FBA8D253CA695300F5FB9A51190B24E2B17653519A3FE500B27DFF90A9FDF8404AFA8FAA1C4F738EB45969846E0A18693C06CA5FE2F2B5F7A33974A9453383E558317468B47DDAEE7A2AB90AA2446155CBF5B6473628C1D6BDA9044D4D96D1E3846AA7A65046C680BB173670FC04E5AC7D8CF41C6F233BD6945C0EA90958E9DBFE67D0EBCD"; char testResult[512] = "9A5BD96DC0CD3B0089FBB6BE7D56BEE638431F5A"; // Get a SHA1 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA1)) != NULL); ByteString b(testData); ByteString osslHash(testResult), shsmHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); // Now recreate the hash in a multiple part operation shsmHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } void HashTests::testSHA224() { char testData[4096] = "8F300FA699500CA5E1E22B38EC06B2EADCE7738CF6A55CB241577D53ED68BD017517C83AEB9CD3A25536FE999B7CD61D9E2BA85C39A7D27CE2CAAC8FE7C12FA1B2905DB85ABF230A813C1A72D2BD93BE0C5A79842FE35C5EF4B2E94524FB9594E3CCC63FE2A4E21D91C25DED832FE8BC9788697051C2042094585187394BD0AFD64FB627F3CCB350874FD0D454BF0254A72DD99ED211F68DC15B94A5682B73B89BF533746E8EEC5CCE45DF55466D7026A95A062EFD49FA270751A8D427095D38FB757FD4D1395B5DC7D302D9CF28C2E2D09796B9E0FC2D1F56BDE005FCD266B097822C170981DE2DB5E92582A612019823A3A062E228AB99AD6A0E47C1DEAC0078460252D83FA11253A3EFD374B2B392F0E27079F9FCACBB8EE6320C7A06327335AB34B757057E6C7FEC5004C4F675D2C4ACC6B359CC13D6F9FBE7E12EA7F6FF753CA8FB68059DB06D9804CBE08AAA55E0F20EFB7094695C1BF0D8E504EAD0836C0E6BB491E1691FDEB9ADFE0C92CED19A612DBCA01FF5A515E32B4EC06BDA00482DE721B6A85F00CAB264B34C5F3749D35603D0216C5AA426BBFF15637D1AE7805ACA572337232C27BDFC9D17D5D129242FD883E3C33250BA089EA03BD794C03D8DB9F57F87DC0A30E37F063B9C4C43518DC9F94E7BB18718D1DC79474CFAF60CBCD5CAA8AAA9FF573E26BB8B722C522ACF561FF34A0716FB7C1217050AD6E8323889B47D7551BC7554909651A9BAFCF5F0FEFD100D35B2E06D89C46E572E3EB5A07FEA702DF10BBCD2CAF2F2A62A9BC162F6369D0DBD9A6D6368ECDAFF4246DEE682C2B20EF4D7BBCCABBE0CD44CFBB531F2190E55C1A650B4D16DB2DA0453B23C4F056C1F791336A7266742976653B2E9377F500AAEFA1EA5FEE3469F4A85A484F69FBFFC1C163F78872AFB79231D9E5B4F8EFE2A9E8487BC33E4EC462F9E451BFEB306964D1F02873EEABCAB0F06361DD463398717537C7C255E3DEF1E9EC1567A600CFEB63F822A3C24B3524225A40F0CE948B0284AEF1F9BBE7618D18839725087DD6BFEE15653B981D6F57ED6685388F3B510140F437E93B92583609D4B873BBA3641B2DB56AB26D3DC27A85866D8F66C4A33D82932ECE277387E583BB20A689BE12B597C6199799A3A53B970596355A46F7F94B9D5E07B09B8C47355CE19D7D2EC1F1DA8F382F7C90ABABDED1D82C8BD673C008E16102025B8C8AD33832953B9E28A1C01353C513D55F4E38C0FBC1FE7C1FB6B93D10B464F851BFE26426BC09C599708CA1CA3413BC4B147CD69A761E688E3846949AC3F455CCDC0DDB4FDBC91D880B38C73B7AD4C8633598F4570E3BCBA3C5E785686E38D2926187CDF0479DF5B818EBDDFDA757C31DF009ED234B3C0F2BC1ADC700FD715AFEE46AE5CBAD02ED086912BE45BE2D61097F008E45067C4ADC4FDFE29220E6CF0C6F7F8"; char testResult[512] = "A4E71A239CED53E936011DF80B516A07DFF13BB5B05BE43C46C05CCD"; // Get a SHA224 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA224)) != NULL); ByteString b(testData); ByteString osslHash(testResult), shsmHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); // Now recreate the hash in a multiple part operation shsmHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } void HashTests::testSHA256() { char testData[4096] = "C75FF0C53CB345524BF9800FDF53CE448F3369F9CA08C817F8F07AEF0689274527F0AF1EE7FB5AE99B37456765F39880640BF6C5582111753758DF49A9A13B52379DA0C7AE930B03BC57CD819D2EBA0E38AD33D10876608B99A69D0A73F001065276055C4B659F62F77E7232B021BC085A2472293D2D1875028444902AB29D78C9919EC52B33C9F839B1F839C7FF39B68669C925F53AFC865C93D3694E2FD3F29FF0B7773BB412D0FDB1B506A4D501F840D01AE9BF18D7558109B10A6E55CD8CF9A5279D559810A0B08C84C2C8C294AFEC06C6219EB1647A51488BCDDAACE7C652BB0D3F1DC552E4B42BAFF52FD17239F4C08DDDA1BBA97D8D35D3A3DA32D66858B2D320A62AAA7C3909C3A34DCF9DAA69BEC13B7B3EAAEA8A56E2C6DB2507C43BE8990ADC4A281B8BFC6C76FAED50217F109594902FF7E0EDFF5C018B0FC76CACFF84FB9EA97D6D543EDA732089E82FDE3B9D087320014680E5EA2B21B534125806B650F3268DB7951460A9E32F2EEAAF69300E6F0B7F846ECBC2904E93E8D0423FBDCC3E34C5085A97636EA9961B00880BC381E37C3A6E3115256B1A9E1A915A401A8E507F97A09BF3881E852FEA614DF76D709DE6DC0FE54500E0C42132E9ACFFE4A4A98654190FC6C14FC3E5F42CDCCAE0DE05DEF5F6961D7D13DE15376F35142C5846013B7D4A8A6AB363EC7932415C556B83787C86491820AA29C2FE31E39A3D73D710C490D1AF863C4166C2301ECF6967506DCFF6F97CAE63245634153072FE27E9C4B5F90B3C42E4BDB4FB0E85A548CDE2D3B480ABFB1ED6F054017B120E41529909AC055A9F5A29E25D0E5D1A8E8550B9C85C300BBAAE030B22BB646B1FD3A90FA1C242A26071423B3E239EF65BE8B347663B6BF63436AFFD311D10FD24C8E8D05CA99A808C41E6C9C7B283FE5FE9E311642349D2799B6D0CACD5826CC6CC5DDA22FB8BBDD6C66BB722697E4558A75B6D24FDD55631C17FCB591CA3CBA180CEC241B0555A91DF4D47A648A7D901B02C1AB557C4E1CF33E277AFE008D586857203FD6CE695C8EDD446F74056B173D6A0B07A2A58B39366B58BB76AF96DF9C37A5A5E1F8419163CEAA304D451DC38B8F142C422FB475869667D55D88F7C2624FC0B29A958BB4A44C6B0439542AAB02319D46B7E482149DC9A7C7BEBE651C7E8404140601CDB3742F58B6EEDA137FA083BA9D297F91B41B34C3535230841F18B672ED0FD817B7E4E3CD1FC018CDA63C21C3C3ED68228DF85B8C26572D1B14EF10D5D0BAF6F3ED4B9A8C3DFEB4EDEA00CE2DB5903D510432BCBA791C1BBDD2770F2616AF855941E1BD710CEE4F17C4C7A9E283B12DE901A88D634E4ADE69ED529328D64F8069033A6B4DA5D8E0E1C0150DB862AAD54F2827B41CE1F21E3F890033FD46E438615DDC527D6D1260BDB79478D6A0BE2B58174648A2387E3AE"; char testResult[512] = "3902802C215A5271439FE3E81AC7F21DA55545F71193A8DA8BEB0EAC8046A43B"; // Get a SHA256 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA256)) != NULL); ByteString b(testData); ByteString osslHash(testResult), shsmHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); // Now recreate the hash in a multiple part operation shsmHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } void HashTests::testSHA384() { char testData[4096] = "11FCD8770F582C2D9C860D1EB4FDBFE40C551C6F3AF41A2540A39BA3A121BFEF995F1727A8703C29D0A44EB85B339F27955E1C679796A72980BB1D1BEF4D51A73174A983D36CDAD56BC1EEBA5DDD642094996531EEC94DE2FB6E0ED4F23BCB2F1D0B25505EB16306473DA17F809BD994FD9A737D29819BCCF94CA225D2EBB9D89DDA6E03E80A9DE87E44B72EFD397F9F344122B6591CED9BFDE8C0C42D8C17223A93F33B7D569291F91B619297F233C1454A168AAE126E89B0ED32B0B69AB095A1BB24BB7F1AAF8EE0BDBB43025EF3339F96C9EA352E78BA0661DE896E8F4DFAA7EF623F2B5305AD338448C5FCBDD6CC1F1222ED1D8F4C634B82591F8906DA8DDA9A0FFB0F1499B5BD08239F7EB3A02ACEC60FB76754D0AC5077C3B733D346F0BDE654CD612F60E2284115297A1557679901A911C2AC7323DA2FF3CD57895D7D181AD43AB7068609CE046B96B445EA08CDF50C40DFAFBA9F7082707A813B9C8E4E9D7F0230D5AFE40174693512DE96E3FAB1C8F6548880823645A0AD811694B293F788D0D523EBD81851594733EF45FC763B956044E29B29C195BDB317FBF97F41C601A2873C25557C3149F648424380FE79E4DC407A9CECD8F14B843C642FD9921F12786C8A1C6F8514C99672038693C5CF1FBE91F903E4ABC9E55B967B2F72FDF1A2EC09C14C94C001BAC47A0C36E9E6F34431381069CFD64D85F11285391A4DC7419B2EE8062F344538413E757EC258192B90F2CCC1186AB9A4ED5CE1290644CDEDAF03A4BF3E94B9F9D132ED159CE03586C5A69EF0A471146378BCCE799A3CD8D627B688BB28C9288F44D1218BC34A05BEAA398371ADC60CA8A2557AB69BE7B737F84BFFA93A1E1115F498600F52144E0D61055A2FC0CD45E20962CB2FF475896D733C74C2E95986389ED74B1497A35E73FEE0F36270CC65D76C1FE27A35E8F1FA0C5CA7F2C6003E21BD6677502CE268EB55B16DA863FA291AA111F338F10592AF86DFC297718365C04839748195E20A64BF42020846A46C94F1728549B8310A7FBCBA2C1441B033639CE52B6DBDA69F6ACC57F2DE6BAC57755734AFE4B77869C4D9B0DC56B115476A86A82F816CB148CDFD2B1DCCBEFCD4559B59AA88C6429F4A9EBB43B641144752A5E6F8BE1B739AA69FEBCB8D7439E5D917CA759982146E627FF81E80CEBC37BE0CF2A6C12A3E84A389FFD25013C491AE90A395D4DBCA81340E86848217AC426603CCAC981B5ED701CE9AB2851DC5F2ED72484FE99767C0FDB6F122B0C67926A637B57EC4F047804BC3A9BD55CBD78B83154BC27B6F8A66085EF02A206F329F3B1531ED657C75E29DF4276070AE5054F484A12990A9DD13C112FB6D3D57AE42E6A048870FDAABA48F73E03344C0E13832BAFCA2AF81AF19E5C28983F7BAAA5135803E78FBDDF7FB53C9B9B709274F05C774C77F0B84"; char testResult[512] = "753659D55E4198325A3FED0A35761EC45038E8963B7525BF00D5A6A5D904DD9FA3FC80AB020185E08B14992ECC36A744"; // Get a SHA384 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA384)) != NULL); ByteString b(testData); ByteString osslHash(testResult), shsmHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); // Now recreate the hash in a multiple part operation shsmHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } void HashTests::testSHA512() { char testData[4096] = "B9D5BD978E1B4A0268331AE4F0C4494EBA71125ED75B9B4244407271A29D93BF5BA0D6641EBF7A210A0905B5EBE675F7B900B89542D0DA6A3952DF9DC5430ECE31F4A5834CCF132724963A088DE43966DC9F46011F2AD458E8FCDBA18F6D183235687A6145401E9FA2EDF60F47F3835D953B5856B1F8308457D9CEC29246DC51F5B42BD5DE38BD89945667579C05756D1C47BB58C2C3D049C58C014C1F6D962BF5EBA1D273F5A7FD6D9291E293CD30B8D8B489E79E54A7A11953EAF4FB6AC7F99910ECE05B511E098B6AD33A599F5A8FA43692FDD9F2A26F316427A2ED1F231E328864CDF9BA2879E0A711F48038E653520C74B7EEA8858F17AC332B87EF4C70A838263C8B17B373161A5A15293D1A7991F0EEAAE0BB69C95DEC22A1CD6808122489703770B5E276735F9D149067A7F3E6A7D10A790253C81778BB79C06D1F98A2CA9C2E8C4BAC0A96F0F9736B85E7BB4F090C5BEB25F087AC037517A9599D94E072D03D9C48665DD17649E001E45966AB8F2C7D24E38AE4F0519F056B034E0ED2CA133F108105BE4823758543791225144AB0B9609F0F861B69EEA8707D6DB9046910F28C6F8E1D47F59DFE9B59F81242FCBE5A71669B90F7B4050E517CF6D3F2FB8759FB7300F12C786D36183FA64692F379D030D0EA90859D9D8E00F27500B41FD716E325E695E3D8EBB40A4E32AFA75F6F21013C8A3261E9C18291DC99142FFF91EAB6C2B55FF5DE03B1DCC88C79635B96F13B66CE6E26A1D5F6154F3C6E5F22AF4B0334FD4521AE57B6B13E2D3B777AF66742635740ED4FF5FC752B908A079A6BBE8499344096549E6FC6FEDBE57AAF2992E7CBB19931F43360415C39D65D2A92775C78DE97C712022460E48651EBDDB9E0527C7EE59F6C817499100C11E884633DC66EF85B176D7A529894CA8F364F559D97DC7CF1769813FB36F8F738E77354C14A560CB98DF92BB5BB16A5A3EDFB75CB78A718C070BE5D37A6F742F88B51BC633FA9E309311BCA908F4D5EE381FB593B7A53E4CE3A529160A2965D0C4CEDC6548D036A1A4FE4576DA9D35E0CDDE9567E792D5C77EFAC17E531F402E0BE99957A7D378E90C009F3231FEE6E3898B5D2C4291EAD396CA748AB0A39469B921BDC5F8066AB7F0D28EE0C502EBC95C2A39DB4241886736F17DE1F33BD384EFDEA951BF775A0D41A499E85D0488016D7A281A9F7C715EBB7CD6AFBA59C1A93A5AEA66D71C3058C5A293141EE4D2C3E65853EFBEFC55912F5C08B9990A66C313F3199C0769CDCA711E877766ECA773EF2FDBC0656B8427CA6442062D911B13F1C2E92D3F0C608B1D8F12914953720021D5648364F953F93CC49946E44FBAF154A2FE3A8055922F784FF9B56D5FAC35B65266A248794101C12750DB8C107D048E551E52EB3952CFA26345B4E21652F5F3B8F85DE04AF9731B75C79DDBD6FE1A5"; char testResult[512] = "E1483A8525CE39705D14D60D8B19BD89087AED5FE6D8913AF8FC3F6F4EA2C1BB5957E205294B1EFAF20AE5EE39A9522F38B4514C3C15ED70BCBBD5821E385F95"; // Get a SHA512 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA512)) != NULL); ByteString b(testData); ByteString osslHash(testResult), shsmHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); // Now recreate the hash in a multiple part operation shsmHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(shsmHash)); CPPUNIT_ASSERT(osslHash == shsmHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } softhsm-2.0.0/src/lib/crypto/test/Makefile.am0000664000175000017500000000153712533040716016016 00000000000000MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../data_mgr \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ `cppunit-config --cflags` check_PROGRAMS = cryptotest cryptotest_SOURCES = cryptotest.cpp \ AESTests.cpp \ DESTests.cpp \ DHTests.cpp \ DSATests.cpp \ ECDHTests.cpp \ ECDSATests.cpp \ GOSTTests.cpp \ HashTests.cpp \ MacTests.cpp \ RNGTests.cpp \ RSATests.cpp \ chisq.c \ ent.c \ iso8859.c \ randtest.c cryptotest_LDADD = ../../libsofthsm_convarch.la cryptotest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` TESTS = cryptotest EXTRA_DIST = $(srcdir)/*.h softhsm-2.0.0/src/lib/crypto/test/DHTests.h0000664000175000017500000000422712533040716015450 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHTests.h Contains test cases to test the DH class *****************************************************************************/ #ifndef _SOFTHSM_V2_DHTESTS_H #define _SOFTHSM_V2_DHTESTS_H #include #include "AsymmetricAlgorithm.h" class DHTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DHTests); CPPUNIT_TEST(testKeyGeneration); CPPUNIT_TEST(testSerialisation); CPPUNIT_TEST(testPKCS8); CPPUNIT_TEST(testDerivation); CPPUNIT_TEST(testDeriveKnownVector); CPPUNIT_TEST_SUITE_END(); public: void testKeyGeneration(); void testSerialisation(); void testPKCS8(); void testDerivation(); void testDeriveKnownVector(); void setUp(); void tearDown(); private: // DH instance AsymmetricAlgorithm* dh; }; #endif // !_SOFTHSM_V2_DHTESTS_H softhsm-2.0.0/src/lib/crypto/test/iso8859.h0000664000175000017500000000267312533040716015265 00000000000000/* This code was taken from http://www.fourmilab.ch/random/ where it states that: This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided “as is” without express or implied warranty. */ /* ISO 8859/1 Latin-1 "ctype" macro replacements. */ extern unsigned char isoalpha[32], isoupper[32], isolower[32]; #define isISOspace(x) ((isascii(((unsigned char) (x))) && isspace(((unsigned char) (x)))) || ((x) == 0xA0)) #define isISOalpha(x) ((isoalpha[(((unsigned char) (x))) / 8] & (0x80 >> ((((unsigned char) (x))) % 8))) != 0) #define isISOupper(x) ((isoupper[(((unsigned char) (x))) / 8] & (0x80 >> ((((unsigned char) (x))) % 8))) != 0) #define isISOlower(x) ((isolower[(((unsigned char) (x))) / 8] & (0x80 >> ((((unsigned char) (x))) % 8))) != 0) #define isISOprint(x) ((((x) >= ' ') && ((x) <= '~')) || ((x) >= 0xA0)) #define toISOupper(x) (isISOlower(x) ? (isascii(((unsigned char) (x))) ? \ toupper(x) : (((((unsigned char) (x)) != 0xDF) && \ (((unsigned char) (x)) != 0xFF)) ? \ (((unsigned char) (x)) - 0x20) : (x))) : (x)) #define toISOlower(x) (isISOupper(x) ? (isascii(((unsigned char) (x))) ? \ tolower(x) : (((unsigned char) (x)) + 0x20)) \ : (x)) softhsm-2.0.0/src/lib/crypto/test/DSATests.h0000664000175000017500000000426412533040716015565 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSATests.h Contains test cases to test the DSA class *****************************************************************************/ #ifndef _SOFTHSM_V2_DSATESTS_H #define _SOFTHSM_V2_DSATESTS_H #include #include "AsymmetricAlgorithm.h" class DSATests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DSATests); CPPUNIT_TEST(testKeyGeneration); CPPUNIT_TEST(testSerialisation); CPPUNIT_TEST(testPKCS8); CPPUNIT_TEST(testSigningVerifying); CPPUNIT_TEST(testSignVerifyKnownVector); CPPUNIT_TEST_SUITE_END(); public: void testKeyGeneration(); void testSerialisation(); void testPKCS8(); void testSigningVerifying(); void testSignVerifyKnownVector(); void setUp(); void tearDown(); private: // DSA instance AsymmetricAlgorithm* dsa; }; #endif // !_SOFTHSM_V2_DSATESTS_H softhsm-2.0.0/src/lib/crypto/test/RSATests.h0000664000175000017500000000436312533040716015603 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSATests.h Contains test cases to test the RSA class *****************************************************************************/ #ifndef _SOFTHSM_V2_RSATESTS_H #define _SOFTHSM_V2_RSATESTS_H #include #include "AsymmetricAlgorithm.h" class RSATests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RSATests); CPPUNIT_TEST(testKeyGeneration); CPPUNIT_TEST(testSerialisation); CPPUNIT_TEST(testPKCS8); CPPUNIT_TEST(testSigningVerifying); CPPUNIT_TEST(testSignVerifyKnownVector); CPPUNIT_TEST(testEncryptDecrypt); CPPUNIT_TEST_SUITE_END(); public: void testKeyGeneration(); void testSerialisation(); void testPKCS8(); void testSigningVerifying(); void testSignVerifyKnownVector(); void testEncryptDecrypt(); void setUp(); void tearDown(); private: // RSA instance AsymmetricAlgorithm* rsa; }; #endif // !_SOFTHSM_V2_RSATESTS_H softhsm-2.0.0/src/lib/crypto/test/GOSTTests.h0000664000175000017500000000463412533040716015733 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** GOSTTests.h Contains test cases to test the GOST implementations *****************************************************************************/ #ifndef _SOFTHSM_V2_HASHTESTS_H #define _SOFTHSM_V2_HASHTESTS_H #include #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include "MacAlgorithm.h" #include "RNG.h" class GOSTTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(GOSTTests); CPPUNIT_TEST(testHash); CPPUNIT_TEST(testHmac); CPPUNIT_TEST(testHashKnownVector); CPPUNIT_TEST(testKeyGeneration); CPPUNIT_TEST(testSerialisation); CPPUNIT_TEST(testSigningVerifying); CPPUNIT_TEST(testSignVerifyKnownVector); CPPUNIT_TEST_SUITE_END(); public: void testHash(); void testHmac(); void testHashKnownVector(); void testKeyGeneration(); void testSerialisation(); void testSigningVerifying(); void testSignVerifyKnownVector(); void setUp(); void tearDown(); private: HashAlgorithm* hash; MacAlgorithm* mac; AsymmetricAlgorithm* gost; RNG* rng; }; #endif // !_SOFTHSM_V2_HASHTESTS_H softhsm-2.0.0/src/lib/crypto/test/RSATests.cpp0000664000175000017500000005267712533040716016151 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSATests.cpp Contains test cases to test the RNG class *****************************************************************************/ #include #include #include #include "RSATests.h" #include "CryptoFactory.h" #include "RNG.h" #include "AsymmetricKeyPair.h" #include "AsymmetricAlgorithm.h" #include "RSAParameters.h" #include "RSAPublicKey.h" #include "RSAPrivateKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(RSATests); void RSATests::setUp() { rsa = NULL; rsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::RSA); // Check the RSA object CPPUNIT_ASSERT(rsa != NULL); } void RSATests::tearDown() { if (rsa != NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(rsa); } fflush(stdout); } void RSATests::testKeyGeneration() { AsymmetricKeyPair* kp; RSAParameters p; // Public exponents to test std::vector exponents; exponents.push_back("010001"); exponents.push_back("03"); exponents.push_back("0B"); exponents.push_back("11"); // Key sizes to test std::vector keySizes; keySizes.push_back(1024); #ifndef WITH_FIPS keySizes.push_back(1025); #endif keySizes.push_back(1280); keySizes.push_back(2048); //keySizes.push_back(4096); for (std::vector::iterator e = exponents.begin(); e != exponents.end(); e++) { for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { p.setE(*e); p.setBitLength(*k); // Generate key-pair CPPUNIT_ASSERT(rsa->generateKeyPair(&kp, &p)); RSAPublicKey* pub = (RSAPublicKey*) kp->getPublicKey(); RSAPrivateKey* priv = (RSAPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getBitLength() == *k); CPPUNIT_ASSERT(priv->getBitLength() == *k); CPPUNIT_ASSERT(pub->getE() == *e); CPPUNIT_ASSERT(priv->getE() == *e); rsa->recycleKeyPair(kp); } } } void RSATests::testSerialisation() { // Generate a 1024-bit key-pair for testing AsymmetricKeyPair* kp; RSAParameters p; p.setE("010001"); p.setBitLength(1024); CPPUNIT_ASSERT(rsa->generateKeyPair(&kp, &p)); CPPUNIT_ASSERT(kp != NULL); // Serialise the parameters ByteString serialisedParams = p.serialise(); // Deserialise the parameters AsymmetricParameters* dP; CPPUNIT_ASSERT(rsa->reconstructParameters(&dP, serialisedParams)); CPPUNIT_ASSERT(dP->areOfType(RSAParameters::type)); RSAParameters* ddP = (RSAParameters*) dP; CPPUNIT_ASSERT(p.getE() == ddP->getE()); CPPUNIT_ASSERT(p.getBitLength() == ddP->getBitLength()); rsa->recycleParameters(dP); // Serialise the key-pair ByteString serialisedKP = kp->serialise(); CPPUNIT_ASSERT(serialisedKP.size() != 0); // Deserialise the key-pair AsymmetricKeyPair* dKP; CPPUNIT_ASSERT(rsa->reconstructKeyPair(&dKP, serialisedKP)); CPPUNIT_ASSERT(serialisedKP.size() == 0); CPPUNIT_ASSERT(dKP != NULL); RSAPublicKey* pub = (RSAPublicKey*) kp->getPublicKey(); RSAPrivateKey* priv = (RSAPrivateKey*) kp->getPrivateKey(); RSAPublicKey* dPub = (RSAPublicKey*) dKP->getPublicKey(); RSAPrivateKey* dPriv = (RSAPrivateKey*) dKP->getPrivateKey(); CPPUNIT_ASSERT(pub->getN() == dPub->getN()); CPPUNIT_ASSERT(pub->getE() == dPub->getE()); CPPUNIT_ASSERT(priv->getP() == dPriv->getP()); CPPUNIT_ASSERT(priv->getQ() == dPriv->getQ()); CPPUNIT_ASSERT(priv->getPQ() == dPriv->getPQ()); CPPUNIT_ASSERT(priv->getDP1() == dPriv->getDP1()); CPPUNIT_ASSERT(priv->getDQ1() == dPriv->getDQ1()); CPPUNIT_ASSERT(priv->getD() == dPriv->getD()); CPPUNIT_ASSERT(priv->getN() == dPriv->getN()); CPPUNIT_ASSERT(priv->getE() == dPriv->getE()); // Serialise and deserialise the public key ByteString serialisedPub = pub->serialise(); RSAPublicKey* desPub; CPPUNIT_ASSERT(rsa->reconstructPublicKey((PublicKey**) &desPub, serialisedPub)); CPPUNIT_ASSERT(serialisedPub.size() == 0); CPPUNIT_ASSERT(desPub != NULL); CPPUNIT_ASSERT(pub->getN() == desPub->getN()); CPPUNIT_ASSERT(pub->getE() == desPub->getE()); // Serialise and deserialise the private key ByteString serialisedPriv = priv->serialise(); RSAPrivateKey* desPriv; CPPUNIT_ASSERT(rsa->reconstructPrivateKey((PrivateKey**) &desPriv, serialisedPriv)); CPPUNIT_ASSERT(serialisedPriv.size() == 0); CPPUNIT_ASSERT(desPriv != NULL); CPPUNIT_ASSERT(priv->getP() == desPriv->getP()); CPPUNIT_ASSERT(priv->getQ() == desPriv->getQ()); CPPUNIT_ASSERT(priv->getPQ() == desPriv->getPQ()); CPPUNIT_ASSERT(priv->getDP1() == desPriv->getDP1()); CPPUNIT_ASSERT(priv->getDQ1() == desPriv->getDQ1()); CPPUNIT_ASSERT(priv->getD() == desPriv->getD()); CPPUNIT_ASSERT(priv->getN() == desPriv->getN()); CPPUNIT_ASSERT(priv->getE() == desPriv->getE()); rsa->recycleKeyPair(kp); rsa->recycleKeyPair(dKP); rsa->recyclePublicKey(desPub); rsa->recyclePrivateKey(desPriv); } void RSATests::testPKCS8() { // Generate a 1024-bit key-pair for testing AsymmetricKeyPair* kp; RSAParameters p; p.setE("010001"); p.setBitLength(1024); CPPUNIT_ASSERT(rsa->generateKeyPair(&kp, &p)); CPPUNIT_ASSERT(kp != NULL); RSAPrivateKey* priv = (RSAPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); RSAPrivateKey* dPriv = (RSAPrivateKey*) rsa->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getP() == dPriv->getP()); CPPUNIT_ASSERT(priv->getQ() == dPriv->getQ()); CPPUNIT_ASSERT(priv->getPQ() == dPriv->getPQ()); CPPUNIT_ASSERT(priv->getDP1() == dPriv->getDP1()); CPPUNIT_ASSERT(priv->getDQ1() == dPriv->getDQ1()); CPPUNIT_ASSERT(priv->getD() == dPriv->getD()); CPPUNIT_ASSERT(priv->getN() == dPriv->getN()); CPPUNIT_ASSERT(priv->getE() == dPriv->getE()); rsa->recycleKeyPair(kp); rsa->recyclePrivateKey(dPriv); } void RSATests::testSigningVerifying() { AsymmetricKeyPair* kp; RSAParameters p; // Public exponents to test std::vector exponents; exponents.push_back("010001"); exponents.push_back("03"); exponents.push_back("0B"); exponents.push_back("11"); // Key sizes to test std::vector keySizes; keySizes.push_back(1024); keySizes.push_back(1280); keySizes.push_back(2048); //keySizes.push_back(4096); // Mechanisms to test std::vector mechanisms; #ifndef WITH_FIPS mechanisms.push_back(AsymMech::RSA_MD5_PKCS); #endif mechanisms.push_back(AsymMech::RSA_SHA1_PKCS); mechanisms.push_back(AsymMech::RSA_SHA224_PKCS); mechanisms.push_back(AsymMech::RSA_SHA256_PKCS); mechanisms.push_back(AsymMech::RSA_SHA384_PKCS); mechanisms.push_back(AsymMech::RSA_SHA512_PKCS); mechanisms.push_back(AsymMech::RSA_SHA1_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA224_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA256_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA384_PKCS_PSS); mechanisms.push_back(AsymMech::RSA_SHA512_PKCS_PSS); #ifndef WITH_FIPS mechanisms.push_back(AsymMech::RSA_SSL); #endif /* Max salt length for SHA512 and 1024-bit RSA is 62 bytes */ RSA_PKCS_PSS_PARAMS pssParams[] = { { HashAlgo::SHA1, AsymRSAMGF::MGF1_SHA1, 20 }, { HashAlgo::SHA224, AsymRSAMGF::MGF1_SHA224, 0 }, { HashAlgo::SHA256, AsymRSAMGF::MGF1_SHA256, 0 }, { HashAlgo::SHA384, AsymRSAMGF::MGF1_SHA384, 48 }, { HashAlgo::SHA512, AsymRSAMGF::MGF1_SHA512, 62 } }; for (std::vector::iterator e = exponents.begin(); e != exponents.end(); e++) { for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { p.setE(*e); p.setBitLength(*k); // Generate key-pair CPPUNIT_ASSERT(rsa->generateKeyPair(&kp, &p)); // Generate some data to sign ByteString dataToSign; RNG* rng = CryptoFactory::i()->getRNG(); CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567)); // Test mechanisms that perform internal hashing for (std::vector::iterator m = mechanisms.begin(); m != mechanisms.end(); m++) { ByteString blockSignature, singlePartSignature; void* param = NULL; size_t paramLen = 0; bool isPSS = false; switch (*m) { case AsymMech::RSA_SHA1_PKCS_PSS: param = &pssParams[0]; paramLen = sizeof(pssParams[0]); isPSS = true; break; case AsymMech::RSA_SHA224_PKCS_PSS: param = &pssParams[1]; paramLen = sizeof(pssParams[1]); isPSS = true; break; case AsymMech::RSA_SHA256_PKCS_PSS: param = &pssParams[2]; paramLen = sizeof(pssParams[2]); isPSS = true; break; case AsymMech::RSA_SHA384_PKCS_PSS: param = &pssParams[3]; paramLen = sizeof(pssParams[3]); isPSS = true; break; case AsymMech::RSA_SHA512_PKCS_PSS: param = &pssParams[4]; paramLen = sizeof(pssParams[4]); isPSS = true; break; default: break; } // Sign the data in blocks CPPUNIT_ASSERT(rsa->signInit(kp->getPrivateKey(), *m, param, paramLen)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign.substr(0, 134))); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign.substr(134, 289))); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign.substr(134 + 289))); CPPUNIT_ASSERT(rsa->signFinal(blockSignature)); // Sign the data in one pass CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, singlePartSignature, *m, param, paramLen)); // If it is not a PSS signature, check if the two signatures match if (!isPSS) { // Check if the two signatures match CPPUNIT_ASSERT(blockSignature == singlePartSignature); } // Now perform multi-pass verification CPPUNIT_ASSERT(rsa->verifyInit(kp->getPublicKey(), *m, param, paramLen)); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign.substr(0, 125))); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign.substr(125, 247))); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign.substr(125 + 247))); CPPUNIT_ASSERT(rsa->verifyFinal(blockSignature)); // And single-pass verification CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, singlePartSignature, *m, param, paramLen)); } // Test mechanisms that do not perform internal hashing // Test PKCS #1 signing CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 35)); // Sign the data ByteString signature; CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA_PKCS)); // Verify the signature CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA_PKCS)); // Test raw RSA signing size_t byteSize = *k >> 3; CPPUNIT_ASSERT(rng->generateRandom(dataToSign, byteSize)); // Strip the topmost bit dataToSign[0] &= 0x7F; // Sign the data CPPUNIT_ASSERT(rsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::RSA)); // Verify the signature CPPUNIT_ASSERT(rsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::RSA)); rsa->recycleKeyPair(kp); } } } void RSATests::testSignVerifyKnownVector() { // These test vectors were taken from the Crypto++ set of test vectors // Crypto++ can be downloaded from www.cryptopp.com #ifndef WITH_FIPS RSAPublicKey* pubKey1 = (RSAPublicKey*) rsa->newPublicKey(); RSAPublicKey* pubKey2 = (RSAPublicKey*) rsa->newPublicKey(); #endif RSAPublicKey* pubKey3 = (RSAPublicKey*) rsa->newPublicKey(); #ifndef WITH_FIPS RSAPrivateKey* privKey1_1 = (RSAPrivateKey*) rsa->newPrivateKey(); RSAPrivateKey* privKey1_2 = (RSAPrivateKey*) rsa->newPrivateKey(); RSAPrivateKey* privKey2_1 = (RSAPrivateKey*) rsa->newPrivateKey(); RSAPrivateKey* privKey2_2 = (RSAPrivateKey*) rsa->newPrivateKey(); #endif RSAPrivateKey* privKey3 = (RSAPrivateKey*) rsa->newPrivateKey(); #ifndef WITH_FIPS // Reconstruct public and private key #1 ByteString n1 = "0A66791DC6988168DE7AB77419BB7FB0C001C62710270075142942E19A8D8C51D053B3E3782A1DE5DC5AF4EBE99468170114A1DFE67CDC9A9AF55D655620BBAB"; ByteString e1 = "010001"; ByteString d1 = "0123C5B61BA36EDB1D3679904199A89EA80C09B9122E1400C09ADCF7784676D01D23356A7D44D6BD8BD50E94BFC723FA87D8862B75177691C11D757692DF8881"; ByteString p1 = "33D48445C859E52340DE704BCDDA065FBB4058D740BD1D67D29E9C146C11CF61"; ByteString q1 = "335E8408866B0FD38DC7002D3F972C67389A65D5D8306566D5C4F2A5AA52628B"; ByteString dp11 = "045EC90071525325D3D46DB79695E9AFACC4523964360E02B119BAA366316241"; ByteString dq11 = "15EB327360C7B60D12E5E2D16BDCD97981D17FBA6B70DB13B20B436E24EADA59"; ByteString pq1 = "2CA6366D72781DFA24D34A9A24CBC2AE927A9958AF426563FF63FB11658A461D"; pubKey1->setN(n1); pubKey1->setE(e1); privKey1_1->setN(n1); privKey1_1->setE(e1); privKey1_1->setD(d1); privKey1_1->setP(p1); privKey1_1->setQ(q1); privKey1_1->setDP1(dp11); privKey1_1->setDQ1(dq11); privKey1_1->setPQ(pq1); // The same key but without CRT factors privKey1_2->setN(n1); privKey1_2->setE(e1); privKey1_2->setD(d1); // Reconstruct public and private key #2 ByteString n2 = "A885B6F851A8079AB8A281DB0297148511EE0D8C07C0D4AE6D6FED461488E0D41E3FF8F281B06A3240B5007A5C2AB4FB6BE8AF88F119DB998368DDDC9710ABED"; ByteString e2 = "010001"; ByteString d2 = "2B259D2CA3DF851EE891F6F4678BDDFD9A131C95D3305C63D2723B4A5B9C960F5EC8BB7DCDDBEBD8B6A38767D64AD451E9383E0891E4EE7506100481F2B49323"; ByteString p2 = "D7103CD676E39824E2BE50B8E6533FE7CB7484348E283802AD2B8D00C80D19DF"; ByteString q2 = "C89996DC169CEB3F227958275968804D4BE9FC4012C3219662F1A438C9950BB3"; ByteString dp12 = "5D8EA4C8AF83A70634D5920C3DB66D908AC3AF57A597FD75BC9BBB856181C185"; ByteString dq12 = "C598E54DAEC8ABC1E907769A6C2BD01653ED0C9960E1EDB7E186FDA922883A99"; ByteString pq2 = "7C6F27B5B51B78AD80FB36E700990CF307866F2943124CBD93D97C137794C104"; pubKey2->setN(n2); pubKey2->setE(e2); privKey2_1->setN(n2); privKey2_1->setE(e2); privKey2_1->setD(d2); privKey2_1->setP(p2); privKey2_1->setQ(q2); privKey2_1->setDP1(dp12); privKey2_1->setDQ1(dq12); privKey2_1->setPQ(pq2); // The same key but without CRT factors privKey2_2->setN(n2); privKey2_2->setE(e2); privKey2_2->setD(d2); #endif ByteString n3 = "A8D68ACD413C5E195D5EF04E1B4FAAF242365CB450196755E92E1215BA59802AAFBADBF2564DD550956ABB54F8B1C917844E5F36195D1088C600E07CADA5C080EDE679F50B3DE32CF4026E514542495C54B1903768791AAE9E36F082CD38E941ADA89BAECADA61AB0DD37AD536BCB0A0946271594836E92AB5517301D45176B5"; ByteString e3 = "03"; ByteString d3 = "1C23C1CCE034BA598F8FD2B7AF37F1D30B090F7362AEE68E5187ADAE49B9955C729F24A863B7A38D6E3C748E2972F6D940B7BA89043A2D6C2100256A1CF0F56A8CD35FC6EE205244876642F6F9C3820A3D9D2C8921DF7D82AAADCAF2D7334D398931DDBBA553190B3A416099F3AA07FD5B26214645A828419E122CFB857AD73B"; ByteString p3 = "C107a2fe924b76e206cb9bc4af2ab7008547c00846bf6d0680b3eac3ebcbd0c7fd7a54c2b9899b08f80cde1d3691eaaa2816b1eb11822d6be7beaf4e30977c49"; ByteString q3 = "DFEA984CE4307EAFC0D140C2BB82861E5DBAC4F8567CBC981D70440DD639492079031486315E305EB83E591C4A2E96064966F7C894C3CA351925B5CE82D8EF0D"; pubKey3->setN(n3); pubKey3->setE(e3); privKey3->setN(n3); privKey3->setE(e3); privKey3->setD(d3); privKey3->setP(p3); privKey3->setQ(q3); #ifndef WITH_FIPS // Test with key #1 const char* testValue1 = "Everyone gets Friday off."; ByteString dataToSign1((const unsigned char*) testValue1, strlen(testValue1)); ByteString expectedSignature1 = "0610761F95FFD1B8F29DA34212947EC2AA0E358866A722F03CC3C41487ADC604A48FF54F5C6BEDB9FB7BD59F82D6E55D8F3174BA361B2214B2D74E8825E04E81"; ByteString signature1_1; ByteString signature1_2; CPPUNIT_ASSERT(rsa->signInit(privKey1_1, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign1)); CPPUNIT_ASSERT(rsa->signFinal(signature1_1)); #ifndef WITH_BOTAN CPPUNIT_ASSERT(rsa->signInit(privKey1_2, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign1)); CPPUNIT_ASSERT(rsa->signFinal(signature1_2)); CPPUNIT_ASSERT(signature1_1 == signature1_2); #endif CPPUNIT_ASSERT(signature1_1 == expectedSignature1); CPPUNIT_ASSERT(rsa->verifyInit(pubKey1, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign1)); CPPUNIT_ASSERT(rsa->verifyFinal(expectedSignature1)); // Test with key #2 const char* testValue2 = "test"; ByteString dataToSign2((const unsigned char*) testValue2, strlen(testValue2)); ByteString expectedSignature2 = "A7E00CE4391F914D82158D9B732759808E25A1C6383FE87A5199157650D4296CF612E9FF809E686A0AF328238306E79965F6D0138138829D9A1A22764306F6CE"; ByteString signature2_1; ByteString signature2_2; CPPUNIT_ASSERT(rsa->signInit(privKey2_1, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign2)); CPPUNIT_ASSERT(rsa->signFinal(signature2_1)); #ifndef WITH_BOTAN CPPUNIT_ASSERT(rsa->signInit(privKey2_2, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign2)); CPPUNIT_ASSERT(rsa->signFinal(signature2_2)); CPPUNIT_ASSERT(signature2_1 == signature2_2); #endif CPPUNIT_ASSERT(signature2_1 == expectedSignature2); CPPUNIT_ASSERT(rsa->verifyInit(pubKey2, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign2)); CPPUNIT_ASSERT(rsa->verifyFinal(expectedSignature2)); #endif // Test with key #3 ByteString dataToSign3 = "D73829497CDDBE41B705FAAC50E7899FDB5A38BF3A459E536357029E64F8796BA47F4FE96BA5A8B9A4396746E2164F55A25368DDD0B9A5188C7AC3DA2D1F742286C3BDEE697F9D546A25EFCFE53191D743FCC6B47833D993D08804DAECA78FB9076C3C017F53E33A90305AF06220974D46BF19ED3C9B84EDBAE98B45A8771258"; ByteString expectedSignature3 = "175015BDA50ABE0FA7D39A8353885CA01BE3A7E7FCC55045744111362EE1914473A48DC537D956294B9E20A1EF661D58537ACDC8DE908FA050630FCC272E6D001045E6FDEED2D10531C8603334C2E8DB39E73E6D9665EE1343F9E4198302D2201B44E8E8D06B3EF49CEE6197582163A8490089CA654C0012FCE1BA6511089750"; ByteString signature3; CPPUNIT_ASSERT(rsa->signInit(privKey3, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->signUpdate(dataToSign3)); CPPUNIT_ASSERT(rsa->signFinal(signature3)); CPPUNIT_ASSERT(signature3 == expectedSignature3); CPPUNIT_ASSERT(rsa->verifyInit(pubKey3, AsymMech::RSA_SHA1_PKCS)); CPPUNIT_ASSERT(rsa->verifyUpdate(dataToSign3)); CPPUNIT_ASSERT(rsa->verifyFinal(expectedSignature3)); #ifndef WITH_FIPS rsa->recyclePublicKey(pubKey1); rsa->recyclePublicKey(pubKey2); #endif rsa->recyclePublicKey(pubKey3); #ifndef WITH_FIPS rsa->recyclePrivateKey(privKey1_1); rsa->recyclePrivateKey(privKey1_2); rsa->recyclePrivateKey(privKey2_1); rsa->recyclePrivateKey(privKey2_2); #endif rsa->recyclePrivateKey(privKey3); } void RSATests::testEncryptDecrypt() { AsymmetricKeyPair* kp; RSAParameters p; // Public exponents to test std::vector exponents; exponents.push_back("010001"); exponents.push_back("03"); exponents.push_back("0B"); exponents.push_back("11"); // Key sizes to test std::vector keySizes; keySizes.push_back(1024); keySizes.push_back(1280); keySizes.push_back(2048); //keySizes.push_back(4096); // Paddings to test std::vector paddings; paddings.push_back(AsymMech::RSA_PKCS); paddings.push_back(AsymMech::RSA_PKCS_OAEP); paddings.push_back(AsymMech::RSA); for (std::vector::iterator e = exponents.begin(); e != exponents.end(); e++) { for (std::vector::iterator k = keySizes.begin(); k != keySizes.end(); k++) { p.setE(*e); p.setBitLength(*k); // Generate key-pair CPPUNIT_ASSERT(rsa->generateKeyPair(&kp, &p)); RNG* rng = CryptoFactory::i()->getRNG(); for (std::vector::iterator pad = paddings.begin(); pad != paddings.end(); pad++) { // Generate some test data to encrypt based on the selected padding ByteString testData; if (*pad == AsymMech::RSA_PKCS) { CPPUNIT_ASSERT(rng->generateRandom(testData, (*k >> 3) - 12)); } else if (*pad == AsymMech::RSA_PKCS_OAEP) { CPPUNIT_ASSERT(rng->generateRandom(testData, (*k >> 3) - 42)); } else if (*pad == AsymMech::RSA) { CPPUNIT_ASSERT(rng->generateRandom(testData, *k >> 3)); testData[0] &= 0x0F; } else { CPPUNIT_ASSERT(true == false); } // Encrypt the data ByteString encryptedData; CPPUNIT_ASSERT(rsa->encrypt(kp->getPublicKey(), testData, encryptedData, *pad)); // The encrypted data length should equal the modulus length CPPUNIT_ASSERT(encryptedData.size() == (*k >> 3)); CPPUNIT_ASSERT(encryptedData != testData); // Now decrypt the data ByteString decryptedData; CPPUNIT_ASSERT(rsa->decrypt(kp->getPrivateKey(), encryptedData, decryptedData, *pad)); // Check that the data was properly decrypted CPPUNIT_ASSERT(decryptedData == testData); } rsa->recycleKeyPair(kp); } } } softhsm-2.0.0/src/lib/crypto/test/ECDHTests.cpp0000664000175000017500000001750712533040716016220 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECDHTests.cpp Contains test cases to test the ECDH class *****************************************************************************/ #include #include #include #include "ECDHTests.h" #include "CryptoFactory.h" #include "RNG.h" #include "AsymmetricKeyPair.h" #include "AsymmetricAlgorithm.h" #ifdef WITH_ECC #include "ECParameters.h" #include "ECPublicKey.h" #include "ECPrivateKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(ECDHTests); void ECDHTests::setUp() { ecdh = NULL; ecdh = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDH); // Check the ECDH object CPPUNIT_ASSERT(ecdh != NULL); } void ECDHTests::tearDown() { if (ecdh != NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdh); } fflush(stdout); } void ECDHTests::testKeyGeneration() { AsymmetricKeyPair* kp; // Curves to test std::vector curves; // Add X9.62 prime256v1 curves.push_back(ByteString("06082a8648ce3d030107")); // Add secp384r1 curves.push_back(ByteString("06052b81040022")); for (std::vector::iterator c = curves.begin(); c != curves.end(); c++) { // Set domain parameters ECParameters* p = new ECParameters; p->setEC(*c); // Generate key-pair CPPUNIT_ASSERT(ecdh->generateKeyPair(&kp, p)); ECPublicKey* pub = (ECPublicKey*) kp->getPublicKey(); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getEC() == *c); CPPUNIT_ASSERT(priv->getEC() == *c); ecdh->recycleParameters(p); ecdh->recycleKeyPair(kp); } } void ECDHTests::testSerialisation() { // Get prime256v1 domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06082a8648ce3d030107")); // Serialise the parameters ByteString serialisedParams = p->serialise(); // Deserialise the parameters AsymmetricParameters* dEC; CPPUNIT_ASSERT(ecdh->reconstructParameters(&dEC, serialisedParams)); CPPUNIT_ASSERT(dEC->areOfType(ECParameters::type)); ECParameters* ddEC = (ECParameters*) dEC; CPPUNIT_ASSERT(p->getEC() == ddEC->getEC()); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(ecdh->generateKeyPair(&kp, dEC)); // Serialise the key-pair ByteString serialisedKP = kp->serialise(); // Deserialise the key-pair AsymmetricKeyPair* dKP; CPPUNIT_ASSERT(ecdh->reconstructKeyPair(&dKP, serialisedKP)); // Check the deserialised key-pair ECPrivateKey* privKey = (ECPrivateKey*) kp->getPrivateKey(); ECPublicKey* pubKey = (ECPublicKey*) kp->getPublicKey(); ECPrivateKey* dPrivKey = (ECPrivateKey*) dKP->getPrivateKey(); ECPublicKey* dPubKey = (ECPublicKey*) dKP->getPublicKey(); CPPUNIT_ASSERT(privKey->getEC() == dPrivKey->getEC()); CPPUNIT_ASSERT(privKey->getD() == dPrivKey->getD()); CPPUNIT_ASSERT(pubKey->getEC() == dPubKey->getEC()); CPPUNIT_ASSERT(pubKey->getQ() == dPubKey->getQ()); ecdh->recycleParameters(p); ecdh->recycleParameters(dEC); ecdh->recycleKeyPair(kp); ecdh->recycleKeyPair(dKP); } void ECDHTests::testPKCS8() { // Get prime256v1 domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06082a8648ce3d030107")); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(ecdh->generateKeyPair(&kp, p)); CPPUNIT_ASSERT(kp != NULL); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); ECPrivateKey* dPriv = (ECPrivateKey*) ecdh->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getEC() == dPriv->getEC()); CPPUNIT_ASSERT(priv->getD() == dPriv->getD()); ecdh->recycleParameters(p); ecdh->recycleKeyPair(kp); ecdh->recyclePrivateKey(dPriv); } void ECDHTests::testDerivation() { AsymmetricKeyPair* kpa; AsymmetricKeyPair* kpb; ECParameters* p; // Curves to test std::vector curves; // Add X9.62 prime256v1 curves.push_back(ByteString("06082a8648ce3d030107")); // Add secp384r1 curves.push_back(ByteString("06052b81040022")); for (std::vector::iterator c = curves.begin(); c != curves.end(); c++) { // Get parameters p = new ECParameters; CPPUNIT_ASSERT(p != NULL); p->setEC(*c); // Generate key-pairs CPPUNIT_ASSERT(ecdh->generateKeyPair(&kpa, p)); CPPUNIT_ASSERT(ecdh->generateKeyPair(&kpb, p)); // Derive secrets SymmetricKey* sa; CPPUNIT_ASSERT(ecdh->deriveKey(&sa, kpb->getPublicKey(), kpa->getPrivateKey())); SymmetricKey* sb; CPPUNIT_ASSERT(ecdh->deriveKey(&sb, kpa->getPublicKey(), kpb->getPrivateKey())); // Must be the same CPPUNIT_ASSERT(sa->getKeyBits() == sb->getKeyBits()); // Clean up ecdh->recycleSymmetricKey(sa); ecdh->recycleSymmetricKey(sb); ecdh->recycleKeyPair(kpa); ecdh->recycleKeyPair(kpb); ecdh->recycleParameters(p); } } void ECDHTests::testDeriveKnownVector() { ECPublicKey* pubKeya = (ECPublicKey*) ecdh->newPublicKey(); ECPublicKey* pubKeyb = (ECPublicKey*) ecdh->newPublicKey(); ECPrivateKey* privKeya = (ECPrivateKey*) ecdh->newPrivateKey(); ECPrivateKey* privKeyb = (ECPrivateKey*) ecdh->newPrivateKey(); // Reconstruct public and private key for Alice ByteString ec = "06082a8648ce3d030107"; // X9.62 prime256v1 ByteString da = "c88f01f510d9ac3f70a292daa2316de544e9aab8afe84049c62a9c57862d1433"; // add 04 (ASN_String) 04 (UNCOMPRESSED) in front! ByteString qa = "044104dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c37725811805271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3"; pubKeya->setEC(ec); pubKeya->setQ(qa); privKeya->setEC(ec); privKeya->setD(da); // Reconstruct public and private key for Bob ByteString db = "c6ef9c5d78ae012a011164acb397ce2088685d8f06bf9be0b283ab46476bee53"; ByteString qb = "044104d12dfb5289c8d4f81208b70270398c342296970a0bccb74c736fc7554494bf6356fbf3ca366cc23e8157854c13c58d6aac23f046ada30f8353e74f33039872ab"; pubKeyb->setEC(ec); pubKeyb->setQ(qb); privKeyb->setEC(ec); privKeyb->setD(db); // Test ByteString expected = "d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de"; SymmetricKey* sa; CPPUNIT_ASSERT(ecdh->deriveKey(&sa, pubKeya, privKeyb)); CPPUNIT_ASSERT(sa->getKeyBits() == expected); SymmetricKey* sb; CPPUNIT_ASSERT(ecdh->deriveKey(&sb, pubKeyb, privKeya)); CPPUNIT_ASSERT(sb->getKeyBits() == expected); ecdh->recyclePublicKey(pubKeya); ecdh->recyclePublicKey(pubKeyb); ecdh->recyclePrivateKey(privKeya); ecdh->recyclePrivateKey(privKeyb); ecdh->recycleSymmetricKey(sa); ecdh->recycleSymmetricKey(sb); } #endif softhsm-2.0.0/src/lib/crypto/test/randtest.h0000664000175000017500000000117012533040716015750 00000000000000/* This code was taken from http://www.fourmilab.ch/random/ where it states that: This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided “as is” without express or implied warranty. */ /* Random test function prototypes */ extern void rt_init(int binmode); extern void rt_add(void *buf, int bufl); extern void rt_end(double *r_ent, double *r_chisq, double *r_mean, double *r_montepicalc, double *r_scc); softhsm-2.0.0/src/lib/crypto/test/ECDSATests.h0000664000175000017500000000430612533040716015772 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECDSATests.h Contains test cases to test the ECDSA class *****************************************************************************/ #ifndef _SOFTHSM_V2_ECDSATESTS_H #define _SOFTHSM_V2_ECDSATESTS_H #include #include "AsymmetricAlgorithm.h" class ECDSATests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ECDSATests); CPPUNIT_TEST(testKeyGeneration); CPPUNIT_TEST(testSerialisation); CPPUNIT_TEST(testPKCS8); CPPUNIT_TEST(testSigningVerifying); CPPUNIT_TEST(testSignVerifyKnownVector); CPPUNIT_TEST_SUITE_END(); public: void testKeyGeneration(); void testSerialisation(); void testPKCS8(); void testSigningVerifying(); void testSignVerifyKnownVector(); void setUp(); void tearDown(); private: // ECDSA instance AsymmetricAlgorithm* ecdsa; }; #endif // !_SOFTHSM_V2_ECDSATESTS_H softhsm-2.0.0/src/lib/crypto/test/DESTests.h0000664000175000017500000000413512533040716015566 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DESTests.h Contains test cases to test the DES implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_DESTESTS_H #define _SOFTHSM_V2_DESTESTS_H #include #include "SymmetricAlgorithm.h" class DESTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DESTests); CPPUNIT_TEST(testBlockSize); CPPUNIT_TEST(testCBC); CPPUNIT_TEST(testECB); CPPUNIT_TEST(testOFB); CPPUNIT_TEST(testCFB); CPPUNIT_TEST_SUITE_END(); public: void testBlockSize(); void testCBC(); void testECB(); void testOFB(); void testCFB(); void setUp(); void tearDown(); private: // DES instance SymmetricAlgorithm* des; }; #endif // !_SOFTHSM_V2_DESTESTS_H softhsm-2.0.0/src/lib/crypto/test/MacTests.cpp0000664000175000017500000005270712533040716016216 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** MacTests.cpp Contains test cases to test the MAC implementations *****************************************************************************/ #include #include #include "MacTests.h" #include "CryptoFactory.h" #include #include "MacAlgorithm.h" #include "RNG.h" CPPUNIT_TEST_SUITE_REGISTRATION(MacTests); void MacTests::setUp() { mac = NULL; rng = NULL; } void MacTests::tearDown() { if (mac != NULL) { CryptoFactory::i()->recycleMacAlgorithm(mac); } fflush(stdout); } #ifndef WITH_FIPS void MacTests::testHMACMD5() { char testData[4096] = "B64CCFF0DC038F4B4B6C77677B1E89774028CFB6F94EE920ABFABC8C389F7DE287D558664FD05836E854458940A486A367C9B771A7938BE7DFFF2C695BB99CB96F946707FB405A0FA94116FC4002FAD47F813C4DAF6F39B579A2C1E607AF0F80E55FC6742ABB46CF25EFBAEF820DACAE925532E0F2AAAD64D23D0E5682DC38FA47F230EAA299C4D87EB76D45D4B4A08BB47AC873A428708F9D236CF9B11831BC713DB5C8F58A4A4DD228B7A370154CCDB92420B01D0B4141B2CBF05E51D364F7A4D7EE20F1299A697AEAE7341EB6C2F5C458D8AA9A33CE6B2C87B42A9C8EABB3A3311E3828935B8743604895A37D0E9717266872B51CBAB50E9399A0E54457F88DB022CD1859D704FE07C2B530BE14A11072133A9D3A8CD94FCA2B22A320EA08D0292DEADAC4BF705B2CDF71CDC13EC72918F2BD8697BA42AA0AAD62E2D549AC639095EFD2EF606414207CD3770A14FA14AAD7EED197A1A61EBF1FCA89CFE2B69E709C98F4299CF6E1DCF34A98F3C89C6357B5DCDCB335C98EA8DBBA64700EFF9B79CCB875FA49C0C8FA8AA98D6B7B83C3818C4078A8433EEEC71423D9B476029C190ECF1552CF59E1BB2ACDB08663FA792D806E5FF5A6D3E4E09C3F6276663A09D5730A9AAB456D4863F2EDEFEF156A7809AA16D3202AA03C64359BAC628EA1D9ABE2D99999C2891ED49C6081DEA6907C93C5873B4D7880DE271D6016075AFF330FDF221790258A99564F1B51B979DE7997F5FD6676F679B4B14222753547C06960ADCC287EDC29E627FB88BD0E73EBC4E631A58DCA425FADFFEE9DBA177EC182CABA803EEE16636599A88C39A828A5FB206F6DDFD6023F560A421FF3D93B6C4A2A27B78283280C2FD5D249C35270EAE8F8947FA07189BB3A03184C1D8DDB12038184C467EE7DA6CD62F1775F316BE3C2FAB947D49DA19B480E8E4CB4C7818D7769351107386311E5EE411DAC5136869C147DA8E782FA60ED69B13C2DE18CF11FD75CE5F8F16993A026FC3441EE3B23DD6002B8F015E5CC336B5559A427864338C098F4857AA40399916614E061BB176AE4457CA72625A37F08F179A14C39B065CF3283E9425355B6504784C0F4FC1D7932F5C14B43A9CE3604935DE695CDB60B1ED58BD71AB540EEDDF9337B0743D8E624E1A932A69FB1FCA21CFE7F6D2FFDA78F2B8D5BCE01C59BC0A3981BB3BBECF345F43ACD571432B742F80491B490FD71F947480FF9D215EC21237F5AF28C31608DA7A6230CAD24EA799506C8C0B1298E9FD09DA496C6B63710920CC0DC14C00944A7D9B9B751D741A828AB35A5926D3653D45531A4D233DE198439D1946633FF6B91DF0744073CC6E3EC3B177414D8ED2AF30515D8688914667F507667776634A2A11BB68F65B363BD56E8CCF957EB4BB0147862D4C17268AFCE5685C8346E1917B8E8618D3888355CE401AAC5D2DF"; char testResult[512] = "1026862877813E17E4371095271E1B56"; // Get a HMAC-MD5 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_MD5)) != NULL); // Key char pk[] = "a_key_for_HMAC-MD5_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult), shsmMac; // Now recreate the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b)); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Now recreate the MAC in a multiple part operation shsmMac.wipe(); CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; rng = NULL; } #endif void MacTests::testHMACSHA1() { char testData[4096] = "EA9E200DE69522895F516F1380536406D205D72B31ACB902CC582B12696579826B5AF47892C4831D8AEBBAE039D87F82096364782B49E2E896AB8077E773AB61E05A8223BF17CBF37AB1BDDA70C9B10D9943AF4109571ECFB029156889249B309EC45A34E2D701F1F4093610A7064B69E7FAE5FB39E39EEF3CAA9D64E50DA8822DF4C8DFA064B165ECA4C9CD2A6AF1A251A1F5D4004123B67A7CC3FAB7462AD43535018479BDFD24A2C4A1C4271F907E40E2057A6271BB2BC9740F753CA3692E7ACACE547E64B9FAE79A96DF3DDFCDA7FDCCC7612E41B0B9BBFA3BDE2102F322E8EC42DA2679531782920FD2E7385F6AC887D578B9D844F6A7288EDF613F3663EB538DBFF14EA29AC8D2F58C703303CD370F55BAF02532A0BCB2F80673F6D84B04A5C3EF9E05B640B4CFFD903272089B9960B54197CB5D10C23BAFEA72EFF79C65E0EABEC628EEB5850AC4A23DC80E857EBA5EC5EDB9DD0A5F391B7F8BD354EC976881C157BD5735AD894F020164A9DF214150C5788BC1CF73C15437DBF21D791C75074DF4B51B5C0ABDC79063AB7B7CEDEDC6412F9FB1F6CA171BE6814E033F32CF1F08236A3DD657DB96CCF7A35434C4D0ACFCA81546B4138A6EF6987A874111946010F78074E69BA83E3F395D1C239A122B259F48140E4B80157738A5D443E1762C55EBB67791D5297B3E900B0B53CA7433FB61D2D03C3B34772C5DF77711437003C6DFF4B03DC0B713491F526F9AE3260F903EF9A1BED641E1B262103D395ACAC3FE6F6F1436F0CB3A13AC69C60101EC394DAFFCAD8EED23893C4BC30485FC68854447A9930C0F4FB9AC5B72EF6512278F09F5A024C7CF5C5617461751CE193E54051AE93DF136725642E1DB98842BAA8B8F6231181F0BAA8393FC2EDB7CF0832BA1FDB76A46C8059732B7492711AD1A12BA584D49885E263789E27664B3893EF2DE5C010C093DE1A735D806E4D48C36A0995EADF011FB50D0CA97AFF26B4698524B9F75386897940434A0A38EAF513845BF0F024014001180C651F76B9E0ECA6499F177A1079395C1785B856D5762550EAD2B47B15AF0A6BFBB1B597E72B9E5E6F61769C27AFC29E4D8A523C89D1D2E5E59B57DE89BE04BDC1DCDA0476A157BCB4DA2F7AC0CAF9351772652E2E5B6261501BDF42C23EA9726CB6C258EE9511684CFEECA1C0598D372808002E250EDD4019F85630FD499C35016B8A99C6BF78E69053B4AE7BE6B84009B505594603B363037212DAFCC669F7482995C74A7CC225245DC2E7D4CACC8A59F67513E1D788F0218DA902F440CD2FEB6C2A90A653B0C2DBE45CC67B47863C1090F3F41AFEA9C53CE5C61A7E6B7212EE3BBE67ED91EB1BA006A931055512046779935F84D7CA306C7F9F3894F91F51EFF6005F5A8BD9DD8828BCEA1C4CC6E5F22CE7F14C0A942243C1205FD7697F09C333AE0B263"; char testResult[512] = "C2FFE4BF83A6FE299CA4A187157F2442EC1527CE"; // Get a HMAC-SHA1 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_SHA1)) != NULL); // Key char pk[] = "a_key_for_HMAC-SHA1_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult), shsmMac; // Now verify the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b)); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Now recreate the MAC in a multiple part operation CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Now recreate a wrong MAC b[5] ^= 0x28; CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac != shsmMac); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; rng = NULL; } void MacTests::testHMACSHA224() { char testData[4096] = "83E369A9F34D645B7E1F2F7BB676A4DFD36C411D5472A9AC6F3945EF5C9A561BB040C38F2F321C582882820C7F44D48CDC5BB84F41818F4AEB226F63078CE131481D26F26C61EE52BD1BFB60EDEDE1E03A8656E87D5662EE0C0AE085E56E488325512467DAC43E99484A16FA419D6704922C1ADE06F7D1188DBEC88384CDBFDCD2E74787AE247A8027EF60383B3B0A7D0D3ADA95BB3AA5F0821AF050A9709C75673F3926CF9AE029158D684F470DE3EE6B00BBC90F85CD6E634E86B67E4D8EB4251B472B02D167790C6E6C38BA9FE39880544EA66EB4C0BFF8AFEB9AFC40ADC24DF191744482F70793CB4A802CF1AB58562CC26D1CAA2E80375BA45507C3E9F7D99223E0E7FE93CAC58B7B0C69231162D2D7DA75EEFD59452642CDC5AA4A118B6D4AD00E8368A44988201C6286CAA8612BCFFF714855DE1E053AFD2EEED9737459540E45AEAB26999C0951228716AF02F0D35264E3411B03D222F331A4695D6DF4E9EE35D5B1015FF0BE46081D7CEC9137824217A711F015639BE76223845F1C2A25A10D29B637C5124CF50AB0CAA1E33D75843D00EAE69C3A189D463377731C3197BF44523936C4F84F143759E3D58891F7B3B51C858EE29BC1DF214AF09C93148172E842A7FC0078D4E106324AAF8862B845F290FE831037B2EFEF2528DF070DD7B1ACD67762CF1071B96FB95C5AA14F7AE13103AF45A1CF3C42C5D53CB5B954F97BA223E70E0098E224BEF8F5430D027B510DFBBC35EE5F9170E4A43BDDFCBAE8B82240DB870B6C7C7E21E21234EFA62F1582A9D150CCE1B8822BD77ED8288B20883AAEEB5BDF9D0EBB8D3FF47DD51B99E9BDB8B8A87D0536CC25D4939ECB13F7B4F7DF5F0BE8231CF3F53CE52D16A29825739B26BA4082975583967180F787ECF98AD956A9CE53759E20960752938C142DF80E57DDCA236A1F596031942016442002683865EDB210073797547D83CE77D3D6C39E2B9034E685BD28D365992E821BECAFC6DF2B60EAE9777FEE7879B176CC602501BA0B0BCB434DFA5517F8D6172647364F235B3C9BA0B1B90FE0FD67CF6650C2D8D2BC08D127DF0AB887F69CDD81D03B4CC7F44A4362C90BB38556D081E51EABD9CA3AA6C877C42FD1B001C030D0B281590696B5BB9C6A78CBE356F7AC72F525300FD13E24755294712DDF48D1AD19F844120306DC99D8CC18516A23BD022CF9DC9CACC168ADDE1C15337F15B3FBEDE4BFA498F2F963E14B7E66CD737A5485227BA1BAA7668D97C58DCE40EE7A843A5E6EB591FF91D6A6292C8A3E95A0B23C1F0B8815BE526EE7C49B5153264BC1207013EA85E9DA37F19BD50DDC9F0A5B9AB4FCFFAD2840B5A8856882E8DF95362DCA13C15328137A2A8318884FCF4D05236CEE9985DB1BA873A9AF5B33E317FA2C0CB94E7C18E46744A374C19D8C9B2788FE50C9E4D237D290555E1077"; char testResult[512] = "4B089658FF932CA07BF7C42E6EC46BFF560BCAF295826D9D3C0BAE1C"; // Get a HMAC-SHA224 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_SHA224)) != NULL); // Key char pk[] = "a_key_for_HMAC-SHA224_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult), shsmMac; // Now recreate the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b)); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Now verify the MAC in a multiple part operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Now don't verify a MAC with different input b[600] ^= 0xff; CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(!mac->verifyFinal(osslMac)); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; rng = NULL; } void MacTests::testHMACSHA256() { char testData[4096] = "FF7E669D7764FABF6E3550E192E660DF1EE237B49F9473D757DEFA1400534F57C81E8B0E99458F74E6F57A5BB71A50D1EF61EDB3B3FB4BCA57896DFBA50C6C55B04D4C8C804DB8EB2A273E25F49AE2742D2AE430BE9A3A07715AF6816E818B63BB1FF8C876A921CF931F693E624CDAD4B54F3ABBEE4A09BF39E0FE3A313B20CD3A36B0EBD677D9D4D7C576B5EA244CF0436110D9D66110C95BE187D6EDA1E81A4456231BE32A1B5F4CDC02B2DA679322AEBAE0B795763888F07F0222ADBF824F31AEC7B80625DC36DA1F0C3DD20C6E8F79A7FA2D286119894E611EE550364428723E9C33A573F18D02F9DC90ED215EF08C95DB1CED68DA864732BC9A56B8B191815BCC12075641E3E87F46EFD3726BC1D6F47AF7BC573C554279C041C7FD5E924093241855507EE2A837E2CE62E7A9898712EDF593217B6425B3EB855D53D31F38E5A0736E34844AFCAD58A15B06D357697DC921C2FCA77091BFC207B0B4F1FA94F923B05817211462104287B43CA72986D9E6E393C9A075C267B2C1706CAD136E9F549A83E58315DE8D0B67852006EFE8B6E0773519FE6DB316EA596E1998B79C19152AADDDF8E025E7EDCB16B5CCBA2C9F990605A6969D3C667D6EDA1DA5AFF476661349712CD73F707BB0FD6F8BF0C13A90DE9C1C5CE9FB696C22849C1205C8435C818E2EE03F2235B502E0C24068B8687AF9ED065910535072DABB83F651FC60E005BEF909F6EE308B37E43DA01366C062168007D733D5EA4A610D1307BA087E8F883864140BBB02E523997A0D83E9BF289B8EC9F83F57FF553485409B0D82E77F32BD2D06A130103B9F3915730EE8BC3FB099B74AE8B32C478A83D0BAD2281C279D6B802F42A80E179F4ABB69AD485BBAE348C6F774285870F53699500CEC045B9521CF22826FAFFBC4EABE9D856B28DDBC6D2A0F318AE9475E82DE2CA6704B743397EFE45F825019B58D9E671181512D780B1BA34D059BFBF8B9B232E337335C1045682635CEF8D3CB1C744D3A7791F5DB323EF8DE768C63931266EAB0DFACAB0F99BC9C5DA234FE48ECDB23A5FDA2E92EC10AF7476B07C4BB85BDD0600B49F41585F9E0DB2B276BBE0FA7C5792B65012B6564561E4814E8D1EE706935A45F969C9AA110A630E354C7243E21436A180046605FE5D31008045A5C4AB4FF5C23585D77D6C839875CC2E960436A3D90F9664D5522EAB08867B95F9641DF0C81D59DCA8ECE8709A3F521532041BDCF7A7535F940BD3569FD2145A1B34E955E04F66E0CA809BA3FA6A347FD0CB69DADBA93DC03CDF547A96CD3159ACA61EFE20F9A566316BB9C746EB851CE51F04823667CDA0D898253BB10C1C5220B2C30461A49C5FF0DEC38264786C6125720B3768629ADABCF694E01795F618FBD0ADE5C91CB5A981BBA581A9664F51DF758D7300E081E57CE20C8A7210BC3558AD240B7"; char testResult[512] = "90A49F8EB80D8ED405EFC8D658FCB9102314598939DCAA090756668056B0228A"; // Get a HMAC-SHA256 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_SHA256)) != NULL); // Key char pk[] = "a_key_for_HMAC-SHA256_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult); // Now verify the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b)); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Now verify the MAC in a multiple part operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Check if bad key is refused osslMac[10] ^= 0x11; CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b)); CPPUNIT_ASSERT(!mac->verifyFinal(osslMac)); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; rng = NULL; } void MacTests::testHMACSHA384() { char testData[4096] = "7D4C4274CFAFABE3605DE7E35B43F10251A441A6F4B03EE142B9EAE3DEC2E30E1A47FBE779D716427B108CCB2A2C2D7561B879B1C021E00E0498D91859BA3E7851EF3FC25A1BC6EADA8524EAEEDCC0E752AD90DFD0EA2F04B71B8ABF56DA85E4D070C91EC4B7723A02C3B52DAE31EEAF8E397CC3E92FA31E5F3292D8C9F45D459D8D1105E539D3979ADC01EB4E0C90BC33351295628BD0C2E1B4B13764EDD66BE9AD67AA7B4A7780264B0A3DBE099B190D25649B692401E0B758AB2A281B2E1AC9B4F7EE051C1B98BE92463F314A86A7FD40A4683A82457699F514563C70F1231C0B667C7B8CAD5910334CF894A9810D7C7C6DFC1E904D8512813A84911580C2AC56BB005A4FFB512A1290501AE795C832C0BF7DEBCD9B1D84CC0BB5B5F19D02FDBAB01F7B7CA47C99F3CB7D4F0D35622C267EBDADB2D089D0DA73FEA15A25C873C27EF72A84F99EC4E6980695BA6468B34B5AEC0746219468FEE88277739123FB51CEBF264140FFF27B94D6F751F26F0BC27387A2EFD038EEE43013AFC8FE94BE8E272B28ABFE2160BA81416113CBC2A1ADD96DD23F7107F4771CF2016501A8918A9A71C476CEDC10BB355BC144C818FD620301793CB16372A80881C5DFE387619ED651626CF44C8EDA8DA5BA8A6895148EE36037D4ADDBC13C5681935EDC5BD9B35F8E91B84C1F593B3E89614879CAE4DF4413E13655079F3CE21449CCA19E0963C925A75BC294F343016518D2F8FCB13ED38D574232602AD2416E94ED7735680439CE042145552F352156FCA722B31BFAA289C3711F170A845143ADFEF49CA53278358A7FECBD605AE9899192990D728CA37218B65DD9978EC4345100E174F3D04A0C8A5611263DABF7DA0BC6CE50BCD338830688B697FEB71909D1A2E09B62C5C4A8C1069C50C8DD6A432ED2B429F6BBFC304D0F0A35167BBDDCBC7F78959058393BC812820AF4917C56EA9233A1567608534F93857EA783B537CE294B4778E4B5D30D5836AE1F0D25B663A62512D2488E959D7FF000F8A70F31CC4CABB51D6F57A842AEABD707122935690F78F1F8BD7EC8544F1E70B9D6D53C50632F4DF5F0BC75630B427B28BAF2249C72F5864A3CE17627BA4F16F8FF13FA19DDF83736B171C024C95EFBC5D90615C495C2B02685C24C6E64E19C804B1DC138B5BC52A6969C4332F6113ED8C38F03A0107513C611A6FF013D2FC0B00859A6A5DFB8626002EA0126D477B5F9C7B5BEAB61A13AA8841A4C11E9DFB6A7164BBC2D40E940D9D10C56D58FBC76B92EA68425C2FF48BAE0CA2AF6F1CFBFFBBD855688C3960538E2D87088472CD73AB6D0FB86D9411310F5311EFCA3B89949A87D408B86B96C29C89A0180AF8957944E2A385A221081870CECC995FFDDD6994B0856ED0DC6303F7FDE5072F0B3D68BB132B0C5D3113939D614677720186052F4F90DD60A1CFD"; char testResult[512] = "AC387A4BB1E4E078C43C69087C206F49F56EC63CE244A429DA56B8EC3CAFBC987090DA7A8F6470874CA6049D20AC5154"; // Get a HMAC-SHA384 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_SHA384)) != NULL); // Key char pk[] = "a_key_for_HMAC-SHA384_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult), shsmMac; // Now recreate the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b)); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Now recreate the MAC in a multiple part operation shsmMac.wipe(); CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Now recreate a different MAC b[100] ^= 0x42; CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b)); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac != shsmMac); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; rng = NULL; } void MacTests::testHMACSHA512() { char testData[4096] = "A7A3B0B40CBAAB9B58F6946D9D15870B56E6832DECB708949EBF98DC4EC9C0AF477216C542A98A3646B6ABB72D89E6B3F18201CC75E93B37C2E8EADAD6827FBBFFD220642A92CABB587B27590ED204F8B2C926777C3DC9E5273CBB38582C103905C074002DAA2D8D16DD907BEFB4C51B49C464FF22B93269274291D1254889E3F677FBA6929AF472AECC02DECF822EABB2F05311E0BA8600B58075D4E49837F81C9565E37EAC96B9C2F3C08E3D818DD507D0CC8064C8CC7553D5A17204F4B92B74E5A441CF9142ED059DB1ADA76C799B10178FB3E76E4E3CAC6B1AD8648D522DCA6C93200E706D947E15422E1CC47742CCBF8E2C1E50492AFFA49BE22D5E34B0ACA62744626E2EF7014EAB17D8E538324D9A764501428A53593D23E3785831C1262F220883E2DEEFC66584A3AEC1F35998F842C5298A5E28653CF40F21C6E2383086C266E2902272198D45B38308904F5D2F614A6857E027D133C5455E75B16B9DB124755ADF06B16F04872D74D1A90F36709D8263B1190D625849F017930763AC1EA548DEC56BFD46D09F32D6ABAE96A778B39FBF22B1D6B3CA43F8E7ED32DB2254018FB1999ED0C4C3CDE710899CB20AB5E1CA706DA3E4E8E65253782379B49B7DEFE4E26DD498A935057E91B8FFB8B110336A554A6C61C26C2DDEEE8631926F8A706171B309B99E3B24030C17609340EBB82C4129B172B64CE6249FED00F05DCD624969BC1E4A29ED028C9821A812CDC310A974B959B29E30888887D9A8688E92F85E2A1683C5E993BCC584979F0B3F7DBE34295E2D852B6444EC4152A0C40F3113B402027E323231FC2EDD8078D6661F598588F68FB83DE9C2CA1491107E1F7B676BE16AA6C62B2FF86056905CFCE1FA57065B20A87B15BF1EADAC5FD94F5368451CE8CC2D363BC184A6E87D3D088CBCDE259845E4046D314660B1C1D4AFC7CCC37C7B1B8BBC7A54B63FE61FCD082966425AC3795F08BE7AFD6F9C66F2C3C50DD1EB6B8F8FC3C1A6A298A442EB6FC14AA906A7DA7854B53205E0A8F91C8D6CC3C41F4795FA70E14BA876548022733E61972F0351BC4187FFDE18E776BD68C5E947D2F0B19206D34770BA8ED63874639BBCEAA8D59771A02AEE654D20C69ACD8D16C42BAED6BD1AC51134F49C2A1D685B045527D4A86A7656439A2587F48F5AC43C5094DC680ECE19EBDD53B39F3B84F36D363D8CE464A20DE7ED50C6E32D5C7A9C3868D9823DF0E0A5FD824D239F67C41BC5AD3615AB51EA8B1A2C50B6D4C8F196F1278D9747B8C0B941509850052E63467950EBCE7B56D5E5C481D39E3958C51AE1267C075D8E62EC7F15400A5B4B91B15789015FBCCCC8186DC888CC0BC70326F1800FF56B01BC39DD1C2421BE6E142627B24822790DA36AD9CEA0661FAA03074FAA6F9EBC243DDCB249334B13D31DC19C0F03C6923CBFFEC6FAA29255"; char testResult[512] = "93E3A4336693965FEEC902F3BDDB064DD63D83EA1E46AA13DA209F8F000C15F366D3F9BE4F8AF189EA96D191D0BDE4CF0FC6C462C214B55ABF78F33BD6DF3DD0"; // Get a HMAC-SHA512 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_SHA512)) != NULL); // Key char pk[] = "a_key_for_HMAC-SHA512_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult); // Now verify the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b)); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Now verify the MAC in a multiple part operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; rng = NULL; } softhsm-2.0.0/src/lib/crypto/test/ECDSATests.cpp0000664000175000017500000002354212533040716016330 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECDSATests.cpp Contains test cases to test the ECDSA class *****************************************************************************/ #include #include #include #include #include "ECDSATests.h" #include "CryptoFactory.h" #include "RNG.h" #include "AsymmetricKeyPair.h" #include "AsymmetricAlgorithm.h" #ifdef WITH_ECC #include "ECParameters.h" #include "ECPublicKey.h" #include "ECPrivateKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(ECDSATests); void ECDSATests::setUp() { ecdsa = NULL; ecdsa = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::ECDSA); // Check the ECDSA object CPPUNIT_ASSERT(ecdsa != NULL); } void ECDSATests::tearDown() { if (ecdsa != NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(ecdsa); } fflush(stdout); } void ECDSATests::testKeyGeneration() { AsymmetricKeyPair* kp; // Curves to test std::vector curves; // Add X9.62 prime256v1 curves.push_back(ByteString("06082a8648ce3d030107")); // Add secp384r1 curves.push_back(ByteString("06052b81040022")); for (std::vector::iterator c = curves.begin(); c != curves.end(); c++) { // Set domain parameters ECParameters* p = new ECParameters; p->setEC(*c); // Generate key-pair CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, p)); ECPublicKey* pub = (ECPublicKey*) kp->getPublicKey(); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getEC() == *c); CPPUNIT_ASSERT(priv->getEC() == *c); ecdsa->recycleParameters(p); ecdsa->recycleKeyPair(kp); } } void ECDSATests::testSerialisation() { // Get prime256v1 domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06082a8648ce3d030107")); // Serialise the parameters ByteString serialisedParams = p->serialise(); // Deserialise the parameters AsymmetricParameters* dEC; CPPUNIT_ASSERT(ecdsa->reconstructParameters(&dEC, serialisedParams)); CPPUNIT_ASSERT(dEC->areOfType(ECParameters::type)); ECParameters* ddEC = (ECParameters*) dEC; CPPUNIT_ASSERT(p->getEC() == ddEC->getEC()); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, dEC)); // Serialise the key-pair ByteString serialisedKP = kp->serialise(); // Deserialise the key-pair AsymmetricKeyPair* dKP; CPPUNIT_ASSERT(ecdsa->reconstructKeyPair(&dKP, serialisedKP)); // Check the deserialised key-pair ECPrivateKey* privKey = (ECPrivateKey*) kp->getPrivateKey(); ECPublicKey* pubKey = (ECPublicKey*) kp->getPublicKey(); ECPrivateKey* dPrivKey = (ECPrivateKey*) dKP->getPrivateKey(); ECPublicKey* dPubKey = (ECPublicKey*) dKP->getPublicKey(); CPPUNIT_ASSERT(privKey->getEC() == dPrivKey->getEC()); CPPUNIT_ASSERT(privKey->getD() == dPrivKey->getD()); CPPUNIT_ASSERT(pubKey->getEC() == dPubKey->getEC()); CPPUNIT_ASSERT(pubKey->getQ() == dPubKey->getQ()); ecdsa->recycleParameters(p); ecdsa->recycleParameters(dEC); ecdsa->recycleKeyPair(kp); ecdsa->recycleKeyPair(dKP); } void ECDSATests::testPKCS8() { // Get prime256v1 domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06082a8648ce3d030107")); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, p)); CPPUNIT_ASSERT(kp != NULL); ECPrivateKey* priv = (ECPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(priv != NULL); // Encode and decode the private key ByteString pkcs8 = priv->PKCS8Encode(); CPPUNIT_ASSERT(pkcs8.size() != 0); ECPrivateKey* dPriv = (ECPrivateKey*) ecdsa->newPrivateKey(); CPPUNIT_ASSERT(dPriv != NULL); CPPUNIT_ASSERT(dPriv->PKCS8Decode(pkcs8)); CPPUNIT_ASSERT(priv->getEC() == dPriv->getEC()); CPPUNIT_ASSERT(priv->getD() == dPriv->getD()); ecdsa->recycleParameters(p); ecdsa->recycleKeyPair(kp); ecdsa->recyclePrivateKey(dPriv); } void ECDSATests::testSigningVerifying() { AsymmetricKeyPair* kp; ECParameters *p; // Curves/Hashes to test std::vector > totest; // Add X9.62 prime256v1 totest.push_back(std::make_pair(ByteString("06082a8648ce3d030107"), HashAlgo::SHA256)); // Add secp384r1 totest.push_back(std::make_pair(ByteString("06052b81040022"), HashAlgo::SHA384)); for (std::vector >::iterator k = totest.begin(); k != totest.end(); k++) { // Get parameters p = new ECParameters; CPPUNIT_ASSERT(p != NULL); p->setEC(k->first); HashAlgorithm *hash; hash = CryptoFactory::i()->getHashAlgorithm(k->second); CPPUNIT_ASSERT(hash != NULL); // Generate key-pair CPPUNIT_ASSERT(ecdsa->generateKeyPair(&kp, p)); // Generate some data to sign ByteString dataToSign; RNG* rng = CryptoFactory::i()->getRNG(); CPPUNIT_ASSERT(rng != NULL); CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567)); // Sign the data CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(dataToSign)); ByteString hResult; CPPUNIT_ASSERT(hash->hashFinal(hResult)); ByteString sig; CPPUNIT_ASSERT(ecdsa->sign(kp->getPrivateKey(), hResult, sig, AsymMech::ECDSA)); // And verify it CPPUNIT_ASSERT(ecdsa->verify(kp->getPublicKey(), hResult, sig, AsymMech::ECDSA)); ecdsa->recycleKeyPair(kp); ecdsa->recycleParameters(p); CryptoFactory::i()->recycleHashAlgorithm(hash); } } void ECDSATests::testSignVerifyKnownVector() { ECPublicKey* pubKey1 = (ECPublicKey*) ecdsa->newPublicKey(); ECPublicKey* pubKey2 = (ECPublicKey*) ecdsa->newPublicKey(); ECPrivateKey* privKey1 = (ECPrivateKey*) ecdsa->newPrivateKey(); ECPrivateKey* privKey2 = (ECPrivateKey*) ecdsa->newPrivateKey(); HashAlgorithm* hash1 = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA256); HashAlgorithm* hash2 = CryptoFactory::i()->getHashAlgorithm(HashAlgo::SHA384); // Reconstruct public and private key #1 ByteString ec1 = "06082a8648ce3d030107"; // X9.62 prime256v1 ByteString d1 = "dc51d3866a15bacde33d96f992fca99da7e6ef0934e7097559c27f1614c88a7f"; // add 04 (ASN_String) 04 (UNCOMPRESSED) in front! ByteString q1 = "0441042442a5cc0ecd015fa3ca31dc8e2bbc70bf42d60cbca20085e0822cb04235e9706fc98bd7e50211a4a27102fa3549df79ebcb4bf246b80945cddfe7d509bbfd7d"; pubKey1->setEC(ec1); pubKey1->setQ(q1); privKey1->setEC(ec1); privKey1->setD(d1); CPPUNIT_ASSERT(hash1 != NULL); // Test with key #1 ByteString data1 = "616263"; // "abc" ByteString goodSignature1 = "cb28e0999b9c7715fd0a80d8e47a77079716cbbf917dd72e97566ea1c066957c86fa3bb4e26cad5bf90b7f81899256ce7594bb1ea0c89212748bff3b3d5b0315"; ByteString badSignature1 = "cb28e0999b9c7715fd0a80d8e47a77079716cbbf917dd72e97566ea1c066957c86fa3bb4e26cad5bf90b7f81899256ce7594bb1ea0c89212748bff3b3d5b0316"; // Reconstruct public and private key #2 ByteString ec2 = "06052b81040022"; // secp384r1 ByteString d2 = "0beb646634ba87735d77ae4809a0ebea865535de4c1e1dcb692e84708e81a5af62e528c38b2a81b35309668d73524d9f"; // add 04 (ASN_String) 04 (UNCOMPRESSED) in front! ByteString q2 = "04610496281bf8dd5e0525ca049c048d345d3082968d10fedf5c5aca0c64e6465a97ea5ce10c9dfec21797415710721f437922447688ba94708eb6e2e4d59f6ab6d7edff9301d249fe49c33096655f5d502fad3d383b91c5e7edaa2b714cc99d5743ca"; pubKey2->setEC(ec2); pubKey2->setQ(q2); privKey2->setEC(ec2); privKey2->setD(d2); CPPUNIT_ASSERT(hash2 != NULL); // Test with key #2 ByteString data2 = "616263"; // "abc" ByteString goodSignature2 = "fb017b914e29149432d8bac29a514640b46f53ddab2c69948084e2930f1c8f7e08e07c9c63f2d21a07dcb56a6af56eb3b263a1305e057f984d38726a1b46874109f417bca112674c528262a40a629af1cbb9f516ce0fa7d2ff630863a00e8b9f"; ByteString badSignature2 = "fb017b914e29149432d8bac29a514640b46f53ddab2c69948084e2930f1c8f7e08e07c9c63f2d21a07dcb56a6af56eb3b263a1305e057f984d38726a1b46874109f417bca112674c528262a40a629af1cbb9f516ce0fa7d2ff630863a00e8b9e"; CPPUNIT_ASSERT(hash1->hashInit()); CPPUNIT_ASSERT(hash1->hashUpdate(data1)); ByteString hResult1; CPPUNIT_ASSERT(hash1->hashFinal(hResult1)); CPPUNIT_ASSERT(ecdsa->verify(pubKey1, hResult1, goodSignature1, AsymMech::ECDSA)); CPPUNIT_ASSERT(!ecdsa->verify(pubKey1, hResult1, badSignature1, AsymMech::ECDSA)); CPPUNIT_ASSERT(hash2->hashInit()); CPPUNIT_ASSERT(hash2->hashUpdate(data2)); ByteString hResult2; CPPUNIT_ASSERT(hash2->hashFinal(hResult2)); CPPUNIT_ASSERT(ecdsa->verify(pubKey2, hResult2, goodSignature2, AsymMech::ECDSA)); CPPUNIT_ASSERT(!ecdsa->verify(pubKey2, hResult2, badSignature2, AsymMech::ECDSA)); ecdsa->recyclePublicKey(pubKey1); ecdsa->recyclePublicKey(pubKey2); ecdsa->recyclePrivateKey(privKey1); ecdsa->recyclePrivateKey(privKey2); CryptoFactory::i()->recycleHashAlgorithm(hash1); CryptoFactory::i()->recycleHashAlgorithm(hash2); } #endif softhsm-2.0.0/src/lib/crypto/test/randtest.c0000664000175000017500000001176212533040716015753 00000000000000/* This code was taken from http://www.fourmilab.ch/random/ where it states that: This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided “as is” without express or implied warranty. */ /* Apply various randomness tests to a stream of bytes by John Walker -- September 1996 http://www.fourmilab.ch/ */ #include #define FALSE 0 #define TRUE 1 #define log2of10 3.32192809488736234787 static int binary = FALSE; /* Treat input as a bitstream */ static long ccount[256], /* Bins to count occurrences of values */ totalc = 0; /* Total bytes counted */ static double prob[256]; /* Probabilities per bin for entropy */ /* RT_LOG2 -- Calculate log to the base 2 */ static double rt_log2(double x) { return log2of10 * log10(x); } #define MONTEN 6 /* Bytes used as Monte Carlo co-ordinates. This should be no more bits than the mantissa of your "double" floating point type. */ static int mp, sccfirst; static unsigned int monte[MONTEN]; static long inmont, mcount; static double cexp, incirc, montex, montey, montepi, scc, sccun, sccu0, scclast, scct1, scct2, scct3, ent, chisq, datasum; /* RT_INIT -- Initialise random test counters. */ void rt_init(int binmode) { int i; binary = binmode; /* Set binary / byte mode */ /* Initialise for calculations */ ent = 0.0; /* Clear entropy accumulator */ chisq = 0.0; /* Clear Chi-Square */ datasum = 0.0; /* Clear sum of bytes for arithmetic mean */ mp = 0; /* Reset Monte Carlo accumulator pointer */ mcount = 0; /* Clear Monte Carlo tries */ inmont = 0; /* Clear Monte Carlo inside count */ incirc = 65535.0 * 65535.0;/* In-circle distance for Monte Carlo */ sccfirst = TRUE; /* Mark first time for serial correlation */ scct1 = scct2 = scct3 = 0.0; /* Clear serial correlation terms */ incirc = pow(pow(256.0, (double) (MONTEN / 2)) - 1, 2.0); for (i = 0; i < 256; i++) { ccount[i] = 0; } totalc = 0; } /* RT_ADD -- Add one or more bytes to accumulation. */ void rt_add(void *buf, int bufl) { unsigned char *bp = (unsigned char *)buf; int oc, c, bean; while (bean = 0, (bufl-- > 0)) { oc = *bp++; do { if (binary) { c = !!(oc & 0x80); } else { c = oc; } ccount[c]++; /* Update counter for this bin */ totalc++; /* Update inside / outside circle counts for Monte Carlo computation of PI */ if (bean == 0) { monte[mp++] = oc; /* Save character for Monte Carlo */ if (mp >= MONTEN) { /* Calculate every MONTEN character */ int mj; mp = 0; mcount++; montex = montey = 0; for (mj = 0; mj < MONTEN / 2; mj++) { montex = (montex * 256.0) + monte[mj]; montey = (montey * 256.0) + monte[(MONTEN / 2) + mj]; } if ((montex * montex + montey * montey) <= incirc) { inmont++; } } } /* Update calculation of serial correlation coefficient */ sccun = c; if (sccfirst) { sccfirst = FALSE; scclast = 0; sccu0 = sccun; } else { scct1 = scct1 + scclast * sccun; } scct2 = scct2 + sccun; scct3 = scct3 + (sccun * sccun); scclast = sccun; oc <<= 1; } while (binary && (++bean < 8)); } } /* RT_END -- Complete calculation and return results. */ void rt_end(double *r_ent, double *r_chisq, double *r_mean, double *r_montepicalc, double *r_scc) { int i; /* Complete calculation of serial correlation coefficient */ scct1 = scct1 + scclast * sccu0; scct2 = scct2 * scct2; scc = totalc * scct3 - scct2; if (scc == 0.0) { scc = -100000; } else { scc = (totalc * scct1 - scct2) / scc; } /* Scan bins and calculate probability for each bin and Chi-Square distribution. The probability will be reused in the entropy calculation below. While we're at it, we sum of all the data which will be used to compute the mean. */ cexp = totalc / (binary ? 2.0 : 256.0); /* Expected count per bin */ for (i = 0; i < (binary ? 2 : 256); i++) { double a = ccount[i] - cexp;; prob[i] = ((double) ccount[i]) / totalc; chisq += (a * a) / cexp; datasum += ((double) i) * ccount[i]; } /* Calculate entropy */ for (i = 0; i < (binary ? 2 : 256); i++) { if (prob[i] > 0.0) { ent += prob[i] * rt_log2(1 / prob[i]); } } /* Calculate Monte Carlo value for PI from percentage of hits within the circle */ montepi = 4.0 * (((double) inmont) / mcount); /* Return results through arguments */ *r_ent = ent; *r_chisq = chisq; *r_mean = datasum / totalc; *r_montepicalc = montepi; *r_scc = scc; } softhsm-2.0.0/src/lib/crypto/test/cryptotest.cpp0000664000175000017500000000401712533040716016702 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** cryptotest.cpp The main test executor for tests on the cryptographic functions in SoftHSM v2 *****************************************************************************/ #include #include #include "CryptoFactory.h" #include "SecureMemoryRegistry.h" int main(int /*argc*/, char** /*argv*/) { CppUnit::TextUi::TestRunner runner; CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest(registry.makeTest()); bool wasSucessful = runner.run(); CryptoFactory::reset(); SecureMemoryRegistry::reset(); return wasSucessful ? 0 : 1; } softhsm-2.0.0/src/lib/crypto/test/Makefile.in0000664000175000017500000011002112552216620016014 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ check_PROGRAMS = cryptotest$(EXEEXT) TESTS = cryptotest$(EXEEXT) subdir = src/lib/crypto/test DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp $(top_srcdir)/test-driver ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = am_cryptotest_OBJECTS = cryptotest.$(OBJEXT) AESTests.$(OBJEXT) \ DESTests.$(OBJEXT) DHTests.$(OBJEXT) DSATests.$(OBJEXT) \ ECDHTests.$(OBJEXT) ECDSATests.$(OBJEXT) GOSTTests.$(OBJEXT) \ HashTests.$(OBJEXT) MacTests.$(OBJEXT) RNGTests.$(OBJEXT) \ RSATests.$(OBJEXT) chisq.$(OBJEXT) ent.$(OBJEXT) \ iso8859.$(OBJEXT) randtest.$(OBJEXT) cryptotest_OBJECTS = $(am_cryptotest_OBJECTS) cryptotest_DEPENDENCIES = ../../libsofthsm_convarch.la AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = cryptotest_LINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(cryptotest_LDFLAGS) $(LDFLAGS) -o $@ AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CFLAGS) $(CFLAGS) AM_V_CC = $(am__v_CC_@AM_V@) am__v_CC_ = $(am__v_CC_@AM_DEFAULT_V@) am__v_CC_0 = @echo " CC " $@; am__v_CC_1 = CCLD = $(CC) LINK = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CCLD = $(am__v_CCLD_@AM_V@) am__v_CCLD_ = $(am__v_CCLD_@AM_DEFAULT_V@) am__v_CCLD_0 = @echo " CCLD " $@; am__v_CCLD_1 = CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(cryptotest_SOURCES) DIST_SOURCES = $(cryptotest_SOURCES) am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags am__tty_colors_dummy = \ mgn= red= grn= lgn= blu= brg= std=; \ am__color_tests=no am__tty_colors = { \ $(am__tty_colors_dummy); \ if test "X$(AM_COLOR_TESTS)" = Xno; then \ am__color_tests=no; \ elif test "X$(AM_COLOR_TESTS)" = Xalways; then \ am__color_tests=yes; \ elif test "X$$TERM" != Xdumb && { test -t 1; } 2>/dev/null; then \ am__color_tests=yes; \ fi; \ if test $$am__color_tests = yes; then \ red=''; \ grn=''; \ lgn=''; \ blu=''; \ mgn=''; \ brg=''; \ std=''; \ fi; \ } am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; am__vpath_adj = case $$p in \ $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ *) f=$$p;; \ esac; am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; am__install_max = 40 am__nobase_strip_setup = \ srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` am__nobase_strip = \ for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" am__nobase_list = $(am__nobase_strip_setup); \ for p in $$list; do echo "$$p $$p"; done | \ sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ if (++n[$$2] == $(am__install_max)) \ { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ END { for (dir in files) print dir, files[dir] }' am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ test -z "$$files" \ || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ $(am__cd) "$$dir" && rm -f $$files; }; \ } am__recheck_rx = ^[ ]*:recheck:[ ]* am__global_test_result_rx = ^[ ]*:global-test-result:[ ]* am__copy_in_global_log_rx = ^[ ]*:copy-in-global-log:[ ]* # A command that, given a newline-separated list of test names on the # standard input, print the name of the tests that are to be re-run # upon "make recheck". am__list_recheck_tests = $(AWK) '{ \ recheck = 1; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ { \ if ((getline line2 < ($$0 ".log")) < 0) \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[nN][Oo]/) \ { \ recheck = 0; \ break; \ } \ else if (line ~ /$(am__recheck_rx)[yY][eE][sS]/) \ { \ break; \ } \ }; \ if (recheck) \ print $$0; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # A command that, given a newline-separated list of test names on the # standard input, create the global log from their .trs and .log files. am__create_global_log = $(AWK) ' \ function fatal(msg) \ { \ print "fatal: making $@: " msg | "cat >&2"; \ exit 1; \ } \ function rst_section(header) \ { \ print header; \ len = length(header); \ for (i = 1; i <= len; i = i + 1) \ printf "="; \ printf "\n\n"; \ } \ { \ copy_in_global_log = 1; \ global_test_result = "RUN"; \ while ((rc = (getline line < ($$0 ".trs"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".trs"); \ if (line ~ /$(am__global_test_result_rx)/) \ { \ sub("$(am__global_test_result_rx)", "", line); \ sub("[ ]*$$", "", line); \ global_test_result = line; \ } \ else if (line ~ /$(am__copy_in_global_log_rx)[nN][oO]/) \ copy_in_global_log = 0; \ }; \ if (copy_in_global_log) \ { \ rst_section(global_test_result ": " $$0); \ while ((rc = (getline line < ($$0 ".log"))) != 0) \ { \ if (rc < 0) \ fatal("failed to read from " $$0 ".log"); \ print line; \ }; \ printf "\n"; \ }; \ close ($$0 ".trs"); \ close ($$0 ".log"); \ }' # Restructured Text title. am__rst_title = { sed 's/.*/ & /;h;s/./=/g;p;x;s/ *$$//;p;g' && echo; } # Solaris 10 'make', and several other traditional 'make' implementations, # pass "-e" to $(SHELL), and POSIX 2008 even requires this. Work around it # by disabling -e (using the XSI extension "set +e") if it's set. am__sh_e_setup = case $$- in *e*) set +e;; esac # Default flags passed to test drivers. am__common_driver_flags = \ --color-tests "$$am__color_tests" \ --enable-hard-errors "$$am__enable_hard_errors" \ --expect-failure "$$am__expect_failure" # To be inserted before the command running the test. Creates the # directory for the log if needed. Stores in $dir the directory # containing $f, in $tst the test, in $log the log. Executes the # developer- defined test setup AM_TESTS_ENVIRONMENT (if any), and # passes TESTS_ENVIRONMENT. Set up options for the wrapper that # will run the test scripts (or their associated LOG_COMPILER, if # thy have one). am__check_pre = \ $(am__sh_e_setup); \ $(am__vpath_adj_setup) $(am__vpath_adj) \ $(am__tty_colors); \ srcdir=$(srcdir); export srcdir; \ case "$@" in \ */*) am__odir=`echo "./$@" | sed 's|/[^/]*$$||'`;; \ *) am__odir=.;; \ esac; \ test "x$$am__odir" = x"." || test -d "$$am__odir" \ || $(MKDIR_P) "$$am__odir" || exit $$?; \ if test -f "./$$f"; then dir=./; \ elif test -f "$$f"; then dir=; \ else dir="$(srcdir)/"; fi; \ tst=$$dir$$f; log='$@'; \ if test -n '$(DISABLE_HARD_ERRORS)'; then \ am__enable_hard_errors=no; \ else \ am__enable_hard_errors=yes; \ fi; \ case " $(XFAIL_TESTS) " in \ *[\ \ ]$$f[\ \ ]* | *[\ \ ]$$dir$$f[\ \ ]*) \ am__expect_failure=yes;; \ *) \ am__expect_failure=no;; \ esac; \ $(AM_TESTS_ENVIRONMENT) $(TESTS_ENVIRONMENT) # A shell command to get the names of the tests scripts with any registered # extension removed (i.e., equivalently, the names of the test logs, with # the '.log' extension removed). The result is saved in the shell variable # '$bases'. This honors runtime overriding of TESTS and TEST_LOGS. Sadly, # we cannot use something simpler, involving e.g., "$(TEST_LOGS:.log=)", # since that might cause problem with VPATH rewrites for suffix-less tests. # See also 'test-harness-vpath-rewrite.sh' and 'test-trs-basic.sh'. am__set_TESTS_bases = \ bases='$(TEST_LOGS)'; \ bases=`for i in $$bases; do echo $$i; done | sed 's/\.log$$//'`; \ bases=`echo $$bases` RECHECK_LOGS = $(TEST_LOGS) AM_RECURSIVE_TARGETS = check recheck TEST_SUITE_LOG = test-suite.log TEST_EXTENSIONS = @EXEEXT@ .test LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver LOG_COMPILE = $(LOG_COMPILER) $(AM_LOG_FLAGS) $(LOG_FLAGS) am__set_b = \ case '$@' in \ */*) \ case '$*' in \ */*) b='$*';; \ *) b=`echo '$@' | sed 's/\.log$$//'`; \ esac;; \ *) \ b='$*';; \ esac am__test_logs1 = $(TESTS:=.log) am__test_logs2 = $(am__test_logs1:@EXEEXT@.log=.log) TEST_LOGS = $(am__test_logs2:.test.log=.log) TEST_LOG_DRIVER = $(SHELL) $(top_srcdir)/test-driver TEST_LOG_COMPILE = $(TEST_LOG_COMPILER) $(AM_TEST_LOG_FLAGS) \ $(TEST_LOG_FLAGS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/.. \ -I$(srcdir)/../.. \ -I$(srcdir)/../../common \ -I$(srcdir)/../../cryptoki_compat \ -I$(srcdir)/../../data_mgr \ -I$(srcdir)/../../object_store \ -I$(srcdir)/../../session_mgr \ -I$(srcdir)/../../slot_mgr \ `cppunit-config --cflags` cryptotest_SOURCES = cryptotest.cpp \ AESTests.cpp \ DESTests.cpp \ DHTests.cpp \ DSATests.cpp \ ECDHTests.cpp \ ECDSATests.cpp \ GOSTTests.cpp \ HashTests.cpp \ MacTests.cpp \ RNGTests.cpp \ RSATests.cpp \ chisq.c \ ent.c \ iso8859.c \ randtest.c cryptotest_LDADD = ../../libsofthsm_convarch.la cryptotest_LDFLAGS = @CRYPTO_LIBS@ -no-install `cppunit-config --libs` EXTRA_DIST = $(srcdir)/*.h all: all-am .SUFFIXES: .SUFFIXES: .c .cpp .lo .log .o .obj .test .test$(EXEEXT) .trs $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/crypto/test/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/crypto/test/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-checkPROGRAMS: @list='$(check_PROGRAMS)'; test -n "$$list" || exit 0; \ echo " rm -f" $$list; \ rm -f $$list || exit $$?; \ test -n "$(EXEEXT)" || exit 0; \ list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ echo " rm -f" $$list; \ rm -f $$list cryptotest$(EXEEXT): $(cryptotest_OBJECTS) $(cryptotest_DEPENDENCIES) $(EXTRA_cryptotest_DEPENDENCIES) @rm -f cryptotest$(EXEEXT) $(AM_V_CXXLD)$(cryptotest_LINK) $(cryptotest_OBJECTS) $(cryptotest_LDADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/AESTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DESTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DHTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DSATests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ECDHTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ECDSATests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/GOSTTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/HashTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/MacTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RNGTests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RSATests.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/chisq.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cryptotest.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ent.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/iso8859.Po@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/randtest.Po@am__quote@ .c.o: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ $< .c.obj: @am__fastdepCC_TRUE@ $(AM_V_CC)$(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .c.lo: @am__fastdepCC_TRUE@ $(AM_V_CC)$(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCC_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCC_FALSE@ $(AM_V_CC@am__nodep@)$(LTCOMPILE) -c -o $@ $< .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-am TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-am CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-am cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags # Recover from deleted '.trs' file; this should ensure that # "rm -f foo.log; make foo.trs" re-run 'foo.test', and re-create # both 'foo.log' and 'foo.trs'. Break the recipe in two subshells # to avoid problems with "make -n". .log.trs: rm -f $< $@ $(MAKE) $(AM_MAKEFLAGS) $< # Leading 'am--fnord' is there to ensure the list of targets does not # expand to empty, as could happen e.g. with make check TESTS=''. am--fnord $(TEST_LOGS) $(TEST_LOGS:.log=.trs): $(am__force_recheck) am--force-recheck: @: $(TEST_SUITE_LOG): $(TEST_LOGS) @$(am__set_TESTS_bases); \ am__f_ok () { test -f "$$1" && test -r "$$1"; }; \ redo_bases=`for i in $$bases; do \ am__f_ok $$i.trs && am__f_ok $$i.log || echo $$i; \ done`; \ if test -n "$$redo_bases"; then \ redo_logs=`for i in $$redo_bases; do echo $$i.log; done`; \ redo_results=`for i in $$redo_bases; do echo $$i.trs; done`; \ if $(am__make_dryrun); then :; else \ rm -f $$redo_logs && rm -f $$redo_results || exit 1; \ fi; \ fi; \ if test -n "$$am__remaking_logs"; then \ echo "fatal: making $(TEST_SUITE_LOG): possible infinite" \ "recursion detected" >&2; \ else \ am__remaking_logs=yes $(MAKE) $(AM_MAKEFLAGS) $$redo_logs; \ fi; \ if $(am__make_dryrun); then :; else \ st=0; \ errmsg="fatal: making $(TEST_SUITE_LOG): failed to create"; \ for i in $$redo_bases; do \ test -f $$i.trs && test -r $$i.trs \ || { echo "$$errmsg $$i.trs" >&2; st=1; }; \ test -f $$i.log && test -r $$i.log \ || { echo "$$errmsg $$i.log" >&2; st=1; }; \ done; \ test $$st -eq 0 || exit 1; \ fi @$(am__sh_e_setup); $(am__tty_colors); $(am__set_TESTS_bases); \ ws='[ ]'; \ results=`for b in $$bases; do echo $$b.trs; done`; \ test -n "$$results" || results=/dev/null; \ all=` grep "^$$ws*:test-result:" $$results | wc -l`; \ pass=` grep "^$$ws*:test-result:$$ws*PASS" $$results | wc -l`; \ fail=` grep "^$$ws*:test-result:$$ws*FAIL" $$results | wc -l`; \ skip=` grep "^$$ws*:test-result:$$ws*SKIP" $$results | wc -l`; \ xfail=`grep "^$$ws*:test-result:$$ws*XFAIL" $$results | wc -l`; \ xpass=`grep "^$$ws*:test-result:$$ws*XPASS" $$results | wc -l`; \ error=`grep "^$$ws*:test-result:$$ws*ERROR" $$results | wc -l`; \ if test `expr $$fail + $$xpass + $$error` -eq 0; then \ success=true; \ else \ success=false; \ fi; \ br='==================='; br=$$br$$br$$br$$br; \ result_count () \ { \ if test x"$$1" = x"--maybe-color"; then \ maybe_colorize=yes; \ elif test x"$$1" = x"--no-color"; then \ maybe_colorize=no; \ else \ echo "$@: invalid 'result_count' usage" >&2; exit 4; \ fi; \ shift; \ desc=$$1 count=$$2; \ if test $$maybe_colorize = yes && test $$count -gt 0; then \ color_start=$$3 color_end=$$std; \ else \ color_start= color_end=; \ fi; \ echo "$${color_start}# $$desc $$count$${color_end}"; \ }; \ create_testsuite_report () \ { \ result_count $$1 "TOTAL:" $$all "$$brg"; \ result_count $$1 "PASS: " $$pass "$$grn"; \ result_count $$1 "SKIP: " $$skip "$$blu"; \ result_count $$1 "XFAIL:" $$xfail "$$lgn"; \ result_count $$1 "FAIL: " $$fail "$$red"; \ result_count $$1 "XPASS:" $$xpass "$$red"; \ result_count $$1 "ERROR:" $$error "$$mgn"; \ }; \ { \ echo "$(PACKAGE_STRING): $(subdir)/$(TEST_SUITE_LOG)" | \ $(am__rst_title); \ create_testsuite_report --no-color; \ echo; \ echo ".. contents:: :depth: 2"; \ echo; \ for b in $$bases; do echo $$b; done \ | $(am__create_global_log); \ } >$(TEST_SUITE_LOG).tmp || exit 1; \ mv $(TEST_SUITE_LOG).tmp $(TEST_SUITE_LOG); \ if $$success; then \ col="$$grn"; \ else \ col="$$red"; \ test x"$$VERBOSE" = x || cat $(TEST_SUITE_LOG); \ fi; \ echo "$${col}$$br$${std}"; \ echo "$${col}Testsuite summary for $(PACKAGE_STRING)$${std}"; \ echo "$${col}$$br$${std}"; \ create_testsuite_report --maybe-color; \ echo "$$col$$br$$std"; \ if $$success; then :; else \ echo "$${col}See $(subdir)/$(TEST_SUITE_LOG)$${std}"; \ if test -n "$(PACKAGE_BUGREPORT)"; then \ echo "$${col}Please report to $(PACKAGE_BUGREPORT)$${std}"; \ fi; \ echo "$$col$$br$$std"; \ fi; \ $$success || exit 1 check-TESTS: @list='$(RECHECK_LOGS)'; test -z "$$list" || rm -f $$list @list='$(RECHECK_LOGS:.log=.trs)'; test -z "$$list" || rm -f $$list @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ log_list=`for i in $$bases; do echo $$i.log; done`; \ trs_list=`for i in $$bases; do echo $$i.trs; done`; \ log_list=`echo $$log_list`; trs_list=`echo $$trs_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) TEST_LOGS="$$log_list"; \ exit $$?; recheck: all $(check_PROGRAMS) @test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) @set +e; $(am__set_TESTS_bases); \ bases=`for i in $$bases; do echo $$i; done \ | $(am__list_recheck_tests)` || exit 1; \ log_list=`for i in $$bases; do echo $$i.log; done`; \ log_list=`echo $$log_list`; \ $(MAKE) $(AM_MAKEFLAGS) $(TEST_SUITE_LOG) \ am__force_recheck=am--force-recheck \ TEST_LOGS="$$log_list"; \ exit $$? cryptotest.log: cryptotest$(EXEEXT) @p='cryptotest$(EXEEXT)'; \ b='cryptotest'; \ $(am__check_pre) $(LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_LOG_DRIVER_FLAGS) $(LOG_DRIVER_FLAGS) -- $(LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) .test.log: @p='$<'; \ $(am__set_b); \ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ --log-file $$b.log --trs-file $$b.trs \ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ "$$tst" $(AM_TESTS_FD_REDIRECT) @am__EXEEXT_TRUE@.test$(EXEEXT).log: @am__EXEEXT_TRUE@ @p='$<'; \ @am__EXEEXT_TRUE@ $(am__set_b); \ @am__EXEEXT_TRUE@ $(am__check_pre) $(TEST_LOG_DRIVER) --test-name "$$f" \ @am__EXEEXT_TRUE@ --log-file $$b.log --trs-file $$b.trs \ @am__EXEEXT_TRUE@ $(am__common_driver_flags) $(AM_TEST_LOG_DRIVER_FLAGS) $(TEST_LOG_DRIVER_FLAGS) -- $(TEST_LOG_COMPILE) \ @am__EXEEXT_TRUE@ "$$tst" $(AM_TESTS_FD_REDIRECT) distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done check-am: all-am $(MAKE) $(AM_MAKEFLAGS) $(check_PROGRAMS) $(MAKE) $(AM_MAKEFLAGS) check-TESTS check: check-am all-am: Makefile installdirs: install: install-am install-exec: install-exec-am install-data: install-data-am uninstall: uninstall-am install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-am install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: -test -z "$(TEST_LOGS)" || rm -f $(TEST_LOGS) -test -z "$(TEST_LOGS:.log=.trs)" || rm -f $(TEST_LOGS:.log=.trs) -test -z "$(TEST_SUITE_LOG)" || rm -f $(TEST_SUITE_LOG) clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-am clean-am: clean-checkPROGRAMS clean-generic clean-libtool \ mostlyclean-am distclean: distclean-am -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-am dvi-am: html: html-am html-am: info: info-am info-am: install-data-am: install-dvi: install-dvi-am install-dvi-am: install-exec-am: install-html: install-html-am install-html-am: install-info: install-info-am install-info-am: install-man: install-pdf: install-pdf-am install-pdf-am: install-ps: install-ps-am install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-am -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-am mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-am pdf-am: ps: ps-am ps-am: uninstall-am: .MAKE: check-am install-am install-strip .PHONY: CTAGS GTAGS TAGS all all-am check check-TESTS check-am clean \ clean-checkPROGRAMS clean-generic clean-libtool cscopelist-am \ ctags ctags-am distclean distclean-compile distclean-generic \ distclean-libtool distclean-tags distdir dvi dvi-am html \ html-am info info-am install install-am install-data \ install-data-am install-dvi install-dvi-am install-exec \ install-exec-am install-html install-html-am install-info \ install-info-am install-man install-pdf install-pdf-am \ install-ps install-ps-am install-strip installcheck \ installcheck-am installdirs maintainer-clean \ maintainer-clean-generic mostlyclean mostlyclean-compile \ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ recheck tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/crypto/test/ent.c0000664000175000017500000000466012533040716014714 00000000000000/* This code was taken from http://www.fourmilab.ch/random/ where it states that: This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided “as is” without express or implied warranty. */ /* ENT -- Entropy calculation and analysis of putative random sequences. Designed and implemented by John "Random" Walker in May 1985. Multiple analyses of random sequences added in December 1985. Bit stream analysis added in September 1997. Terse mode output, getopt() command line processing, optional stdin input, and HTML documentation added in October 1998. Documentation for the -t (terse output) option added in July 2006. Replaced table look-up for chi square to probability conversion with algorithmic computation in January 2008. For additional information and the latest version, see http://www.fourmilab.ch/random/ */ #include #include #include #include #ifdef _WIN32 #include #include #else #include #endif #include "iso8859.h" #include "randtest.h" #define UPDATE "January 28th, 2008" #define FALSE 0 #define TRUE 1 #ifdef M_PI #define PI M_PI #else #define PI 3.14159265358979323846 #endif extern double pochisq(const double ax, const int df); /* Main program */ void doEnt ( unsigned char* data, size_t len, double* pEntropy, double* pChiProbability, double* pArithMean, double* pMontePi, double* pSerialCorrelation ) { size_t s; long ccount[256]; /* Bins to count occurrences of values */ double montepi, chip, scc, ent, mean, chisq; /* Initialise for calculations */ rt_init(FALSE); /* Scan input file and count character occurrences */ for (s = 0; s < len; s++) { unsigned char ocb = data[s]; ccount[ocb]++; /* Update counter for this bin */ rt_add(&ocb, 1); } /* Complete calculation and return sequence metrics */ rt_end(&ent, &chisq, &mean, &montepi, &scc); /* Calculate probability of observed distribution occurring from the results of the Chi-Square test */ chip = pochisq(chisq, 255); /* Print bin counts if requested */ /* Return calculated results */ *pEntropy = ent; *pChiProbability = chip; *pArithMean = mean; *pMontePi = montepi; *pSerialCorrelation = scc; } softhsm-2.0.0/src/lib/crypto/test/chisq.c0000664000175000017500000000774312533040716015242 00000000000000/* This code was taken from http://www.fourmilab.ch/random/ where it states that: This software is in the public domain. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, without any conditions or restrictions. This software is provided “as is” without express or implied warranty. */ /* Compute probability of measured Chi Square value. This code was developed by Gary Perlman of the Wang Institute (full citation below) and has been minimally modified for use in this program. */ #include /*HEADER Module: z.c Purpose: compute approximations to normal z distribution probabilities Programmer: Gary Perlman Organization: Wang Institute, Tyngsboro, MA 01879 Copyright: none Tabstops: 4 */ #define Z_MAX 6.0 /* maximum meaningful z value */ /*FUNCTION poz: probability of normal z value */ /*ALGORITHM Adapted from a polynomial approximation in: Ibbetson D, Algorithm 209 Collected Algorithms of the CACM 1963 p. 616 Note: This routine has six digit accuracy, so it is only useful for absolute z values < 6. For z values >= to 6.0, poz() returns 0.0. */ static double /*VAR returns cumulative probability from -oo to z */ poz(const double z) /*VAR normal z value */ { double y, x, w; if (z == 0.0) { x = 0.0; } else { y = 0.5 * fabs(z); if (y >= (Z_MAX * 0.5)) { x = 1.0; } else if (y < 1.0) { w = y * y; x = ((((((((0.000124818987 * w -0.001075204047) * w +0.005198775019) * w -0.019198292004) * w +0.059054035642) * w -0.151968751364) * w +0.319152932694) * w -0.531923007300) * w +0.797884560593) * y * 2.0; } else { y -= 2.0; x = (((((((((((((-0.000045255659 * y +0.000152529290) * y -0.000019538132) * y -0.000676904986) * y +0.001390604284) * y -0.000794620820) * y -0.002034254874) * y +0.006549791214) * y -0.010557625006) * y +0.011630447319) * y -0.009279453341) * y +0.005353579108) * y -0.002141268741) * y +0.000535310849) * y +0.999936657524; } } return (z > 0.0 ? ((x + 1.0) * 0.5) : ((1.0 - x) * 0.5)); } /* Module: chisq.c Purpose: compute approximations to chisquare distribution probabilities Contents: pochisq() Uses: poz() in z.c (Algorithm 209) Programmer: Gary Perlman Organization: Wang Institute, Tyngsboro, MA 01879 Copyright: none Tabstops: 4 */ #define LOG_SQRT_PI 0.5723649429247000870717135 /* log (sqrt (pi)) */ #define I_SQRT_PI 0.5641895835477562869480795 /* 1 / sqrt (pi) */ #define BIGX 20.0 /* max value to represent exp (x) */ #define ex(x) (((x) < -BIGX) ? 0.0 : exp(x)) /*FUNCTION pochisq: probability of chi sqaure value */ /*ALGORITHM Compute probability of chi square value. Adapted from: Hill, I. D. and Pike, M. C. Algorithm 299 Collected Algorithms for the CACM 1967 p. 243 Updated for rounding errors based on remark in ACM TOMS June 1985, page 185 */ double pochisq( const double ax, /* obtained chi-square value */ const int df /* degrees of freedom */ ) { double x = ax; double a, y, s; double e, c, z; int even; /* true if df is an even number */ if (x <= 0.0 || df < 1) { return 1.0; } a = 0.5 * x; even = (2 * (df / 2)) == df; y = 0.0; if (df > 1) { y = ex(-a); } s = (even ? y : (2.0 * poz(-sqrt(x)))); if (df > 2) { x = 0.5 * (df - 1.0); z = (even ? 1.0 : 0.5); if (a > BIGX) { e = (even ? 0.0 : LOG_SQRT_PI); c = log(a); while (z <= x) { e = log(z) + e; s += ex(c * z - a - e); z += 1.0; } return (s); } else { e = (even ? 1.0 : (I_SQRT_PI / sqrt(a))); c = 0.0; while (z <= x) { e = e * (a / z); c = c + e; z += 1.0; } return (c * y + s); } } else { return s; } } softhsm-2.0.0/src/lib/crypto/test/AESTests.cpp0000664000175000017500000005446012533040716016124 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AESTests.cpp Contains test cases to test the AES implementation *****************************************************************************/ #include #include #include "AESTests.h" #include "CryptoFactory.h" #include "AESKey.h" #include CPPUNIT_TEST_SUITE_REGISTRATION(AESTests); void AESTests::setUp() { aes = NULL; aes = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::AES); // Check the return value CPPUNIT_ASSERT(aes != NULL); } void AESTests::tearDown() { if (aes != NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(aes); } fflush(stdout); } void AESTests::testBlockSize() { CPPUNIT_ASSERT(aes->getBlockSize() == 16); } void AESTests::testCBC() { char testKeys128[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "89436760984679018453504364534464", "49587346983643545706904580436731" }; char testKeys192[][49] = { "000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101213141516171819", "404142434445464748494A4B4C4D4E4F5051525354555657", "096874395874290867409857496743857632098479834634", "439867439058743095864395348375043296845094854983" }; char testKeys256[][65] = { "0000000000000000000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20", "404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F", "4394398576098257436095746985679043867498572406874967416846341641", "4369006859867098670492857409386741095643756930847023587048579014" }; char testData[][256] = { "4938673409687134684698438657403986439058740935874395813968496846", "549813644389670948567490687546098245665626527788", "64398769586792586795867965624526", "468376458463264536" }; char testResult[5][4][3][256] = { { { "6CAEC72F5E101C66550215ACAB6B874C62E7BD074C0A09A8EE4562EFCB4E560A3E90FA0F50391087824FC27F57618E5C", "E20E3123AC64FCA5536E0A2DC48DBEBCECB3F260EFF4A0EB99D72F57EF38DED336EB9DD0B968D24C91E63974E7445A21", "C7910B1634DB493998608875A4652B20C64202ED507D9DBA06F62EB20A63C32FB6C9669D42A0AC29D773E6D40A63A2AC" }, { "8F48A65BF638FEDB7E6F59BAC8C110FEBA933F106D564119B88569E758B7FB83", "125E1D93DC2C43A6FAFC508DB6F9A4A9F390D102C2300F0A3617CE95027BFAA3", "FACB8DEF1B476400DE9796D5058E9086ECF04C927F5C160161C7A34D8288EB3C" }, { "C810E96482F109C9A05D2B1BEBAC7966BB7784F58A5478C1A07EC0DB39F6D87B", "2385391BB8F2DD97280B1FAEFACB6B5C4FE12A2274D6B967509CF18500A640D6", "47549520EADA1A5D931EACCC922F88BA2E386089BF97C790FD2CD38553334AE4" }, { "A7D9EAE80224624188CAA7012140E946", "6ECD5C71ECA4AB9C3B71E91721CA2043", "2F77AA438E9259F268985668B00650E5" } }, { { "FCB2FB6BF8ED8910F023A934EB9DA550E4D5B469D75B9390F4A207E54F29412450E52E980862DC80B89F6D1D10B68AA5", "7EF0F65513CFE3E0D21305E2ECCBB3554B0DE119720C5A86337E57F74795BC23ED9CB82A951DE3D00D7A0DC8997319DD", "5B83BFDB6EF3AEA5191F2EE3366EDE10480E9459C0DE2994DD9C6408A377DFFF8121A38CFD1AA864559B9A435A3BDD6D" }, { "81D667193D42BF19C456F4A1F7070C047D94C7EE8136FA315F938162FDDA20C1", "2EFBA2B689C0F775097F98B569A1F20004F1A75F0C53473969DBE586ABCAE04D", "447326913AA4565951D987F59B48870DD9285EEFCF64B429C2220E4F3E0D9DE2" }, { "891DF30BAEA2D24408A9C788D59DBAC7A6F34311813216311E18E9ED7122DB1A", "F1629B62ECDF3CDAA3DA0EBB31EE37691AF4EB2B6F9CF04A9861935B2C167D02", "C7BD348D5E6696CB8BA813B96EA5C42C5C3C3629D18FC9DAF1B50A0AE4843C5B" }, { "91C44D109D46C8E8656793680D43BE94", "E68D8E49A19F155B7ED7253120B0D117", "FAED8666F695C85283ECF51C96DB41CE" } }, { { "0CCFB49FE2B7E93A556E56B2C616885FBB0515F55A4210FE2F492A4775F078655CB21691CA6A54819C2D885954809D00", "2FC6C785D683FC35304DD161A21FA1B256F9FBB2817F1F3BEBCE7C1E292EC6999641AA6953C0FAB6DFC2942CABD32DFB", "31FAF4E3DA19D2372666AC635FFE361E33AD7865AEF616273D8F3B471F77A0998C6A41497168A65F621D912C54A4AF28" }, { "0B3842152A6365ED14AD952ABBBAF0EED2E8F36250DD25DDA301490FDE05219B", "696BF21A887A04E194DCC18719E1BD623D8BD25A0CEF5EC2E21312ACE6C81F40", "A2C8E61471EC80FE39AC0D8F720FEA8F2D23D04596A751C755E51CD357BCA5E0" }, { "5E0EA3AFBE191A16854C7960F087958F577EA4F80160F521A12D2211FAC25E16", "F5475B4FD48F969123C9F7FB08C7E902CCA282F167BBAFF1A7C7EDDB7BCBAC76", "380CB860EC6DEF4F9329F4BE826DE1FE61A71629DD978F00BEFB349ACBD0BAD8" }, { "BA1452E755E6A43E43B10DD2C1530093", "07CA52926D4E8F2F6055E6E0251CB9E5", "AB99E5FEE195B4433667AD3074A9322E" } }, { { "D2D46E577723B30E6B5FC96DC18B2C55E0EACCB07CE07C7F30FD113A987E2A2059AB7DF8985C1AE525EFAD9CE111893C", "CC5B220688AC0231DBC03C8886C0D0109840B9E58FBB1A6B6C261ED9E7979E951818033A25778FF328786D1777790078", "4B4A0B3D6D4E770BECC574BF66CD401942DC4D0DCD0EC65F99B2925B688BB217FCB5C946BE986C440C93279F4670CD43" }, { "29C76D62D3C4F7FECCBFD7A73B06E2ECA7AA3B2D4BE79EC945B0B88C813264D8", "B898DCE11F3D6BB2182208E0BBBA7F404FE415D4D6D0772960E7CE3549B9899C", "11E9552009836B51F241E972D680A9F397260163D9D5369BFC1B136FB4206966" }, { "539FC6EDAE21EDDC1CC4650367F527467916A6990E540146238AA9CD6B3B4ADE", "2D9DE2BC47DAFCF7867134110C541EBCD72D67B1B23DEF6805DBFF4A4D90EF91", "BF484690835FF61C4A7873A996EEB91F553978A40360E192273D3923E04DFE1E" }, { "4910EFFFBF571C98D51802F04A42213E", "EDD1880FC4D41293BC74B98AF3D8A010", "F8BCC258A6CD7FAA4EDF16A3CF5573C4" } }, { { "C2061BD0B4274B5CB4E408B492991F4195FDBFCDED1BC57442151B182BA6E8075AAF858F357C262E0034B9B5F839D823", "6EEFEBCC9F8C607D21A158E23980EFA6EC234DC6EA668A446F467F4AE87521F18DC1800D87A5EBC63C444F810557B61D", "00C952BA54614A1F11B0D59F3F469A859F62CCE0D35073B91B461302A7F37BD0B23401482DFCEE66ABD12C05615C9862" }, { "B36553D93EEF04AE247DBCBDDB8C039FFAC8AC1B0EF14C2E4BA653F089924451", "90670C9DE58F95431591FA2BE8EA1B4B3F5BDBFC0B5199F94A41E4FC7B6B1645", "A065415413D3A08E4B42A3F2681B8D122167A1E3F92D38C305761D9BF80131F1" }, { "12A758F161543F2842138B8C2453C3A05A90BE9F92CB3DD10C40AB9D1D746B49", "DF1F4DDFFE1032C812FC6F35AB2B3A7B0E8D26DA49DEC8F5E08D108DB1283BEA", "FDCB66159E1B5CF1BE9F7271EF2C35D5E9F7485E32D16C6AC865E64619DB8724" }, { "1FC224DCB64848B5E8F9FB91C542991F", "1F8C5F65F9205098B47E26894B9154D9", "19763CAC206EDFDEBEDAD9C274DEE1C1" } } }; char testIV[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "69836472094875029486750948672066", "48670943876904867104398574908554" }; for (int i = 0; i < 5; i++) { ByteString keyData128(testKeys128[i]); ByteString keyData192(testKeys192[i]); ByteString keyData256(testKeys256[i]); AESKey aesKey128(128); CPPUNIT_ASSERT(aesKey128.setKeyBits(keyData128)); AESKey aesKey192(192); CPPUNIT_ASSERT(aesKey192.setKeyBits(keyData192)); AESKey aesKey256(256); CPPUNIT_ASSERT(aesKey256.setKeyBits(keyData256)); ByteString IV(testIV[i]); for (int j = 0; j < 4; j++) { ByteString plainText(testData[j]), shsmPlainText; ByteString cipherText; ByteString shsmCipherText, OB; // Test 128-bit key cipherText = ByteString(testResult[i][j][0]); // Now, do the same thing using our AES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(aes->encryptInit(&aesKey128, SymMode::CBC, IV)); CPPUNIT_ASSERT(aes->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(aes->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(aes->decryptInit(&aesKey128, SymMode::CBC, IV)); CPPUNIT_ASSERT(aes->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(aes->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 192-bit key cipherText = ByteString(testResult[i][j][1]); // Now, do the same thing using our AES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(aes->encryptInit(&aesKey192, SymMode::CBC, IV)); CPPUNIT_ASSERT(aes->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(aes->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(aes->decryptInit(&aesKey192, SymMode::CBC, IV)); CPPUNIT_ASSERT(aes->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(aes->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 256-bit key cipherText = ByteString(testResult[i][j][2]); // Now, do the same thing using our AES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(aes->encryptInit(&aesKey256, SymMode::CBC, IV)); CPPUNIT_ASSERT(aes->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(aes->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(aes->decryptInit(&aesKey256, SymMode::CBC, IV)); CPPUNIT_ASSERT(aes->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(aes->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); } } } void AESTests::testECB() { char testKeys128[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "89436760984679018453504364534464", "49587346983643545706904580436731" }; char testKeys192[][49] = { "000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101213141516171819", "404142434445464748494A4B4C4D4E4F5051525354555657", "096874395874290867409857496743857632098479834634", "439867439058743095864395348375043296845094854983" }; char testKeys256[][65] = { "0000000000000000000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20", "404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F", "4394398576098257436095746985679043867498572406874967416846341641", "4369006859867098670492857409386741095643756930847023587048579014" }; char testData[][256] = { "4938673409687134684698438657403986439058740935874395813968496846", "549813644389670948567490687546098245665626527788", "64398769586792586795867965624526", "468376458463264536" }; char testResult[5][4][3][256] = { { { "6CAEC72F5E101C66550215ACAB6B874CD26479922B98D9839D7DA729B557ABA00143DB63EE66B0CDFF9F69917680151E", "E20E3123AC64FCA5536E0A2DC48DBEBC0E4E53BDA45FFC97C677951A891A6B7502BB292527E726FD51EB29894D6F0AAD", "C7910B1634DB493998608875A4652B205750B3B761DA7718E120C23A575F7D821F788FE6D86C317549697FBF0C07FA43" }, { "8F48A65BF638FEDB7E6F59BAC8C110FE0E5E6370CBEFACFA0D7A5744030A481B", "125E1D93DC2C43A6FAFC508DB6F9A4A933738D14C219340D5F4D7203DEDCA7E1", "FACB8DEF1B476400DE9796D5058E90863A9A8C8BB2420B9A85BA3E8F87BB48F2" }, { "C810E96482F109C9A05D2B1BEBAC79660143DB63EE66B0CDFF9F69917680151E", "2385391BB8F2DD97280B1FAEFACB6B5C02BB292527E726FD51EB29894D6F0AAD", "47549520EADA1A5D931EACCC922F88BA1F788FE6D86C317549697FBF0C07FA43" }, { "A7D9EAE80224624188CAA7012140E946", "6ECD5C71ECA4AB9C3B71E91721CA2043", "2F77AA438E9259F268985668B00650E5" } }, { { "8947CE273536C8A4D1E878F38371B9A8D2B3B45496779386CBA32CA70001D6AA6CC00A66D2AD83FFD76E9A2BCAD89A01", "B151340CFECADA3AE176637D0A78686E2063E1A602C85D03AE648BDF4FA57C36F7F1878D088644BD5FB43D3C0FE1C30C", "C19AE024C8F6B8E3383F675DF463512E273AAD7D0B88F22D5225EF09D2E37118D45D7C5AA26BCA9D6B1D5DDBF68F9EF6" }, { "16C30BBAE7CDB2EE1E02275B79A064F6EE69FB37C8E039400435782F550CF86A", "F6C869D28D2D167C50BEE8F605D33021CB9173567B8B4AB3EEC68F0298324B78", "07DB563F7E31F1E670A02F97E8D120C7EE3FCEBBF2FDC2D37FC17D93ED1A778B" }, { "52902B599686234833C4D420A9BF17FF6CC00A66D2AD83FFD76E9A2BCAD89A01", "B17FA9EA89D5578A844B3D82891330B1F7F1878D088644BD5FB43D3C0FE1C30C", "74BC55BE85291E0D1FA4A4444051CF65D45D7C5AA26BCA9D6B1D5DDBF68F9EF6" }, { "3F00CAAC6FA432A7C1826CA4DA7C55D6", "9C2DBF449FF2C4AC1CFD7C43D200D33A", "E2183AB600A986806D86ADA4EE38E562" } }, { { "23741EF993CBA04E5C67B42A16CA4D100BA6DF745E6D90818500DEC1CFC9811DBD3ACBFC853ED5DE825266C3B1883EC4", "F14D0EB7DFDB9B8960B0E47D7F4828E8756C38BA83655AAC466986ECB229A66FA390265A4BF5F50A8DFFAD253701E418", "0AAE579A796C94AF4FFB9D7C71381CB5E68E15465F30D7085A72D0CCEC7030BBC9CB7B3859E1A550BCBF11B624022C56" }, { "AFCD6801459845C88548CC337BDD4D8B87E81D9D6AC945E14E3C4E0AC976A4B9", "117129A4775FC84E703F2F2C54B1B55DC4A79241F6CB0A37A8D551D71983D944", "1128250DA7C9A1BBE6A61AC01F28D4D9E3027C3625BD5514AE5DFE4B9132DAFA" }, { "B275BDAF14AE286643C533258343F822BD3ACBFC853ED5DE825266C3B1883EC4", "93ACFCCFE2C4736B6492A673A59DACE2A390265A4BF5F50A8DFFAD253701E418", "2C2165E6491662A855FD7A20CDFF23BDC9CB7B3859E1A550BCBF11B624022C56" }, { "30BBF52D760BAEA653FD03E5E84E583A", "F5F55DF3FC4D9CF2A2829BACA774A51A", "7EE196D148C11FA4998A90C6C7932395" } }, { { "44C2B3344B002BB7A6994E1C74CC7BA70CE55BF44FD96506B553F0EFD3FE02B28329D59D480B0C1714A0DC60EB9FA8CE", "568C7627FD2519BE6031F052DE8F680860F7680460E92A524EA912174BE17B1337D593DEF15FB5BA64F03D1AAE276775", "99E36C0097BCFE41945C064EFA476FF4AA6048F909BEDE32A649F1035A2FB83CD601D09C3FDB36BC61B8CDE5BDD73804" }, { "D748E8E93D29775BD8831E3BC1E1ABF75F484C7CC693521A66A5AB1637822E40", "010103778E123E5140F8D0356DA831E1587DB7E416AE9FAD14C6E2F78DC83148", "A8B8926E8FB762A1AB8CD9FA08507D77872C8EAAAFF3527572F49497B8B366C9" }, { "CFF3212C7E94C2DD65EC1CDC998D6C4B8329D59D480B0C1714A0DC60EB9FA8CE", "324D16FEEC9DCA75A80F4B80175F8A7537D593DEF15FB5BA64F03D1AAE276775", "850567F4F0200CFBF88F1A6D35CAF6D9D601D09C3FDB36BC61B8CDE5BDD73804" }, { "417F142D7609AE701B3D263FFECE4502", "E0DC994D8DC01C4EB2ECD19AD120C3D1", "FB26CC4E48B40EAB755FF65164EFB406" } }, { { "048AEE75741BC60D01B512A53FEE97238F294743E7A351FAF589DD9E040BB8AF0F59D8F60E9C700F10025B5E69828819", "67FB10E52640B1E060F3D7868524721AC375DC76628B0D79C5F40ADC653FC001B50C33356548289D3E70EB7FBC0E2B56", "31953FF249D7519D3C39FB21D70A41033286A320193CC938C5ACBBCA2B25340829799212E3CABACE0BFD4424427705AB" }, { "8D8D50FA4619F0E1B821DCA4ACBDFD46AE92D76A0B95A0331D61C4A7032D9705", "10685E8F632AC41D92E3A0403BB20C79868BD6F94691226EC54D7220C45E7233", "C5FF99FD1BC2BFDBEA62894B279DE6CBF51CCD00362A557DB9D9102DAF623A50" }, { "0330B8FF58E4E6E956B4F81F7A4770200F59D8F60E9C700F10025B5E69828819", "C79BABE5B34B305B05E38013DC5568F7B50C33356548289D3E70EB7FBC0E2B56", "98BEE460FF803288C898A900DD08CE2529799212E3CABACE0BFD4424427705AB" }, { "9A4FD3A26DD0D3A12F224E5E7A06EB76", "B86FE6F088C3A6497F21BCB29DB703D1", "313CC604B301DACA48CDB6F405AA7938" } } }; char testIV[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "69836472094875029486750948672066", "48670943876904867104398574908554" }; for (int i = 0; i < 5; i++) { ByteString keyData128(testKeys128[i]); ByteString keyData192(testKeys192[i]); ByteString keyData256(testKeys256[i]); AESKey aesKey128(128); CPPUNIT_ASSERT(aesKey128.setKeyBits(keyData128)); AESKey aesKey192(192); CPPUNIT_ASSERT(aesKey192.setKeyBits(keyData192)); AESKey aesKey256(256); CPPUNIT_ASSERT(aesKey256.setKeyBits(keyData256)); ByteString IV(testIV[i]); for (int j = 0; j < 4; j++) { ByteString plainText(testData[j]), shsmPlainText; ByteString cipherText; ByteString shsmCipherText, OB; // Test 128-bit key // Get the reference for the encrypted data cipherText = ByteString(testResult[i][j][0]); // Now, do the same thing using our AES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(aes->encryptInit(&aesKey128, SymMode::ECB, IV)); CPPUNIT_ASSERT(aes->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(aes->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(aes->decryptInit(&aesKey128, SymMode::ECB, IV)); CPPUNIT_ASSERT(aes->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(aes->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 192-bit key cipherText = ByteString(testResult[i][j][1]); // Now, do the same thing using our AES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(aes->encryptInit(&aesKey192, SymMode::ECB, IV)); CPPUNIT_ASSERT(aes->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(aes->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(aes->decryptInit(&aesKey192, SymMode::ECB, IV)); CPPUNIT_ASSERT(aes->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(aes->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 256-bit key cipherText = ByteString(testResult[i][j][2]); // Now, do the same thing using our AES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(aes->encryptInit(&aesKey256, SymMode::ECB, IV)); CPPUNIT_ASSERT(aes->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(aes->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(aes->decryptInit(&aesKey256, SymMode::ECB, IV)); CPPUNIT_ASSERT(aes->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(aes->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); } } } void AESTests::testWrap(const char testKeK[][128], const char testKey[][128], const char testCt[][128], const int testCnt, SymWrap::Type mode) { for (int i = 0; i < testCnt; i++) { ByteString kekData(testKeK[i]); ByteString keyData(testKey[i]); AESKey aesKeK(kekData.size() * 8); CPPUNIT_ASSERT(aesKeK.setKeyBits(kekData)); ByteString wrapped; ByteString expectedCt(testCt[i]); CPPUNIT_ASSERT(aes->wrapKey(&aesKeK, mode, keyData, wrapped)); CPPUNIT_ASSERT(wrapped.size() == expectedCt.size()); CPPUNIT_ASSERT(wrapped == expectedCt); ByteString unwrapped; CPPUNIT_ASSERT(aes->unwrapKey(&aesKeK, mode, wrapped, unwrapped)); CPPUNIT_ASSERT(unwrapped.size() == keyData.size()); CPPUNIT_ASSERT(unwrapped == keyData); /* #ifdef HAVE_AES_KEY_WRAP_PAD keyData.resize(20); ByteString padwrapped; CPPUNIT_ASSERT(aes->wrapKey(&aesKeK, SymWrap::AES_KEYWRAP_PAD, keyData, padwrapped)); CPPUNIT_ASSERT(padwrapped.size() == 32); ByteString padunwrapped; CPPUNIT_ASSERT(aes->unwrapKey(&aesKeK, SymWrap::AES_KEYWRAP_PAD, padwrapped, padunwrapped)); CPPUNIT_ASSERT(padunwrapped == keyData); #endif */ } } // RFC 3394 tests void AESTests::testWrapWoPad() { char testKeK[][128] = { "000102030405060708090A0B0C0D0E0F", // section 4.1 "000102030405060708090A0B0C0D0E0F1011121314151617", // section 4.2 "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", // section 4.3 "000102030405060708090A0B0C0D0E0F1011121314151617", // section 4.4 "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", // section 4.5 "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", // section 4.6 }; char testKey[][128] = { "00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFF0001020304050607", "00112233445566778899AABBCCDDEEFF0001020304050607", "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F" }; char testCt[][128] = { "1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5", "96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D", "64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7", "031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2", "A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1", "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21" }; testWrap(testKeK, testKey, testCt, sizeof(testKeK) / 128, SymWrap::AES_KEYWRAP); } // RFC 5649 tests void AESTests::testWrapPad() { char testKeK[][128] = { "5840DF6E29B02AF1AB493B705BF16EA1AE8338F4DCC176A8", // section 6 example 1 "5840DF6E29B02AF1AB493B705BF16EA1AE8338F4DCC176A8", // section 6 example 2 }; char testKey[][128] = { "C37B7E6492584340BED12207808941155068F738", "466F7250617369" }; char testCt[][128] = { "138BDEAA9B8FA7FC61F97742E72248EE5AE6AE5360D1AE6A5F54F373FA543B6A", "AFBEB0F07DFBF5419200F2CCB50BB24F" }; testWrap(testKeK, testKey, testCt, sizeof(testKeK) / 128, SymWrap::AES_KEYWRAP_PAD); } softhsm-2.0.0/src/lib/crypto/test/AESTests.h0000664000175000017500000000447412533040716015571 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AESTests.h Contains test cases to test the AES implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_AESTESTS_H #define _SOFTHSM_V2_AESTESTS_H #include #include "SymmetricAlgorithm.h" class AESTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(AESTests); CPPUNIT_TEST(testBlockSize); CPPUNIT_TEST(testCBC); CPPUNIT_TEST(testECB); #ifdef HAVE_AES_KEY_WRAP CPPUNIT_TEST(testWrapWoPad); #endif #ifdef HAVE_AES_KEY_WRAP_PAD CPPUNIT_TEST(testWrapPad); #endif CPPUNIT_TEST_SUITE_END(); public: void testBlockSize(); void testCBC(); void testECB(); void testWrapWoPad(); void testWrapPad(); void setUp(); void tearDown(); private: // AES instance SymmetricAlgorithm* aes; void testWrap(const char testKeK[][128], const char testKey[][128], const char testCt[][128], const int testCnt, SymWrap::Type mode); }; #endif // !_SOFTHSM_V2_AESTESTS_H softhsm-2.0.0/src/lib/crypto/test/MacTests.h0000664000175000017500000000436712533040716015662 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** MacTests.h Contains test cases to test the MAC implementations *****************************************************************************/ #ifndef _SOFTHSM_V2_MACTESTS_H #define _SOFTHSM_V2_MACTESTS_H #include #include "MacAlgorithm.h" #include "RNG.h" class MacTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(MacTests); #ifndef WITH_FIPS CPPUNIT_TEST(testHMACMD5); #endif CPPUNIT_TEST(testHMACSHA1); CPPUNIT_TEST(testHMACSHA224); CPPUNIT_TEST(testHMACSHA256); CPPUNIT_TEST(testHMACSHA384); CPPUNIT_TEST(testHMACSHA512); CPPUNIT_TEST_SUITE_END(); public: #ifndef WITH_FIPS void testHMACMD5(); #endif void testHMACSHA1(); void testHMACSHA224(); void testHMACSHA256(); void testHMACSHA384(); void testHMACSHA512(); void setUp(); void tearDown(); private: MacAlgorithm* mac; RNG* rng; }; #endif // !_SOFTHSM_V2_MACTESTS_H softhsm-2.0.0/src/lib/crypto/test/ent.h0000664000175000017500000000353212533040716014716 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ent.h Header file to give access to the modified ent.c implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_ENT_H #define _SOFTHSM_V2_ENT_H #if defined(__cplusplus) extern "C" { #endif void doEnt ( unsigned char* data, size_t len, double* pEntropy, double* pChiProbability, double* pArithMean, double* pMontePi, double* pSerialCorrelation ); #if defined(__cplusplus) } #endif #endif // !_SOFTHSM_V2_ENT_H softhsm-2.0.0/src/lib/crypto/test/ECDHTests.h0000664000175000017500000000425112533040716015655 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECDHTests.h Contains test cases to test the ECDH class *****************************************************************************/ #ifndef _SOFTHSM_V2_ECDHTESTS_H #define _SOFTHSM_V2_ECDHTESTS_H #include #include "AsymmetricAlgorithm.h" class ECDHTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ECDHTests); CPPUNIT_TEST(testKeyGeneration); CPPUNIT_TEST(testSerialisation); CPPUNIT_TEST(testPKCS8); CPPUNIT_TEST(testDerivation); CPPUNIT_TEST(testDeriveKnownVector); CPPUNIT_TEST_SUITE_END(); public: void testKeyGeneration(); void testSerialisation(); void testPKCS8(); void testDerivation(); void testDeriveKnownVector(); void setUp(); void tearDown(); private: // ECDH instance AsymmetricAlgorithm* ecdh; }; #endif // !_SOFTHSM_V2_ECDHTESTS_H softhsm-2.0.0/src/lib/crypto/test/DESTests.cpp0000664000175000017500000010064712533040716016126 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DESTests.cpp Contains test cases to test the DES implementation *****************************************************************************/ #include #include #include "DESTests.h" #include "CryptoFactory.h" #include "DESKey.h" #include CPPUNIT_TEST_SUITE_REGISTRATION(DESTests); void DESTests::setUp() { des = NULL; des = CryptoFactory::i()->getSymmetricAlgorithm(SymAlgo::DES); // Check the return value CPPUNIT_ASSERT(des != NULL); } void DESTests::tearDown() { if (des != NULL) { CryptoFactory::i()->recycleSymmetricAlgorithm(des); } fflush(stdout); } void DESTests::testBlockSize() { CPPUNIT_ASSERT(des->getBlockSize() == 8); } void DESTests::testCBC() { #ifndef WITH_FIPS char testKeys56[][17] = { "0000000000000000", "0102030405060708", "4041424344454647", "4698436794236871", "0940278947239572" }; char testKeys112[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "64398647034486943598534703463870", "87406984068406984607412103517413" }; #endif char testKeys168[][49] = { "000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101112131415161718", "404142434445464748494A4B4C4D4E4F5051525354555657", "643906874509874309687459084769847562436043696747", "430135460496813044639085714376487549490586439575" }; char testData[][256] = { "4938673409687134684698438657403986439058740935874395813968496846", "549813644389670948567490687546098245665626527788", "64398769586792586795867965624526", "468376458463264536" }; char testResult[5][4][3][256] = { { { "ACC8B1BE444EEA9E016A46EF600E9B3FB2C87DE8CE9BE5394917AABB0A04639A3BFF1E250FE971D7", "ACC8B1BE444EEA9E016A46EF600E9B3FB2C87DE8CE9BE5394917AABB0A04639A3BFF1E250FE971D7", "ACC8B1BE444EEA9E016A46EF600E9B3FB2C87DE8CE9BE5394917AABB0A04639A3BFF1E250FE971D7" }, { "F9A1913AA27A05379506BE00D5F7398F67722076A3439E759BA729A58E8FEE64", "F9A1913AA27A05379506BE00D5F7398F67722076A3439E759BA729A58E8FEE64", "F9A1913AA27A05379506BE00D5F7398F67722076A3439E759BA729A58E8FEE64" }, { "36FD5581BB31F3E27910895DC2F2599CD0F8B8F002220588", "36FD5581BB31F3E27910895DC2F2599CD0F8B8F002220588", "36FD5581BB31F3E27910895DC2F2599CD0F8B8F002220588" }, { "B81DA29972385E55CB453A17B6D88D22", "B81DA29972385E55CB453A17B6D88D22", "B81DA29972385E55CB453A17B6D88D22" } }, { { "EE16FFE3CC4D4589766FA0957FB728A75D44A00D9BEBE2D43C4D4F3A5AFDB49730CFD4DF46D3AEF6", "A070EE9DED89EE198E0E9B3CEB4879BB0244AB7FCD3450ED044BB5EE0AC8F7797383FDB8AAEF77B8", "E7C594590C9CA00B376B702CE3B92C3F699B3EEEB2CEA08FA551350C837BF031FCAF4E1E97450327" }, { "D4142C47C700069F3E71EA6B1EF301B9B97261543ED75B32242C05A253B077B8", "102BBE7D93CD0EF66280D3FA1F2A3976FB9C4D1B155D19E4985ADB86015DDE8C", "600C3A75AC6EB4C4609BA6B7ED273ED56E59CD49FC911C33DD8DFCA384BAA462" }, { "47452120CD84CC32FC72F3B8600E5C43EEE192A29BC6BCB7", "ADCF4292A32E51A7843CC8590E6934083A2CC847082FF2B4", "D0FA596AC00BDA870999FD3FA2494C3C8B40B261EB3066F6" }, { "6BD20CDBE6E6ECAD6ED829FB43E92751", "AE4379E371E295F63423F861B59111F0", "2757FC58EDEEB8499EA9B49AB2729BAD" } }, { { "298621D5237F6230067DE7871DDBA6991E85CA14AD661D21357240923604D23A6A4119277B75B331", "2C9F4FC0ACE7C8A4847472A0D5DDD42F36D3B2C46144B5A0ECDBB59806472E6257952DFD4DB9EBE5", "679A832C630207E76BC1FF8371C61CA2518E37FE97EDED1B171E3E11807250145736949368AC822B" }, { "80FFD37B545675BB8C7CD317A73AB48CC0A39D3D9C11474EC3FD1220A066C034", "F9228036718792EE86A85626AB1BC05E17F9CE21FF5D1723D0442CE852F004C3", "D5F5F1EA7D8C2038FEDCBEDF157A5D2469A941FEC696D74DB8359CA5AECDD4CE" }, { "1ABB1CC10F589D993030A978B1B7F44AD52FFFEBF23638CA", "D2423F54FA4978C95E4B13EF4DD6AA82DFD772F0FDAF5AD1", "8128EC49D71F5711E5304E7C4423C63AD0EFC45453B66583" }, { "B9EE976AB97396047510C1DEA5C86A4B", "46BA1930042146B31BD8FAF3AE6F3414", "46EF3BCCA73E33C03D81BFE0DFFA7ABD" } }, { { "30D1B2556D516F20C2FD117FE0355845FBB0B11ABE5922A7EAA19C3A48E30207218321B3F0F30A6D", "CBFA560297901DD691CDFDF98675BD7FF3A64FDCC0EF02F29C81105D3ECAC4E2803E2279F4476B35", "4A30EC10433BE3695DC2B064E6240419C7BF81F1EE7640D5E2FFFA106666A2CEBF18DB954A992B5E" }, { "61FFB2E5A73170603E48F9823E6DF7105C9A909CC2F5CEDBEA7E60C076355B37", "8408BD722B12031D17A1645AA59B05E2A50F7002B19877D6EB1C9BB7107C523F", "97EF5791017B10CF07FB8144C19633522CBBE55DC63EF608F8734EE6484C0B0E" }, { "7205DC463B3D5EC858C8E7A13844A1A8FF21C0D615CA56AF", "D5D08C1DC728A47CD55A2ACBB811294962022E745F4BCDF4", "7761189D73039A3F06BDDF00B308D7A43BE7BEA1CE9D042E" }, { "1702428661BA4CFE686CFDEDFFAA6A27", "9218A89B0A7AEC7E6E2AF1CA493B2829", "6EEB9F7DDF66CED3DB74F7E8DE0CB2CD" } }, { { "4FD3A4C759827F6E188E542B83A858026C17FD1DEF21477A964D122B62EE55FA9DB3CCF05A768C83", "F2C8B52652970805EE60ECECC8369C98443463F1C3A5A6357DFDFEE6B7F1EF0CF05523B5469E4555", "21FCBDC92C07F112D19742F5100F2A995E27CB282D73DF5CFEC802C629A279BD4E498C98D170003E" }, { "3FD4C32A44DC0A9605A5A793C57E94826E80FC9E8E9620BBC2E02FE41A62A2D3", "4FC88F1E88C3B5A76CF6BE5FA8205BA6F7FA201F7C40E8F0F9CA156E140A4EC5", "CCE31260C967F4B9BB3D2D31F82320715E434C1313D911C58CE7E42AA78DA831" }, { "714766BE5CB60DA99DC0BD4E7E655ADE7F26E45F372EF1BF", "00064542E2B4821B4E9173DA6FD1ABAE45C5E5CF26DB506D", "4D88D531C20E63A39372F275329BDBEBE15E7D2C32F2A98F" }, { "4933917C9B56124914D2B76DE221BA13", "7F2D1CA9D942630FE1E954E4176E84A5", "9A46902F3997F0EB121981DAEC6D89C4" } } }; char testIV[][33] = { "0000000000000000", "0102030405060708", "4041424344454647", "4693867334098764", "6209876098547207" }; for (int i = 0; i < 5; i++) { #ifndef WITH_FIPS ByteString keyData56(testKeys56[i]); CPPUNIT_ASSERT(keyData56.size() == 8); ByteString keyData112(testKeys112[i]); CPPUNIT_ASSERT(keyData112.size() == 16); #endif ByteString keyData168(testKeys168[i]); CPPUNIT_ASSERT(keyData168.size() == 24); #ifndef WITH_FIPS DESKey desKey56(56); CPPUNIT_ASSERT(desKey56.setKeyBits(keyData56)); DESKey desKey112(112); CPPUNIT_ASSERT(desKey112.setKeyBits(keyData112)); #endif DESKey desKey168(168); CPPUNIT_ASSERT(desKey168.setKeyBits(keyData168)); ByteString IV(testIV[i]); for (int j = 0; j < 4; j++) { ByteString plainText(testData[j]), shsmPlainText; ByteString cipherText; ByteString shsmCipherText, OB; #ifndef WITH_FIPS // Test 56-bit key cipherText = ByteString(testResult[i][j][0]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey56, SymMode::CBC, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey56, SymMode::CBC, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 112-bit key cipherText = ByteString(testResult[i][j][1]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey112, SymMode::CBC, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey112, SymMode::CBC, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); #endif // Test 168-bit key cipherText = ByteString(testResult[i][j][2]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey168, SymMode::CBC, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey168, SymMode::CBC, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); } } } void DESTests::testECB() { #ifndef WITH_FIPS char testKeys56[][17] = { "0000000000000000", "0102030405060708", "4041424344454647", "4698436794236871", "0940278947239572" }; char testKeys112[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "64398647034486943598534703463870", "87406984068406984607412103517413" }; #endif char testKeys168[][49] = { "000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101112131415161718", "404142434445464748494A4B4C4D4E4F5051525354555657", "643906874509874309687459084769847562436043696747", "430135460496813044639085714376487549490586439575" }; char testData[][256] = { "4938673409687134684698438657403986439058740935874395813968496846", "549813644389670948567490687546098245665626527788", "64398769586792586795867965624526", "468376458463264536" }; char testResult[5][4][3][256] = { { { "ACC8B1BE444EEA9E44404B8595B7667982F1BDF99F419F083249964334F2B15F7E422822773666C0", "ACC8B1BE444EEA9E44404B8595B7667982F1BDF99F419F083249964334F2B15F7E422822773666C0", "ACC8B1BE444EEA9E44404B8595B7667982F1BDF99F419F083249964334F2B15F7E422822773666C0" }, { "F9A1913AA27A0537CA0BB1A6417C4037978BC92CEFCD10BB7E422822773666C0", "F9A1913AA27A0537CA0BB1A6417C4037978BC92CEFCD10BB7E422822773666C0", "F9A1913AA27A0537CA0BB1A6417C4037978BC92CEFCD10BB7E422822773666C0" }, { "36FD5581BB31F3E2ADA81678B64A0F3C7E422822773666C0", "36FD5581BB31F3E2ADA81678B64A0F3C7E422822773666C0", "36FD5581BB31F3E2ADA81678B64A0F3C7E422822773666C0" }, { "B81DA29972385E55EA1F3677CDC02D27", "B81DA29972385E55EA1F3677CDC02D27", "B81DA29972385E55EA1F3677CDC02D27" } }, { { "278B2CA6259C30E180CCB62E69F0841F235507E2FB3404FC2BC223E37E32B3A78207EA5D3E19A5FD", "417579E3ABEF6F0D620B4FF88E2220457466420803140BFEFBA062A2A41D7C15061019377C6BFD8A", "A676D0404F0F105B2073B9DD19C8C434428098BFC5AF1292FE12477340395F118F45B5BE23F16C4E" }, { "7D004390E5638E54077E2551B01BD52BFA1B98403ECE1AEF8207EA5D3E19A5FD", "391B84593FEA836450318A6E943F1C3A4A6BD74E5001EB7A061019377C6BFD8A", "DEAF58111ECCCB449F0C2564B52E360E4AACC8672ABBDF1A8F45B5BE23F16C4E" }, { "A6947F9EF4159BAE636A70B904059BC38207EA5D3E19A5FD", "14ADFE212E27BF7F409395B45577F2C8061019377C6BFD8A", "FF87BF761FC159F4442B3B4593233BC48F45B5BE23F16C4E" }, { "3A1777DAAAC85389EE0B499A90AE1739", "376E61DF2EAFE5B523964A03885AD085", "E4D81EE64FE8FB187EB7B5E80E075C73" } }, { { "F105809DF621715F4D3492E1EEC4A7DE0775A0632ECC13429DF0DC695A60882FA47F93E855A1445B", "77C85215179312315997B4D0E997DB413176C80A8ED9F5EB9B726200224CE97C20A8A19F543BCCBD", "AF1477E32B5BB1CA46D26B6020B3B48DB0A90A97B1BA60F032ADA648296EC92DEE924AA617423FD1" }, { "0FB3C3D9D93E0025F87909CD351D0116C0F684A204015E2CA47F93E855A1445B", "67A66DB3209C406D2FE31AF6C36D24C7B32D0F8F1EAFA90020A8A19F543BCCBD", "F85B1F07D788C59CD3DE6D562A175725DF596847ADEA8764EE924AA617423FD1" }, { "243A34CD70CE3819B9510980B6EFF3EAA47F93E855A1445B", "997E145467B88D9D4C923797F539AC1620A8A19F543BCCBD", "836788D7AD1F879B405438775FFD6D76EE924AA617423FD1" }, { "70856D6B67EE353F27EBB96462DACE63", "D02F2A92C175A58001D89C4AEC476384", "4ED379A40187826CAA90D2D6A05D5A9B" } }, { { "C79F67ABCE6F741CF6D5B7B4870397779AEB89F48805DD1A28305E804A4A2B91114E1CF0C7FA91DA", "42956EA3B9415E8FE75B667A7C6B1ADF64D08E53C38DE733A776A97C7A8FC27E32945078552FA3E2", "3685365AD0F07609E13CCDE69CEDC8CCA0C37262A87B734286B9119643AC3BABE435BDA25919BE86" }, { "09B882774309CC2B117586F5FA8BF7E4A5DA2A65E137665B114E1CF0C7FA91DA", "0E52A9ABE753758D3C4F6326A8F689282D1DAB8AF6FC8CFF32945078552FA3E2", "8DB6B9D50B5B8CE7DA56546CFF36C16BA3159E0EB7BD649AE435BDA25919BE86" }, { "025F9704F6ACD844BCFC6EBA809CD871114E1CF0C7FA91DA", "1692C6A1DF9192C6D4125991EA9A9CBE32945078552FA3E2", "6B848E67225EDDCCD7E8EC89ACDAA0AFE435BDA25919BE86" }, { "9D01CD89916AEE48AFE528A376E07AE9", "6FA6A689405048060D65E1B1240B76B7", "7EADEB7073D2EA995C5ED613C978817F" } }, { { "A98D0E8E72C589D80D240F192CF65C30FF3A1AB9D8CE54B09AA249C72E395AC3B40F19A649C1B237", "33AC43C7A936665859431D18C089EE45F1356C34F5DF462D81BBFA42380A7E4F6732A473091A3673", "FD4F2F77CCE20147CD0932B2E2D8D5978523F6A03D59E31E1F678A5DA4C350132E94F199555C371E" }, { "39453F3BF3C0CAE54279D96F4592359A5AEE6DD04D5F6162B40F19A649C1B237", "E2AFCEEFF2317C520D890D7F2CB91ACD99D5DCAEC9C409016732A473091A3673", "CB19BF88B2DEDDE981E048379A47BDF77ED5F815034CB07A2E94F199555C371E" }, { "9D466BACFA69266F7CC26D2C8B8CD203B40F19A649C1B237", "265FDBCCF5F2325B3C8770ABEEECA4166732A473091A3673", "C61E9B86A8A663AE1566CFFCF2046D6B2E94F199555C371E" }, { "380091B24160152B63EF067F6C189385", "548EB237B455CBA0100A5C52A6F28C2B", "066C3B0C5E6AF1E9BDD3DDAE5040F809" } } }; char testIV[][33] = { "0000000000000000", "0102030405060708", "4041424344454647", "4693867334098764", "6209876098547207" }; for (int i = 0; i < 5; i++) { #ifndef WITH_FIPS ByteString keyData56(testKeys56[i]); CPPUNIT_ASSERT(keyData56.size() == 8); ByteString keyData112(testKeys112[i]); CPPUNIT_ASSERT(keyData112.size() == 16); #endif ByteString keyData168(testKeys168[i]); CPPUNIT_ASSERT(keyData168.size() == 24); #ifndef WITH_FIPS DESKey desKey56(56); CPPUNIT_ASSERT(desKey56.setKeyBits(keyData56)); DESKey desKey112(112); CPPUNIT_ASSERT(desKey112.setKeyBits(keyData112)); #endif DESKey desKey168(168); CPPUNIT_ASSERT(desKey168.setKeyBits(keyData168)); ByteString IV(testIV[i]); for (int j = 0; j < 4; j++) { ByteString plainText(testData[j]), shsmPlainText; ByteString cipherText; ByteString shsmCipherText, OB; #ifndef WITH_FIPS // Test 56-bit key cipherText = ByteString(testResult[i][j][0]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey56, SymMode::ECB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey56, SymMode::ECB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 112-bit key cipherText = ByteString(testResult[i][j][1]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey112, SymMode::ECB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey112, SymMode::ECB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); #endif // Test 168-bit key cipherText = ByteString(testResult[i][j][2]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey168, SymMode::ECB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey168, SymMode::ECB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); } } } void DESTests::testOFB() { #ifndef WITH_FIPS char testKeys56[][17] = { "0000000000000000", "0102030405060708", "4041424344454647", "4698436794236871", "0940278947239572" }; char testKeys112[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "64398647034486943598534703463870", "87406984068406984607412103517413" }; #endif char testKeys168[][49] = { "000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101112131415161718", "404142434445464748494A4B4C4D4E4F5051525354555657", "643906874509874309687459084769847562436043696747", "430135460496813044639085714376487549490586439575" }; char testData[][256] = { "4938673409687134684698438657403986439058740935874395813968496846", "549813644389670948567490687546098245665626527788", "64398769586792586795867965624526", "468376458463264536" }; char testResult[5][4][3][256] = { { { "C59E2ADDC8D9529368469843865740390AE5DDB1B5B816204395813968496846", "C59E2ADDC8D9529368469843865740390AE5DDB1B5B816204395813968496846", "C59E2ADDC8D9529368469843865740390AE5DDB1B5B816204395813968496846" }, { "D83E5E8D823844AE48567490687546090EE32BBFE7E3542F", "D83E5E8D823844AE48567490687546090EE32BBFE7E3542F", "D83E5E8D823844AE48567490687546090EE32BBFE7E3542F" }, { "E89FCA8099D6B1FF6795867965624526", "E89FCA8099D6B1FF6795867965624526", "E89FCA8099D6B1FF6795867965624526" }, { "CA253BAC45D205E236", "CA253BAC45D205E236", "CA253BAC45D205E236" } }, { { "3E9FB188FC11138D05109EA396CA48E1681DF27A857C3C4A9E92D3DC85A5F313", "3440BEFCF35DC87716D8440F71BAF9ACD0441E10B9E5B525F0584499620086E2", "DDB35281888DF064195C42D45E4E2571AD62113A228B5107D1AC849861C199C0" }, { "233FC5D8B6F005B02500727078E84ED16C1B0474D7277E45", "29E0CAACB9BCDE4A36C8A8DC9F98FF9CD442E81EEBBEF72A", "C01326D1C26CE659394CAE07B06C2341A964E73470D01308" }, { "139E51D5AD1EF0E10AC3809975FF4DFE", "19415EA1A2522B1B190B5A35928FFCB3", "F0B2B2DCD9821308168F5CEEBD7B206E" }, { "3124A0F9711A44FC5B", "3BFBAF8D7E569F0648", "D20843F00586A71547" } }, { { "E376288A10BD52CB7162ADA9A732D24B574B1E7CB4FF5C791FFEA2E481AD3049", "FD82CFAE85B8581FFCF489F467D94B1B4FAAAEDDE4EC531ABD30D7EA235896AA", "24D9411BA456571900244AEA3EA7159BAA96522B6F891606A8D9A559FE218A9B" }, { "FED65CDA5A5C44F65172417A4910D47B534DE872E6A41E76", "E022BBFECF594E22DCE4652789FB4D2B4BAC58D3B6B71115", "3979354BEEB741242034A639D08513ABAE90A4253DD25409" }, { "CE77C8D741B2B1A77EB1B3934407D754", "D0832FF3D4B7BB73F32797CE84EC4E04", "09D8A146F559B4750FF754D0DD921084" }, { "ECCD39FB9DB605BA2F", "F239DEDF08B30F6EA2", "2B62506A295D00685E" } }, { { "740A4786C73A7C6B52DAF270161895E13B4437C56B9837827C2FE237532F4C19", "581B63C58404AEBECFDFD51D74A79836C11514685B47F3B02A2419AF0AA8C625", "D5FCB196868673D136D480E0B6EFC33C589131D87A4AC004A6E0DE8ADC8DE611" }, { "69AA33D68DDB6A5672CA1EA3F83A93D13F42C1CB39C3758D", "45BB1795CEE5B883EFCF39CE9A859E06C513E266091CB1BF", "C85CC5C6CC6765EC16C46C3358CDC50C5C97C7D62811820B" }, { "590BA7DB96359F075D09EC4AF52D90FE", "751A8398D50B4DD2C00CCB2797929D29", "F8FD51CBD78990BD39079EDA55DAC623" }, { "7BB156F74A312B1A0C", "57A072B4090FF9CF91", "DA47A0E70B8D24A068" } }, { { "0855A84EAD2176C3F10B9DCFC8D1A379AF616FC5C5CD4E6D434353C52832F9F6", "A8420E97462B0215AAC1DB0835D4064C6A8B123327FC396C9520BEA70B59B412", "3461DEDF1B4893E16706900E1DDBE351E90C1300B9B01E8A518A01AD56E9AC8C" }, { "15F5DC1EE7C060FED11B711C26F3A549AB6799CB97960C62", "B5E27AC70CCA14288AD137DBDBF6007C6E8DE43D75A77B63", "29C1AA8F51A985DC47167CDDF3F9E561ED0AE50EEBEB5C85" }, { "25544813FC2E95AFFED883F52BE4A666", "8543EECA1724E179A512C532D6E10353", "19603E824A47708D68D58E34FEEEE64E" }, { "07EEB93F202A21B2AF", "A7F91FE6CB205564F4", "3BDACFAE9643C49039" } } }; char testIV[][33] = { "0000000000000000", "0102030405060708", "4041424344454647", "4693867334098764", "6209876098547207" }; for (int i = 0; i < 5; i++) { #ifndef WITH_FIPS ByteString keyData56(testKeys56[i]); CPPUNIT_ASSERT(keyData56.size() == 8); ByteString keyData112(testKeys112[i]); CPPUNIT_ASSERT(keyData112.size() == 16); #endif ByteString keyData168(testKeys168[i]); CPPUNIT_ASSERT(keyData168.size() == 24); #ifndef WITH_FIPS DESKey desKey56(56); CPPUNIT_ASSERT(desKey56.setKeyBits(keyData56)); DESKey desKey112(112); CPPUNIT_ASSERT(desKey112.setKeyBits(keyData112)); #endif DESKey desKey168(168); CPPUNIT_ASSERT(desKey168.setKeyBits(keyData168)); ByteString IV(testIV[i]); for (int j = 0; j < 4; j++) { ByteString plainText(testData[j]), shsmPlainText; ByteString cipherText; ByteString shsmCipherText, OB; #ifndef WITH_FIPS // Test 56-bit key cipherText = ByteString(testResult[i][j][0]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey56, SymMode::OFB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey56, SymMode::OFB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 112-bit key cipherText = ByteString(testResult[i][j][1]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey112, SymMode::OFB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey112, SymMode::OFB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); #endif // Test 168-bit key cipherText = ByteString(testResult[i][j][2]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey168, SymMode::OFB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey168, SymMode::OFB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); } } } void DESTests::testCFB() { #ifndef WITH_FIPS char testKeys56[][17] = { "0000000000000000", "0102030405060708", "4041424344454647", "4698436794236871", "0940278947239572" }; char testKeys112[][33] = { "00000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F10", "404142434445464748494A4B4C4D4E4F", "64398647034486943598534703463870", "87406984068406984607412103517413" }; #endif char testKeys168[][49] = { "000000000000000000000000000000000000000000000000", "0102030405060708090A0B0C0D0E0F101112131415161718", "404142434445464748494A4B4C4D4E4F5051525354555657", "643906874509874309687459084769847562436043696747", "430135460496813044639085714376487549490586439575" }; char testData[][256] = { "4938673409687134684698438657403986439058740935874395813968496846", "549813644389670948567490687546098245665626527788", "64398769586792586795867965624526", "468376458463264536" }; char testResult[5][4][3][256] = { { { "C59E2ADDC8D95293F8ED346ADAF018111F0B6726349664FF9B02C46C2EC5B96F", "C59E2ADDC8D95293F8ED346ADAF018111F0B6726349664FF9B02C46C2EC5B96F", "C59E2ADDC8D95293F8ED346ADAF018111F0B6726349664FF9B02C46C2EC5B96F" }, { "D83E5E8D823844AE748E369586FA76A2BFD1E668EC78D67B", "D83E5E8D823844AE748E369586FA76A2BFD1E668EC78D67B", "D83E5E8D823844AE748E369586FA76A2BFD1E668EC78D67B" }, { "E89FCA8099D6B1FFB3A24C435B847A73", "E89FCA8099D6B1FFB3A24C435B847A73", "E89FCA8099D6B1FFB3A24C435B847A73" }, { "CA253BAC45D205E270", "CA253BAC45D205E270", "CA253BAC45D205E270" } }, { { "3E9FB188FC11138D49C438ABB98A3846671A4DB257AA62C7929CD55A43E46D88", "3440BEFCF35DC8773DD631A9C8CCF222009D45E301BBF6432A78E99416CE87D8", "DDB35281888DF06446772085E3DE849298B4BE0089979260DDC59FACB17AD0BE" }, { "233FC5D8B6F005B0966FB313EA0DDFBECF19CBC937445A56", "29E0CAACB9BCDE4AB219A19AA77E2C9A407C98A18BD56FDF", "C01326D1C26CE6592FA4E9909D93A85BE005431046661C73" }, { "139E51D5AD1EF0E1E74DD9919AE65DB6", "19415EA1A2522B1B5972F5DCBEEF4E01", "F0B2B2DCD9821308815ADB01F0A16B76" }, { "3124A0F9711A44FC92", "3BFBAF8D7E569F06CF", "D20843F00586A715DB" } }, { { "E376288A10BD52CB06B42B4582A425907D2DF490EC14B478507BCDE58CE95B02", "FD82CFAE85B8581F1409EB62D06A98E05C401607619DE1235822E2DEB74737E1", "24D9411BA4565719BE9FF1A4D91F23B3BF8980A706747077583C8EB84AF63745" }, { "FED65CDA5A5C44F619325429C78F464D271807342B10F899", "E022BBFECF594E22ABC22FA25024B6FD8F61337CBD1F023D", "3979354BEEB741241F0D219B5521A488F870C849275FF8B9" }, { "CE77C8D741B2B1A7E488B94EB32C96FD", "D0832FF3D4B7BB73AEC7646A3686ABCF", "09D8A146F559B475A6258D03BC6F8BD3" }, { "ECCD39FB9DB605BAB2", "F239DEDF08B30F6EE4", "2B62506A295D00687E" } }, { { "740A4786C73A7C6B435071A654DA8FCC75BA3299969E327A2ABC7024378CF3AA", "581B63C58404AEBE49FA5FA4032918813075279E836DFE9BAEDF37D9B21ABEE1", "D5FCB196868673D1FA9C8A67E6A2449354B292E1A76BA11C416A394116857B29" }, { "69AA33D68DDB6A561FB6D6218FAC0E812514782FC6059E46", "45BB1795CEE5B883232EBCCB672FC9C4803C6B827825FE94", "C85CC5C6CC6765EC466B8F8AC8DFC91CB916F617873AF187" }, { "590BA7DB96359F07DB2F2CE68748425C", "751A8398D50B4DD24E4681B6D0E880FC", "F8FD51CBD78990BD5D088ECA798DA0E6" }, { "7BB156F74A312B1A8C", "57A072B4090FF9CF1B", "DA47A0E70B8D24A043" } }, { { "0855A84EAD2176C3D2C3DE4FB868CA2C1B0DF550E187E29808C45594C070FBF4", "A8420E97462B02158D2CABD1574D072F8D83123CED9BA7CEDD7C2799E168F32D", "3461DEDF1B4893E182BE36017DEBC6669B15269DFA4435A31EB1A0CE6A845176" }, { "15F5DC1EE7C060FEDC9B1B43A20588E7A073A300BEFC4CAD", "B5E27AC70CCA142857CB807226DC1EA9B31BE81C0FDCD3FB", "29C1AA8F51A985DC7E530E6EB7AEAC246F2ED097D09851CC" }, { "25544813FC2E95AF817E0897D4E22ECD", "8543EECA1724E179543979F02103C150", "19603E824A47708D80E29D3A61BAE5EA" }, { "07EEB93F202A21B250", "A7F91FE6CB205564F2", "3BDACFAE9643C49027" } } }; char testIV[][33] = { "0000000000000000", "0102030405060708", "4041424344454647", "4693867334098764", "6209876098547207" }; for (int i = 0; i < 5; i++) { #ifndef WITH_FIPS ByteString keyData56(testKeys56[i]); CPPUNIT_ASSERT(keyData56.size() == 8); ByteString keyData112(testKeys112[i]); CPPUNIT_ASSERT(keyData112.size() == 16); #endif ByteString keyData168(testKeys168[i]); CPPUNIT_ASSERT(keyData168.size() == 24); #ifndef WITH_FIPS DESKey desKey56(56); CPPUNIT_ASSERT(desKey56.setKeyBits(keyData56)); DESKey desKey112(112); CPPUNIT_ASSERT(desKey112.setKeyBits(keyData112)); #endif DESKey desKey168(168); CPPUNIT_ASSERT(desKey168.setKeyBits(keyData168)); ByteString IV(testIV[i]); for (int j = 0; j < 4; j++) { ByteString plainText(testData[j]), shsmPlainText; ByteString cipherText; ByteString shsmCipherText, OB; #ifndef WITH_FIPS // Test 56-bit key cipherText = ByteString(testResult[i][j][0]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey56, SymMode::CFB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey56, SymMode::CFB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); // Test 112-bit key cipherText = ByteString(testResult[i][j][1]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey112, SymMode::CFB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey112, SymMode::CFB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); #endif // Test 168-bit key cipherText = ByteString(testResult[i][j][2]); // Now, do the same thing using our DES implementation shsmCipherText.wipe(); CPPUNIT_ASSERT(des->encryptInit(&desKey168, SymMode::CFB, IV)); CPPUNIT_ASSERT(des->encryptUpdate(plainText, OB)); shsmCipherText += OB; CPPUNIT_ASSERT(des->encryptFinal(OB)); shsmCipherText += OB; CPPUNIT_ASSERT(shsmCipherText == cipherText); // Check that we can get the plain text shsmPlainText.wipe(); CPPUNIT_ASSERT(des->decryptInit(&desKey168, SymMode::CFB, IV)); CPPUNIT_ASSERT(des->decryptUpdate(shsmCipherText, OB)); shsmPlainText += OB; CPPUNIT_ASSERT(des->decryptFinal(OB)); shsmPlainText += OB; CPPUNIT_ASSERT(shsmPlainText == plainText); } } } softhsm-2.0.0/src/lib/crypto/test/HashTests.h0000664000175000017500000000432112533040716016033 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HashTests.h Contains test cases to test the hash implementations *****************************************************************************/ #ifndef _SOFTHSM_V2_HASHTESTS_H #define _SOFTHSM_V2_HASHTESTS_H #include #include "HashAlgorithm.h" #include "RNG.h" class HashTests : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(HashTests); #ifndef WITH_FIPS CPPUNIT_TEST(testMD5); #endif CPPUNIT_TEST(testSHA1); CPPUNIT_TEST(testSHA224); CPPUNIT_TEST(testSHA256); CPPUNIT_TEST(testSHA384); CPPUNIT_TEST(testSHA512); CPPUNIT_TEST_SUITE_END(); public: #ifndef WITH_FIPS void testMD5(); #endif void testSHA1(); void testSHA224(); void testSHA256(); void testSHA384(); void testSHA512(); void setUp(); void tearDown(); private: HashAlgorithm* hash; RNG* rng; }; #endif // !_SOFTHSM_V2_HASHTESTS_H softhsm-2.0.0/src/lib/crypto/test/GOSTTests.cpp0000664000175000017500000003054612533040716016267 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** GOSTTests.cpp Contains test cases to test the GOST implementations *****************************************************************************/ #include #include #include "GOSTTests.h" #include "CryptoFactory.h" #include #include "AsymmetricAlgorithm.h" #include "AsymmetricKeyPair.h" #include "HashAlgorithm.h" #include "MacAlgorithm.h" #include "RNG.h" #ifdef WITH_GOST #include "ECParameters.h" #include "GOSTPublicKey.h" #include "GOSTPrivateKey.h" CPPUNIT_TEST_SUITE_REGISTRATION(GOSTTests); void GOSTTests::setUp() { hash = NULL; mac = NULL; gost = NULL; rng = NULL; gost = CryptoFactory::i()->getAsymmetricAlgorithm(AsymAlgo::GOST); // Check the GOST object CPPUNIT_ASSERT(gost != NULL); } void GOSTTests::tearDown() { if (hash != NULL) { CryptoFactory::i()->recycleHashAlgorithm(hash); } if (mac != NULL) { CryptoFactory::i()->recycleMacAlgorithm(mac); } if (gost != NULL) { CryptoFactory::i()->recycleAsymmetricAlgorithm(gost); } fflush(stdout); } void GOSTTests::testHash() { char testData[4096] = "FE5A773751EAB2F18921C04806D6907444557B4469CDA7C822288E5065DA58F448A27FA0B4C8786853F246B093E3DBFDC332759D7764B6D057895184D9B82E626DF70AEB99B969EA35E5BE4D50C7406EA4A7450AC063933F96F77960EE711A445593119CF69061702CB4797F214FA440C94127E3DCD92F2C71B39D354C6F4284E030DCBFCB91EA5E543E0E3560ECD355091850BA080287BD87B74BB84A8892E0F2172F136D187305179F23EB8296BF1798405BAB52E201F22BCA5B793C5BA6F2CA15F154598EEC73E7E61B405262F6FE5FDC0F9AE0528801C3F965956C79A6C6805EDD0C6515AEA27D1DB9D70A56B0F13A544429C448FB6DB390C0E367EDF997E0B681ADE3846D77D1898F06FB60CB2384015F3749BD1E8163E532529E4D3BB8B200BBE79DA76D4865621FF2E583A1A1F8EBFB7A51B65DC9152B173A7DF91C6943F2FE497CDBC306827146199ADA925DD42B8A48429F5B6E3670AA85A44BDFAB3D273EA6711B996B5C27E04949BE61ED9ECB932F429ADCF31A2E0E9F83FCB1CE6BC0EE81627D1F9D08ECD599F16A1D68B256B002E90A8B4E5830A049ECE9ADF1D50C027EC537DD5412AA1509E91CEF358B2D495D3B37651987F51D9643A5AF2E0EF3D8C02E6023BB76FF8F1EB5CD018FA32BD7886A1A46A7D5CA15E4E0CDB793F0C1986EF4480305801A518B1D4596AAA741C093FC7AD075B637B1B2CC4DA33B6EB6D549001B33E1753C9C4358FB541FDE6541238BD011CD8ACAFB4CFF15B289872956DFBCC732593E838B6300E48ED3455CD101920114640A5B7C1250E419B7D771EC65934F53176BBD7A61A36D6D3D64A1F29C3D41745993636F812930E2936E9ED34E92A3C31239176ED3F78461EE80C54D92CBD9EF9F5746F8069809A38549FC7A8FD99FB350C27230966D6001D3136114A7BDCDEE495B72E4A633845BC88400DEDADC2FA2CD8640049CDB4F8F695C45EACF24FD573E1FB1670F688C9D7706A9AE9EB30E0DFDD54C7F3F3EE6F9BBFBBED6DB6E7C7B979E677DCD8457949DC271BD6ACB445B16247D8DAC1B59D45B8FFBBFDAEA20A5C450E0F93B399AE69887E1C721B0EF86C8CD37FC7514C4F2B70AA1E757DE95DCC3B74C6E18E51D272D433330826435B7CBA6C099558B51E408B1BFE60E876141A74195A00BF914F2536D92170FB43E078D98F784E6F150ED2B16DB5B629EBABF16444639C87A544050E03FB7CCD538DA29C45CE764F68682B48BF8AE5ED43064E833338A88605B1743FEB025D5F5607BB13A2078A99924A2D4818CD582ACDC1556FAEBA70959DE8498F3FCBF85BD269A7DF23A3AD5704908978031667C7BF4A85D1EF42F3ED144670E6EEB5D8213DB43B0B7B43767FD4277EF0EC52B5718A7D187A003DE8E5DFF9C3A3CD520615FB9B52281506E5BB033818E0912980A8BCAA54E21C5630B9E863C83"; char testResult[512] = "3EC65819A084AD30712C4B3EB69CE130A8C7221EA3D8A9996D4BA6F298BC39F9"; // Get a GOST R 34.11-94 hash instance CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::GOST)) != NULL); ByteString b(testData); ByteString osslHash(testResult), gostHash; // Now recreate the hash using our implementation in a single operation CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b)); CPPUNIT_ASSERT(hash->hashFinal(gostHash)); CPPUNIT_ASSERT(osslHash == gostHash); // Now recreate the hash in a single part operation gostHash.wipe(); CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(hash->hashUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(hash->hashFinal(gostHash)); CPPUNIT_ASSERT(osslHash == gostHash); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; rng = NULL; } void GOSTTests::testHmac() { char testData[4096] = "1450414E94B2CEA9E202B8ACC9C358EBA5334C20CF1B7D13E8B79BE63A0A938A340CF710D539262F406787AF7188990C7D75780C265E37750510FA6AAA742D01C753548219C20B1283CCA9D30AA5A8650D0C5EE63FE10268F9CD5996F8DB0158C6FAD147AE41C0E565F6FBC85115E17BB0B448208075D1CF79CF70574098E7116A5C5EFFDB05DCD83E71DB4860B3AEC2612FB9DE1B010229A413055724AB07F4131B04800286D3C4895A158E7B1301F8010E718C76CC69B34C643D2B1EACC00F9CD0DEBC83425256B2524B34D61EBA32FE5F79FE0A1F9360E3CFB4C88CE7CC3C36E969A37827AD5FD79BFAC08CCA1786F30F34ADC605545F04BA96CA4A4E3DF7FEC36E43406E9CD68D708CBAC4C54B2E18E38535BD1A8029FD7393B5462AB688F8146445295E5473B15B26EC129A24C78B7198D558209E827C38426D747FB0D2B04F1EE7B142B7B736EFF4B819B5420F4642E77181617BEC8074109B463F4C53A6F3507A0B4419B2D7CC0B6CF89FAA2CAEAC17BF19E6A94E0BF346D0F77C47EDB29CBD204483E53853401779AEA0998B993E39EA4C5003326C017A5A3BD0C5591D4F822641FAE9DBDF78B15DC5BA326150F89C864774A8DBF6464B259A29C00D9BCC63F61B3B45FF19E6FD0CDA2BE17608488B0E5C6CC5C596F035C8E580C30FC7C6FE2428F3509511B9D7FE77CF53C5B0E8E66BB573B3D467B74B5493A4E8EA49A79B7E2D36A6C0A600C6B13DC617C3FAF927B2CB251279CFF4228254CB6022AE9D97A36894EBCB305B179284E5D2F330266B2B600E248D3C4B8121A8D698183A38BFB5A40C5E85CB08EF0BFB0242E418D11DD648B9B84E072A70D3FBA8A9B0CEE05BFD71AC945543E306824F9A4DCBA05BBE0027B475A020BD764B53AA5A187C089A2DEF8F3A96D38491A61CE5F3DA625F7F4EF38130B0F5DAA14E2236F4CD95FF0C31E7D6C1CC15CDE7D9D4F95326AE721812458D413CD6C758671C9A85D10F7692CE31A600483F6444F45E74C45B7CF886E63D0158E19C0B87BE6CD9FC4B74D72CB004D3BD7ADF60E162F4967E5EF3BCA0AF2DD7ED1DDE4097B5BA250281DB7E46C22A25A49ABDB1B2D148710128DC1F1A18CD0D762A1D2EB5D5D602336EE3F0A0095592E938A79BDEE72CF801015AD5871A8D907298E13F960A1417FDFA87C3FE3DA9490B73B45326C3161D9DE6460E37208665FDC90CF894A0301198F5FAA5A315FC562B2837194662A58DA13065760571172D42306BB57ECCFA578E9C927C211A1F7C1983DE1AE1EAB0A264AFDC18CD56F14E0429E80B0DDE9A5AF527952A7B6ABECFCB64CBDA3C3E7A024FC5CA3B655FAF5A2787FDB22C1DD3160827C886A119FD2833DA87E60F18B6A969916D35F559BCEA40D6E5E53F84FA5C46DD5DD09D0802A21F64F00EA755F95234AF913DBFB380CC370754448E46EDFC7CCC"; char testResult[512] = "8D9D660D7BCAB705F14A90CB9A31F7B5206F9936E1B56F2489DA188A90C49CA3"; // Get an HMAC GOST R34.11-94 instance CPPUNIT_ASSERT((mac = CryptoFactory::i()->getMacAlgorithm(MacAlgo::HMAC_GOST)) != NULL); // Key char pk[] = "a_key_for_HMAC-GOST_R-34.11-94_test"; ByteString k((unsigned char *)pk, sizeof(pk)); SymmetricKey key; CPPUNIT_ASSERT(key.setKeyBits(k)); ByteString b(testData); ByteString osslMac(testResult), shsmMac; // Now verify the MAC using our implementation in a single operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b)); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Now verify the MAC in a multiple part operation CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->verifyUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->verifyFinal(osslMac)); // Now recreate the MAC in a single part operation CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b)); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Now recreate the MAC in a multiple part operation shsmMac.wipe(); CPPUNIT_ASSERT(mac->signInit(&key)); CPPUNIT_ASSERT(mac->signUpdate(b.substr(0, 567))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567, 989))); CPPUNIT_ASSERT(mac->signUpdate(b.substr(567 + 989))); CPPUNIT_ASSERT(mac->signFinal(shsmMac)); CPPUNIT_ASSERT(osslMac == shsmMac); // Check if bad key is refused osslMac[10] ^= 0x11; CPPUNIT_ASSERT(mac->verifyInit(&key)); CPPUNIT_ASSERT(mac->verifyUpdate(b)); CPPUNIT_ASSERT(!mac->verifyFinal(osslMac)); CryptoFactory::i()->recycleMacAlgorithm(mac); mac = NULL; } void GOSTTests::testHashKnownVector() { CPPUNIT_ASSERT((hash = CryptoFactory::i()->getHashAlgorithm(HashAlgo::GOST)) != NULL); // Message to hash for test #1 ByteString msg = "6d65737361676520646967657374"; // "message digest" ByteString expected = "bc6041dd2aa401ebfa6e9886734174febdb4729aa972d60f549ac39b29721ba0"; ByteString result; // Test #1 CPPUNIT_ASSERT(hash->hashInit()); CPPUNIT_ASSERT(hash->hashUpdate(msg)); CPPUNIT_ASSERT(hash->hashFinal(result)); CPPUNIT_ASSERT(result == expected); CryptoFactory::i()->recycleHashAlgorithm(hash); hash = NULL; } void GOSTTests::testKeyGeneration() { AsymmetricKeyPair* kp; // Set domain parameters ByteString curve = "06072a850302022301"; ECParameters* p = new ECParameters; p->setEC(curve); // Generate key-pair CPPUNIT_ASSERT(gost->generateKeyPair(&kp, p)); GOSTPublicKey* pub = (GOSTPublicKey*) kp->getPublicKey(); GOSTPrivateKey* priv = (GOSTPrivateKey*) kp->getPrivateKey(); CPPUNIT_ASSERT(pub->getQ().size() == 64); CPPUNIT_ASSERT(priv->getD().size() == 32); gost->recycleParameters(p); gost->recycleKeyPair(kp); } void GOSTTests::testSerialisation() { // Get GOST R 34.10-2001 params-A domain parameters ECParameters* p = new ECParameters; p->setEC(ByteString("06072a850302022301")); // Serialise the parameters ByteString serialisedParams = p->serialise(); // Deserialise the parameters AsymmetricParameters* dEC; CPPUNIT_ASSERT(gost->reconstructParameters(&dEC, serialisedParams)); CPPUNIT_ASSERT(dEC->areOfType(ECParameters::type)); ECParameters* ddEC = (ECParameters*) dEC; CPPUNIT_ASSERT(p->getEC() == ddEC->getEC()); // Generate a key-pair AsymmetricKeyPair* kp; CPPUNIT_ASSERT(gost->generateKeyPair(&kp, dEC)); // Serialise the key-pair ByteString serialisedKP = kp->serialise(); // Deserialise the key-pair AsymmetricKeyPair* dKP; CPPUNIT_ASSERT(gost->reconstructKeyPair(&dKP, serialisedKP)); // Check the deserialised key-pair GOSTPrivateKey* privKey = (GOSTPrivateKey*) kp->getPrivateKey(); GOSTPublicKey* pubKey = (GOSTPublicKey*) kp->getPublicKey(); GOSTPrivateKey* dPrivKey = (GOSTPrivateKey*) dKP->getPrivateKey(); GOSTPublicKey* dPubKey = (GOSTPublicKey*) dKP->getPublicKey(); CPPUNIT_ASSERT(privKey->getD() == dPrivKey->getD()); CPPUNIT_ASSERT(pubKey->getQ() == dPubKey->getQ()); gost->recycleParameters(p); gost->recycleParameters(dEC); gost->recycleKeyPair(kp); gost->recycleKeyPair(dKP); } void GOSTTests::testSigningVerifying() { AsymmetricKeyPair* kp; ECParameters *p; ByteString curve = "06072a850302022301"; // Get parameters p = new ECParameters; CPPUNIT_ASSERT(p != NULL); p->setEC(curve); // Generate key-pair CPPUNIT_ASSERT(gost->generateKeyPair(&kp, p)); // Generate some data to sign ByteString dataToSign; RNG* rng = CryptoFactory::i()->getRNG(); CPPUNIT_ASSERT(rng != NULL); CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567)); // Sign the data ByteString sig; CPPUNIT_ASSERT(gost->sign(kp->getPrivateKey(), dataToSign, sig, AsymMech::GOST_GOST)); // And verify it CPPUNIT_ASSERT(gost->verify(kp->getPublicKey(), dataToSign, sig, AsymMech::GOST_GOST)); gost->recycleKeyPair(kp); gost->recycleParameters(p); } void GOSTTests::testSignVerifyKnownVector() { // TODO } #endif softhsm-2.0.0/src/lib/crypto/OSSLDH.cpp0000664000175000017500000002077212533040716014505 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDH.cpp OpenSSL Diffie-Hellman asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDH.h" #include "CryptoFactory.h" #include "DHParameters.h" #include "OSSLDHKeyPair.h" #include "OSSLUtil.h" #include #include #include #include // Signing functions bool OSSLDH::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("DH does not support signing"); return false; } bool OSSLDH::signUpdate(const ByteString& /*dataToSign*/) { ERROR_MSG("DH does not support signing"); return false; } bool OSSLDH::signFinal(ByteString& /*signature*/) { ERROR_MSG("DH does not support signing"); return false; } // Verification functions bool OSSLDH::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("DH does not support verifying"); return false; } bool OSSLDH::verifyUpdate(const ByteString& /*originalData*/) { ERROR_MSG("DH does not support verifying"); return false; } bool OSSLDH::verifyFinal(const ByteString& /*signature*/) { ERROR_MSG("DH does not support verifying"); return false; } // Encryption functions bool OSSLDH::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DH does not support encryption"); return false; } // Decryption functions bool OSSLDH::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DH does not support decryption"); return false; } // Key factory bool OSSLDH::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(DHParameters::type)) { ERROR_MSG("Invalid parameters supplied for DH key generation"); return false; } DHParameters* params = (DHParameters*) parameters; // Generate the key-pair DH* dh = DH_new(); if (dh == NULL) { ERROR_MSG("Failed to instantiate OpenSSL DH object"); return false; } if (dh->p != NULL) BN_clear_free(dh->p); dh->p = OSSL::byteString2bn(params->getP()); if (dh->g != NULL) BN_clear_free(dh->g); dh->g = OSSL::byteString2bn(params->getG()); // PKCS#3: 2^(l-1) <= x < 2^l if (params->getXBitLength() > 0) { if (dh->priv_key == NULL) dh->priv_key = BN_new(); if (BN_rand(dh->priv_key, params->getXBitLength(), 0, 0) != 1) { ERROR_MSG("DH private key generation failed (0x%08X)", ERR_get_error()); DH_free(dh); return false; } } if (DH_generate_key(dh) != 1) { ERROR_MSG("DH key generation failed (0x%08X)", ERR_get_error()); DH_free(dh); return false; } // Create an asymmetric key-pair object to return OSSLDHKeyPair* kp = new OSSLDHKeyPair(); ((OSSLDHPublicKey*) kp->getPublicKey())->setFromOSSL(dh); ((OSSLDHPrivateKey*) kp->getPrivateKey())->setFromOSSL(dh); *ppKeyPair = kp; // Release the key DH_free(dh); return true; } bool OSSLDH::deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey) { // Check parameters if ((ppSymmetricKey == NULL) || (publicKey == NULL) || (privateKey == NULL)) { return false; } // Get keys DH *pub = ((OSSLDHPublicKey *)publicKey)->getOSSLKey(); DH *priv = ((OSSLDHPrivateKey *)privateKey)->getOSSLKey(); if (pub == NULL || pub->pub_key == NULL || priv == NULL) { ERROR_MSG("Failed to get OpenSSL DH keys"); return false; } // Derive the secret ByteString secret; secret.resize(DH_size(priv));; if (DH_compute_key(&secret[0], pub->pub_key, priv) <= 0) { ERROR_MSG("DH key derivation failed (0x%08X)", ERR_get_error()); return false; } *ppSymmetricKey = new SymmetricKey; if (*ppSymmetricKey == NULL) return false; if (!(*ppSymmetricKey)->setKeyBits(secret)) { delete *ppSymmetricKey; *ppSymmetricKey = NULL; return false; } return true; } unsigned long OSSLDH::getMinKeySize() { #ifdef WITH_FIPS // OPENSSL_DH_FIPS_MIN_MODULUS_BITS is 1024 return 1024; #else return 512; #endif } unsigned long OSSLDH::getMaxKeySize() { return OPENSSL_DH_MAX_MODULUS_BITS; } bool OSSLDH::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/) { if ((ppParams == NULL) || (parameters == NULL)) { return false; } size_t bitLen = (size_t) parameters; if (bitLen < getMinKeySize() || bitLen > getMaxKeySize()) { ERROR_MSG("This DH key size is not supported"); return false; } DH* dh = DH_generate_parameters(bitLen, 2, NULL, NULL); if (dh == NULL) { ERROR_MSG("Failed to generate %d bit DH parameters", bitLen); return false; } // Store the DH parameters DHParameters* params = new DHParameters(); ByteString p = OSSL::bn2ByteString(dh->p); params->setP(p); ByteString g = OSSL::bn2ByteString(dh->g); params->setG(g); *ppParams = params; DH_free(dh); return true; } bool OSSLDH::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); OSSLDHKeyPair* kp = new OSSLDHKeyPair(); bool rv = true; if (!((DHPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((DHPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool OSSLDH::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLDHPublicKey* pub = new OSSLDHPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool OSSLDH::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLDHPrivateKey* priv = new OSSLDHPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* OSSLDH::newPublicKey() { return (PublicKey*) new OSSLDHPublicKey(); } PrivateKey* OSSLDH::newPrivateKey() { return (PrivateKey*) new OSSLDHPrivateKey(); } AsymmetricParameters* OSSLDH::newParameters() { return (AsymmetricParameters*) new DHParameters(); } bool OSSLDH::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } DHParameters* params = new DHParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } softhsm-2.0.0/src/lib/crypto/OSSLECDSA.h0000664000175000017500000000725212533040716014474 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECDSA.h OpenSSL ECDSA asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLECDSA_H #define _SOFTHSM_V2_OSSLECDSA_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class OSSLECDSA : public AsymmetricAlgorithm { public: // Destructor virtual ~OSSLECDSA() { } // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: }; #endif // !_SOFTHSM_V2_OSSLECDSA_H softhsm-2.0.0/src/lib/crypto/DESKey.h0000664000175000017500000000357212533040716014241 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DESKey.h Base class for symmetric key classes *****************************************************************************/ #ifndef _SOFTHSM_V2_DESKEY_H #define _SOFTHSM_V2_DESKEY_H #include "config.h" #include "ByteString.h" #include "Serialisable.h" #include "SymmetricKey.h" class DESKey : public SymmetricKey { public: // Base constructor DESKey(size_t inBitLen = 0) : SymmetricKey(inBitLen) { } // Set the key virtual bool setKeyBits(const ByteString& keybits); }; #endif // !_SOFTHSM_V2_DESKEY_H softhsm-2.0.0/src/lib/crypto/BotanMD5.cpp0000664000175000017500000000331512533040716015054 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanMD5.cpp Botan MD5 implementation *****************************************************************************/ #include "config.h" #include "BotanMD5.h" #include int BotanMD5::getHashSize() { return 16; } Botan::HashFunction* BotanMD5::getHash() const { return new Botan::MD5(); } softhsm-2.0.0/src/lib/crypto/BotanSHA224.cpp0000664000175000017500000000334412533040716015334 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA224.cpp Botan SHA224 implementation *****************************************************************************/ #include "config.h" #include "BotanSHA224.h" #include int BotanSHA224::getHashSize() { return 28; } Botan::HashFunction* BotanSHA224::getHash() const { return new Botan::SHA_224(); } softhsm-2.0.0/src/lib/crypto/OSSLEVPHashAlgorithm.cpp0000664000175000017500000000572112533040716017314 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLEVPHashAlgorithm.cpp Base class for OpenSSL hash algorithm classes *****************************************************************************/ #include "config.h" #include "OSSLEVPHashAlgorithm.h" // Destructor OSSLEVPHashAlgorithm::~OSSLEVPHashAlgorithm() { EVP_MD_CTX_cleanup(&curCTX); } // Hashing functions bool OSSLEVPHashAlgorithm::hashInit() { if (!HashAlgorithm::hashInit()) { return false; } // Initialize the context EVP_MD_CTX_init(&curCTX); // Initialize EVP digesting if (!EVP_DigestInit_ex(&curCTX, getEVPHash(), NULL)) { ERROR_MSG("EVP_DigestInit failed"); EVP_MD_CTX_cleanup(&curCTX); ByteString dummy; HashAlgorithm::hashFinal(dummy); return false; } return true; } bool OSSLEVPHashAlgorithm::hashUpdate(const ByteString& data) { if (!HashAlgorithm::hashUpdate(data)) { return false; } // Continue digesting if (data.size() == 0) { return true; } if (!EVP_DigestUpdate(&curCTX, (unsigned char*) data.const_byte_str(), data.size())) { ERROR_MSG("EVP_DigestUpdate failed"); EVP_MD_CTX_cleanup(&curCTX); ByteString dummy; HashAlgorithm::hashFinal(dummy); return false; } return true; } bool OSSLEVPHashAlgorithm::hashFinal(ByteString& hashedData) { if (!HashAlgorithm::hashFinal(hashedData)) { return false; } hashedData.resize(EVP_MD_size(getEVPHash())); unsigned int outLen = hashedData.size(); if (!EVP_DigestFinal_ex(&curCTX, &hashedData[0], &outLen)) { ERROR_MSG("EVP_DigestFinal failed"); EVP_MD_CTX_cleanup(&curCTX); return false; } hashedData.resize(outLen); EVP_MD_CTX_cleanup(&curCTX); return true; } softhsm-2.0.0/src/lib/crypto/GOSTPrivateKey.h0000664000175000017500000000504312533040716015730 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** GOSTPrivateKey.h GOST R 34.10-2001 private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_GOSTPRIVATEKEY_H #define _SOFTHSM_V2_GOSTPRIVATEKEY_H #include "config.h" #include "PrivateKey.h" class GOSTPrivateKey : public PrivateKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const = 0; // Setters for the GOST private key components virtual void setD(const ByteString& inD); // Setters for the GOST public key components virtual void setEC(const ByteString& inEC); // Getters for the GOST private key components virtual const ByteString& getD() const; // Getters for the GOST public key components virtual const ByteString& getEC() const; // Serialisation virtual ByteString serialise() const = 0; virtual bool deserialise(ByteString& serialised) = 0; protected: // Private components ByteString d; // Public components ByteString ec; }; #endif // !_SOFTHSM_V2_GOSTPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/BotanRSAPublicKey.cpp0000664000175000017500000000627112533040716016730 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSAPublicKey.cpp Botan RSA public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanRSAPublicKey.h" #include "BotanUtil.h" #include // Constructors BotanRSAPublicKey::BotanRSAPublicKey() { rsa = NULL; } BotanRSAPublicKey::BotanRSAPublicKey(const Botan::RSA_PublicKey* inRSA) { rsa = NULL; setFromBotan(inRSA); } // Destructor BotanRSAPublicKey::~BotanRSAPublicKey() { delete rsa; } // The type /*static*/ const char* BotanRSAPublicKey::type = "Botan RSA Public Key"; // Check if the key is of the given type bool BotanRSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Set from OpenSSL representation void BotanRSAPublicKey::setFromBotan(const Botan::RSA_PublicKey* inRSA) { ByteString inN = BotanUtil::bigInt2ByteString(inRSA->get_n()); setN(inN); ByteString inE = BotanUtil::bigInt2ByteString(inRSA->get_e()); setE(inE); } // Setters for the RSA public key components void BotanRSAPublicKey::setN(const ByteString& inN) { RSAPublicKey::setN(inN); if (rsa) { delete rsa; rsa = NULL; } } void BotanRSAPublicKey::setE(const ByteString& inE) { RSAPublicKey::setE(inE); if (rsa) { delete rsa; rsa = NULL; } } // Retrieve the Botan representation of the key Botan::RSA_PublicKey* BotanRSAPublicKey::getBotanKey() { if (!rsa) { createBotanKey(); } return rsa; } // Create the Botan representation of the key void BotanRSAPublicKey::createBotanKey() { if (n.size() != 0 && e.size() != 0) { if (rsa) { delete rsa; rsa = NULL; } try { rsa = new Botan::RSA_PublicKey(BotanUtil::byteString2bigInt(n), BotanUtil::byteString2bigInt(e)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } softhsm-2.0.0/src/lib/crypto/BotanAES.h0000664000175000017500000000430712533040716014546 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanAES.h Botan AES implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANAES_H #define _SOFTHSM_V2_BOTANAES_H #include #include "config.h" #include "BotanSymmetricAlgorithm.h" class BotanAES : public BotanSymmetricAlgorithm { public: // Destructor virtual ~BotanAES() { } // Wrap/Unwrap keys virtual bool wrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); virtual bool unwrapKey(const SymmetricKey* key, const SymWrap::Type mode, const ByteString& in, ByteString& out); // Return the block size virtual size_t getBlockSize() const; protected: // Return the right Botan cipher for the operation virtual std::string getCipher() const; }; #endif // !_SOFTHSM_V2_BOTANAES_H softhsm-2.0.0/src/lib/crypto/AsymmetricParameters.h0000664000175000017500000000412112533040716017305 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymmetricParameters.h Base class for asymmetric parameter classes *****************************************************************************/ #ifndef _SOFTHSM_V2_ASYMMETRICPARAMETERS_H #define _SOFTHSM_V2_ASYMMETRICPARAMETERS_H #include "config.h" #include "ByteString.h" #include "Serialisable.h" class AsymmetricParameters : public Serialisable { public: // Base constructors AsymmetricParameters() { } AsymmetricParameters(const AsymmetricParameters& /*in*/) { } // Destructor virtual ~AsymmetricParameters() { } // Check if it is of the given type virtual bool areOfType(const char* type) = 0; // Serialisation virtual ByteString serialise() const = 0; }; #endif // !_SOFTHSM_V2_ASYMMETRICPARAMETERS_H softhsm-2.0.0/src/lib/crypto/OSSLECDSA.cpp0000664000175000017500000002340412533040716015024 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECDSA.cpp OpenSSL ECDSA asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "OSSLECDSA.h" #include "CryptoFactory.h" #include "ECParameters.h" #include "OSSLECKeyPair.h" #include "OSSLUtil.h" #include #include #include #include #include // Signing functions bool OSSLECDSA::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { if (mechanism != AsymMech::ECDSA) { ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); return false; } // Check if the private key is the right type if (!privateKey->isOfType(OSSLECPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } OSSLECPrivateKey* pk = (OSSLECPrivateKey*) privateKey; EC_KEY* eckey = pk->getOSSLKey(); if (eckey == NULL) { ERROR_MSG("Could not get the OpenSSL private key"); return false; } // Use the OpenSSL implementation and not any engine ECDSA_set_method(eckey, ECDSA_get_default_method()); // Perform the signature operation size_t len = pk->getOrderLength(); if (len == 0) { ERROR_MSG("Could not get the order length"); return false; } signature.resize(2 * len); memset(&signature[0], 0, 2 * len); ECDSA_SIG *sig = ECDSA_do_sign(dataToSign.const_byte_str(), dataToSign.size(), eckey); if (sig == NULL) { ERROR_MSG("ECDSA sign failed (0x%08X)", ERR_get_error()); return false; } // Store the 2 values with padding BN_bn2bin(sig->r, &signature[len - BN_num_bytes(sig->r)]); BN_bn2bin(sig->s, &signature[2 * len - BN_num_bytes(sig->s)]); ECDSA_SIG_free(sig); return true; } bool OSSLECDSA::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDSA does not support multi part signing"); return false; } bool OSSLECDSA::signUpdate(const ByteString& /*dataToSign*/) { ERROR_MSG("ECDSA does not support multi part signing"); return false; } bool OSSLECDSA::signFinal(ByteString& /*signature*/) { ERROR_MSG("ECDSA does not support multi part signing"); return false; } // Verification functions bool OSSLECDSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { if (mechanism != AsymMech::ECDSA) { ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); return false; } // Check if the private key is the right type if (!publicKey->isOfType(OSSLECPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } OSSLECPublicKey* pk = (OSSLECPublicKey*) publicKey; EC_KEY* eckey = pk->getOSSLKey(); if (eckey == NULL) { ERROR_MSG("Could not get the OpenSSL public key"); return false; } // Use the OpenSSL implementation and not any engine ECDSA_set_method(eckey, ECDSA_get_default_method()); // Perform the verify operation size_t len = pk->getOrderLength(); if (len == 0) { ERROR_MSG("Could not get the order length"); return false; } if (signature.size() != 2 * len) { ERROR_MSG("Invalid buffer length"); return false; } ECDSA_SIG* sig = ECDSA_SIG_new(); if (sig == NULL) { ERROR_MSG("Could not create an ECDSA_SIG object"); return false; } if (sig->r != NULL) BN_clear_free(sig->r); const unsigned char *s = signature.const_byte_str(); sig->r = BN_bin2bn(s, len, NULL); if (sig->s != NULL) BN_clear_free(sig->s); sig->s = BN_bin2bn(s + len, len, NULL); if (sig->r == NULL || sig->s == NULL) { ERROR_MSG("Could not add data to the ECDSA_SIG object"); ECDSA_SIG_free(sig); return false; } int ret = ECDSA_do_verify(originalData.const_byte_str(), originalData.size(), sig, eckey); if (ret != 1) { if (ret < 0) ERROR_MSG("ECDSA verify failed (0x%08X)", ERR_get_error()); ECDSA_SIG_free(sig); return false; } ECDSA_SIG_free(sig); return true; } bool OSSLECDSA::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDSA does not support multi part verifying"); return false; } bool OSSLECDSA::verifyUpdate(const ByteString& /*originalData*/) { ERROR_MSG("ECDSA does not support multi part verifying"); return false; } bool OSSLECDSA::verifyFinal(const ByteString& /*signature*/) { ERROR_MSG("ECDSA does not support multi part verifying"); return false; } // Encryption functions bool OSSLECDSA::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDSA does not support encryption"); return false; } // Decryption functions bool OSSLECDSA::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDSA does not support decryption"); return false; } // Key factory bool OSSLECDSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(ECParameters::type)) { ERROR_MSG("Invalid parameters supplied for ECDSA key generation"); return false; } ECParameters* params = (ECParameters*) parameters; // Generate the key-pair EC_KEY* eckey = EC_KEY_new(); if (eckey == NULL) { ERROR_MSG("Failed to instantiate OpenSSL ECDSA object"); return false; } EC_GROUP* grp = OSSL::byteString2grp(params->getEC()); EC_KEY_set_group(eckey, grp); EC_GROUP_free(grp); if (!EC_KEY_generate_key(eckey)) { ERROR_MSG("ECDSA key generation failed (0x%08X)", ERR_get_error()); EC_KEY_free(eckey); return false; } // Create an asymmetric key-pair object to return OSSLECKeyPair* kp = new OSSLECKeyPair(); ((OSSLECPublicKey*) kp->getPublicKey())->setFromOSSL(eckey); ((OSSLECPrivateKey*) kp->getPrivateKey())->setFromOSSL(eckey); *ppKeyPair = kp; // Release the key EC_KEY_free(eckey); return true; } unsigned long OSSLECDSA::getMinKeySize() { // Smallest EC group is secp112r1 return 112; } unsigned long OSSLECDSA::getMaxKeySize() { // Biggest EC group is secp521r1 return 521; } bool OSSLECDSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); OSSLECKeyPair* kp = new OSSLECKeyPair(); bool rv = true; if (!((ECPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((ECPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool OSSLECDSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLECPublicKey* pub = new OSSLECPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool OSSLECDSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLECPrivateKey* priv = new OSSLECPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* OSSLECDSA::newPublicKey() { return (PublicKey*) new OSSLECPublicKey(); } PrivateKey* OSSLECDSA::newPrivateKey() { return (PrivateKey*) new OSSLECPrivateKey(); } AsymmetricParameters* OSSLECDSA::newParameters() { return (AsymmetricParameters*) new ECParameters(); } bool OSSLECDSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } ECParameters* params = new ECParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } #endif softhsm-2.0.0/src/lib/crypto/BotanGOSTKeyPair.cpp0000664000175000017500000000432112533040716016526 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTKeyPair.cpp Botan GOST R 34.10-2001 key-pair class *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "BotanGOSTKeyPair.h" // Set the public key void BotanGOSTKeyPair::setPublicKey(BotanGOSTPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void BotanGOSTKeyPair::setPrivateKey(BotanGOSTPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* BotanGOSTKeyPair::getPublicKey() { return &pubKey; } const PublicKey* BotanGOSTKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* BotanGOSTKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* BotanGOSTKeyPair::getConstPrivateKey() const { return &privKey; } #endif softhsm-2.0.0/src/lib/crypto/DSAParameters.cpp0000664000175000017500000000550212533040716016136 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSAParameters.cpp DSA parameters (only used for key generation) *****************************************************************************/ #include "config.h" #include "log.h" #include "DSAParameters.h" #include // The type /*static*/ const char* DSAParameters::type = "Generic DSA parameters"; // Set the public prime p void DSAParameters::setP(const ByteString& inP) { p = inP; } // Set the public subprime q void DSAParameters::setQ(const ByteString& inQ) { q = inQ; } // Set the generator g void DSAParameters::setG(const ByteString& inG) { g = inG; } // Get the public prime p const ByteString& DSAParameters::getP() const { return p; } // Get the public subprime q const ByteString& DSAParameters::getQ() const { return q; } // Get the generator g const ByteString& DSAParameters::getG() const { return g; } // Are the parameters of the given type? bool DSAParameters::areOfType(const char* inType) { return (strcmp(type, inType) == 0); } // Serialisation ByteString DSAParameters::serialise() const { return p.serialise() + q.serialise() + g.serialise(); } bool DSAParameters::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); ByteString dG = ByteString::chainDeserialise(serialised); if ((dP.size() == 0) || (dQ.size() == 0) || (dG.size() == 0)) { return false; } setP(dP); setQ(dQ); setG(dG); return true; } softhsm-2.0.0/src/lib/crypto/RSAParameters.cpp0000664000175000017500000000516012533040716016154 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSAParameters.h RSA parameters (only used for key generation) *****************************************************************************/ #include "config.h" #include "log.h" #include "RSAParameters.h" #include // The type /*static*/ const char* RSAParameters::type = "Generic RSA parameters"; // Set the public exponent void RSAParameters::setE(const ByteString& inE) { e = inE; } // Set the bit length void RSAParameters::setBitLength(const size_t inBitLen) { bitLen = inBitLen; } // Get the public exponent const ByteString& RSAParameters::getE() const { return e; } // Get the bit length size_t RSAParameters::getBitLength() const { return bitLen; } // Are the parameters of the given type? bool RSAParameters::areOfType(const char* inType) { return (strcmp(type, inType) == 0); } // Serialisation ByteString RSAParameters::serialise() const { ByteString len(bitLen); return e.serialise() + len.serialise(); } bool RSAParameters::deserialise(ByteString& serialised) { ByteString dE = ByteString::chainDeserialise(serialised); ByteString dLen = ByteString::chainDeserialise(serialised); if ((dE.size() == 0) || (dLen.size() == 0)) { return false; } setE(dE); setBitLength(dLen.long_val()); return true; } softhsm-2.0.0/src/lib/crypto/BotanDSAKeyPair.cpp0000664000175000017500000000424212533040716016363 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSAKeyPair.cpp Botan DSA key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDSAKeyPair.h" // Set the public key void BotanDSAKeyPair::setPublicKey(BotanDSAPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void BotanDSAKeyPair::setPrivateKey(BotanDSAPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* BotanDSAKeyPair::getPublicKey() { return &pubKey; } const PublicKey* BotanDSAKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* BotanDSAKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* BotanDSAKeyPair::getConstPrivateKey() const { return &privKey; } softhsm-2.0.0/src/lib/crypto/AsymmetricKeyPair.cpp0000664000175000017500000000333112533040716017103 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymmetricKeyPair.cpp Asymmetric key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "AsymmetricKeyPair.h" ByteString AsymmetricKeyPair::serialise() const { return getConstPublicKey()->serialise().serialise() + getConstPrivateKey()->serialise().serialise(); } softhsm-2.0.0/src/lib/crypto/AsymmetricAlgorithm.cpp0000664000175000017500000001364712533040716017500 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymmetricAlgorithm.cpp Base class for asymmetric algorithm classes *****************************************************************************/ #include "config.h" #include "log.h" #include "AsymmetricAlgorithm.h" // Base constructor AsymmetricAlgorithm::AsymmetricAlgorithm() { currentOperation = NONE; currentMechanism = AsymMech::Unknown; currentPadding = AsymMech::Unknown; currentPublicKey = NULL; currentPrivateKey = NULL; } // Signing functions bool AsymmetricAlgorithm::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { // Compose from multi-part operations return (signInit(privateKey, mechanism, param, paramLen) && signUpdate(dataToSign) && signFinal(signature)); } bool AsymmetricAlgorithm::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { if ((currentOperation != NONE) || (privateKey == NULL)) { return false; } currentPrivateKey = privateKey; currentMechanism = mechanism; currentOperation = SIGN; return true; } bool AsymmetricAlgorithm::signUpdate(const ByteString& /*dataToSign*/) { if (currentOperation != SIGN) { return false; } return true; } bool AsymmetricAlgorithm::signFinal(ByteString& /*signature*/) { if (currentOperation != SIGN) { return false; } currentOperation = NONE; currentPrivateKey = NULL; currentMechanism = AsymMech::Unknown; return true; } // Verification functions bool AsymmetricAlgorithm::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { // Compose from multi-part operations return (verifyInit(publicKey, mechanism, param, paramLen) && verifyUpdate(originalData) && verifyFinal(signature)); } bool AsymmetricAlgorithm::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { if ((currentOperation != NONE) || (publicKey == NULL)) { return false; } currentOperation = VERIFY; currentPublicKey = publicKey; currentMechanism = mechanism; return true; } bool AsymmetricAlgorithm::verifyUpdate(const ByteString& /*originalData*/) { if (currentOperation != VERIFY) { return false; } return true; } bool AsymmetricAlgorithm::verifyFinal(const ByteString& /*signature*/) { if (currentOperation != VERIFY) { return false; } currentOperation = NONE; currentPublicKey = NULL; currentMechanism = AsymMech::Unknown; return true; } // Returns true for mechanisms which have 'tick mark' in Wrap&Unwrap column in PKCS #11 Mechanisms v2.30 bool AsymmetricAlgorithm::isWrappingMech(AsymMech::Type padding) { switch (padding) { case AsymMech::RSA: case AsymMech::RSA_PKCS: case AsymMech::RSA_PKCS_OAEP: return true; default: return false; } } // Wrap/Unwrap keys bool AsymmetricAlgorithm::wrapKey(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding) { if (!isWrappingMech(padding)) return false; return encrypt(publicKey, data, encryptedData, padding); } bool AsymmetricAlgorithm::unwrapKey(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding) { if (!isWrappingMech(padding)) return false; return decrypt(privateKey, encryptedData, data, padding); } bool AsymmetricAlgorithm::generateParameters(AsymmetricParameters** /*ppParams*/, void* /*parameters = NULL*/, RNG* /*rng = NULL*/) { return false; } bool AsymmetricAlgorithm::deriveKey(SymmetricKey** /*ppSymmetricKey*/, PublicKey* /*publicKey*/, PrivateKey* /*privateKey*/) { return false; } bool AsymmetricAlgorithm::reconstructParameters(AsymmetricParameters** /*ppParams*/, ByteString& /*serialisedData*/) { return false; } AsymmetricParameters* AsymmetricAlgorithm::newParameters() { return NULL; } // Key recycling -- override these functions in a derived class if you need to perform specific cleanup void AsymmetricAlgorithm::recycleKeyPair(AsymmetricKeyPair* toRecycle) { delete toRecycle; } void AsymmetricAlgorithm::recycleParameters(AsymmetricParameters* toRecycle) { delete toRecycle; } void AsymmetricAlgorithm::recyclePublicKey(PublicKey* toRecycle) { delete toRecycle; } void AsymmetricAlgorithm::recyclePrivateKey(PrivateKey* toRecycle) { delete toRecycle; } void AsymmetricAlgorithm::recycleSymmetricKey(SymmetricKey* toRecycle) { delete toRecycle; } softhsm-2.0.0/src/lib/crypto/OSSLECPublicKey.h0000664000175000017500000000466312533040716015757 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECPublicKey.h OpenSSL Elliptic Curve public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLECPUBLICKEY_H #define _SOFTHSM_V2_OSSLECPUBLICKEY_H #include "config.h" #include "ECPublicKey.h" #include class OSSLECPublicKey : public ECPublicKey { public: // Constructors OSSLECPublicKey(); OSSLECPublicKey(const EC_KEY* inECKEY); // Destructor virtual ~OSSLECPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the EC public key components virtual void setEC(const ByteString& inEC); virtual void setQ(const ByteString& inQ); // Set from OpenSSL representation virtual void setFromOSSL(const EC_KEY* inECKEY); // Retrieve the OpenSSL representation of the key EC_KEY* getOSSLKey(); private: // The internal OpenSSL representation EC_KEY* eckey; }; #endif // !_SOFTHSM_V2_OSSLDSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLUtil.cpp0000664000175000017500000000743612533040716015131 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLUtil.h OpenSSL convenience functions *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLUtil.h" #include // Convert an OpenSSL BIGNUM to a ByteString ByteString OSSL::bn2ByteString(const BIGNUM* bn) { ByteString rv; if (bn != NULL) { rv.resize(BN_num_bytes(bn)); BN_bn2bin(bn, &rv[0]); } return rv; } // Convert a ByteString to an OpenSSL BIGNUM BIGNUM* OSSL::byteString2bn(const ByteString& byteString) { return BN_bin2bn(byteString.const_byte_str(), byteString.size(), NULL); } #ifdef WITH_ECC // Convert an OpenSSL EC GROUP to a ByteString ByteString OSSL::grp2ByteString(const EC_GROUP* grp) { ByteString rv; if (grp != NULL) { rv.resize(i2d_ECPKParameters(grp, NULL)); unsigned char *p = &rv[0]; i2d_ECPKParameters(grp, &p); } return rv; } // Convert a ByteString to an OpenSSL EC GROUP EC_GROUP* OSSL::byteString2grp(const ByteString& byteString) { const unsigned char *p = byteString.const_byte_str(); return d2i_ECPKParameters(NULL, &p, byteString.size()); } // POINT_CONVERSION_UNCOMPRESSED 0x04 // Convert an OpenSSL EC POINT in the given EC GROUP to a ByteString ByteString OSSL::pt2ByteString(const EC_POINT* pt, const EC_GROUP* grp) { ByteString rv; if (pt != NULL && grp != NULL) { size_t len = EC_POINT_point2oct(grp, pt, POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); if (len > 0x7f) { ERROR_MSG("Oversized EC point"); return rv; } rv.resize(len + 2); rv[0] = V_ASN1_OCTET_STRING; rv[1] = len & 0x7f; EC_POINT_point2oct(grp, pt, POINT_CONVERSION_UNCOMPRESSED, &rv[2], len, NULL); } return rv; } // Convert a ByteString to an OpenSSL EC POINT in the given EC GROUP EC_POINT* OSSL::byteString2pt(const ByteString& byteString, const EC_GROUP* grp) { size_t len = byteString.size(); if (len < 2) { ERROR_MSG("Undersized EC point"); return NULL; } len -= 2; if (len > 0x7f) { ERROR_MSG("Oversized EC point"); return NULL; } ByteString repr = byteString; if (repr[0] != V_ASN1_OCTET_STRING) { ERROR_MSG("EC point tag is not OCTET STRING"); return NULL; } if (repr[1] != len) { if (repr[1] < len) { ERROR_MSG("Underrun EC point"); } else { ERROR_MSG("Overrun EC point"); } return NULL; } EC_POINT* pt = EC_POINT_new(grp); if (!EC_POINT_oct2point(grp, pt, &repr[2], len, NULL)) { EC_POINT_free(pt); return NULL; } return pt; } #endif softhsm-2.0.0/src/lib/crypto/RSAParameters.h0000664000175000017500000000451212533040716015621 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSAParameters.h RSA parameters (only used for key generation) *****************************************************************************/ #ifndef _SOFTHSM_V2_RSAPARAMETERS_H #define _SOFTHSM_V2_RSAPARAMETERS_H #include "config.h" #include "ByteString.h" #include "AsymmetricParameters.h" class RSAParameters : public AsymmetricParameters { public: // Base constructor RSAParameters() : bitLen(0) { } // The type static const char* type; // Set the public exponent void setE(const ByteString& inE); // Set the bit length void setBitLength(const size_t inBitLen); // Get the public exponent const ByteString& getE() const; // Get the bit length size_t getBitLength() const; // Are the parameters of the given type? virtual bool areOfType(const char* inType); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); private: ByteString e; size_t bitLen; }; #endif // !_SOFTHSM_V2_RSAPARAMETERS_H softhsm-2.0.0/src/lib/crypto/ECPublicKey.cpp0000664000175000017500000000532512533040716015605 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECPublicKey.cpp Elliptic Curve public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "ECPublicKey.h" #include // Set the type /*static*/ const char* ECPublicKey::type = "Abstract EC public key"; // Check if the key is of the given type bool ECPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long ECPublicKey::getBitLength() const { return getQ().size() * 8; } // Get the output length unsigned long ECPublicKey::getOutputLength() const { return getOrderLength() * 2; } // Setters for the EC public key components void ECPublicKey::setEC(const ByteString& inEC) { ec = inEC; } void ECPublicKey::setQ(const ByteString& inQ) { q = inQ; } // Getters for the EC public key components const ByteString& ECPublicKey::getEC() const { return ec; } const ByteString& ECPublicKey::getQ() const { return q; } // Serialisation ByteString ECPublicKey::serialise() const { return ec.serialise() + q.serialise(); } bool ECPublicKey::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); if ((dEC.size() == 0) || (dQ.size() == 0)) { return false; } setEC(dEC); setQ(dQ); return true; } softhsm-2.0.0/src/lib/crypto/BotanDES.cpp0000664000175000017500000000732312533040716015105 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDES.cpp Botan (3)DES implementation *****************************************************************************/ #include "config.h" #include "BotanDES.h" #include #include "odd.h" bool BotanDES::wrapKey(const SymmetricKey* /*key*/, const SymWrap::Type /*mode*/, const ByteString& /*in*/, ByteString& /*out*/) { ERROR_MSG("DES does not support key wrapping"); return false; } bool BotanDES::unwrapKey(const SymmetricKey* /*key*/, const SymWrap::Type /*mode*/, const ByteString& /*in*/, ByteString& /*out*/) { ERROR_MSG("DES does not support key unwrapping"); return false; } std::string BotanDES::getCipher() const { std::string algo; std::string mode; std::string padding; if (currentKey == NULL) return ""; // Check currentKey bit length; 3DES only supports 56-bit, 112-bit or 168-bit keys switch (currentKey->getBitLen()) { case 56: // People shouldn't really be using 56-bit DES keys, generate a warning DEBUG_MSG("CAUTION: use of 56-bit DES keys is not recommended!"); algo = "DES"; break; case 112: case 168: algo = "TripleDES"; break; default: ERROR_MSG("Invalid DES currentKey length (%d bits)", currentKey->getBitLen()); return ""; } // Determine the cipher mode switch (currentCipherMode) { case SymMode::CBC: mode = "CBC"; break; case SymMode::CFB: mode = "CFB"; break; case SymMode::ECB: mode = "ECB"; break; case SymMode::OFB: mode = "OFB"; break; default: ERROR_MSG("Invalid DES cipher mode %i", currentCipherMode); return ""; } // Check padding mode if (currentCipherMode == SymMode::OFB || currentCipherMode == SymMode::CFB) { padding = ""; } else if (currentPaddingMode) { padding = "/PKCS7"; } else { padding = "/NoPadding"; } return algo + "/" + mode + padding; } bool BotanDES::generateKey(SymmetricKey& key, RNG* rng /* = NULL */) { if (rng == NULL) { return false; } if (key.getBitLen() == 0) { return false; } ByteString keyBits; // don't count parity bit if (!rng->generateRandom(keyBits, key.getBitLen()/7)) { return false; } // fix the odd parity size_t i; for (i = 0; i < keyBits.size(); i++) { keyBits[i] = odd_parity[keyBits[i]]; } return key.setKeyBits(keyBits); } size_t BotanDES::getBlockSize() const { // The block size is 64 bits return 64 >> 3; } softhsm-2.0.0/src/lib/crypto/OSSLSHA224.cpp0000664000175000017500000000326112533040716015047 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA224.h OpenSSL SHA224 implementation *****************************************************************************/ #include "config.h" #include "OSSLSHA224.h" #include int OSSLSHA224::getHashSize() { return 28; } const EVP_MD* OSSLSHA224::getEVPHash() const { return EVP_sha224(); } softhsm-2.0.0/src/lib/crypto/DSAPrivateKey.h0000664000175000017500000000524012533040716015562 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSAPrivateKey.h DSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_DSAPRIVATEKEY_H #define _SOFTHSM_V2_DSAPRIVATEKEY_H #include "config.h" #include "PrivateKey.h" class DSAPrivateKey : public PrivateKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Setters for the DSA private key components virtual void setX(const ByteString& inX); // Setters for the DSA domain parameters virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setG(const ByteString& inG); // Getters for the DSA private key components virtual const ByteString& getX() const; // Getters for the DSA domain parameters virtual const ByteString& getP() const; virtual const ByteString& getQ() const; virtual const ByteString& getG() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Private components ByteString x; // Domain parameters ByteString p,q,g; }; #endif // !_SOFTHSM_V2_DSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLDHKeyPair.h0000664000175000017500000000440212533040716015427 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDHKeyPair.h OpenSSL Diffie-Hellman key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDHKEYPAIR_H #define _SOFTHSM_V2_OSSLDHKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "OSSLDHPublicKey.h" #include "OSSLDHPrivateKey.h" class OSSLDHKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(OSSLDHPublicKey& publicKey); // Set the private key void setPrivateKey(OSSLDHPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key OSSLDHPublicKey pubKey; // The private key OSSLDHPrivateKey privKey; }; #endif // !_SOFTHSM_V2_OSSLDHKEYPAIR_H softhsm-2.0.0/src/lib/crypto/BotanGOST.cpp0000664000175000017500000002510512533040716015244 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOST.cpp Botan GOST R 34.10-2001 asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "BotanGOST.h" #include "BotanRNG.h" #include "CryptoFactory.h" #include "BotanCryptoFactory.h" #include "ECParameters.h" #include "BotanGOSTKeyPair.h" #include "BotanUtil.h" #include #include #include #include // Constructor BotanGOST::BotanGOST() { signer = NULL; verifier = NULL; } // Destructor BotanGOST::~BotanGOST() { delete signer; delete verifier; } // Signing functions bool BotanGOST::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!privateKey->isOfType(BotanGOSTPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } std::string emsa; switch (mechanism) { case AsymMech::GOST: emsa = "Raw"; break; case AsymMech::GOST_GOST: emsa = "EMSA1(GOST-34.11)"; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } BotanGOSTPrivateKey* pk = (BotanGOSTPrivateKey*) currentPrivateKey; Botan::GOST_3410_PrivateKey* botanKey = pk->getBotanKey(); if (botanKey == NULL) { ERROR_MSG("Could not get the Botan private key"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } try { signer = new Botan::PK_Signer(*botanKey, emsa); // Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster. } catch (...) { ERROR_MSG("Could not create the signer token"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool BotanGOST::signUpdate(const ByteString& dataToSign) { if (!AsymmetricAlgorithm::signUpdate(dataToSign)) { return false; } try { if (dataToSign.size() != 0) { signer->update(dataToSign.const_byte_str(), dataToSign.size()); } } catch (...) { ERROR_MSG("Could not add data to signer token"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); delete signer; signer = NULL; return false; } return true; } bool BotanGOST::signFinal(ByteString& signature) { if (!AsymmetricAlgorithm::signFinal(signature)) { return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 std::vector signResult; #else Botan::SecureVector signResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); signResult = signer->signature(*rng->getRNG()); } catch (...) { ERROR_MSG("Could not sign the data"); delete signer; signer = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete signer; signer = NULL; return true; } // Verification functions bool BotanGOST::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen)) { return false; } // Check if the public key is the right type if (!publicKey->isOfType(BotanGOSTPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } std::string emsa; switch (mechanism) { case AsymMech::GOST: emsa = "Raw"; break; case AsymMech::GOST_GOST: emsa = "EMSA1(GOST-34.11)"; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } BotanGOSTPublicKey* pk = (BotanGOSTPublicKey*) currentPublicKey; Botan::GOST_3410_PublicKey* botanKey = pk->getBotanKey(); if (botanKey == NULL) { ERROR_MSG("Could not get the Botan public key"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } try { verifier = new Botan::PK_Verifier(*botanKey, emsa); } catch (...) { ERROR_MSG("Could not create the verifier token"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool BotanGOST::verifyUpdate(const ByteString& originalData) { if (!AsymmetricAlgorithm::verifyUpdate(originalData)) { return false; } try { if (originalData.size() != 0) { verifier->update(originalData.const_byte_str(), originalData.size()); } } catch (...) { ERROR_MSG("Could not add data to the verifier token"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); delete verifier; verifier = NULL; return false; } return true; } bool BotanGOST::verifyFinal(const ByteString& signature) { if (!AsymmetricAlgorithm::verifyFinal(signature)) { return false; } // Perform the verify operation bool verResult; try { verResult = verifier->check_signature(signature.const_byte_str(), signature.size()); } catch (...) { ERROR_MSG("Could not check the signature"); delete verifier; verifier = NULL; return false; } delete verifier; verifier = NULL; return verResult; } // Encryption functions bool BotanGOST::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("GOST does not support encryption"); return false; } // Decryption functions bool BotanGOST::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("GOST does not support decryption"); return false; } // Key factory bool BotanGOST::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(ECParameters::type)) { ERROR_MSG("Invalid parameters supplied for GOST key generation"); return false; } ECParameters* params = (ECParameters*) parameters; // Generate the key-pair Botan::GOST_3410_PrivateKey* eckp = NULL; try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); eckp = new Botan::GOST_3410_PrivateKey(*rng->getRNG(), BotanUtil::byteString2ECGroup(params->getEC())); } catch (...) { ERROR_MSG("GOST key generation failed"); return false; } // Create an asymmetric key-pair object to return BotanGOSTKeyPair* kp = new BotanGOSTKeyPair(); ((BotanGOSTPublicKey*) kp->getPublicKey())->setFromBotan(eckp); ((BotanGOSTPrivateKey*) kp->getPrivateKey())->setFromBotan(eckp); *ppKeyPair = kp; // Release the key delete eckp; return true; } unsigned long BotanGOST::getMinKeySize() { return 0; } unsigned long BotanGOST::getMaxKeySize() { return 0; } bool BotanGOST::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); BotanGOSTKeyPair* kp = new BotanGOSTKeyPair(); bool rv = true; if (!((BotanGOSTPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((BotanGOSTPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool BotanGOST::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanGOSTPublicKey* pub = new BotanGOSTPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool BotanGOST::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanGOSTPrivateKey* priv = new BotanGOSTPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* BotanGOST::newPublicKey() { return (PublicKey*) new BotanGOSTPublicKey(); } PrivateKey* BotanGOST::newPrivateKey() { return (PrivateKey*) new BotanGOSTPrivateKey(); } AsymmetricParameters* BotanGOST::newParameters() { return (AsymmetricParameters*) new ECParameters(); } bool BotanGOST::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } ECParameters* params = new ECParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } #endif softhsm-2.0.0/src/lib/crypto/DSAParameters.h0000664000175000017500000000463612533040716015612 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSAParameters.h DSA parameters (only used for key generation) *****************************************************************************/ #ifndef _SOFTHSM_V2_DSAPARAMETERS_H #define _SOFTHSM_V2_DSAPARAMETERS_H #include "config.h" #include "ByteString.h" #include "AsymmetricParameters.h" class DSAParameters : public AsymmetricParameters { public: // The type static const char* type; // Set the public prime p void setP(const ByteString& inP); // Set the public subprime q void setQ(const ByteString& inQ); // Set the generator g void setG(const ByteString& inG); // Get the public prime p const ByteString& getP() const; // Get the public subprime q const ByteString& getQ() const; // Get the generator g const ByteString& getG() const; // Are the parameters of the given type? virtual bool areOfType(const char* inType); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); private: ByteString p; ByteString q; ByteString g; }; #endif // !_SOFTHSM_V2_DSAPARAMETERS_H softhsm-2.0.0/src/lib/crypto/RNG.h0000664000175000017500000000371012533040716013575 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RNG.h Base class for random number generator classes *****************************************************************************/ #ifndef _SOFTHSM_V2_RNG_H #define _SOFTHSM_V2_RNG_H #include "config.h" #include "ByteString.h" struct RNGImpl { enum Type { Unknown, Default }; }; class RNG { public: // Base constructor RNG() { } // Destructor virtual ~RNG() { } // Generate random data virtual bool generateRandom(ByteString& data, const size_t len) = 0; // Seed the random pool virtual void seed(ByteString& seedData) = 0; private: }; #endif // !_SOFTHSM_V2_RNG_H softhsm-2.0.0/src/lib/crypto/OSSLSHA384.h0000664000175000017500000000346312533040716014527 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA384.h OpenSSL SHA384 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLSHA384_H #define _SOFTHSM_V2_OSSLSHA384_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLSHA384 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLSHA384_H softhsm-2.0.0/src/lib/crypto/BotanDHPrivateKey.h0000664000175000017500000000710212533040716016431 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDHPrivateKey.h Botan Diffie-Hellman private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDHPRIVATEKEY_H #define _SOFTHSM_V2_BOTANDHPRIVATEKEY_H #include "config.h" #include "DHPrivateKey.h" #include // Derived from the DH_PrivateKey class class BotanDH_PrivateKey : public Botan::DH_PublicKey, public virtual Botan::DL_Scheme_PrivateKey { public: #if BOTAN_VERSION_MINOR == 11 std::vector public_value() const; #else Botan::MemoryVector public_value() const; #endif // Constructors #if BOTAN_VERSION_MINOR == 11 BotanDH_PrivateKey(const Botan::AlgorithmIdentifier& alg_id, const Botan::secure_vector& key_bits, Botan::RandomNumberGenerator& rng); #else BotanDH_PrivateKey(const Botan::AlgorithmIdentifier& alg_id, const Botan::MemoryRegion& key_bits, Botan::RandomNumberGenerator& rng); #endif BotanDH_PrivateKey(Botan::RandomNumberGenerator& rng, const Botan::DL_Group& grp, const Botan::BigInt& x = 0); ~BotanDH_PrivateKey(); Botan::DH_PrivateKey* impl; }; class BotanDHPrivateKey : public DHPrivateKey { public: // Constructors BotanDHPrivateKey(); BotanDHPrivateKey(const BotanDH_PrivateKey* inDH); // Destructor virtual ~BotanDHPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DH private key components virtual void setX(const ByteString& inX); // Setters for the DH public key components virtual void setP(const ByteString& inP); virtual void setG(const ByteString& inG); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from Botan representation virtual void setFromBotan(const BotanDH_PrivateKey* inDH); // Retrieve the Botan representation of the key BotanDH_PrivateKey* getBotanKey(); private: // The internal Botan representation BotanDH_PrivateKey* dh; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANDHPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLECKeyPair.h0000664000175000017500000000440212533040716015423 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECKeyPair.h OpenSSL Elliptic Curve key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLECKEYPAIR_H #define _SOFTHSM_V2_OSSLECKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "OSSLECPublicKey.h" #include "OSSLECPrivateKey.h" class OSSLECKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(OSSLECPublicKey& publicKey); // Set the private key void setPrivateKey(OSSLECPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key OSSLECPublicKey pubKey; // The private key OSSLECPrivateKey privKey; }; #endif // !_SOFTHSM_V2_OSSLECKEYPAIR_H softhsm-2.0.0/src/lib/crypto/BotanDSA.cpp0000664000175000017500000003631712533040716015106 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSA.cpp Botan DSA asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDSA.h" #include "BotanRNG.h" #include "CryptoFactory.h" #include "BotanCryptoFactory.h" #include "DSAParameters.h" #include "BotanDSAKeyPair.h" #include "BotanUtil.h" #include #include #include #include // Constructor BotanDSA::BotanDSA() { signer = NULL; verifier = NULL; } // Destructor BotanDSA::~BotanDSA() { delete signer; delete verifier; } // Signing functions bool BotanDSA::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { std::string emsa; if (mechanism == AsymMech::DSA) { emsa = "Raw"; } else { // Call default implementation return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen); } // Check if the private key is the right type if (!privateKey->isOfType(BotanDSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } BotanDSAPrivateKey* pk = (BotanDSAPrivateKey*) privateKey; Botan::DSA_PrivateKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan private key"); return false; } try { signer = new Botan::PK_Signer(*botanKey, emsa); // Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster. } catch (...) { ERROR_MSG("Could not create the signer token"); return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 std::vector signResult; #else Botan::SecureVector signResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); signResult = signer->sign_message(dataToSign.const_byte_str(), dataToSign.size(), *rng->getRNG()); } catch (...) { ERROR_MSG("Could not sign the data"); delete signer; signer = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete signer; signer = NULL; return true; } bool BotanDSA::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen)) { return false; } // Check if the private key is the right type if (!privateKey->isOfType(BotanDSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } std::string emsa; switch (mechanism) { case AsymMech::DSA_SHA1: emsa = "EMSA1(SHA-160)"; break; case AsymMech::DSA_SHA224: emsa = "EMSA1(SHA-224)"; break; case AsymMech::DSA_SHA256: emsa = "EMSA1(SHA-256)"; break; case AsymMech::DSA_SHA384: emsa = "EMSA1(SHA-384)"; break; case AsymMech::DSA_SHA512: emsa = "EMSA1(SHA-512)"; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } BotanDSAPrivateKey* pk = (BotanDSAPrivateKey*) currentPrivateKey; Botan::DSA_PrivateKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan private key"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } try { signer = new Botan::PK_Signer(*botanKey, emsa); // Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster. } catch (...) { ERROR_MSG("Could not create the signer token"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); return false; } return true; } bool BotanDSA::signUpdate(const ByteString& dataToSign) { if (!AsymmetricAlgorithm::signUpdate(dataToSign)) { return false; } try { if (dataToSign.size() != 0) { signer->update(dataToSign.const_byte_str(), dataToSign.size()); } } catch (...) { ERROR_MSG("Could not add data to signer token"); ByteString dummy; AsymmetricAlgorithm::signFinal(dummy); delete signer; signer = NULL; return false; } return true; } bool BotanDSA::signFinal(ByteString& signature) { if (!AsymmetricAlgorithm::signFinal(signature)) { return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 std::vector signResult; #else Botan::SecureVector signResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); signResult = signer->signature(*rng->getRNG()); } catch (...) { ERROR_MSG("Could not sign the data"); delete signer; signer = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete signer; signer = NULL; return true; } // Verification functions bool BotanDSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { std::string emsa; if (mechanism == AsymMech::DSA) { emsa = "Raw"; } else { // Call the generic function return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen); } // Check if the public key is the right type if (!publicKey->isOfType(BotanDSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } BotanDSAPublicKey* pk = (BotanDSAPublicKey*) publicKey; Botan::DSA_PublicKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan public key"); return false; } try { verifier = new Botan::PK_Verifier(*botanKey, emsa); } catch (...) { ERROR_MSG("Could not create the verifier token"); return false; } // Perform the verify operation bool verResult; try { verResult = verifier->verify_message(originalData.const_byte_str(), originalData.size(), signature.const_byte_str(), signature.size()); } catch (...) { ERROR_MSG("Could not check the signature"); delete verifier; verifier = NULL; return false; } delete verifier; verifier = NULL; return verResult; } bool BotanDSA::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param /* = NULL */, const size_t paramLen /* = 0 */) { if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen)) { return false; } // Check if the public key is the right type if (!publicKey->isOfType(BotanDSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } std::string emsa; switch (mechanism) { case AsymMech::DSA_SHA1: emsa = "EMSA1(SHA-160)"; break; case AsymMech::DSA_SHA224: emsa = "EMSA1(SHA-224)"; break; case AsymMech::DSA_SHA256: emsa = "EMSA1(SHA-256)"; break; case AsymMech::DSA_SHA384: emsa = "EMSA1(SHA-384)"; break; case AsymMech::DSA_SHA512: emsa = "EMSA1(SHA-512)"; break; default: ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } BotanDSAPublicKey* pk = (BotanDSAPublicKey*) currentPublicKey; Botan::DSA_PublicKey* botanKey = pk->getBotanKey(); if (!botanKey) { ERROR_MSG("Could not get the Botan public key"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } try { verifier = new Botan::PK_Verifier(*botanKey, emsa); } catch (...) { ERROR_MSG("Could not create the verifier token"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); return false; } return true; } bool BotanDSA::verifyUpdate(const ByteString& originalData) { if (!AsymmetricAlgorithm::verifyUpdate(originalData)) { return false; } try { if (originalData.size() != 0) { verifier->update(originalData.const_byte_str(), originalData.size()); } } catch (...) { ERROR_MSG("Could not add data to the verifier token"); ByteString dummy; AsymmetricAlgorithm::verifyFinal(dummy); delete verifier; verifier = NULL; return false; } return true; } bool BotanDSA::verifyFinal(const ByteString& signature) { if (!AsymmetricAlgorithm::verifyFinal(signature)) { return false; } // Perform the verify operation bool verResult; try { verResult = verifier->check_signature(signature.const_byte_str(), signature.size()); } catch (...) { ERROR_MSG("Could not check the signature"); delete verifier; verifier = NULL; return false; } delete verifier; verifier = NULL; return verResult; } // Encryption functions bool BotanDSA::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DSA does not support encryption"); return false; } // Decryption functions bool BotanDSA::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("DSA does not support decryption"); return false; } // Key factory bool BotanDSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(DSAParameters::type)) { ERROR_MSG("Invalid parameters supplied for DSA key generation"); return false; } DSAParameters* params = (DSAParameters*) parameters; // Generate the key-pair Botan::DSA_PrivateKey* dsa = NULL; try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); dsa = new Botan::DSA_PrivateKey(*rng->getRNG(), Botan::DL_Group(BotanUtil::byteString2bigInt(params->getP()), BotanUtil::byteString2bigInt(params->getQ()), BotanUtil::byteString2bigInt(params->getG()))); } catch (...) { ERROR_MSG("DSA key generation failed"); return false; } // Create an asymmetric key-pair object to return BotanDSAKeyPair* kp = new BotanDSAKeyPair(); ((BotanDSAPublicKey*) kp->getPublicKey())->setFromBotan(dsa); ((BotanDSAPrivateKey*) kp->getPrivateKey())->setFromBotan(dsa); *ppKeyPair = kp; // Release the key delete dsa; return true; } unsigned long BotanDSA::getMinKeySize() { return 512; } unsigned long BotanDSA::getMaxKeySize() { // Taken from OpenSSL return 10000; } bool BotanDSA::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/) { if ((ppParams == NULL) || (parameters == NULL)) { return false; } size_t bitLen = (size_t) parameters; if (bitLen < getMinKeySize() || bitLen > getMaxKeySize()) { ERROR_MSG("This DSA key size is not supported"); return false; } Botan::DL_Group* group = NULL; // Taken from OpenSSL size_t qLen = bitLen >= 2048 ? 256 : 160; try { BotanRNG* brng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); group = new Botan::DL_Group(*brng->getRNG(), Botan::DL_Group::Prime_Subgroup, bitLen, qLen); } catch (...) { ERROR_MSG("Failed to generate %d bit DSA parameters", bitLen); return false; } // Store the DSA parameters DSAParameters* params = new DSAParameters(); ByteString p = BotanUtil::bigInt2ByteString(group->get_p()); params->setP(p); ByteString q = BotanUtil::bigInt2ByteString(group->get_q()); params->setQ(q); ByteString g = BotanUtil::bigInt2ByteString(group->get_g()); params->setG(g); *ppParams = params; delete group; return true; } bool BotanDSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); BotanDSAKeyPair* kp = new BotanDSAKeyPair(); bool rv = true; if (!((DSAPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((DSAPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool BotanDSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanDSAPublicKey* pub = new BotanDSAPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool BotanDSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanDSAPrivateKey* priv = new BotanDSAPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* BotanDSA::newPublicKey() { return (PublicKey*) new BotanDSAPublicKey(); } PrivateKey* BotanDSA::newPrivateKey() { return (PrivateKey*) new BotanDSAPrivateKey(); } AsymmetricParameters* BotanDSA::newParameters() { return (AsymmetricParameters*) new DSAParameters(); } bool BotanDSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } DSAParameters* params = new DSAParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } softhsm-2.0.0/src/lib/crypto/GOSTPrivateKey.cpp0000664000175000017500000000452312533040716016265 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** GOSTPrivateKey.cpp GOST R 34.10-2001 private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "GOSTPrivateKey.h" #include // Set the type /*static*/ const char* GOSTPrivateKey::type = "Abstract GOST private key"; // Check if the key is of the given type bool GOSTPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long GOSTPrivateKey::getBitLength() const { return getD().bits(); } // Setters for the GOST private key components void GOSTPrivateKey::setD(const ByteString& inD) { d = inD; } // Setters for the GOST public key components void GOSTPrivateKey::setEC(const ByteString& inEC) { ec = inEC; } // Getters for the GOST private key components const ByteString& GOSTPrivateKey::getD() const { return d; } // Getters for the GOST public key components const ByteString& GOSTPrivateKey::getEC() const { return ec; } softhsm-2.0.0/src/lib/crypto/BotanGOSTKeyPair.h0000664000175000017500000000450612533040716016200 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTKeyPair.h Botan GOST R 34.10-2001 key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANGOSTKEYPAIR_H #define _SOFTHSM_V2_BOTANGOSTKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "BotanGOSTPublicKey.h" #include "BotanGOSTPrivateKey.h" class BotanGOSTKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(BotanGOSTPublicKey& publicKey); // Set the private key void setPrivateKey(BotanGOSTPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key BotanGOSTPublicKey pubKey; // The private key BotanGOSTPrivateKey privKey; }; #endif // !_SOFTHSM_V2_BOTANGOSTKEYPAIR_H softhsm-2.0.0/src/lib/crypto/Makefile.in0000664000175000017500000011471412552216620015052 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ # Compile with support of OpenSSL @WITH_OPENSSL_TRUE@am__append_1 = OSSLAES.cpp \ @WITH_OPENSSL_TRUE@ OSSLCryptoFactory.cpp \ @WITH_OPENSSL_TRUE@ OSSLDES.cpp \ @WITH_OPENSSL_TRUE@ OSSLDH.cpp \ @WITH_OPENSSL_TRUE@ OSSLDHKeyPair.cpp \ @WITH_OPENSSL_TRUE@ OSSLDHPrivateKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLDHPublicKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLDSA.cpp \ @WITH_OPENSSL_TRUE@ OSSLDSAKeyPair.cpp \ @WITH_OPENSSL_TRUE@ OSSLDSAPrivateKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLDSAPublicKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLECDH.cpp \ @WITH_OPENSSL_TRUE@ OSSLECDSA.cpp \ @WITH_OPENSSL_TRUE@ OSSLECKeyPair.cpp \ @WITH_OPENSSL_TRUE@ OSSLECPrivateKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLECPublicKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLEVPHashAlgorithm.cpp \ @WITH_OPENSSL_TRUE@ OSSLEVPMacAlgorithm.cpp \ @WITH_OPENSSL_TRUE@ OSSLEVPSymmetricAlgorithm.cpp \ @WITH_OPENSSL_TRUE@ OSSLGOST.cpp \ @WITH_OPENSSL_TRUE@ OSSLGOSTKeyPair.cpp \ @WITH_OPENSSL_TRUE@ OSSLGOSTPrivateKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLGOSTPublicKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLGOSTR3411.cpp \ @WITH_OPENSSL_TRUE@ OSSLHMAC.cpp \ @WITH_OPENSSL_TRUE@ OSSLMD5.cpp \ @WITH_OPENSSL_TRUE@ OSSLRNG.cpp \ @WITH_OPENSSL_TRUE@ OSSLRSA.cpp \ @WITH_OPENSSL_TRUE@ OSSLRSAKeyPair.cpp \ @WITH_OPENSSL_TRUE@ OSSLRSAPrivateKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLRSAPublicKey.cpp \ @WITH_OPENSSL_TRUE@ OSSLSHA1.cpp \ @WITH_OPENSSL_TRUE@ OSSLSHA224.cpp \ @WITH_OPENSSL_TRUE@ OSSLSHA256.cpp \ @WITH_OPENSSL_TRUE@ OSSLSHA384.cpp \ @WITH_OPENSSL_TRUE@ OSSLSHA512.cpp \ @WITH_OPENSSL_TRUE@ OSSLUtil.cpp # Compile with support of Botan @WITH_BOTAN_TRUE@am__append_2 = BotanAES.cpp \ @WITH_BOTAN_TRUE@ BotanCryptoFactory.cpp \ @WITH_BOTAN_TRUE@ BotanDES.cpp \ @WITH_BOTAN_TRUE@ BotanDH.cpp \ @WITH_BOTAN_TRUE@ BotanDHKeyPair.cpp \ @WITH_BOTAN_TRUE@ BotanDHPrivateKey.cpp \ @WITH_BOTAN_TRUE@ BotanDHPublicKey.cpp \ @WITH_BOTAN_TRUE@ BotanDSA.cpp \ @WITH_BOTAN_TRUE@ BotanDSAKeyPair.cpp \ @WITH_BOTAN_TRUE@ BotanDSAPrivateKey.cpp \ @WITH_BOTAN_TRUE@ BotanDSAPublicKey.cpp \ @WITH_BOTAN_TRUE@ BotanECDH.cpp \ @WITH_BOTAN_TRUE@ BotanECDHKeyPair.cpp \ @WITH_BOTAN_TRUE@ BotanECDHPrivateKey.cpp \ @WITH_BOTAN_TRUE@ BotanECDHPublicKey.cpp \ @WITH_BOTAN_TRUE@ BotanECDSA.cpp \ @WITH_BOTAN_TRUE@ BotanECDSAKeyPair.cpp \ @WITH_BOTAN_TRUE@ BotanECDSAPrivateKey.cpp \ @WITH_BOTAN_TRUE@ BotanECDSAPublicKey.cpp \ @WITH_BOTAN_TRUE@ BotanGOST.cpp \ @WITH_BOTAN_TRUE@ BotanGOSTKeyPair.cpp \ @WITH_BOTAN_TRUE@ BotanGOSTPrivateKey.cpp \ @WITH_BOTAN_TRUE@ BotanGOSTPublicKey.cpp \ @WITH_BOTAN_TRUE@ BotanGOSTR3411.cpp \ @WITH_BOTAN_TRUE@ BotanHashAlgorithm.cpp \ @WITH_BOTAN_TRUE@ BotanHMAC.cpp \ @WITH_BOTAN_TRUE@ BotanMacAlgorithm.cpp \ @WITH_BOTAN_TRUE@ BotanMD5.cpp \ @WITH_BOTAN_TRUE@ BotanRNG.cpp \ @WITH_BOTAN_TRUE@ BotanRSA.cpp \ @WITH_BOTAN_TRUE@ BotanRSAKeyPair.cpp \ @WITH_BOTAN_TRUE@ BotanRSAPrivateKey.cpp \ @WITH_BOTAN_TRUE@ BotanRSAPublicKey.cpp \ @WITH_BOTAN_TRUE@ BotanSHA1.cpp \ @WITH_BOTAN_TRUE@ BotanSHA224.cpp \ @WITH_BOTAN_TRUE@ BotanSHA256.cpp \ @WITH_BOTAN_TRUE@ BotanSHA384.cpp \ @WITH_BOTAN_TRUE@ BotanSHA512.cpp \ @WITH_BOTAN_TRUE@ BotanSymmetricAlgorithm.cpp \ @WITH_BOTAN_TRUE@ BotanUtil.cpp subdir = src/lib/crypto DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \ $(top_srcdir)/depcomp ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = LTLIBRARIES = $(noinst_LTLIBRARIES) libsofthsm_crypto_la_DEPENDENCIES = am__libsofthsm_crypto_la_SOURCES_DIST = AsymmetricAlgorithm.cpp \ AsymmetricKeyPair.cpp CryptoFactory.cpp DESKey.cpp \ DHParameters.cpp DHPublicKey.cpp DHPrivateKey.cpp \ DSAParameters.cpp DSAPublicKey.cpp DSAPrivateKey.cpp \ ECParameters.cpp ECPublicKey.cpp ECPrivateKey.cpp \ GOSTPublicKey.cpp GOSTPrivateKey.cpp HashAlgorithm.cpp \ MacAlgorithm.cpp RSAParameters.cpp RSAPrivateKey.cpp \ RSAPublicKey.cpp SymmetricAlgorithm.cpp SymmetricKey.cpp \ OSSLAES.cpp OSSLCryptoFactory.cpp OSSLDES.cpp OSSLDH.cpp \ OSSLDHKeyPair.cpp OSSLDHPrivateKey.cpp OSSLDHPublicKey.cpp \ OSSLDSA.cpp OSSLDSAKeyPair.cpp OSSLDSAPrivateKey.cpp \ OSSLDSAPublicKey.cpp OSSLECDH.cpp OSSLECDSA.cpp \ OSSLECKeyPair.cpp OSSLECPrivateKey.cpp OSSLECPublicKey.cpp \ OSSLEVPHashAlgorithm.cpp OSSLEVPMacAlgorithm.cpp \ OSSLEVPSymmetricAlgorithm.cpp OSSLGOST.cpp OSSLGOSTKeyPair.cpp \ OSSLGOSTPrivateKey.cpp OSSLGOSTPublicKey.cpp OSSLGOSTR3411.cpp \ OSSLHMAC.cpp OSSLMD5.cpp OSSLRNG.cpp OSSLRSA.cpp \ OSSLRSAKeyPair.cpp OSSLRSAPrivateKey.cpp OSSLRSAPublicKey.cpp \ OSSLSHA1.cpp OSSLSHA224.cpp OSSLSHA256.cpp OSSLSHA384.cpp \ OSSLSHA512.cpp OSSLUtil.cpp BotanAES.cpp \ BotanCryptoFactory.cpp BotanDES.cpp BotanDH.cpp \ BotanDHKeyPair.cpp BotanDHPrivateKey.cpp BotanDHPublicKey.cpp \ BotanDSA.cpp BotanDSAKeyPair.cpp BotanDSAPrivateKey.cpp \ BotanDSAPublicKey.cpp BotanECDH.cpp BotanECDHKeyPair.cpp \ BotanECDHPrivateKey.cpp BotanECDHPublicKey.cpp BotanECDSA.cpp \ BotanECDSAKeyPair.cpp BotanECDSAPrivateKey.cpp \ BotanECDSAPublicKey.cpp BotanGOST.cpp BotanGOSTKeyPair.cpp \ BotanGOSTPrivateKey.cpp BotanGOSTPublicKey.cpp \ BotanGOSTR3411.cpp BotanHashAlgorithm.cpp BotanHMAC.cpp \ BotanMacAlgorithm.cpp BotanMD5.cpp BotanRNG.cpp BotanRSA.cpp \ BotanRSAKeyPair.cpp BotanRSAPrivateKey.cpp \ BotanRSAPublicKey.cpp BotanSHA1.cpp BotanSHA224.cpp \ BotanSHA256.cpp BotanSHA384.cpp BotanSHA512.cpp \ BotanSymmetricAlgorithm.cpp BotanUtil.cpp @WITH_OPENSSL_TRUE@am__objects_1 = OSSLAES.lo OSSLCryptoFactory.lo \ @WITH_OPENSSL_TRUE@ OSSLDES.lo OSSLDH.lo OSSLDHKeyPair.lo \ @WITH_OPENSSL_TRUE@ OSSLDHPrivateKey.lo OSSLDHPublicKey.lo \ @WITH_OPENSSL_TRUE@ OSSLDSA.lo OSSLDSAKeyPair.lo \ @WITH_OPENSSL_TRUE@ OSSLDSAPrivateKey.lo OSSLDSAPublicKey.lo \ @WITH_OPENSSL_TRUE@ OSSLECDH.lo OSSLECDSA.lo OSSLECKeyPair.lo \ @WITH_OPENSSL_TRUE@ OSSLECPrivateKey.lo OSSLECPublicKey.lo \ @WITH_OPENSSL_TRUE@ OSSLEVPHashAlgorithm.lo \ @WITH_OPENSSL_TRUE@ OSSLEVPMacAlgorithm.lo \ @WITH_OPENSSL_TRUE@ OSSLEVPSymmetricAlgorithm.lo OSSLGOST.lo \ @WITH_OPENSSL_TRUE@ OSSLGOSTKeyPair.lo OSSLGOSTPrivateKey.lo \ @WITH_OPENSSL_TRUE@ OSSLGOSTPublicKey.lo OSSLGOSTR3411.lo \ @WITH_OPENSSL_TRUE@ OSSLHMAC.lo OSSLMD5.lo OSSLRNG.lo \ @WITH_OPENSSL_TRUE@ OSSLRSA.lo OSSLRSAKeyPair.lo \ @WITH_OPENSSL_TRUE@ OSSLRSAPrivateKey.lo OSSLRSAPublicKey.lo \ @WITH_OPENSSL_TRUE@ OSSLSHA1.lo OSSLSHA224.lo OSSLSHA256.lo \ @WITH_OPENSSL_TRUE@ OSSLSHA384.lo OSSLSHA512.lo OSSLUtil.lo @WITH_BOTAN_TRUE@am__objects_2 = BotanAES.lo BotanCryptoFactory.lo \ @WITH_BOTAN_TRUE@ BotanDES.lo BotanDH.lo BotanDHKeyPair.lo \ @WITH_BOTAN_TRUE@ BotanDHPrivateKey.lo BotanDHPublicKey.lo \ @WITH_BOTAN_TRUE@ BotanDSA.lo BotanDSAKeyPair.lo \ @WITH_BOTAN_TRUE@ BotanDSAPrivateKey.lo BotanDSAPublicKey.lo \ @WITH_BOTAN_TRUE@ BotanECDH.lo BotanECDHKeyPair.lo \ @WITH_BOTAN_TRUE@ BotanECDHPrivateKey.lo BotanECDHPublicKey.lo \ @WITH_BOTAN_TRUE@ BotanECDSA.lo BotanECDSAKeyPair.lo \ @WITH_BOTAN_TRUE@ BotanECDSAPrivateKey.lo \ @WITH_BOTAN_TRUE@ BotanECDSAPublicKey.lo BotanGOST.lo \ @WITH_BOTAN_TRUE@ BotanGOSTKeyPair.lo BotanGOSTPrivateKey.lo \ @WITH_BOTAN_TRUE@ BotanGOSTPublicKey.lo BotanGOSTR3411.lo \ @WITH_BOTAN_TRUE@ BotanHashAlgorithm.lo BotanHMAC.lo \ @WITH_BOTAN_TRUE@ BotanMacAlgorithm.lo BotanMD5.lo BotanRNG.lo \ @WITH_BOTAN_TRUE@ BotanRSA.lo BotanRSAKeyPair.lo \ @WITH_BOTAN_TRUE@ BotanRSAPrivateKey.lo BotanRSAPublicKey.lo \ @WITH_BOTAN_TRUE@ BotanSHA1.lo BotanSHA224.lo BotanSHA256.lo \ @WITH_BOTAN_TRUE@ BotanSHA384.lo BotanSHA512.lo \ @WITH_BOTAN_TRUE@ BotanSymmetricAlgorithm.lo BotanUtil.lo am_libsofthsm_crypto_la_OBJECTS = AsymmetricAlgorithm.lo \ AsymmetricKeyPair.lo CryptoFactory.lo DESKey.lo \ DHParameters.lo DHPublicKey.lo DHPrivateKey.lo \ DSAParameters.lo DSAPublicKey.lo DSAPrivateKey.lo \ ECParameters.lo ECPublicKey.lo ECPrivateKey.lo \ GOSTPublicKey.lo GOSTPrivateKey.lo HashAlgorithm.lo \ MacAlgorithm.lo RSAParameters.lo RSAPrivateKey.lo \ RSAPublicKey.lo SymmetricAlgorithm.lo SymmetricKey.lo \ $(am__objects_1) $(am__objects_2) libsofthsm_crypto_la_OBJECTS = $(am_libsofthsm_crypto_la_OBJECTS) AM_V_lt = $(am__v_lt_@AM_V@) am__v_lt_ = $(am__v_lt_@AM_DEFAULT_V@) am__v_lt_0 = --silent am__v_lt_1 = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) depcomp = $(SHELL) $(top_srcdir)/depcomp am__depfiles_maybe = depfiles am__mv = mv -f CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS) LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \ $(AM_CXXFLAGS) $(CXXFLAGS) AM_V_CXX = $(am__v_CXX_@AM_V@) am__v_CXX_ = $(am__v_CXX_@AM_DEFAULT_V@) am__v_CXX_0 = @echo " CXX " $@; am__v_CXX_1 = CXXLD = $(CXX) CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@ AM_V_CXXLD = $(am__v_CXXLD_@AM_V@) am__v_CXXLD_ = $(am__v_CXXLD_@AM_DEFAULT_V@) am__v_CXXLD_0 = @echo " CXXLD " $@; am__v_CXXLD_1 = SOURCES = $(libsofthsm_crypto_la_SOURCES) DIST_SOURCES = $(am__libsofthsm_crypto_la_SOURCES_DIST) RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in AM_CPPFLAGS = -I$(srcdir)/../common \ -I$(srcdir)/../cryptoki_compat \ -I$(srcdir)/../data_mgr \ -I$(srcdir)/.. \ @CRYPTO_INCLUDES@ noinst_LTLIBRARIES = libsofthsm_crypto.la libsofthsm_crypto_la_SOURCES = AsymmetricAlgorithm.cpp \ AsymmetricKeyPair.cpp CryptoFactory.cpp DESKey.cpp \ DHParameters.cpp DHPublicKey.cpp DHPrivateKey.cpp \ DSAParameters.cpp DSAPublicKey.cpp DSAPrivateKey.cpp \ ECParameters.cpp ECPublicKey.cpp ECPrivateKey.cpp \ GOSTPublicKey.cpp GOSTPrivateKey.cpp HashAlgorithm.cpp \ MacAlgorithm.cpp RSAParameters.cpp RSAPrivateKey.cpp \ RSAPublicKey.cpp SymmetricAlgorithm.cpp SymmetricKey.cpp \ $(am__append_1) $(am__append_2) libsofthsm_crypto_la_LIBADD = @CRYPTO_LIBS@ SUBDIRS = test EXTRA_DIST = $(srcdir)/*.h $(srcdir)/*.cpp all: all-recursive .SUFFIXES: .SUFFIXES: .cpp .lo .o .obj $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/lib/crypto/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/lib/crypto/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): clean-noinstLTLIBRARIES: -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ test -z "$$locs" || { \ echo rm -f $${locs}; \ rm -f $${locs}; \ } libsofthsm_crypto.la: $(libsofthsm_crypto_la_OBJECTS) $(libsofthsm_crypto_la_DEPENDENCIES) $(EXTRA_libsofthsm_crypto_la_DEPENDENCIES) $(AM_V_CXXLD)$(CXXLINK) $(libsofthsm_crypto_la_OBJECTS) $(libsofthsm_crypto_la_LIBADD) $(LIBS) mostlyclean-compile: -rm -f *.$(OBJEXT) distclean-compile: -rm -f *.tab.c @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/AsymmetricAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/AsymmetricKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanAES.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanCryptoFactory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDES.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDH.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDHKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDHPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDHPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDSA.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDSAKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanDSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDH.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDHKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDHPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDHPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDSA.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDSAKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanECDSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanGOST.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanGOSTKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanGOSTPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanGOSTPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanGOSTR3411.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanHMAC.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanHashAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanMD5.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanMacAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanRNG.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanRSA.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanRSAKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanRSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanRSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanSHA1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanSHA224.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanSHA256.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanSHA384.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanSHA512.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanSymmetricAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BotanUtil.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/CryptoFactory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DESKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DHParameters.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DHPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DHPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DSAParameters.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ECParameters.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ECPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ECPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/GOSTPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/GOSTPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/HashAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/MacAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLAES.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLCryptoFactory.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDES.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDH.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDHKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDHPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDHPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDSA.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDSAKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLDSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLECDH.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLECDSA.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLECKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLECPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLECPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLEVPHashAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLEVPMacAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLEVPSymmetricAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLGOST.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLGOSTKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLGOSTPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLGOSTPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLGOSTR3411.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLHMAC.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLMD5.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLRNG.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLRSA.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLRSAKeyPair.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLRSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLRSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLSHA1.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLSHA224.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLSHA256.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLSHA384.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLSHA512.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/OSSLUtil.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RSAParameters.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RSAPrivateKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/RSAPublicKey.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SymmetricAlgorithm.Plo@am__quote@ @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/SymmetricKey.Plo@am__quote@ .cpp.o: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ $< .cpp.obj: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'` .cpp.lo: @am__fastdepCXX_TRUE@ $(AM_V_CXX)$(LTCXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< @am__fastdepCXX_TRUE@ $(AM_V_at)$(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo @AMDEP_TRUE@@am__fastdepCXX_FALSE@ $(AM_V_CXX)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ @AMDEP_TRUE@@am__fastdepCXX_FALSE@ DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@ @am__fastdepCXX_FALSE@ $(AM_V_CXX@am__nodep@)$(LTCXXCOMPILE) -c -o $@ $< mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile $(LTLIBRARIES) installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ mostlyclean-am distclean: distclean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile distclean-am: clean-am distclean-compile distclean-generic \ distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -rf ./$(DEPDIR) -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool \ clean-noinstLTLIBRARIES cscopelist-am ctags ctags-am distclean \ distclean-compile distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-compile mostlyclean-generic \ mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/src/lib/crypto/BotanSHA512.cpp0000664000175000017500000000334412533040716015334 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSHA512.cpp Botan SHA512 implementation *****************************************************************************/ #include "config.h" #include "BotanSHA512.h" #include int BotanSHA512::getHashSize() { return 64; } Botan::HashFunction* BotanSHA512::getHash() const { return new Botan::SHA_512(); } softhsm-2.0.0/src/lib/crypto/OSSLSHA384.cpp0000664000175000017500000000326112533040716015056 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA384.h OpenSSL SHA384 implementation *****************************************************************************/ #include "config.h" #include "OSSLSHA384.h" #include int OSSLSHA384::getHashSize() { return 48; } const EVP_MD* OSSLSHA384::getEVPHash() const { return EVP_sha384(); } softhsm-2.0.0/src/lib/crypto/BotanDHKeyPair.cpp0000664000175000017500000000424312533040716016250 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDHKeyPair.cpp Botan Diffie-Hellman key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDHKeyPair.h" // Set the public key void BotanDHKeyPair::setPublicKey(BotanDHPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void BotanDHKeyPair::setPrivateKey(BotanDHPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* BotanDHKeyPair::getPublicKey() { return &pubKey; } const PublicKey* BotanDHKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* BotanDHKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* BotanDHKeyPair::getConstPrivateKey() const { return &privKey; } softhsm-2.0.0/src/lib/crypto/BotanUtil.cpp0000664000175000017500000001060712533040716015406 00000000000000 /* * Copyright (c) .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanUtil.h Botan convenience functions *****************************************************************************/ #include "config.h" #include "BotanUtil.h" #include #include #include // Convert a Botan BigInt to a ByteString ByteString BotanUtil::bigInt2ByteString(const Botan::BigInt& bigInt) { ByteString rv; rv.resize(bigInt.bytes()); bigInt.binary_encode(&rv[0]); return rv; } // Used when extracting little-endian data ByteString BotanUtil::bigInt2ByteStringPrefix(const Botan::BigInt& bigInt, size_t size) { ByteString rv; if (size > bigInt.bytes()) { size_t diff = size - bigInt.bytes(); rv.resize(size); memset(&rv[0], '\0', diff); bigInt.binary_encode(&rv[0] + diff); } else { rv.resize(bigInt.bytes()); bigInt.binary_encode(&rv[0]); } return rv; } // Convert a ByteString to an Botan BigInt Botan::BigInt BotanUtil::byteString2bigInt(const ByteString& byteString) { return Botan::BigInt(byteString.const_byte_str(), byteString.size()); } #if defined(WITH_ECC) || defined(WITH_GOST) // Convert a Botan EC group to a ByteString ByteString BotanUtil::ecGroup2ByteString(const Botan::EC_Group& ecGroup) { #if BOTAN_VERSION_MINOR == 11 std::vector der = ecGroup.DER_encode(Botan::EC_DOMPAR_ENC_OID); #else Botan::SecureVector der = ecGroup.DER_encode(Botan::EC_DOMPAR_ENC_OID); #endif return ByteString(&der[0], der.size()); } // Convert a ByteString to a Botan EC group Botan::EC_Group BotanUtil::byteString2ECGroup(const ByteString& byteString) { #if BOTAN_VERSION_MINOR == 11 std::vector der(byteString.size()); memcpy(&der[0], byteString.const_byte_str(), byteString.size()); return Botan::EC_Group(der); #else return Botan::EC_Group(Botan::MemoryVector(byteString.const_byte_str(), byteString.size())); #endif } // Convert a Botan EC point to a ByteString ByteString BotanUtil::ecPoint2ByteString(const Botan::PointGFp& ecPoint) { ByteString point; try { #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector repr = Botan::EC2OSP(ecPoint, Botan::PointGFp::UNCOMPRESSED); Botan::secure_vector der; #else Botan::SecureVector repr = Botan::EC2OSP(ecPoint, Botan::PointGFp::UNCOMPRESSED); Botan::SecureVector der; #endif der = Botan::DER_Encoder() .encode(repr, Botan::OCTET_STRING) .get_contents(); point.resize(der.size()); memcpy(&point[0], &der[0], der.size()); } catch (...) { ERROR_MSG("Can't convert from EC point"); } return point; } // Convert a ByteString to a Botan EC point Botan::PointGFp BotanUtil::byteString2ECPoint(const ByteString& byteString, const Botan::EC_Group& ecGroup) { #if BOTAN_VERSION_MINOR == 11 std::vector repr; #else Botan::SecureVector repr; #endif Botan::BER_Decoder(byteString.const_byte_str(), byteString.size()) .decode(repr, Botan::OCTET_STRING) .verify_end(); return Botan::OS2ECP(&repr[0], repr.size(), ecGroup.get_curve()); } #endif softhsm-2.0.0/src/lib/crypto/DHPrivateKey.cpp0000664000175000017500000000603112533040716016000 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHPrivateKey.cpp Diffie-Hellman private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "DHPrivateKey.h" #include // Set the type /*static*/ const char* DHPrivateKey::type = "Abstract DH private key"; // Check if the key is of the given type bool DHPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long DHPrivateKey::getBitLength() const { return getP().bits(); } // Get the output length unsigned long DHPrivateKey::getOutputLength() const { return getP().size(); } // Setters for the DH private key components void DHPrivateKey::setX(const ByteString& inX) { x = inX; } // Setters for the DH public key components void DHPrivateKey::setP(const ByteString& inP) { p = inP; } void DHPrivateKey::setG(const ByteString& inG) { g = inG; } // Getters for the DH private key components const ByteString& DHPrivateKey::getX() const { return x; } // Getters for the DH public key components const ByteString& DHPrivateKey::getP() const { return p; } const ByteString& DHPrivateKey::getG() const { return g; } // Serialisation ByteString DHPrivateKey::serialise() const { return p.serialise() + g.serialise() + x.serialise(); } bool DHPrivateKey::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dG = ByteString::chainDeserialise(serialised); ByteString dX = ByteString::chainDeserialise(serialised); if ((dP.size() == 0) || (dG.size() == 0) || (dX.size() == 0)) { return false; } setP(dP); setG(dG); setX(dX); return true; } softhsm-2.0.0/src/lib/crypto/OSSLECDH.cpp0000664000175000017500000001736112533040716014715 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLECDH.cpp OpenSSL Diffie-Hellman asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "OSSLECDH.h" #include "CryptoFactory.h" #include "ECParameters.h" #include "OSSLECKeyPair.h" #include "OSSLUtil.h" #include #include #include #include // Signing functions bool OSSLECDH::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDH does not support signing"); return false; } bool OSSLECDH::signUpdate(const ByteString& /*dataToSign*/) { ERROR_MSG("ECDH does not support signing"); return false; } bool OSSLECDH::signFinal(ByteString& /*signature*/) { ERROR_MSG("ECDH does not support signing"); return false; } // Verification functions bool OSSLECDH::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDH does not support verifying"); return false; } bool OSSLECDH::verifyUpdate(const ByteString& /*originalData*/) { ERROR_MSG("ECDH does not support verifying"); return false; } bool OSSLECDH::verifyFinal(const ByteString& /*signature*/) { ERROR_MSG("ECDH does not support verifying"); return false; } // Encryption functions bool OSSLECDH::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDH does not support encryption"); return false; } // Decryption functions bool OSSLECDH::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDH does not support decryption"); return false; } // Key factory bool OSSLECDH::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(ECParameters::type)) { ERROR_MSG("Invalid parameters supplied for ECDH key generation"); return false; } ECParameters* params = (ECParameters*) parameters; // Generate the key-pair EC_KEY* eckey = EC_KEY_new(); if (eckey == NULL) { ERROR_MSG("Failed to instantiate OpenSSL ECDH object"); return false; } EC_GROUP* grp = OSSL::byteString2grp(params->getEC()); EC_KEY_set_group(eckey, grp); EC_GROUP_free(grp); if (!EC_KEY_generate_key(eckey)) { ERROR_MSG("ECDH key generation failed (0x%08X)", ERR_get_error()); EC_KEY_free(eckey); return false; } // Create an asymmetric key-pair object to return OSSLECKeyPair* kp = new OSSLECKeyPair(); ((OSSLECPublicKey*) kp->getPublicKey())->setFromOSSL(eckey); ((OSSLECPrivateKey*) kp->getPrivateKey())->setFromOSSL(eckey); *ppKeyPair = kp; // Release the key EC_KEY_free(eckey); return true; } bool OSSLECDH::deriveKey(SymmetricKey **ppSymmetricKey, PublicKey* publicKey, PrivateKey* privateKey) { // Check parameters if ((ppSymmetricKey == NULL) || (publicKey == NULL) || (privateKey == NULL)) { return false; } // Get keys EC_KEY *pub = ((OSSLECPublicKey *)publicKey)->getOSSLKey(); EC_KEY *priv = ((OSSLECPrivateKey *)privateKey)->getOSSLKey(); if (pub == NULL || EC_KEY_get0_public_key(pub) == NULL || priv == NULL) { ERROR_MSG("Failed to get OpenSSL ECDH keys"); return false; } // Use the OpenSSL implementation and not any engine ECDH_set_method(pub, ECDH_get_default_method()); ECDH_set_method(priv, ECDH_get_default_method()); // Derive the secret ByteString secret; secret.resize(((OSSLECPublicKey *)publicKey)->getOrderLength());; int outlen = ECDH_compute_key(&secret[0], secret.size(), EC_KEY_get0_public_key(pub), priv, NULL); if (outlen <= 0) { ERROR_MSG("ECDH key derivation failed (0x%08X)", ERR_get_error()); return false; } secret.resize(outlen); *ppSymmetricKey = new SymmetricKey; if (*ppSymmetricKey == NULL) return false; if (!(*ppSymmetricKey)->setKeyBits(secret)) { delete *ppSymmetricKey; *ppSymmetricKey = NULL; return false; } return true; } unsigned long OSSLECDH::getMinKeySize() { // Smallest EC group is secp112r1 return 112; } unsigned long OSSLECDH::getMaxKeySize() { // Biggest EC group is secp521r1 return 521; } bool OSSLECDH::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); OSSLECKeyPair* kp = new OSSLECKeyPair(); bool rv = true; if (!((ECPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((ECPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool OSSLECDH::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLECPublicKey* pub = new OSSLECPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool OSSLECDH::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } OSSLECPrivateKey* priv = new OSSLECPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* OSSLECDH::newPublicKey() { return (PublicKey*) new OSSLECPublicKey(); } PrivateKey* OSSLECDH::newPrivateKey() { return (PrivateKey*) new OSSLECPrivateKey(); } AsymmetricParameters* OSSLECDH::newParameters() { return (AsymmetricParameters*) new ECParameters(); } bool OSSLECDH::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } ECParameters* params = new ECParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } #endif softhsm-2.0.0/src/lib/crypto/BotanECDSAKeyPair.h0000664000175000017500000000450512533040716016242 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSAKeyPair.h Botan ECDSA key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANECDSAKEYPAIR_H #define _SOFTHSM_V2_BOTANECDSAKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "BotanECDSAPublicKey.h" #include "BotanECDSAPrivateKey.h" class BotanECDSAKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(BotanECDSAPublicKey& publicKey); // Set the private key void setPrivateKey(BotanECDSAPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key BotanECDSAPublicKey pubKey; // The private key BotanECDSAPrivateKey privKey; }; #endif // !_SOFTHSM_V2_BOTANECDSAKEYPAIR_H softhsm-2.0.0/src/lib/crypto/BotanHMAC.h0000664000175000017500000000530412533040716014644 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanHMAC.h Botan HMAC implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANHMAC_H #define _SOFTHSM_V2_BOTANHMAC_H #include "config.h" #include "BotanMacAlgorithm.h" #include #include class BotanHMACMD5 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; class BotanHMACSHA1 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; class BotanHMACSHA224 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; class BotanHMACSHA256 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; class BotanHMACSHA384 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; class BotanHMACSHA512 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; #ifdef WITH_GOST class BotanHMACGOSTR3411 : public BotanMacAlgorithm { protected: virtual std::string getHash() const; virtual size_t getMacSize() const; }; #endif #endif // !_SOFTHSM_V2_BOTANHMAC_H softhsm-2.0.0/src/lib/crypto/OSSLMD5.h0000664000175000017500000000344112533040716014236 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLMD5.h OpenSSL MD5 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLMD5_H #define _SOFTHSM_V2_OSSLMD5_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLMD5 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLMD5_H softhsm-2.0.0/src/lib/crypto/BotanDSAPrivateKey.cpp0000664000175000017500000001324312533040716017103 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSAPrivateKey.cpp Botan DSA private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "BotanDSAPrivateKey.h" #include "BotanCryptoFactory.h" #include "BotanRNG.h" #include "BotanUtil.h" #include #include #include #include #include // Constructors BotanDSAPrivateKey::BotanDSAPrivateKey() { dsa = NULL; } BotanDSAPrivateKey::BotanDSAPrivateKey(const Botan::DSA_PrivateKey* inDSA) { dsa = NULL; setFromBotan(inDSA); } // Destructor BotanDSAPrivateKey::~BotanDSAPrivateKey() { delete dsa; } // The type /*static*/ const char* BotanDSAPrivateKey::type = "Botan DSA Private Key"; // Set from Botan representation void BotanDSAPrivateKey::setFromBotan(const Botan::DSA_PrivateKey* inDSA) { ByteString inP = BotanUtil::bigInt2ByteString(inDSA->group_p()); setP(inP); ByteString inQ = BotanUtil::bigInt2ByteString(inDSA->group_q()); setQ(inQ); ByteString inG = BotanUtil::bigInt2ByteString(inDSA->group_g()); setG(inG); ByteString inX = BotanUtil::bigInt2ByteString(inDSA->get_x()); setX(inX); } // Check if the key is of the given type bool BotanDSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the DSA private key components void BotanDSAPrivateKey::setX(const ByteString& inX) { DSAPrivateKey::setX(inX); if (dsa) { delete dsa; dsa = NULL; } } // Setters for the DSA domain parameters void BotanDSAPrivateKey::setP(const ByteString& inP) { DSAPrivateKey::setP(inP); if (dsa) { delete dsa; dsa = NULL; } } void BotanDSAPrivateKey::setQ(const ByteString& inQ) { DSAPrivateKey::setQ(inQ); if (dsa) { delete dsa; dsa = NULL; } } void BotanDSAPrivateKey::setG(const ByteString& inG) { DSAPrivateKey::setG(inG); if (dsa) { delete dsa; dsa = NULL; } } // Encode into PKCS#8 DER ByteString BotanDSAPrivateKey::PKCS8Encode() { ByteString der; createBotanKey(); if (dsa == NULL) return der; #if BOTAN_VERSION_MINOR == 11 const Botan::secure_vector ber = Botan::PKCS8::BER_encode(*dsa); #else const Botan::SecureVector ber = Botan::PKCS8::BER_encode(*dsa); #endif der.resize(ber.size()); memcpy(&der[0], &ber[0], ber.size()); return der; } // Decode from PKCS#8 BER bool BotanDSAPrivateKey::PKCS8Decode(const ByteString& ber) { Botan::DataSource_Memory source(ber.const_byte_str(), ber.size()); if (source.end_of_data()) return false; #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector keydata; #else Botan::SecureVector keydata; #endif Botan::AlgorithmIdentifier alg_id; Botan::DSA_PrivateKey* key = NULL; try { Botan::BER_Decoder(source) .start_cons(Botan::SEQUENCE) .decode_and_check(0, "Unknown PKCS #8 version number") .decode(alg_id) .decode(keydata, Botan::OCTET_STRING) .discard_remaining() .end_cons(); if (keydata.empty()) throw Botan::Decoding_Error("PKCS #8 private key decoding failed"); if (Botan::OIDS::lookup(alg_id.oid).compare("DSA")) { ERROR_MSG("Decoded private key not DSA"); return false; } BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); key = new Botan::DSA_PrivateKey(alg_id, keydata, *rng->getRNG()); if (key == NULL) return false; setFromBotan(key); delete key; } catch (std::exception& e) { ERROR_MSG("Decode failed on %s", e.what()); return false; } return true; } // Retrieve the Botan representation of the key Botan::DSA_PrivateKey* BotanDSAPrivateKey::getBotanKey() { if (!dsa) { createBotanKey(); } return dsa; } // Create the Botan representation of the key void BotanDSAPrivateKey::createBotanKey() { // y is not needed // Todo: Either q or x is needed. Both is not needed if (p.size() != 0 && q.size() != 0 && g.size() != 0 && x.size() != 0) { if (dsa) { delete dsa; dsa = NULL; } try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); dsa = new Botan::DSA_PrivateKey(*rng->getRNG(), Botan::DL_Group(BotanUtil::byteString2bigInt(p), BotanUtil::byteString2bigInt(q), BotanUtil::byteString2bigInt(g)), BotanUtil::byteString2bigInt(x)); } catch (...) { ERROR_MSG("Could not create the Botan private key"); } } } softhsm-2.0.0/src/lib/crypto/BotanCryptoFactory.cpp0000664000175000017500000001716512533040716017307 00000000000000/* * Copyright (c) 2010 SURFnet bv * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanCryptoFactory.cpp This is a Botan based cryptographic algorithm factory *****************************************************************************/ #include "config.h" #include "BotanCryptoFactory.h" #include "BotanAES.h" #include "BotanDES.h" #include "BotanDSA.h" #include "BotanDH.h" #ifdef WITH_ECC #include "BotanECDH.h" #include "BotanECDSA.h" #endif #include "BotanMD5.h" #include "BotanRNG.h" #include "BotanRSA.h" #include "BotanSHA1.h" #include "BotanSHA224.h" #include "BotanSHA256.h" #include "BotanSHA384.h" #include "BotanSHA512.h" #ifdef WITH_GOST #include "BotanGOST.h" #include "BotanGOSTR3411.h" #endif #include "BotanHMAC.h" #include #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) #include #endif // Initialise the one-and-only instance #ifdef HAVE_CXX11 std::unique_ptr BotanCryptoFactory::instance(nullptr); #else std::auto_ptr BotanCryptoFactory::instance(NULL); #endif // Constructor BotanCryptoFactory::BotanCryptoFactory() { #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) wasInitialized = false; // Check if Botan has already been initialized if (Botan::Global_State_Management::global_state_exists()) { wasInitialized = true; } // Init the Botan crypto library if (!wasInitialized) { Botan::LibraryInitializer::initialize("thread_safe=true"); } #else Botan::LibraryInitializer::initialize("thread_safe=true"); #endif // Create mutex rngsMutex = MutexFactory::i()->getMutex(); } // Destructor BotanCryptoFactory::~BotanCryptoFactory() { // Delete the RNGs #ifdef HAVE_PTHREAD_H std::map::iterator it; for (it=rngs.begin(); it != rngs.end(); it++) { delete (BotanRNG*)it->second; } #elif _WIN32 std::map::iterator it; for (it=rngs.begin(); it != rngs.end(); it++) { delete (BotanRNG*)it->second; } #endif // Delete the mutex MutexFactory::i()->recycleMutex(rngsMutex); // Deinitialize the Botan crypto lib #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,11,14) if (!wasInitialized) { Botan::LibraryInitializer::deinitialize(); } #else Botan::LibraryInitializer::deinitialize(); #endif } // Return the one-and-only instance BotanCryptoFactory* BotanCryptoFactory::i() { if (!instance.get()) { instance.reset(new BotanCryptoFactory()); } return instance.get(); } // This will destroy the one-and-only instance. void BotanCryptoFactory::reset() { instance.reset(); } // Create a concrete instance of a symmetric algorithm SymmetricAlgorithm* BotanCryptoFactory::getSymmetricAlgorithm(SymAlgo::Type algorithm) { switch (algorithm) { case SymAlgo::AES: return new BotanAES(); case SymAlgo::DES: case SymAlgo::DES3: return new BotanDES(); default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Create a concrete instance of an asymmetric algorithm AsymmetricAlgorithm* BotanCryptoFactory::getAsymmetricAlgorithm(AsymAlgo::Type algorithm) { switch (algorithm) { case AsymAlgo::RSA: return new BotanRSA(); case AsymAlgo::DSA: return new BotanDSA(); case AsymAlgo::DH: return new BotanDH(); #ifdef WITH_ECC case AsymAlgo::ECDH: return new BotanECDH(); case AsymAlgo::ECDSA: return new BotanECDSA(); #endif #ifdef WITH_GOST case AsymAlgo::GOST: return new BotanGOST(); #endif default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Create a concrete instance of a hash algorithm HashAlgorithm* BotanCryptoFactory::getHashAlgorithm(HashAlgo::Type algorithm) { switch (algorithm) { case HashAlgo::MD5: return new BotanMD5(); case HashAlgo::SHA1: return new BotanSHA1(); case HashAlgo::SHA224: return new BotanSHA224(); case HashAlgo::SHA256: return new BotanSHA256(); case HashAlgo::SHA384: return new BotanSHA384(); case HashAlgo::SHA512: return new BotanSHA512(); #ifdef WITH_GOST case HashAlgo::GOST: return new BotanGOSTR3411(); #endif default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Create a concrete instance of a MAC algorithm MacAlgorithm* BotanCryptoFactory::getMacAlgorithm(MacAlgo::Type algorithm) { switch (algorithm) { case MacAlgo::HMAC_MD5: return new BotanHMACMD5(); case MacAlgo::HMAC_SHA1: return new BotanHMACSHA1(); case MacAlgo::HMAC_SHA224: return new BotanHMACSHA224(); case MacAlgo::HMAC_SHA256: return new BotanHMACSHA256(); case MacAlgo::HMAC_SHA384: return new BotanHMACSHA384(); case MacAlgo::HMAC_SHA512: return new BotanHMACSHA512(); #ifdef WITH_GOST case MacAlgo::HMAC_GOST: return new BotanHMACGOSTR3411(); #endif default: // No algorithm implementation is available ERROR_MSG("Unknown algorithm '%i'", algorithm); return NULL; } // No algorithm implementation is available return NULL; } // Get the global RNG (may be an unique RNG per thread) RNG* BotanCryptoFactory::getRNG(RNGImpl::Type name /* = RNGImpl::Default */) { if (name == RNGImpl::Default) { RNG *threadRNG = NULL; // Lock access to the map MutexLocker lock(rngsMutex); #ifdef HAVE_PTHREAD_H // Get thread ID pthread_t threadID = pthread_self(); // Find the RNG std::map::iterator findIt; findIt=rngs.find(threadID); if (findIt != rngs.end()) { return findIt->second; } threadRNG = new BotanRNG(); rngs[threadID] = threadRNG; #elif _WIN32 // Get thread ID DWORD threadID = GetCurrentThreadId(); // Find the RNG std::map::iterator findIt; findIt=rngs.find(threadID); if (findIt != rngs.end()) { return findIt->second; } threadRNG = new BotanRNG(); rngs[threadID] = threadRNG; #else #error "There are no thread-specific data implementations for your operating system yet" #endif return threadRNG; } else { // No RNG implementation is available ERROR_MSG("Unknown RNG '%i'", name); return NULL; } } softhsm-2.0.0/src/lib/crypto/BotanGOSTPrivateKey.cpp0000664000175000017500000001116112533040716017245 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTPrivateKey.cpp Botan GOST R 34.10-2001 private key class *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "BotanGOSTPrivateKey.h" #include "BotanCryptoFactory.h" #include "BotanRNG.h" #include "BotanUtil.h" #include // Constructors BotanGOSTPrivateKey::BotanGOSTPrivateKey() { eckey = NULL; } BotanGOSTPrivateKey::BotanGOSTPrivateKey(const Botan::GOST_3410_PrivateKey* inECKEY) { BotanGOSTPrivateKey(); setFromBotan(inECKEY); } // Destructor BotanGOSTPrivateKey::~BotanGOSTPrivateKey() { delete eckey; } // The type /*static*/ const char* BotanGOSTPrivateKey::type = "Botan GOST Private Key"; // Get the base point order length unsigned long BotanGOSTPrivateKey::getOrderLength() const { try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); return group.get_order().bytes(); } catch (...) { ERROR_MSG("Can't get EC group for order length"); return 0; } } // Get the output length unsigned long BotanGOSTPrivateKey::getOutputLength() const { return getOrderLength() * 2; } // Set from Botan representation void BotanGOSTPrivateKey::setFromBotan(const Botan::GOST_3410_PrivateKey* inECKEY) { ByteString inEC = BotanUtil::ecGroup2ByteString(inECKEY->domain()); setEC(inEC); ByteString inD = BotanUtil::bigInt2ByteStringPrefix(inECKEY->private_value(), 32); setD(inD); } // Check if the key is of the given type bool BotanGOSTPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the GOST private key components void BotanGOSTPrivateKey::setD(const ByteString& inD) { GOSTPrivateKey::setD(inD); if (eckey) { delete eckey; eckey = NULL; } } // Setters for the GOST public key components void BotanGOSTPrivateKey::setEC(const ByteString& inEC) { GOSTPrivateKey::setEC(inEC); if (eckey) { delete eckey; eckey = NULL; } } // Serialisation ByteString BotanGOSTPrivateKey::serialise() const { return ec.serialise() + d.serialise(); } bool BotanGOSTPrivateKey::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); ByteString dD = ByteString::chainDeserialise(serialised); if ((dEC.size() == 0) || (dD.size() == 0)) { return false; } setEC(dEC); setD(dD); return true; } // Encode into PKCS#8 DER ByteString BotanGOSTPrivateKey::PKCS8Encode() { ByteString der; // TODO return der; } // Decode from PKCS#8 BER bool BotanGOSTPrivateKey::PKCS8Decode(const ByteString& /*ber*/) { return false; } // Retrieve the Botan representation of the key Botan::GOST_3410_PrivateKey* BotanGOSTPrivateKey::getBotanKey() { if (!eckey) { createBotanKey(); } return eckey; } // Create the Botan representation of the key void BotanGOSTPrivateKey::createBotanKey() { if (ec.size() != 0 && d.size() != 0) { if (eckey) { delete eckey; eckey = NULL; } try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); eckey = new Botan::GOST_3410_PrivateKey(*rng->getRNG(), group, BotanUtil::byteString2bigInt(d)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } #endif softhsm-2.0.0/src/lib/crypto/HashAlgorithm.cpp0000664000175000017500000000410612533040716016234 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** HashAlgorithm.cpp Base class for hash algorithm classes *****************************************************************************/ #include "config.h" #include "HashAlgorithm.h" // Base constructor HashAlgorithm::HashAlgorithm() { currentOperation = NONE; } // Hashing functions bool HashAlgorithm::hashInit() { if (currentOperation != NONE) { return false; } currentOperation = HASHING; return true; } bool HashAlgorithm::hashUpdate(const ByteString& /*data*/) { if (currentOperation != HASHING) { return false; } return true; } bool HashAlgorithm::hashFinal(ByteString& /*hashedData*/) { if (currentOperation != HASHING) { return false; } currentOperation = NONE; return true; } softhsm-2.0.0/src/lib/crypto/BotanGOSTPrivateKey.h0000664000175000017500000000602112533040716016711 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOSTPrivateKey.h Botan GOST R 34.10-2001 private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANGOSTPRIVATEKEY_H #define _SOFTHSM_V2_BOTANGOSTPRIVATEKEY_H #include "config.h" #include "GOSTPrivateKey.h" #include class BotanGOSTPrivateKey : public GOSTPrivateKey { public: // Constructors BotanGOSTPrivateKey(); BotanGOSTPrivateKey(const Botan::GOST_3410_PrivateKey* inECKEY); // Destructor virtual ~BotanGOSTPrivateKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the output length virtual unsigned long getOutputLength() const; // Get the base point order length virtual unsigned long getOrderLength() const; // Setters for the GOST private key components virtual void setD(const ByteString& inD); // Setters for the GOST public key components virtual void setEC(const ByteString& inEC); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); // Encode into PKCS#8 DER virtual ByteString PKCS8Encode(); // Decode from PKCS#8 BER virtual bool PKCS8Decode(const ByteString& ber); // Set from Botan representation virtual void setFromBotan(const Botan::GOST_3410_PrivateKey* inECKEY); // Retrieve the Botan representation of the key Botan::GOST_3410_PrivateKey* getBotanKey(); private: // The internal Botan representation Botan::GOST_3410_PrivateKey* eckey; // Create the Botan representation of the key void createBotanKey(); }; #endif // !_SOFTHSM_V2_BOTANGOSTPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLUtil.h0000664000175000017500000000463612533040716014575 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLUtil.h OpenSSL convenience functions *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLUTIL_H #define _SOFTHSM_V2_OSSLUTIL_H #include "config.h" #include "ByteString.h" #include #ifdef WITH_ECC #include #endif namespace OSSL { // Convert an OpenSSL BIGNUM to a ByteString ByteString bn2ByteString(const BIGNUM* bn); // Convert a ByteString to an OpenSSL BIGNUM BIGNUM* byteString2bn(const ByteString& byteString); #ifdef WITH_ECC // Convert an OpenSSL EC GROUP to a ByteString ByteString grp2ByteString(const EC_GROUP* grp); // Convert a ByteString to an OpenSSL EC GROUP EC_GROUP* byteString2grp(const ByteString& byteString); // Convert an OpenSSL EC POINT in the given EC GROUP to a ByteString ByteString pt2ByteString(const EC_POINT* pt, const EC_GROUP* grp); // Convert a ByteString to an OpenSSL EC POINT in the given EC GROUP EC_POINT* byteString2pt(const ByteString& byteString, const EC_GROUP* grp); #endif } #endif // !_SOFTHSM_V2_OSSLUTIL_H softhsm-2.0.0/src/lib/crypto/DSAPublicKey.cpp0000664000175000017500000000625312533040716015726 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DSAPublicKey.cpp DSA public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "DSAPublicKey.h" #include // Set the type /*static*/ const char* DSAPublicKey::type = "Abstract DSA public key"; // Check if the key is of the given type bool DSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long DSAPublicKey::getBitLength() const { return getP().bits(); } // Get the output length unsigned long DSAPublicKey::getOutputLength() const { return getQ().size() * 2; } // Setters for the DSA public key components void DSAPublicKey::setP(const ByteString& inP) { p = inP; } void DSAPublicKey::setQ(const ByteString& inQ) { q = inQ; } void DSAPublicKey::setG(const ByteString& inG) { g = inG; } void DSAPublicKey::setY(const ByteString& inY) { y = inY; } // Getters for the DSA public key components const ByteString& DSAPublicKey::getP() const { return p; } const ByteString& DSAPublicKey::getQ() const { return q; } const ByteString& DSAPublicKey::getG() const { return g; } const ByteString& DSAPublicKey::getY() const { return y; } // Serialisation ByteString DSAPublicKey::serialise() const { return p.serialise() + q.serialise() + g.serialise() + y.serialise(); } bool DSAPublicKey::deserialise(ByteString& serialised) { ByteString dP = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); ByteString dG = ByteString::chainDeserialise(serialised); ByteString dY = ByteString::chainDeserialise(serialised); if ((dP.size() == 0) || (dQ.size() == 0) || (dG.size() == 0) || (dY.size() == 0)) { return false; } setP(dP); setQ(dQ); setG(dG); setY(dY); return true; } softhsm-2.0.0/src/lib/crypto/OSSLDHPublicKey.h0000664000175000017500000000455612533040716015764 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDHPublicKey.h OpenSSL Diffie-Hellman public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDHPUBLICKEY_H #define _SOFTHSM_V2_OSSLDHPUBLICKEY_H #include "config.h" #include "DHPublicKey.h" #include class OSSLDHPublicKey : public DHPublicKey { public: // Constructors OSSLDHPublicKey(); OSSLDHPublicKey(const DH* inDH); // Destructor virtual ~OSSLDHPublicKey(); // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Setters for the DH public key components virtual void setP(const ByteString& inP); virtual void setG(const ByteString& inG); virtual void setY(const ByteString& inY); // Set from OpenSSL representation virtual void setFromOSSL(const DH* inDH); // Retrieve the OpenSSL representation of the key DH* getOSSLKey(); private: // The internal OpenSSL representation DH* dh; }; #endif // !_SOFTHSM_V2_OSSLDHPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/DESKey.cpp0000664000175000017500000000400212533040716014561 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DESKey.cpp DES key class *****************************************************************************/ #include "config.h" #include "ByteString.h" #include "Serialisable.h" #include "DESKey.h" // Set the key bool DESKey::setKeyBits(const ByteString& keybits) { if (bitLen > 0) { // Check if the correct input data is supplied size_t expectedLen = 0; switch(bitLen) { case 56: expectedLen = 8; break; case 112: expectedLen = 16; break; case 168: expectedLen = 24; break; }; // Check the length if (keybits.size() != expectedLen) { return false; } } keyData = keybits; return true; } softhsm-2.0.0/src/lib/crypto/OSSLSHA256.cpp0000664000175000017500000000326112533040716015054 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA256.h OpenSSL SHA256 implementation *****************************************************************************/ #include "config.h" #include "OSSLSHA256.h" #include int OSSLSHA256::getHashSize() { return 32; } const EVP_MD* OSSLSHA256::getEVPHash() const { return EVP_sha256(); } softhsm-2.0.0/src/lib/crypto/RSAPublicKey.h0000664000175000017500000000455712533040716015416 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSAPublicKey.h RSA public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_RSAPUBLICKEY_H #define _SOFTHSM_V2_RSAPUBLICKEY_H #include "config.h" #include "PublicKey.h" class RSAPublicKey : public PublicKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Setters for the RSA public key components virtual void setN(const ByteString& inN); virtual void setE(const ByteString& inE); // Getters for the RSA public key components virtual const ByteString& getN() const; virtual const ByteString& getE() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Public components ByteString n,e; }; #endif // !_SOFTHSM_V2_RSAPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/BotanECDSA.cpp0000664000175000017500000002360412533040716015311 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSA.cpp Botan ECDSA asymmetric algorithm implementation *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDSA.h" #include "BotanRNG.h" #include "CryptoFactory.h" #include "BotanCryptoFactory.h" #include "ECParameters.h" #include "BotanECDSAKeyPair.h" #include "BotanUtil.h" #include #include #include #include // Constructor BotanECDSA::BotanECDSA() { signer = NULL; verifier = NULL; } // Destructor BotanECDSA::~BotanECDSA() { delete signer; delete verifier; } // Signing functions bool BotanECDSA::sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { std::string emsa; if (mechanism == AsymMech::ECDSA) { emsa = "Raw"; } else { ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); return false; } // Check if the private key is the right type if (!privateKey->isOfType(BotanECDSAPrivateKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } BotanECDSAPrivateKey* pk = (BotanECDSAPrivateKey*) privateKey; Botan::ECDSA_PrivateKey* botanKey = pk->getBotanKey(); if (botanKey == NULL) { ERROR_MSG("Could not get the Botan private key"); return false; } try { signer = new Botan::PK_Signer(*botanKey, emsa); // Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster. } catch (...) { ERROR_MSG("Could not create the signer token"); return false; } // Perform the signature operation #if BOTAN_VERSION_MINOR == 11 std::vector signResult; #else Botan::SecureVector signResult; #endif try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); signResult = signer->sign_message(dataToSign.const_byte_str(), dataToSign.size(), *rng->getRNG()); } catch (...) { ERROR_MSG("Could not sign the data"); delete signer; signer = NULL; return false; } // Return the result signature.resize(signResult.size()); #if BOTAN_VERSION_MINOR == 11 memcpy(&signature[0], signResult.data(), signResult.size()); #else memcpy(&signature[0], signResult.begin(), signResult.size()); #endif delete signer; signer = NULL; return true; } // Signing functions bool BotanECDSA::signInit(PrivateKey* /*privateKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDSA does not support multi part signing"); return false; } bool BotanECDSA::signUpdate(const ByteString& /*dataToSign*/) { ERROR_MSG("ECDSA does not support multi part signing"); return false; } bool BotanECDSA::signFinal(ByteString& /*signature*/) { ERROR_MSG("ECDSA does not support multi part signing"); return false; } // Verification functions bool BotanECDSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { std::string emsa; if (mechanism == AsymMech::ECDSA) { emsa = "Raw"; } else { ERROR_MSG("Invalid mechanism supplied (%i)", mechanism); return false; } // Check if the public key is the right type if (!publicKey->isOfType(BotanECDSAPublicKey::type)) { ERROR_MSG("Invalid key type supplied"); return false; } BotanECDSAPublicKey* pk = (BotanECDSAPublicKey*) publicKey; Botan::ECDSA_PublicKey* botanKey = pk->getBotanKey(); if (botanKey == NULL) { ERROR_MSG("Could not get the Botan public key"); return false; } try { verifier = new Botan::PK_Verifier(*botanKey, emsa); } catch (...) { ERROR_MSG("Could not create the verifier token"); return false; } // Perform the verify operation bool verResult; try { verResult = verifier->verify_message(originalData.const_byte_str(), originalData.size(), signature.const_byte_str(), signature.size()); } catch (...) { ERROR_MSG("Could not check the signature"); delete verifier; verifier = NULL; return false; } delete verifier; verifier = NULL; return verResult; } // Verification functions bool BotanECDSA::verifyInit(PublicKey* /*publicKey*/, const AsymMech::Type /*mechanism*/, const void* /* param = NULL */, const size_t /* paramLen = 0 */) { ERROR_MSG("ECDSA does not support multi part verifying"); return false; } bool BotanECDSA::verifyUpdate(const ByteString& /*originalData*/) { ERROR_MSG("ECDSA does not support multi part verifying"); return false; } bool BotanECDSA::verifyFinal(const ByteString& /*signature*/) { ERROR_MSG("ECDSA does not support multi part verifying"); return false; } // Encryption functions bool BotanECDSA::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/, ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDSA does not support encryption"); return false; } // Decryption functions bool BotanECDSA::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/, ByteString& /*data*/, const AsymMech::Type /*padding*/) { ERROR_MSG("ECDSA does not support decryption"); return false; } // Key factory bool BotanECDSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */) { // Check parameters if ((ppKeyPair == NULL) || (parameters == NULL)) { return false; } if (!parameters->areOfType(ECParameters::type)) { ERROR_MSG("Invalid parameters supplied for ECDSA key generation"); return false; } ECParameters* params = (ECParameters*) parameters; // Generate the key-pair Botan::ECDSA_PrivateKey* eckp = NULL; try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); eckp = new Botan::ECDSA_PrivateKey(*rng->getRNG(), BotanUtil::byteString2ECGroup(params->getEC())); } catch (...) { ERROR_MSG("ECDSA key generation failed"); return false; } // Create an asymmetric key-pair object to return BotanECDSAKeyPair* kp = new BotanECDSAKeyPair(); ((BotanECDSAPublicKey*) kp->getPublicKey())->setFromBotan(eckp); ((BotanECDSAPrivateKey*) kp->getPrivateKey())->setFromBotan(eckp); *ppKeyPair = kp; // Release the key delete eckp; return true; } unsigned long BotanECDSA::getMinKeySize() { // Smallest EC group is secp112r1 return 112; } unsigned long BotanECDSA::getMaxKeySize() { // Biggest EC group is secp521r1 return 521; } bool BotanECDSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData) { // Check input if ((ppKeyPair == NULL) || (serialisedData.size() == 0)) { return false; } ByteString dPub = ByteString::chainDeserialise(serialisedData); ByteString dPriv = ByteString::chainDeserialise(serialisedData); BotanECDSAKeyPair* kp = new BotanECDSAKeyPair(); bool rv = true; if (!((ECPublicKey*) kp->getPublicKey())->deserialise(dPub)) { rv = false; } if (!((ECPrivateKey*) kp->getPrivateKey())->deserialise(dPriv)) { rv = false; } if (!rv) { delete kp; return false; } *ppKeyPair = kp; return true; } bool BotanECDSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData) { // Check input if ((ppPublicKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanECDSAPublicKey* pub = new BotanECDSAPublicKey(); if (!pub->deserialise(serialisedData)) { delete pub; return false; } *ppPublicKey = pub; return true; } bool BotanECDSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData) { // Check input if ((ppPrivateKey == NULL) || (serialisedData.size() == 0)) { return false; } BotanECDSAPrivateKey* priv = new BotanECDSAPrivateKey(); if (!priv->deserialise(serialisedData)) { delete priv; return false; } *ppPrivateKey = priv; return true; } PublicKey* BotanECDSA::newPublicKey() { return (PublicKey*) new BotanECDSAPublicKey(); } PrivateKey* BotanECDSA::newPrivateKey() { return (PrivateKey*) new BotanECDSAPrivateKey(); } AsymmetricParameters* BotanECDSA::newParameters() { return (AsymmetricParameters*) new ECParameters(); } bool BotanECDSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData) { // Check input parameters if ((ppParams == NULL) || (serialisedData.size() == 0)) { return false; } ECParameters* params = new ECParameters(); if (!params->deserialise(serialisedData)) { delete params; return false; } *ppParams = params; return true; } #endif softhsm-2.0.0/src/lib/crypto/BotanSymmetricAlgorithm.h0000664000175000017500000000545412533040716017765 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanSymmetricAlgorithm.h Botan symmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANSYMMETRICALGORITHM_H #define _SOFTHSM_V2_BOTANSYMMETRICALGORITHM_H #include #include "config.h" #include "SymmetricKey.h" #include "SymmetricAlgorithm.h" #include class BotanSymmetricAlgorithm : public SymmetricAlgorithm { public: // Constructor BotanSymmetricAlgorithm(); // Destructor virtual ~BotanSymmetricAlgorithm(); // Encryption functions virtual bool encryptInit(const SymmetricKey* key, const SymMode::Type mode = SymMode::CBC, const ByteString& IV = ByteString(), bool padding = true); virtual bool encryptUpdate(const ByteString& data, ByteString& encryptedData); virtual bool encryptFinal(ByteString& encryptedData); // Decryption functions virtual bool decryptInit(const SymmetricKey* key, const SymMode::Type mode = SymMode::CBC, const ByteString& IV = ByteString(), bool padding = true); virtual bool decryptUpdate(const ByteString& encryptedData, ByteString& data); virtual bool decryptFinal(ByteString& data); // Return the block size virtual size_t getBlockSize() const = 0; protected: // Return the right cipher for the operation virtual std::string getCipher() const = 0; private: // The current context Botan::Pipe* cryption; }; #endif // !_SOFTHSM_V2_BOTANSYMMETRICALGORITHM_H softhsm-2.0.0/src/lib/crypto/OSSLDHKeyPair.cpp0000664000175000017500000000417112533040716015765 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDHKeyPair.cpp OpenSSL Diffie-Hellman key-pair class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLDHKeyPair.h" // Set the public key void OSSLDHKeyPair::setPublicKey(OSSLDHPublicKey& publicKey) { pubKey = publicKey; } // Set the private key void OSSLDHKeyPair::setPrivateKey(OSSLDHPrivateKey& privateKey) { privKey = privateKey; } // Return the public key PublicKey* OSSLDHKeyPair::getPublicKey() { return &pubKey; } const PublicKey* OSSLDHKeyPair::getConstPublicKey() const { return &pubKey; } // Return the private key PrivateKey* OSSLDHKeyPair::getPrivateKey() { return &privKey; } const PrivateKey* OSSLDHKeyPair::getConstPrivateKey() const { return &privKey; } softhsm-2.0.0/src/lib/crypto/ECPrivateKey.h0000664000175000017500000000513212533040716015442 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECPrivateKey.h Elliptic Curve private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_ECPRIVATEKEY_H #define _SOFTHSM_V2_ECPRIVATEKEY_H #include "config.h" #include "PrivateKey.h" class ECPrivateKey : public PrivateKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Get the base point order length virtual unsigned long getOrderLength() const = 0; // Setters for the EC private key components virtual void setD(const ByteString& inD); // Setters for the EC public key components virtual void setEC(const ByteString& inEC); // Getters for the EC private key components virtual const ByteString& getD() const; // Getters for the EC public key components virtual const ByteString& getEC() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Private components ByteString d; // Public components ByteString ec; }; #endif // !_SOFTHSM_V2_ECPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/AsymmetricKeyPair.h0000664000175000017500000000442112533040716016551 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** AsymmetricKeyPair.h Base class for asymmetric key-pair classes *****************************************************************************/ #ifndef _SOFTHSM_V2_ASYMMETRICKEYPAIR_H #define _SOFTHSM_V2_ASYMMETRICKEYPAIR_H #include "config.h" #include "ByteString.h" #include "PublicKey.h" #include "PrivateKey.h" #include "Serialisable.h" class AsymmetricKeyPair : public Serialisable { public: // Base constructors AsymmetricKeyPair() { } AsymmetricKeyPair(const AsymmetricKeyPair& /*in*/) { } // Destructor virtual ~AsymmetricKeyPair() { } // Return the public key virtual PublicKey* getPublicKey() = 0; virtual const PublicKey* getConstPublicKey() const = 0; // Return the private key virtual PrivateKey* getPrivateKey() = 0; virtual const PrivateKey* getConstPrivateKey() const = 0; // Serialise the contents virtual ByteString serialise() const; }; #endif // !_SOFTHSM_V2_ASYMMETRICKEYPAIR_H softhsm-2.0.0/src/lib/crypto/BotanECDHPrivateKey.cpp0000664000175000017500000001437112533040716017202 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDHPrivateKey.cpp Botan ECDH private key class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDHPrivateKey.h" #include "BotanCryptoFactory.h" #include "BotanRNG.h" #include "BotanUtil.h" #include #include #include #include #include #include // Constructors BotanECDHPrivateKey::BotanECDHPrivateKey() { eckey = NULL; } BotanECDHPrivateKey::BotanECDHPrivateKey(const Botan::ECDH_PrivateKey* inECKEY) { eckey = NULL; setFromBotan(inECKEY); } // Destructor BotanECDHPrivateKey::~BotanECDHPrivateKey() { delete eckey; } // The type /*static*/ const char* BotanECDHPrivateKey::type = "Botan ECDH Private Key"; // Get the base point order length unsigned long BotanECDHPrivateKey::getOrderLength() const { try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); return group.get_order().bytes(); } catch (...) { ERROR_MSG("Can't get EC group for order length"); return 0; } } // Set from Botan representation void BotanECDHPrivateKey::setFromBotan(const Botan::ECDH_PrivateKey* inECKEY) { ByteString inEC = BotanUtil::ecGroup2ByteString(inECKEY->domain()); setEC(inEC); ByteString inD = BotanUtil::bigInt2ByteString(inECKEY->private_value()); setD(inD); } // Check if the key is of the given type bool BotanECDHPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the ECDH private key components void BotanECDHPrivateKey::setD(const ByteString& inD) { ECPrivateKey::setD(inD); if (eckey) { delete eckey; eckey = NULL; } } // Setters for the ECDH public key components void BotanECDHPrivateKey::setEC(const ByteString& inEC) { ECPrivateKey::setEC(inEC); if (eckey) { delete eckey; eckey = NULL; } } // Encode into PKCS#8 DER ByteString BotanECDHPrivateKey::PKCS8Encode() { ByteString der; createBotanKey(); if (eckey == NULL) return der; const size_t PKCS8_VERSION = 0; // No OID for ECDH const Botan::OID oid("1.2.840.10045.2.1"); // Force EC_DOMPAR_ENC_OID #if BOTAN_VERSION_MINOR == 11 const std::vector parameters = eckey->domain().DER_encode(Botan::EC_DOMPAR_ENC_OID); const Botan::AlgorithmIdentifier alg_id(oid, parameters); const Botan::secure_vector ber = Botan::DER_Encoder() .start_cons(Botan::SEQUENCE) .encode(PKCS8_VERSION) .encode(alg_id) .encode(eckey->pkcs8_private_key(), Botan::OCTET_STRING) .end_cons() .get_contents(); #else const Botan::MemoryVector parameters = eckey->domain().DER_encode(Botan::EC_DOMPAR_ENC_OID); const Botan::AlgorithmIdentifier alg_id(oid, parameters); const Botan::SecureVector ber = Botan::DER_Encoder() .start_cons(Botan::SEQUENCE) .encode(PKCS8_VERSION) .encode(alg_id) .encode(eckey->pkcs8_private_key(), Botan::OCTET_STRING) .end_cons() .get_contents(); #endif der.resize(ber.size()); memcpy(&der[0], &ber[0], ber.size()); return der; } // Decode from PKCS#8 BER bool BotanECDHPrivateKey::PKCS8Decode(const ByteString& ber) { Botan::DataSource_Memory source(ber.const_byte_str(), ber.size()); if (source.end_of_data()) return false; #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector keydata; #else Botan::SecureVector keydata; #endif Botan::AlgorithmIdentifier alg_id; const Botan::OID oid("1.2.840.10045.2.1"); Botan::ECDH_PrivateKey* key = NULL; try { Botan::BER_Decoder(source) .start_cons(Botan::SEQUENCE) .decode_and_check(0, "Unknown PKCS #8 version number") .decode(alg_id) .decode(keydata, Botan::OCTET_STRING) .discard_remaining() .end_cons(); if (keydata.empty()) throw Botan::Decoding_Error("PKCS #8 private key decoding failed"); // Botan defines == but not != ?! if (!(alg_id.oid == oid)) { ERROR_MSG("Decoded private key not ECDH"); return false; } key = new Botan::ECDH_PrivateKey(alg_id, keydata); if (key == NULL) return false; setFromBotan(key); delete key; } catch (std::exception& e) { ERROR_MSG("Decode failed on %s", e.what()); return false; } return true; } // Retrieve the Botan representation of the key Botan::ECDH_PrivateKey* BotanECDHPrivateKey::getBotanKey() { if (!eckey) { createBotanKey(); } return eckey; } // Create the Botan representation of the key void BotanECDHPrivateKey::createBotanKey() { if (ec.size() != 0 && d.size() != 0) { if (eckey) { delete eckey; eckey = NULL; } try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); eckey = new Botan::ECDH_PrivateKey(*rng->getRNG(), group, BotanUtil::byteString2bigInt(d)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } #endif softhsm-2.0.0/src/lib/crypto/odd.h0000664000175000017500000000617712533040716013727 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** odd.h Odd parity table *****************************************************************************/ #ifndef _SOFTHSM_V2_ODD_H #define _SOFTHSM_V2_ODD_H const unsigned char odd_parity[256] = { 0x01, 0x01, 0x02, 0x02, 0x04, 0x04, 0x07, 0x07, 0x08, 0x08, 0x0B, 0x0B, 0x0D, 0x0D, 0x0E, 0x0E, 0x10, 0x10, 0x13, 0x13, 0x15, 0x15, 0x16, 0x16, 0x19, 0x19, 0x1A, 0x1A, 0x1C, 0x1C, 0x1F, 0x1F, 0x20, 0x20, 0x23, 0x23, 0x25, 0x25, 0x26, 0x26, 0x29, 0x29, 0x2A, 0x2A, 0x2C, 0x2C, 0x2F, 0x2F, 0x31, 0x31, 0x32, 0x32, 0x34, 0x34, 0x37, 0x37, 0x38, 0x38, 0x3B, 0x3B, 0x3D, 0x3D, 0x3E, 0x3E, 0x40, 0x40, 0x43, 0x43, 0x45, 0x45, 0x46, 0x46, 0x49, 0x49, 0x4A, 0x4A, 0x4C, 0x4C, 0x4F, 0x4F, 0x51, 0x51, 0x52, 0x52, 0x54, 0x54, 0x57, 0x57, 0x58, 0x58, 0x5B, 0x5B, 0x5D, 0x5D, 0x5E, 0x5E, 0x61, 0x61, 0x62, 0x62, 0x64, 0x64, 0x67, 0x67, 0x68, 0x68, 0x6B, 0x6B, 0x6D, 0x6D, 0x6E, 0x6E, 0x70, 0x70, 0x73, 0x73, 0x75, 0x75, 0x76, 0x76, 0x79, 0x79, 0x7A, 0x7A, 0x7C, 0x7C, 0x7F, 0x7F, 0x80, 0x80, 0x83, 0x83, 0x85, 0x85, 0x86, 0x86, 0x89, 0x89, 0x8A, 0x8A, 0x8C, 0x8C, 0x8F, 0x8F, 0x91, 0x91, 0x92, 0x92, 0x94, 0x94, 0x97, 0x97, 0x98, 0x98, 0x9B, 0x9B, 0x9D, 0x9D, 0x9E, 0x9E, 0xA1, 0xA1, 0xA2, 0xA2, 0xA4, 0xA4, 0xA7, 0xA7, 0xA8, 0xA8, 0xAB, 0xAB, 0xAD, 0xAD, 0xAE, 0xAE, 0xB0, 0xB0, 0xB3, 0xB3, 0xB5, 0xB5, 0xB6, 0xB6, 0xB9, 0xB9, 0xBA, 0xBA, 0xBC, 0xBC, 0xBF, 0xBF, 0xC1, 0xC1, 0xC2, 0xC2, 0xC4, 0xC4, 0xC7, 0xC7, 0xC8, 0xC8, 0xCB, 0xCB, 0xCD, 0xCD, 0xCE, 0xCE, 0xD0, 0xD0, 0xD3, 0xD3, 0xD5, 0xD5, 0xD6, 0xD6, 0xD9, 0xD9, 0xDA, 0xDA, 0xDC, 0xDC, 0xDF, 0xDF, 0xE0, 0xE0, 0xE3, 0xE3, 0xE5, 0xE5, 0xE6, 0xE6, 0xE9, 0xE9, 0xEA, 0xEA, 0xEC, 0xEC, 0xEF, 0xEF, 0xF1, 0xF1, 0xF2, 0xF2, 0xF4, 0xF4, 0xF7, 0xF7, 0xF8, 0xF8, 0xFB, 0xFB, 0xFD, 0xFD, 0xFE, 0xFE }; #endif // !_SOFTHSM_V2_ODD_H softhsm-2.0.0/src/lib/crypto/BotanGOST.h0000664000175000017500000000666612533040716014724 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanGOST.h Botan GOST R 34.10-2001 asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANGOST_H #define _SOFTHSM_V2_BOTANGOST_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class BotanGOST : public AsymmetricAlgorithm { public: // Constructor BotanGOST(); // Destructor virtual ~BotanGOST(); // Signing functions virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: Botan::PK_Signer* signer; Botan::PK_Verifier* verifier; }; #endif // !_SOFTHSM_V2_BOTANGOST_H softhsm-2.0.0/src/lib/crypto/SymmetricKey.h0000664000175000017500000000443112533040716015575 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SymmetricKey.h Base class for symmetric key classes *****************************************************************************/ #ifndef _SOFTHSM_V2_SYMMETRICKEY_H #define _SOFTHSM_V2_SYMMETRICKEY_H #include "config.h" #include "ByteString.h" #include "Serialisable.h" class SymmetricKey : public Serialisable { public: // Base constructors SymmetricKey(size_t inBitLen = 0); SymmetricKey(const SymmetricKey& in); // Destructor virtual ~SymmetricKey() { } // Set the key virtual bool setKeyBits(const ByteString& keybits); // Get the key virtual const ByteString& getKeyBits() const; // Serialisation virtual ByteString serialise() const; // Set the bit length virtual void setBitLen(const size_t inBitLen); // Retrieve the bit length virtual size_t getBitLen() const; protected: // The key ByteString keyData; // The key length in bits size_t bitLen; }; #endif // !_SOFTHSM_V2_SYMMETRICKEY_H softhsm-2.0.0/src/lib/crypto/BotanRSA.h0000664000175000017500000000746112533040716014567 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanRSA.h Botan RSA asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANRSA_H #define _SOFTHSM_V2_BOTANRSA_H #include "config.h" #include "AsymmetricAlgorithm.h" #include "HashAlgorithm.h" #include class BotanRSA : public AsymmetricAlgorithm { public: // Constructor BotanRSA(); // Destructor virtual ~BotanRSA(); // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: Botan::PK_Signer* signer; Botan::PK_Verifier* verifier; }; #endif // !_SOFTHSM_V2_BOTANRSA_H softhsm-2.0.0/src/lib/crypto/ECPrivateKey.cpp0000664000175000017500000000547112533040716016003 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECPrivateKey.cpp Elliptic Curve private key class *****************************************************************************/ #include "config.h" #include "log.h" #include "ECPrivateKey.h" #include // Set the type /*static*/ const char* ECPrivateKey::type = "Abstract EC private key"; // Check if the key is of the given type bool ECPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Get the bit length unsigned long ECPrivateKey::getBitLength() const { return getD().bits(); } // Get the output length unsigned long ECPrivateKey::getOutputLength() const { return getOrderLength() * 2; } // Setters for the EC private key components void ECPrivateKey::setD(const ByteString& inD) { d = inD; } // Setters for the EC public key components void ECPrivateKey::setEC(const ByteString& inEC) { ec = inEC; } // Getters for the EC private key components const ByteString& ECPrivateKey::getD() const { return d; } // Getters for the EC public key components const ByteString& ECPrivateKey::getEC() const { return ec; } // Serialisation ByteString ECPrivateKey::serialise() const { return ec.serialise() + d.serialise(); } bool ECPrivateKey::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); ByteString dD = ByteString::chainDeserialise(serialised); if ((dEC.size() == 0) || (dD.size() == 0)) { return false; } setEC(dEC); setD(dD); return true; } softhsm-2.0.0/src/lib/crypto/DHParameters.h0000664000175000017500000000474712533040716015501 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** DHParameters.h Diffie-Hellman parameters (only used for key generation) *****************************************************************************/ #ifndef _SOFTHSM_V2_DHPARAMETERS_H #define _SOFTHSM_V2_DHPARAMETERS_H #include "config.h" #include "ByteString.h" #include "AsymmetricParameters.h" class DHParameters : public AsymmetricParameters { public: // Base constructors DHParameters() : bitLen(0) { } // The type static const char* type; // Set the public prime p void setP(const ByteString& inP); // Set the generator g void setG(const ByteString& inG); // Set the optional bit length void setXBitLength(const size_t inBitLen); // Get the public prime p const ByteString& getP() const; // Get the generator g const ByteString& getG() const; // Get the optional bit length size_t getXBitLength() const; // Are the parameters of the given type? virtual bool areOfType(const char* inType); // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); private: ByteString p; ByteString g; size_t bitLen; }; #endif // !_SOFTHSM_V2_DHPARAMETERS_H softhsm-2.0.0/src/lib/crypto/OSSLSHA1.h0000664000175000017500000000344712533040716014353 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLSHA1.h OpenSSL SHA1 implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLSHA1_H #define _SOFTHSM_V2_OSSLSHA1_H #include "config.h" #include "OSSLEVPHashAlgorithm.h" #include class OSSLSHA1 : public OSSLEVPHashAlgorithm { virtual int getHashSize(); protected: virtual const EVP_MD* getEVPHash() const; }; #endif // !_SOFTHSM_V2_OSSLSHA1_H softhsm-2.0.0/src/lib/crypto/GOSTPublicKey.h0000664000175000017500000000462512533040716015541 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** GOSTPublicKey.h GOST R 34.10-2001 public key class *****************************************************************************/ #ifndef _SOFTHSM_V2_GOSTPUBLICKEY_H #define _SOFTHSM_V2_GOSTPUBLICKEY_H #include "config.h" #include "PublicKey.h" class GOSTPublicKey : public PublicKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const = 0; // Setters for the GOST public key components virtual void setQ(const ByteString& inQ); virtual void setEC(const ByteString& inEC); // Getters for the GOST public key components virtual const ByteString& getQ() const; virtual const ByteString& getEC() const; // Serialisation virtual ByteString serialise() const = 0; virtual bool deserialise(ByteString& serialised) = 0; protected: // Public components ByteString q, ec; }; #endif // !_SOFTHSM_V2_GOSTPUBLICKEY_H softhsm-2.0.0/src/lib/crypto/OSSLEVPSymmetricAlgorithm.h0000664000175000017500000000545212533040716020053 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLEVPSymmetricAlgorithm.h OpenSSL symmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLEVPSYMMETRICALGORITHM_H #define _SOFTHSM_V2_OSSLEVPSYMMETRICALGORITHM_H #include #include #include "config.h" #include "SymmetricKey.h" #include "SymmetricAlgorithm.h" class OSSLEVPSymmetricAlgorithm : public SymmetricAlgorithm { public: // Constructor OSSLEVPSymmetricAlgorithm(); // Destructor virtual ~OSSLEVPSymmetricAlgorithm(); // Encryption functions virtual bool encryptInit(const SymmetricKey* key, const SymMode::Type mode = SymMode::CBC, const ByteString& IV = ByteString(), bool padding = true); virtual bool encryptUpdate(const ByteString& data, ByteString& encryptedData); virtual bool encryptFinal(ByteString& encryptedData); // Decryption functions virtual bool decryptInit(const SymmetricKey* key, const SymMode::Type mode = SymMode::CBC, const ByteString& IV = ByteString(), bool padding = true); virtual bool decryptUpdate(const ByteString& encryptedData, ByteString& data); virtual bool decryptFinal(ByteString& data); // Return the block size virtual size_t getBlockSize() const = 0; protected: // Return the right EVP cipher for the operation virtual const EVP_CIPHER* getCipher() const = 0; private: // The current EVP context EVP_CIPHER_CTX* pCurCTX; }; #endif // !_SOFTHSM_V2_OSSLEVPSYMMETRICALGORITHM_H softhsm-2.0.0/src/lib/crypto/ECParameters.cpp0000664000175000017500000000441112533040716016014 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** ECParameters.cpp Elliptic Curve parameters (only used for key generation) *****************************************************************************/ #include "config.h" #include "log.h" #include "ECParameters.h" #include // The type /*static*/ const char* ECParameters::type = "Generic EC parameters"; // Set the curve OID ec void ECParameters::setEC(const ByteString& inEC) { ec = inEC; } // Get the curve OID ec const ByteString& ECParameters::getEC() const { return ec; } // Are the parameters of the given type? bool ECParameters::areOfType(const char* inType) { return (strcmp(type, inType) == 0); } // Serialisation ByteString ECParameters::serialise() const { return ec.serialise(); } bool ECParameters::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); if (dEC.size() == 0) { return false; } setEC(dEC); return true; } softhsm-2.0.0/src/lib/crypto/SymmetricKey.cpp0000664000175000017500000000451212533040716016130 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** SymmetricKey.cpp Base class for symmetric key classes *****************************************************************************/ #include "config.h" #include "ByteString.h" #include "Serialisable.h" #include "SymmetricKey.h" // Base constructors SymmetricKey::SymmetricKey(size_t inBitLen /* = 0 */) { bitLen = inBitLen; } SymmetricKey::SymmetricKey(const SymmetricKey& in) { keyData = in.keyData; bitLen = in.bitLen; } // Set the key bool SymmetricKey::setKeyBits(const ByteString& keybits) { if ((bitLen > 0) && ((keybits.size() * 8) != bitLen)) { return false; } keyData = keybits; return true; } // Get the key const ByteString& SymmetricKey::getKeyBits() const { return keyData; } // Serialisation ByteString SymmetricKey::serialise() const { return keyData; } // Set the bit length void SymmetricKey::setBitLen(const size_t inBitLen) { bitLen = inBitLen; } // Retrieve the bit length size_t SymmetricKey::getBitLen() const { return bitLen; } softhsm-2.0.0/src/lib/crypto/OSSLRSAPublicKey.cpp0000664000175000017500000000603412533040716016442 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLRSAPublicKey.cpp OpenSSL RSA public key class *****************************************************************************/ #include "config.h" #include "log.h" #include "OSSLRSAPublicKey.h" #include "OSSLUtil.h" #include #include // Constructors OSSLRSAPublicKey::OSSLRSAPublicKey() { rsa = RSA_new(); // Use the OpenSSL implementation and not any engine RSA_set_method(rsa, RSA_get_default_method()); } OSSLRSAPublicKey::OSSLRSAPublicKey(const RSA* inRSA) { rsa = RSA_new(); // Use the OpenSSL implementation and not any engine RSA_set_method(rsa, RSA_PKCS1_SSLeay()); setFromOSSL(inRSA); } // Destructor OSSLRSAPublicKey::~OSSLRSAPublicKey() { RSA_free(rsa); } // The type /*static*/ const char* OSSLRSAPublicKey::type = "OpenSSL RSA Public Key"; // Check if the key is of the given type bool OSSLRSAPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Set from OpenSSL representation void OSSLRSAPublicKey::setFromOSSL(const RSA* inRSA) { if (inRSA->n) { ByteString inN = OSSL::bn2ByteString(inRSA->n); setN(inN); } if (inRSA->e) { ByteString inE = OSSL::bn2ByteString(inRSA->e); setE(inE); } } // Setters for the RSA public key components void OSSLRSAPublicKey::setN(const ByteString& inN) { RSAPublicKey::setN(inN); if (rsa->n) { BN_clear_free(rsa->n); rsa->n = NULL; } rsa->n = OSSL::byteString2bn(inN); } void OSSLRSAPublicKey::setE(const ByteString& inE) { RSAPublicKey::setE(inE); if (rsa->e) { BN_clear_free(rsa->e); rsa->e = NULL; } rsa->e = OSSL::byteString2bn(inE); } // Retrieve the OpenSSL representation of the key RSA* OSSLRSAPublicKey::getOSSLKey() { return rsa; } softhsm-2.0.0/src/lib/crypto/OSSLGOSTPublicKey.cpp0000664000175000017500000001040112533040716016562 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLGOSTPublicKey.cpp OpenSSL GOST R 34.10-2001 public key class *****************************************************************************/ #include "config.h" #ifdef WITH_GOST #include "log.h" #include "OSSLGOSTPublicKey.h" #include #include // the 37 bytes of prefix const unsigned char gost_prefix[] = { 0x30, 0x63, 0x30, 0x1c, 0x06, 0x06, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x13, 0x30, 0x12, 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x23, 0x01, 0x06, 0x07, 0x2a, 0x85, 0x03, 0x02, 0x02, 0x1e, 0x01, 0x03, 0x43, 0x00, 0x04, 0x40 }; // Constructors OSSLGOSTPublicKey::OSSLGOSTPublicKey() { pkey = EVP_PKEY_new(); } OSSLGOSTPublicKey::OSSLGOSTPublicKey(const EVP_PKEY* inPKEY) { OSSLGOSTPublicKey(); setFromOSSL(inPKEY); } // Destructor OSSLGOSTPublicKey::~OSSLGOSTPublicKey() { EVP_PKEY_free(pkey); } // The type /*static*/ const char* OSSLGOSTPublicKey::type = "OpenSSL GOST Public Key"; // Get the output length unsigned long OSSLGOSTPublicKey::getOutputLength() const { return getQ().size(); } // Set from OpenSSL representation void OSSLGOSTPublicKey::setFromOSSL(const EVP_PKEY* pkey) { ByteString der; int len = i2d_PUBKEY((EVP_PKEY*) pkey, NULL); if (len != 37 + 64) { ERROR_MSG("bad GOST public key encoding length %d", len); return; } der.resize(len); unsigned char *p = &der[0]; i2d_PUBKEY((EVP_PKEY*) pkey, &p); // can check: der is prefix + 64 bytes setQ(der.substr(37)); ByteString inEC; const EC_KEY* eckey = (const EC_KEY*) EVP_PKEY_get0((EVP_PKEY*) pkey); int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(eckey)); inEC.resize(i2d_ASN1_OBJECT(OBJ_nid2obj(nid), NULL)); p = &inEC[0]; i2d_ASN1_OBJECT(OBJ_nid2obj(nid), &p); setEC(inEC); } // Check if the key is of the given type bool OSSLGOSTPublicKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the GOST public key components void OSSLGOSTPublicKey::setEC(const ByteString& inEC) { GOSTPublicKey::setEC(inEC); } void OSSLGOSTPublicKey::setQ(const ByteString& inQ) { GOSTPublicKey::setQ(inQ); if (inQ.size() != 64) { ERROR_MSG("bad GOST public key size %zu", q.size()); return; } ByteString der; der.resize(37 + 64); memcpy(&der[0], gost_prefix, 37); memcpy(&der[37], inQ.const_byte_str(), 64); const unsigned char *p = &der[0]; if (d2i_PUBKEY(&pkey, &p, (long) der.size()) == NULL) ERROR_MSG("d2i_PUBKEY failed"); } // Serialisation ByteString OSSLGOSTPublicKey::serialise() const { return ec.serialise() + q.serialise(); } bool OSSLGOSTPublicKey::deserialise(ByteString& serialised) { ByteString dEC = ByteString::chainDeserialise(serialised); ByteString dQ = ByteString::chainDeserialise(serialised); if ((dEC.size() == 0) || (dQ.size() == 0)) { return false; } setEC(dEC); setQ(dQ); return true; } // Retrieve the OpenSSL representation of the key EVP_PKEY* OSSLGOSTPublicKey::getOSSLKey() { return pkey; } #endif softhsm-2.0.0/src/lib/crypto/BotanECDSAPrivateKey.cpp0000664000175000017500000001427412533040716017320 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanECDSAPrivateKey.cpp Botan ECDSA private key class *****************************************************************************/ #include "config.h" #ifdef WITH_ECC #include "log.h" #include "BotanECDSAPrivateKey.h" #include "BotanCryptoFactory.h" #include "BotanRNG.h" #include "BotanUtil.h" #include #include #include #include #include #include // Constructors BotanECDSAPrivateKey::BotanECDSAPrivateKey() { eckey = NULL; } BotanECDSAPrivateKey::BotanECDSAPrivateKey(const Botan::ECDSA_PrivateKey* inECKEY) { eckey = NULL; setFromBotan(inECKEY); } // Destructor BotanECDSAPrivateKey::~BotanECDSAPrivateKey() { delete eckey; } // The type /*static*/ const char* BotanECDSAPrivateKey::type = "Botan ECDSA Private Key"; // Get the base point order length unsigned long BotanECDSAPrivateKey::getOrderLength() const { try { Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); return group.get_order().bytes(); } catch (...) { ERROR_MSG("Can't get EC group for order length"); return 0; } } // Set from Botan representation void BotanECDSAPrivateKey::setFromBotan(const Botan::ECDSA_PrivateKey* inECKEY) { ByteString inEC = BotanUtil::ecGroup2ByteString(inECKEY->domain()); setEC(inEC); ByteString inD = BotanUtil::bigInt2ByteString(inECKEY->private_value()); setD(inD); } // Check if the key is of the given type bool BotanECDSAPrivateKey::isOfType(const char* inType) { return !strcmp(type, inType); } // Setters for the ECDSA private key components void BotanECDSAPrivateKey::setD(const ByteString& inD) { ECPrivateKey::setD(inD); if (eckey) { delete eckey; eckey = NULL; } } // Setters for the ECDSA public key components void BotanECDSAPrivateKey::setEC(const ByteString& inEC) { ECPrivateKey::setEC(inEC); if (eckey) { delete eckey; eckey = NULL; } } // Encode into PKCS#8 DER ByteString BotanECDSAPrivateKey::PKCS8Encode() { ByteString der; createBotanKey(); if (eckey == NULL) return der; // Force EC_DOMPAR_ENC_OID const size_t PKCS8_VERSION = 0; #if BOTAN_VERSION_MINOR == 11 const std::vector parameters = eckey->domain().DER_encode(Botan::EC_DOMPAR_ENC_OID); const Botan::AlgorithmIdentifier alg_id(eckey->get_oid(), parameters); const Botan::secure_vector ber = Botan::DER_Encoder() .start_cons(Botan::SEQUENCE) .encode(PKCS8_VERSION) .encode(alg_id) .encode(eckey->pkcs8_private_key(), Botan::OCTET_STRING) .end_cons() .get_contents(); #else const Botan::MemoryVector parameters = eckey->domain().DER_encode(Botan::EC_DOMPAR_ENC_OID); const Botan::AlgorithmIdentifier alg_id(eckey->get_oid(), parameters); const Botan::SecureVector ber = Botan::DER_Encoder() .start_cons(Botan::SEQUENCE) .encode(PKCS8_VERSION) .encode(alg_id) .encode(eckey->pkcs8_private_key(), Botan::OCTET_STRING) .end_cons() .get_contents(); #endif der.resize(ber.size()); memcpy(&der[0], &ber[0], ber.size()); return der; } // Decode from PKCS#8 BER bool BotanECDSAPrivateKey::PKCS8Decode(const ByteString& ber) { Botan::DataSource_Memory source(ber.const_byte_str(), ber.size()); if (source.end_of_data()) return false; #if BOTAN_VERSION_MINOR == 11 Botan::secure_vector keydata; #else Botan::SecureVector keydata; #endif Botan::AlgorithmIdentifier alg_id; Botan::ECDSA_PrivateKey* key = NULL; try { Botan::BER_Decoder(source) .start_cons(Botan::SEQUENCE) .decode_and_check(0, "Unknown PKCS #8 version number") .decode(alg_id) .decode(keydata, Botan::OCTET_STRING) .discard_remaining() .end_cons(); if (keydata.empty()) throw Botan::Decoding_Error("PKCS #8 private key decoding failed"); if (Botan::OIDS::lookup(alg_id.oid).compare("ECDSA")) { ERROR_MSG("Decoded private key not ECDSA"); return false; } key = new Botan::ECDSA_PrivateKey(alg_id, keydata); if (key == NULL) return false; setFromBotan(key); delete key; } catch (std::exception& e) { ERROR_MSG("Decode failed on %s", e.what()); return false; } return true; } // Retrieve the Botan representation of the key Botan::ECDSA_PrivateKey* BotanECDSAPrivateKey::getBotanKey() { if (!eckey) { createBotanKey(); } return eckey; } // Create the Botan representation of the key void BotanECDSAPrivateKey::createBotanKey() { if (ec.size() != 0 && d.size() != 0) { if (eckey) { delete eckey; eckey = NULL; } try { BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG(); Botan::EC_Group group = BotanUtil::byteString2ECGroup(ec); eckey = new Botan::ECDSA_PrivateKey(*rng->getRNG(), group, BotanUtil::byteString2bigInt(d)); } catch (...) { ERROR_MSG("Could not create the Botan public key"); } } } #endif softhsm-2.0.0/src/lib/crypto/BotanDSA.h0000664000175000017500000000760312533040716014547 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanDSA.h Botan DSA asymmetric algorithm implementation *****************************************************************************/ #ifndef _SOFTHSM_V2_BOTANDSA_H #define _SOFTHSM_V2_BOTANDSA_H #include "config.h" #include "AsymmetricAlgorithm.h" #include class BotanDSA : public AsymmetricAlgorithm { public: // Constructor BotanDSA(); // Destructor virtual ~BotanDSA(); // Signing functions virtual bool sign(PrivateKey* privateKey, const ByteString& dataToSign, ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signInit(PrivateKey* privateKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool signUpdate(const ByteString& dataToSign); virtual bool signFinal(ByteString& signature); // Verification functions virtual bool verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism, const void* param = NULL, const size_t paramLen = 0); virtual bool verifyUpdate(const ByteString& originalData); virtual bool verifyFinal(const ByteString& signature); // Encryption functions virtual bool encrypt(PublicKey* publicKey, const ByteString& data, ByteString& encryptedData, const AsymMech::Type padding); // Decryption functions virtual bool decrypt(PrivateKey* privateKey, const ByteString& encryptedData, ByteString& data, const AsymMech::Type padding); // Key factory virtual bool generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* rng = NULL); virtual unsigned long getMinKeySize(); virtual unsigned long getMaxKeySize(); virtual bool generateParameters(AsymmetricParameters** ppParams, void* parameters = NULL, RNG* rng = NULL); virtual bool reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData); virtual bool reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData); virtual bool reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData); virtual bool reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData); virtual PublicKey* newPublicKey(); virtual PrivateKey* newPrivateKey(); virtual AsymmetricParameters* newParameters(); private: Botan::PK_Signer* signer; Botan::PK_Verifier* verifier; }; #endif // !_SOFTHSM_V2_BOTANDSA_H softhsm-2.0.0/src/lib/crypto/BotanHMAC.cpp0000664000175000017500000000472612533040716015206 00000000000000/* * Copyright (c) 2010 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** BotanHMAC.cpp Botan HMAC implementation *****************************************************************************/ #include "config.h" #include "BotanHMAC.h" std::string BotanHMACMD5::getHash() const { return "MD5"; } size_t BotanHMACMD5::getMacSize() const { return 16; } std::string BotanHMACSHA1::getHash() const { return "SHA-1"; } size_t BotanHMACSHA1::getMacSize() const { return 20; } std::string BotanHMACSHA224::getHash() const { return "SHA-224"; } size_t BotanHMACSHA224::getMacSize() const { return 28; } std::string BotanHMACSHA256::getHash() const { return "SHA-256"; } size_t BotanHMACSHA256::getMacSize() const { return 32; } std::string BotanHMACSHA384::getHash() const { return "SHA-384"; } size_t BotanHMACSHA384::getMacSize() const { return 48; } std::string BotanHMACSHA512::getHash() const { return "SHA-512"; } size_t BotanHMACSHA512::getMacSize() const { return 64; } #ifdef WITH_GOST std::string BotanHMACGOSTR3411::getHash() const { return "GOST-34.11"; } size_t BotanHMACGOSTR3411::getMacSize() const { return 32; } #endif softhsm-2.0.0/src/lib/crypto/RSAPrivateKey.h0000664000175000017500000000602412533040716015601 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** RSAPrivateKey.h RSA private key class *****************************************************************************/ #ifndef _SOFTHSM_V2_RSAPRIVATEKEY_H #define _SOFTHSM_V2_RSAPRIVATEKEY_H #include "config.h" #include "PrivateKey.h" class RSAPrivateKey : public PrivateKey { public: // The type static const char* type; // Check if the key is of the given type virtual bool isOfType(const char* inType); // Get the bit length virtual unsigned long getBitLength() const; // Get the output length virtual unsigned long getOutputLength() const; // Setters for the RSA private key components virtual void setP(const ByteString& inP); virtual void setQ(const ByteString& inQ); virtual void setPQ(const ByteString& inPQ); virtual void setDP1(const ByteString& inDP1); virtual void setDQ1(const ByteString& inDQ1); virtual void setD(const ByteString& inD); // Setters for the RSA public key components virtual void setN(const ByteString& inN); virtual void setE(const ByteString& inE); // Getters for the RSA private key components virtual const ByteString& getP() const; virtual const ByteString& getQ() const; virtual const ByteString& getPQ() const; virtual const ByteString& getDP1() const; virtual const ByteString& getDQ1() const; virtual const ByteString& getD() const; // Getters for the RSA public key components virtual const ByteString& getN() const; virtual const ByteString& getE() const; // Serialisation virtual ByteString serialise() const; virtual bool deserialise(ByteString& serialised); protected: // Private components ByteString p,q,pq,dp1,dq1,d; // Public components ByteString n,e; }; #endif // !_SOFTHSM_V2_RSAPRIVATEKEY_H softhsm-2.0.0/src/lib/crypto/OSSLDSAKeyPair.h0000664000175000017500000000440212533040716015543 00000000000000/* * Copyright (c) 2010 SURFnet bv * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** OSSLDSAKeyPair.h OpenSSL DSA key-pair class *****************************************************************************/ #ifndef _SOFTHSM_V2_OSSLDSAKEYPAIR_H #define _SOFTHSM_V2_OSSLDSAKEYPAIR_H #include "config.h" #include "AsymmetricKeyPair.h" #include "OSSLDSAPublicKey.h" #include "OSSLDSAPrivateKey.h" class OSSLDSAKeyPair : public AsymmetricKeyPair { public: // Set the public key void setPublicKey(OSSLDSAPublicKey& publicKey); // Set the private key void setPrivateKey(OSSLDSAPrivateKey& privateKey); // Return the public key virtual PublicKey* getPublicKey(); virtual const PublicKey* getConstPublicKey() const; // Return the private key virtual PrivateKey* getPrivateKey(); virtual const PrivateKey* getConstPrivateKey() const; private: // The public key OSSLDSAPublicKey pubKey; // The private key OSSLDSAPrivateKey privKey; }; #endif // !_SOFTHSM_V2_OSSLDSAKEYPAIR_H softhsm-2.0.0/src/lib/P11Objects.cpp0000664000175000017500000014567712533040716014060 00000000000000/* * Copyright (c) 2011 .SE (The Internet Infrastructure Foundation) * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 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. */ /***************************************************************************** P11Objects.cpp This class respresent a PKCS#11 object *****************************************************************************/ #include "config.h" #include "P11Objects.h" #include #include // Constructor P11Object::P11Object() { initialized = false; osobject = NULL; } // Destructor P11Object::~P11Object() { std::map cleanUp = attributes; attributes.clear(); for (std::map::iterator i = cleanUp.begin(); i != cleanUp.end(); i++) { if (i->second == NULL) { continue; } delete i->second; i->second = NULL; } } // Add attributes bool P11Object::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; osobject = inobject; // Create attributes P11Attribute* attrClass = new P11AttrClass(osobject); P11Attribute* attrToken = new P11AttrToken(osobject); P11Attribute* attrPrivate = new P11AttrPrivate(osobject); P11Attribute* attrModifiable = new P11AttrModifiable(osobject); P11Attribute* attrLabel = new P11AttrLabel(osobject); P11Attribute* attrCopyable = new P11AttrCopyable(osobject); // Initialize the attributes if ( !attrClass->init() || !attrToken->init() || !attrPrivate->init() || !attrModifiable->init() || !attrLabel->init() || !attrCopyable->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrClass; delete attrToken; delete attrPrivate; delete attrModifiable; delete attrLabel; delete attrCopyable; return false; } // Add them to the map attributes[attrClass->getType()] = attrClass; attributes[attrToken->getType()] = attrToken; attributes[attrPrivate->getType()] = attrPrivate; attributes[attrModifiable->getType()] = attrModifiable; attributes[attrLabel->getType()] = attrLabel; attributes[attrCopyable->getType()] = attrCopyable; initialized = true; return true; } CK_RV P11Object::loadTemplate(Token *token, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount) { bool isPrivate = this->isPrivate(); // [PKCS#11 v2.3 pg.131] // 1. If the specified attribute (i.e. the attribute specified by the // type field) for the object cannot be revealed because the object // is sensitive or unextractable, then the ulValueLen field in that // tripple is modified to hold the value -1 (i.e., when it is cast // to a CK_LONG, it holds -1). // // 2. Otherwise, if the specified attribute for the object is invalid // (the object does not possess such and attribute), then the // ulValueLen field in that triple is modified to hold the value -1. // // 3. Otherwise, if the pValue field has the value NULL_PTR, then the // ulValueLen field is modified to hold the exact length of the // specified attribute for the object. // // 4. Otherwise, if the length specified in ulValueLen is large enough // to hold the value of the specified attribute for the object, then // that attribute is copied into the buffer located at pValue, and // the ulValueLen field is modified to hold the exact length of the // attribute. // // 5. Otherwise, the ulValueLen field is modified to hold the value -1. // If case 3 or 4 applies to all the requested attributes, then the call will return CKR_OK. for (CK_ULONG i = 0; i < ulAttributeCount; ++i) { P11Attribute* attr = attributes[pTemplate[i].type]; // case 2 of the attribute checks if (attr == NULL) { pTemplate[i].ulValueLen = (CK_ULONG)-1; // If case 2 applies to any of the requested attributes, then the call should // return the value CKR_ATTRIBUTE_TYPE_INVALID. return CKR_ATTRIBUTE_TYPE_INVALID; } // case 1,3,4 and 5 of the attribute checks are done while retrieving the attribute itself. CK_RV retrieve_rv = attr->retrieve(token, isPrivate, pTemplate[i].pValue, &pTemplate[i].ulValueLen); if (retrieve_rv != CKR_OK) { // If case 1 applies to any of the requested attributes, then the call should // return the value CKR_ATTRIBUTE_SENSITIVE. // If case 5 applies to any of the requested attributes, then the call should // return the value CKR_BUFFER_TOO_SMALL. return retrieve_rv; } } // As usual if more than one of these error codes is applicable, Cryptoki may // return any of them. Only if none of them applies to any of the requested // attributes will CKR_OK be returned. return CKR_OK; } // Save template CK_RV P11Object::saveTemplate(Token *token, bool isPrivate, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulAttributeCount, int op) { if (osobject == NULL) return CKR_GENERAL_ERROR; if (osobject->startTransaction() == false) return CKR_GENERAL_ERROR; // [PKCS#11 v2.3 pg. 62] OBJECT_OP_COPY // If the CKA_COPYABLE attribute of the object to be copied is set to CK_FALSE, C_CopyObject // returns CKR_COPY_PROHIBITED. if (op == OBJECT_OP_COPY) { if (!isCopyable()) { osobject->abortTransaction(); return CKR_COPY_PROHIBITED; } } for (CK_ULONG i = 0; i < ulAttributeCount; i++) { // [PKCS#11 v2.3 pg. 61] OBJECT_OP_CREATE | OBJECT_OP_SET | OBJECT_OP_COPY // 1. If the supplied template specifies a value for an invalid attribute, then the attempt // should fail with the error code CKR_ATTRIBUTE_TYPE_INVALID. An attribute // is valid if it is either one of the attributes described in the Cryptoki specification or an // additional vendor-specific attribute supported by the library and token. P11Attribute* attr = attributes[pTemplate[i].type]; if (attr == NULL) { osobject->abortTransaction(); return CKR_ATTRIBUTE_TYPE_INVALID; } // Additonal checks are done while updating the attributes themselves. CK_RV rv = attr->update(token,isPrivate, pTemplate[i].pValue, pTemplate[i].ulValueLen, op); if (rv != CKR_OK) { osobject->abortTransaction(); return rv; } } // [PKCS#11 v2.3 pg. 60] // 4. If the attribute values in the supplied template, together with any default attribute // values and any attribute values contributed to the object by the object-creation // function itself, are insufficient to fully specify the object to create, then the attempt // should fail with the error code CKR_TEMPLATE_INCOMPLETE. // All attributes that have to be specified are marked as such in the specification. // The following checks are relevant here: for (std::map::iterator i = attributes.begin(); i != attributes.end(); i++) { CK_ULONG checks = i->second->getChecks(); // ck1 Must be specified when object is created with C_CreateObject. // ck3 Must be specified when object is generated with C_GenerateKey or C_GenerateKeyPair. // ck5 Must be specified when object is unwrapped with C_UnwrapKey. if (((checks & P11Attribute::ck1) == P11Attribute::ck1 && op == OBJECT_OP_CREATE) || ((checks & P11Attribute::ck3) == P11Attribute::ck3 && op == OBJECT_OP_GENERATE) || ((checks & P11Attribute::ck5) == P11Attribute::ck5 && op == OBJECT_OP_UNWRAP)) { bool isSpecified = false; for (CK_ULONG n = 0; n < ulAttributeCount; n++) { if (i->first == pTemplate[n].type) { isSpecified = true; break; } } if (!isSpecified) { ERROR_MSG("Mandatory attribute (0x%08X) was not specified in template", (unsigned int)i->first); return CKR_TEMPLATE_INCOMPLETE; } } } // [PKCS#11 v2.3 pg. 60] // 5. If the attribute values in the supplied template, together with any default attribute // values and any attribute values contributed to the object by the object-creation // function itself, are inconsistent, then the attempt should fail with the error code // CKR_TEMPLATE_INCONSISTENT. A set of attribute values is inconsistent if not // all of its members can be satisfied simultaneously by the token, although each value // individually is valid in Cryptoki. One example of an inconsistent template would be // using a template which specifies two different values for the same attribute. Another // example would be trying to create a secret key object with an attribute which is // appropriate for various types of public keys or private keys, but not for secret keys. // A final example would be a template with an attribute that violates some token // specific requirement. Note that this final example of an inconsistent template is // token-dependent—on a different token, such a template might not be inconsistent. if (osobject->commitTransaction() == false) { return CKR_GENERAL_ERROR; } return CKR_OK; } bool P11Object::isPrivate() { // Get the CKA_PRIVATE attribute, when the attribute is // not present return the default value which we have // chosen to be CK_FALSE. if (!osobject->attributeExists(CKA_PRIVATE)) return false; return osobject->getBooleanValue(CKA_PRIVATE, false); } bool P11Object::isCopyable() { // Get the CKA_COPYABLE attribute, when the attribute is not // present return the default value which is CK_TRUE. if (!osobject->attributeExists(CKA_COPYABLE)) return true; return osobject->getBooleanValue(CKA_COPYABLE, true); } bool P11Object::isModifiable() { // Get the CKA_MODIFIABLE attribute, when the attribute is // not present return the default value which is CK_TRUE. if (!osobject->attributeExists(CKA_MODIFIABLE)) return true; return osobject->getBooleanValue(CKA_MODIFIABLE, true); } // Constructor P11DataObj::P11DataObj() { initialized = false; } // Add attributes bool P11DataObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; // Set default values for attributes that will be introduced in the parent if (!inobject->attributeExists(CKA_CLASS) || inobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_DATA) { OSAttribute setClass((unsigned long)CKO_DATA); inobject->setAttribute(CKA_CLASS, setClass); } // Create parent if (!P11Object::init(inobject)) return false; // Create attributes P11Attribute* attrApplication = new P11AttrApplication(osobject); P11Attribute* attrObjectID = new P11AttrObjectID(osobject); // NOTE: There is no mention in the PKCS#11 v2.3 spec that for a Data // Object the CKA_VALUE attribute may be modified after creation ! // Therefore we assume it is not allowed to change the CKA_VALUE // attribute of a Data Object. P11Attribute* attrValue = new P11AttrValue(osobject,0); // Initialize the attributes if ( !attrApplication->init() || !attrObjectID->init() || !attrValue->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrApplication; delete attrObjectID; delete attrValue; return false; } // Add them to the map attributes[attrApplication->getType()] = attrApplication; attributes[attrObjectID->getType()] = attrObjectID; attributes[attrValue->getType()] = attrValue; initialized = true; return true; } // Constructor P11CertificateObj::P11CertificateObj() { initialized = false; } // Add attributes bool P11CertificateObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; // Set default values for attributes that will be introduced in the parent if (!inobject->attributeExists(CKA_CLASS) || inobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_CERTIFICATE) { OSAttribute setClass((unsigned long)CKO_CERTIFICATE); inobject->setAttribute(CKA_CLASS, setClass); } // Create parent if (!P11Object::init(inobject)) return false; // Create attributes P11Attribute* attrCertificateType = new P11AttrCertificateType(osobject); P11Attribute* attrTrusted = new P11AttrTrusted(osobject); P11Attribute* attrCertificateCategory = new P11AttrCertificateCategory(osobject); // TODO: CKA_CHECK_VALUE is accepted, but we do not calculate it P11Attribute* attrCheckValue = new P11AttrCheckValue(osobject); // NOTE: Because these attributes are used in a certificate object // where the CKA_VALUE containing the certificate data is not // modifiable, we assume that this attribute is also not modifiable. // There is also no explicit mention of these attributes being modifiable. P11Attribute* attrStartDate = new P11AttrStartDate(osobject,0); P11Attribute* attrEndDate = new P11AttrEndDate(osobject,0); // Initialize the attributes if ( !attrCertificateType->init() || !attrTrusted->init() || !attrCertificateCategory->init() || !attrCheckValue->init() || !attrStartDate->init() || !attrEndDate->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrCertificateType; delete attrTrusted; delete attrCertificateCategory; delete attrCheckValue; delete attrStartDate; delete attrEndDate; return false; } // Add them to the map attributes[attrCertificateType->getType()] = attrCertificateType; attributes[attrTrusted->getType()] = attrTrusted; attributes[attrCertificateCategory->getType()] = attrCertificateCategory; attributes[attrCheckValue->getType()] = attrCheckValue; attributes[attrStartDate->getType()] = attrStartDate; attributes[attrEndDate->getType()] = attrEndDate; initialized = true; return true; } // Constructor P11X509CertificateObj::P11X509CertificateObj() { initialized = false; } // Add attributes bool P11X509CertificateObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; // Set default values for attributes that will be introduced in the parent if (!inobject->attributeExists(CKA_CERTIFICATE_TYPE) || inobject->getUnsignedLongValue(CKA_CERTIFICATE_TYPE, CKC_VENDOR_DEFINED) != CKC_X_509) { OSAttribute setCertType((unsigned long)CKC_X_509); inobject->setAttribute(CKA_CERTIFICATE_TYPE, setCertType); } // Create parent if (!P11CertificateObj::init(inobject)) return false; // Create attributes P11Attribute* attrSubject = new P11AttrSubject(osobject,P11Attribute::ck1); P11Attribute* attrID = new P11AttrID(osobject); P11Attribute* attrIssuer = new P11AttrIssuer(osobject); P11Attribute* attrSerialNumber = new P11AttrSerialNumber(osobject); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck14); P11Attribute* attrURL = new P11AttrURL(osobject); P11Attribute* attrHashOfSubjectPublicKey = new P11AttrHashOfSubjectPublicKey(osobject); P11Attribute* attrHashOfIssuerPublicKey = new P11AttrHashOfIssuerPublicKey(osobject); P11Attribute* attrJavaMidpSecurityDomain = new P11AttrJavaMidpSecurityDomain(osobject); P11Attribute* attrNameHashAlgorithm = new P11AttrNameHashAlgorithm(osobject); // Initialize the attributes if ( !attrSubject->init() || !attrID->init() || !attrIssuer->init() || !attrSerialNumber->init() || !attrValue->init() || !attrURL->init() || !attrHashOfSubjectPublicKey->init() || !attrHashOfIssuerPublicKey->init() || !attrJavaMidpSecurityDomain->init() || !attrNameHashAlgorithm->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrSubject; delete attrID; delete attrIssuer; delete attrSerialNumber; delete attrValue; delete attrURL; delete attrHashOfSubjectPublicKey; delete attrHashOfIssuerPublicKey; delete attrJavaMidpSecurityDomain; delete attrNameHashAlgorithm; return false; } // Add them to the map attributes[attrSubject->getType()] = attrSubject; attributes[attrID->getType()] = attrID; attributes[attrIssuer->getType()] = attrIssuer; attributes[attrSerialNumber->getType()] = attrSerialNumber; attributes[attrValue->getType()] = attrValue; attributes[attrURL->getType()] = attrURL; attributes[attrHashOfSubjectPublicKey->getType()] = attrHashOfSubjectPublicKey; attributes[attrHashOfIssuerPublicKey->getType()] = attrHashOfIssuerPublicKey; attributes[attrJavaMidpSecurityDomain->getType()] = attrJavaMidpSecurityDomain; attributes[attrNameHashAlgorithm->getType()] = attrNameHashAlgorithm; return true; } // Constructor P11OpenPGPPublicKeyObj::P11OpenPGPPublicKeyObj() { initialized = false; } // Add attributes bool P11OpenPGPPublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; // Set default values for attributes that will be introduced in the parent if (!inobject->attributeExists(CKA_CERTIFICATE_TYPE) || inobject->getUnsignedLongValue(CKA_CERTIFICATE_TYPE, CKC_VENDOR_DEFINED) != CKC_OPENPGP) { OSAttribute setCertType((unsigned long)CKC_OPENPGP); inobject->setAttribute(CKA_CERTIFICATE_TYPE, setCertType); } // Create parent if (!P11CertificateObj::init(inobject)) return false; // Create attributes P11Attribute* attrSubject = new P11AttrSubject(osobject,P11Attribute::ck1); P11Attribute* attrID = new P11AttrID(osobject); P11Attribute* attrIssuer = new P11AttrIssuer(osobject); P11Attribute* attrSerialNumber = new P11AttrSerialNumber(osobject); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck14); P11Attribute* attrURL = new P11AttrURL(osobject); // Initialize the attributes if ( !attrSubject->init() || !attrID->init() || !attrIssuer->init() || !attrSerialNumber->init() || !attrValue->init() || !attrURL->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrSubject; delete attrID; delete attrIssuer; delete attrSerialNumber; delete attrValue; delete attrURL; return false; } // Add them to the map attributes[attrSubject->getType()] = attrSubject; attributes[attrID->getType()] = attrID; attributes[attrIssuer->getType()] = attrIssuer; attributes[attrSerialNumber->getType()] = attrSerialNumber; attributes[attrValue->getType()] = attrValue; attributes[attrURL->getType()] = attrURL; return true; } // Constructor P11KeyObj::P11KeyObj() { initialized = false; } // Add attributes bool P11KeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; // Create parent if (!P11Object::init(inobject)) return false; // Create attributes P11Attribute* attrKeyType = new P11AttrKeyType(osobject,P11Attribute::ck5); P11Attribute* attrID = new P11AttrID(osobject); P11Attribute* attrStartDate = new P11AttrStartDate(osobject,P11Attribute::ck8); P11Attribute* attrEndDate = new P11AttrEndDate(osobject,P11Attribute::ck8); P11Attribute* attrDerive = new P11AttrDerive(osobject); P11Attribute* attrLocal = new P11AttrLocal(osobject,P11Attribute::ck6); P11Attribute* attrKeyGenMechanism = new P11AttrKeyGenMechanism(osobject); // TODO: CKA_ALLOWED_MECHANISMS is not supported // Initialize the attributes if ( !attrKeyType->init() || !attrID->init() || !attrStartDate->init() || !attrEndDate->init() || !attrDerive->init() || !attrLocal->init() || !attrKeyGenMechanism->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrKeyType; delete attrID; delete attrStartDate; delete attrEndDate; delete attrDerive; delete attrLocal; delete attrKeyGenMechanism; return false; } // Add them to the map attributes[attrKeyType->getType()] = attrKeyType; attributes[attrID->getType()] = attrID; attributes[attrStartDate->getType()] = attrStartDate; attributes[attrEndDate->getType()] = attrEndDate; attributes[attrDerive->getType()] = attrDerive; attributes[attrLocal->getType()] = attrLocal; attributes[attrKeyGenMechanism->getType()] = attrKeyGenMechanism; initialized = true; return true; } // Constructor P11PublicKeyObj::P11PublicKeyObj() { initialized = false; } // Add attributes bool P11PublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_CLASS) || inobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_PUBLIC_KEY) { OSAttribute setClass((unsigned long)CKO_PUBLIC_KEY); inobject->setAttribute(CKA_CLASS, setClass); } // Create parent if (!P11KeyObj::init(inobject)) return false; if (initialized) return true; // Create attributes P11Attribute* attrSubject = new P11AttrSubject(osobject,P11Attribute::ck8); P11Attribute* attrEncrypt = new P11AttrEncrypt(osobject); P11Attribute* attrVerify = new P11AttrVerify(osobject); P11Attribute* attrVerifyRecover = new P11AttrVerifyRecover(osobject); P11Attribute* attrWrap = new P11AttrWrap(osobject); P11Attribute* attrTrusted = new P11AttrTrusted(osobject); P11Attribute* attrWrapTemplate = new P11AttrWrapTemplate(osobject); // Initialize the attributes if ( !attrSubject->init() || !attrEncrypt->init() || !attrVerify->init() || !attrVerifyRecover->init() || !attrWrap->init() || !attrTrusted->init() || !attrWrapTemplate->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrSubject; delete attrEncrypt; delete attrVerify; delete attrVerifyRecover; delete attrWrap; delete attrTrusted; delete attrWrapTemplate; return false; } // Add them to the map attributes[attrSubject->getType()] = attrSubject; attributes[attrEncrypt->getType()] = attrEncrypt; attributes[attrVerify->getType()] = attrVerify; attributes[attrVerifyRecover->getType()] = attrVerifyRecover; attributes[attrWrap->getType()] = attrWrap; attributes[attrTrusted->getType()] = attrTrusted; attributes[attrWrapTemplate->getType()] = attrWrapTemplate; initialized = true; return true; } // Constructor P11RSAPublicKeyObj::P11RSAPublicKeyObj() { initialized = false; } // Add attributes bool P11RSAPublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_RSA) { OSAttribute setKeyType((unsigned long)CKK_RSA); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PublicKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrModulus = new P11AttrModulus(osobject); P11Attribute* attrModulusBits = new P11AttrModulusBits(osobject); P11Attribute* attrPublicExponent = new P11AttrPublicExponent(osobject,P11Attribute::ck1); // Initialize the attributes if ( !attrModulus->init() || !attrModulusBits->init() || !attrPublicExponent->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrModulus; delete attrModulusBits; delete attrPublicExponent; return false; } // Add them to the map attributes[attrModulus->getType()] = attrModulus; attributes[attrModulusBits->getType()] = attrModulusBits; attributes[attrPublicExponent->getType()] = attrPublicExponent; initialized = true; return true; } // Constructor P11DSAPublicKeyObj::P11DSAPublicKeyObj() { initialized = false; } // Add attributes bool P11DSAPublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DSA) { OSAttribute setKeyType((unsigned long)CKK_DSA); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PublicKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrPrime = new P11AttrPrime(osobject,P11Attribute::ck3); P11Attribute* attrSubPrime = new P11AttrSubPrime(osobject,P11Attribute::ck3); P11Attribute* attrBase = new P11AttrBase(osobject,P11Attribute::ck3); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4); // Initialize the attributes if ( !attrPrime->init() || !attrSubPrime->init() || !attrBase->init() || !attrValue->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrPrime; delete attrSubPrime; delete attrBase; delete attrValue; return false; } // Add them to the map attributes[attrPrime->getType()] = attrPrime; attributes[attrSubPrime->getType()] = attrSubPrime; attributes[attrBase->getType()] = attrBase; attributes[attrValue->getType()] = attrValue; initialized = true; return true; } // Constructor P11ECPublicKeyObj::P11ECPublicKeyObj() { initialized = false; } // Add attributes bool P11ECPublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_EC) { OSAttribute setKeyType((unsigned long)CKK_EC); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PublicKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrEcParams = new P11AttrEcParams(osobject,P11Attribute::ck3); P11Attribute* attrEcPoint = new P11AttrEcPoint(osobject); // Initialize the attributes if ( !attrEcParams->init() || !attrEcPoint->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrEcParams; delete attrEcPoint; return false; } // Add them to the map attributes[attrEcParams->getType()] = attrEcParams; attributes[attrEcPoint->getType()] = attrEcPoint; initialized = true; return true; } // Constructor P11DHPublicKeyObj::P11DHPublicKeyObj() { initialized = false; } // Add attributes bool P11DHPublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DH) { OSAttribute setKeyType((unsigned long)CKK_DH); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PublicKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrPrime = new P11AttrPrime(osobject,P11Attribute::ck3); P11Attribute* attrBase = new P11AttrBase(osobject,P11Attribute::ck3); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4); // Initialize the attributes if ( !attrPrime->init() || !attrBase->init() || !attrValue->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrPrime; delete attrBase; delete attrValue; return false; } // Add them to the map attributes[attrPrime->getType()] = attrPrime; attributes[attrBase->getType()] = attrBase; attributes[attrValue->getType()] = attrValue; initialized = true; return true; } // Constructor P11GOSTPublicKeyObj::P11GOSTPublicKeyObj() { initialized = false; } // Add attributes bool P11GOSTPublicKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_GOSTR3410) { OSAttribute setKeyType((unsigned long)CKK_GOSTR3410); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PublicKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4); P11Attribute* attrGostR3410Params = new P11AttrGostR3410Params(osobject,P11Attribute::ck3); P11Attribute* attrGostR3411Params = new P11AttrGostR3411Params(osobject,P11Attribute::ck3); P11Attribute* attrGost28147Params = new P11AttrGost28147Params(osobject,P11Attribute::ck8); // Initialize the attributes if ( !attrValue->init() || !attrGostR3410Params->init() || !attrGostR3411Params->init() || !attrGost28147Params->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrValue; delete attrGostR3410Params; delete attrGostR3411Params; delete attrGost28147Params; return false; } // Add them to the map attributes[attrValue->getType()] = attrValue; attributes[attrGostR3410Params->getType()] = attrGostR3410Params; attributes[attrGostR3411Params->getType()] = attrGostR3411Params; attributes[attrGost28147Params->getType()] = attrGost28147Params; initialized = true; return true; } //constructor P11PrivateKeyObj::P11PrivateKeyObj() { initialized = false; } // Add attributes bool P11PrivateKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_CLASS) || inobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_PRIVATE_KEY) { OSAttribute setClass((unsigned long)CKO_PRIVATE_KEY); inobject->setAttribute(CKA_CLASS, setClass); } // Create parent if (!P11KeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrSubject = new P11AttrSubject(osobject,P11Attribute::ck8); P11Attribute* attrSensitive = new P11AttrSensitive(osobject); P11Attribute* attrDecrypt = new P11AttrDecrypt(osobject); P11Attribute* attrSign = new P11AttrSign(osobject); P11Attribute* attrSignRecover = new P11AttrSignRecover(osobject); P11Attribute* attrUnwrap = new P11AttrUnwrap(osobject); P11Attribute* attrExtractable = new P11AttrExtractable(osobject); P11Attribute* attrAlwaysSensitive = new P11AttrAlwaysSensitive(osobject); P11Attribute* attrNeverExtractable = new P11AttrNeverExtractable(osobject); P11Attribute* attrWrapWithTrusted = new P11AttrWrapWithTrusted(osobject); P11Attribute* attrUnwrapTemplate = new P11AttrUnwrapTemplate(osobject); // TODO: CKA_ALWAYS_AUTHENTICATE is accepted, but we do not use it P11Attribute* attrAlwaysAuthenticate = new P11AttrAlwaysAuthenticate(osobject); // Initialize the attributes if ( !attrSubject->init() || !attrSensitive->init() || !attrDecrypt->init() || !attrSign->init() || !attrSignRecover->init() || !attrUnwrap->init() || !attrExtractable->init() || !attrAlwaysSensitive->init() || !attrNeverExtractable->init() || !attrWrapWithTrusted->init() || !attrUnwrapTemplate->init() || !attrAlwaysAuthenticate->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrSubject; delete attrSensitive; delete attrDecrypt; delete attrSign; delete attrSignRecover; delete attrUnwrap; delete attrExtractable; delete attrAlwaysSensitive; delete attrNeverExtractable; delete attrWrapWithTrusted; delete attrUnwrapTemplate; delete attrAlwaysAuthenticate; return false; } // Add them to the map attributes[attrSubject->getType()] = attrSubject; attributes[attrSensitive->getType()] = attrSensitive; attributes[attrDecrypt->getType()] = attrDecrypt; attributes[attrSign->getType()] = attrSign; attributes[attrSignRecover->getType()] = attrSignRecover; attributes[attrUnwrap->getType()] = attrUnwrap; attributes[attrExtractable->getType()] = attrExtractable; attributes[attrAlwaysSensitive->getType()] = attrAlwaysSensitive; attributes[attrNeverExtractable->getType()] = attrNeverExtractable; attributes[attrWrapWithTrusted->getType()] = attrWrapWithTrusted; attributes[attrUnwrapTemplate->getType()] = attrUnwrapTemplate; attributes[attrAlwaysAuthenticate->getType()] = attrAlwaysAuthenticate; initialized = true; return true; } // Constructor P11RSAPrivateKeyObj::P11RSAPrivateKeyObj() { initialized = false; } // Add attributes bool P11RSAPrivateKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_RSA) { OSAttribute setKeyType((unsigned long)CKK_RSA); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PrivateKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrModulus = new P11AttrModulus(osobject,P11Attribute::ck6); P11Attribute* attrPublicExponent = new P11AttrPublicExponent(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrPrivateExponent = new P11AttrPrivateExponent(osobject); P11Attribute* attrPrime1 = new P11AttrPrime1(osobject); P11Attribute* attrPrime2 = new P11AttrPrime2(osobject); P11Attribute* attrExponent1 = new P11AttrExponent1(osobject); P11Attribute* attrExponent2 = new P11AttrExponent2(osobject); P11Attribute* attrCoefficient = new P11AttrCoefficient(osobject); // Initialize the attributes if ( !attrModulus->init() || !attrPublicExponent->init() || !attrPrivateExponent->init() || !attrPrime1->init() || !attrPrime2->init() || !attrExponent1->init() || !attrExponent2->init() || !attrCoefficient->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrModulus; delete attrPublicExponent; delete attrPrivateExponent; delete attrPrime1; delete attrPrime2; delete attrExponent1; delete attrExponent2; delete attrCoefficient; return false; } // Add them to the map attributes[attrModulus->getType()] = attrModulus; attributes[attrPublicExponent->getType()] = attrPublicExponent; attributes[attrPrivateExponent->getType()] = attrPrivateExponent; attributes[attrPrime1->getType()] = attrPrime1; attributes[attrPrime2->getType()] = attrPrime2; attributes[attrExponent1->getType()] = attrExponent1; attributes[attrExponent2->getType()] = attrExponent2; attributes[attrCoefficient->getType()] = attrCoefficient; initialized = true; return true; } // Constructor P11DSAPrivateKeyObj::P11DSAPrivateKeyObj() { initialized = false; } // Add attributes bool P11DSAPrivateKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DSA) { OSAttribute setKeyType((unsigned long)CKK_DSA); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PrivateKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrPrime = new P11AttrPrime(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrSubPrime = new P11AttrSubPrime(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrBase = new P11AttrBase(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); // Initialize the attributes if ( !attrPrime->init() || !attrSubPrime->init() || !attrBase->init() || !attrValue->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrPrime; delete attrSubPrime; delete attrBase; delete attrValue; return false; } // Add them to the map attributes[attrPrime->getType()] = attrPrime; attributes[attrSubPrime->getType()] = attrSubPrime; attributes[attrBase->getType()] = attrBase; attributes[attrValue->getType()] = attrValue; initialized = true; return true; } // Constructor P11ECPrivateKeyObj::P11ECPrivateKeyObj() { initialized = false; } // Add attributes bool P11ECPrivateKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_EC) { OSAttribute setKeyType((unsigned long)CKK_EC); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PrivateKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrEcParams = new P11AttrEcParams(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); // Initialize the attributes if ( !attrEcParams->init() || !attrValue->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrEcParams; delete attrValue; return false; } // Add them to the map attributes[attrEcParams->getType()] = attrEcParams; attributes[attrValue->getType()] = attrValue; initialized = true; return true; } // Constructor P11DHPrivateKeyObj::P11DHPrivateKeyObj() { initialized = false; } // Add attributes bool P11DHPrivateKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DH) { OSAttribute setKeyType((unsigned long)CKK_DH); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PrivateKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrPrime = new P11AttrPrime(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrBase = new P11AttrBase(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); P11Attribute* attrValueBits = new P11AttrValueBits(osobject); // Initialize the attributes if ( !attrPrime->init() || !attrBase->init() || !attrValue->init() || !attrValueBits->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrPrime; delete attrBase; delete attrValue; delete attrValueBits; return false; } // Add them to the map attributes[attrPrime->getType()] = attrPrime; attributes[attrBase->getType()] = attrBase; attributes[attrValue->getType()] = attrValue; attributes[attrValueBits->getType()] = attrValueBits; initialized = true; return true; } // Constructor P11GOSTPrivateKeyObj::P11GOSTPrivateKeyObj() { initialized = false; } // Add attributes bool P11GOSTPrivateKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_GOSTR3410) { OSAttribute setKeyType((unsigned long)CKK_GOSTR3410); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11PrivateKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); P11Attribute* attrGostR3410Params = new P11AttrGostR3410Params(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrGostR3411Params = new P11AttrGostR3411Params(osobject,P11Attribute::ck4|P11Attribute::ck6); P11Attribute* attrGost28147Params = new P11AttrGost28147Params(osobject,P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck8); // Initialize the attributes if ( !attrValue->init() || !attrGostR3410Params->init() || !attrGostR3411Params->init() || !attrGost28147Params->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrValue; delete attrGostR3410Params; delete attrGostR3411Params; delete attrGost28147Params; return false; } // Add them to the map attributes[attrValue->getType()] = attrValue; attributes[attrGostR3410Params->getType()] = attrGostR3410Params; attributes[attrGostR3411Params->getType()] = attrGostR3411Params; attributes[attrGost28147Params->getType()] = attrGost28147Params; initialized = true; return true; } // Constructor P11SecretKeyObj::P11SecretKeyObj() { initialized = false; } // Add attributes bool P11SecretKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_CLASS) || inobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_SECRET_KEY) { OSAttribute setClass((unsigned long)CKO_SECRET_KEY); inobject->setAttribute(CKA_CLASS, setClass); } // Create parent if (!P11KeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrSensitive = new P11AttrSensitive(osobject); P11Attribute* attrEncrypt = new P11AttrEncrypt(osobject); P11Attribute* attrDecrypt = new P11AttrDecrypt(osobject); P11Attribute* attrSign = new P11AttrSign(osobject); P11Attribute* attrVerify = new P11AttrVerify(osobject); P11Attribute* attrWrap = new P11AttrWrap(osobject); P11Attribute* attrUnwrap = new P11AttrUnwrap(osobject); P11Attribute* attrExtractable = new P11AttrExtractable(osobject); P11Attribute* attrAlwaysSensitive = new P11AttrAlwaysSensitive(osobject); P11Attribute* attrNeverExtractable = new P11AttrNeverExtractable(osobject); // TODO: CKA_CHECK_VALUE is accepted, but we do not calculate it P11Attribute* attrCheckValue = new P11AttrCheckValue(osobject); P11Attribute* attrWrapWithTrusted = new P11AttrWrapWithTrusted(osobject); P11Attribute* attrTrusted = new P11AttrTrusted(osobject); P11Attribute* attrWrapTemplate = new P11AttrWrapTemplate(osobject); P11Attribute* attrUnwrapTemplate = new P11AttrUnwrapTemplate(osobject); // Initialize the attributes if ( !attrSensitive->init() || !attrEncrypt->init() || !attrDecrypt->init() || !attrSign->init() || !attrVerify->init() || !attrWrap->init() || !attrUnwrap->init() || !attrExtractable->init() || !attrAlwaysSensitive->init() || !attrNeverExtractable->init() || !attrCheckValue->init() || !attrWrapWithTrusted->init() || !attrTrusted->init() || !attrWrapTemplate->init() || !attrUnwrapTemplate->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrSensitive; delete attrEncrypt; delete attrDecrypt; delete attrSign; delete attrVerify; delete attrWrap; delete attrUnwrap; delete attrExtractable; delete attrAlwaysSensitive; delete attrNeverExtractable; delete attrCheckValue; delete attrWrapWithTrusted; delete attrTrusted; delete attrWrapTemplate; delete attrUnwrapTemplate; return false; } // Add them to the map attributes[attrSensitive->getType()] = attrSensitive; attributes[attrEncrypt->getType()] = attrEncrypt; attributes[attrDecrypt->getType()] = attrDecrypt; attributes[attrSign->getType()] = attrSign; attributes[attrVerify->getType()] = attrVerify; attributes[attrWrap->getType()] = attrWrap; attributes[attrUnwrap->getType()] = attrUnwrap; attributes[attrExtractable->getType()] = attrExtractable; attributes[attrAlwaysSensitive->getType()] = attrAlwaysSensitive; attributes[attrNeverExtractable->getType()] = attrNeverExtractable; attributes[attrCheckValue->getType()] = attrCheckValue; attributes[attrWrapWithTrusted->getType()] = attrWrapWithTrusted; attributes[attrTrusted->getType()] = attrTrusted; attributes[attrWrapTemplate->getType()] = attrWrapTemplate; attributes[attrUnwrapTemplate->getType()] = attrUnwrapTemplate; initialized = true; return true; } // Constructor P11GenericSecretKeyObj::P11GenericSecretKeyObj() { initialized = false; keytype = CKK_VENDOR_DEFINED; } // Add attributes bool P11GenericSecretKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != keytype) { OSAttribute setKeyType(keytype); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11SecretKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); P11Attribute* attrValueLen = new P11AttrValueLen(osobject); // Initialize the attributes if ( !attrValue->init() || !attrValueLen->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrValue; delete attrValueLen; return false; } // Add them to the map attributes[attrValue->getType()] = attrValue; attributes[attrValueLen->getType()] = attrValueLen; initialized = true; return true; } // Set Key Type bool P11GenericSecretKeyObj::setKeyType(CK_KEY_TYPE inKeytype) { if (!initialized) { keytype = inKeytype; return true; } else return false; } // Get Key Type CK_KEY_TYPE P11GenericSecretKeyObj::getKeyType() { return keytype; } // Constructor P11AESSecretKeyObj::P11AESSecretKeyObj() { initialized = false; } // Add attributes bool P11AESSecretKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_AES) { OSAttribute setKeyType((unsigned long)CKK_AES); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11SecretKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); P11Attribute* attrValueLen = new P11AttrValueLen(osobject,P11Attribute::ck6); // Initialize the attributes if ( !attrValue->init() || !attrValueLen->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrValue; delete attrValueLen; return false; } // Add them to the map attributes[attrValue->getType()] = attrValue; attributes[attrValueLen->getType()] = attrValueLen; initialized = true; return true; } // Constructor P11DESSecretKeyObj::P11DESSecretKeyObj() { initialized = false; keytype = CKK_VENDOR_DEFINED; } // Add attributes bool P11DESSecretKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != keytype) { OSAttribute setKeyType(keytype); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11SecretKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); // Initialize the attributes if (!attrValue->init()) { ERROR_MSG("Could not initialize the attribute"); delete attrValue; return false; } // Add them to the map attributes[attrValue->getType()] = attrValue; initialized = true; return true; } // Set Key Type bool P11DESSecretKeyObj::setKeyType(CK_KEY_TYPE inKeytype) { if (!initialized) { keytype = inKeytype; return true; } else return false; } // Get Key Type CK_KEY_TYPE P11DESSecretKeyObj::getKeyType() { return keytype; } // Constructor P11GOSTSecretKeyObj::P11GOSTSecretKeyObj() { initialized = false; } // Add attributes bool P11GOSTSecretKeyObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_GOST28147) { OSAttribute setKeyType((unsigned long)CKK_GOST28147); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11SecretKeyObj::init(inobject)) return false; // Create attributes P11Attribute* attrValue = new P11AttrValue(osobject,P11Attribute::ck1|P11Attribute::ck4|P11Attribute::ck6|P11Attribute::ck7); P11Attribute* attrGost28147Params = new P11AttrGost28147Params(osobject,P11Attribute::ck1|P11Attribute::ck3|P11Attribute::ck5); // Initialize the attributes if ( !attrValue->init() || !attrGost28147Params->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrValue; delete attrGost28147Params; return false; } // Add them to the map attributes[attrValue->getType()] = attrValue; attributes[attrGost28147Params->getType()] = attrGost28147Params; initialized = true; return true; } // Constructor P11DomainObj::P11DomainObj() { initialized = false; } // Add attributes bool P11DomainObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_CLASS) || inobject->getUnsignedLongValue(CKA_CLASS, CKO_VENDOR_DEFINED) != CKO_DOMAIN_PARAMETERS) { OSAttribute setClass((unsigned long)CKO_DOMAIN_PARAMETERS); inobject->setAttribute(CKA_CLASS, setClass); } // Create parent if (!P11Object::init(inobject)) return false; // Create attributes P11Attribute* attrKeyType = new P11AttrKeyType(osobject); P11Attribute* attrLocal = new P11AttrLocal(osobject); // Initialize the attributes if ( !attrKeyType->init() || !attrLocal->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrKeyType; delete attrLocal; return false; } // Add them to the map attributes[attrKeyType->getType()] = attrKeyType; attributes[attrLocal->getType()] = attrLocal; initialized = true; return true; } // Constructor P11DSADomainObj::P11DSADomainObj() { initialized = false; } // Add attributes bool P11DSADomainObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DSA) { OSAttribute setKeyType((unsigned long)CKK_DSA); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11DomainObj::init(inobject)) return false; // Create attributes P11Attribute* attrPrime = new P11AttrPrime(osobject,P11Attribute::ck4); P11Attribute* attrSubPrime = new P11AttrSubPrime(osobject,P11Attribute::ck4); P11Attribute* attrBase = new P11AttrBase(osobject,P11Attribute::ck4); P11Attribute* attrPrimeBits = new P11AttrPrimeBits(osobject); // Initialize the attributes if ( !attrPrime->init() || !attrSubPrime->init() || !attrBase->init() || !attrPrimeBits->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrPrime; delete attrSubPrime; delete attrBase; delete attrPrimeBits; return false; } // Add them to the map attributes[attrPrime->getType()] = attrPrime; attributes[attrSubPrime->getType()] = attrSubPrime; attributes[attrBase->getType()] = attrBase; attributes[attrPrimeBits->getType()] = attrPrimeBits; initialized = true; return true; } // Constructor P11DHDomainObj::P11DHDomainObj() { initialized = false; } // Add attributes bool P11DHDomainObj::init(OSObject *inobject) { if (initialized) return true; if (inobject == NULL) return false; if (!inobject->attributeExists(CKA_KEY_TYPE) || inobject->getUnsignedLongValue(CKA_KEY_TYPE, CKK_VENDOR_DEFINED) != CKK_DH) { OSAttribute setKeyType((unsigned long)CKK_DH); inobject->setAttribute(CKA_KEY_TYPE, setKeyType); } // Create parent if (!P11DomainObj::init(inobject)) return false; // Create attributes P11Attribute* attrPrime = new P11AttrPrime(osobject,P11Attribute::ck4); P11Attribute* attrBase = new P11AttrBase(osobject,P11Attribute::ck4); P11Attribute* attrPrimeBits = new P11AttrPrimeBits(osobject); // Initialize the attributes if ( !attrPrime->init() || !attrBase->init() || !attrPrimeBits->init() ) { ERROR_MSG("Could not initialize the attribute"); delete attrPrime; delete attrBase; delete attrPrimeBits; return false; } // Add them to the map attributes[attrPrime->getType()] = attrPrime; attributes[attrBase->getType()] = attrBase; attributes[attrPrimeBits->getType()] = attrPrimeBits; initialized = true; return true; } softhsm-2.0.0/src/Makefile.in0000664000175000017500000004612512552216620012764 00000000000000# Makefile.in generated by automake 1.14.1 from Makefile.am. # @configure_input@ # Copyright (C) 1994-2013 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. @SET_MAKE@ VPATH = @srcdir@ am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)' am__make_running_with_option = \ case $${target_option-} in \ ?) ;; \ *) echo "am__make_running_with_option: internal error: invalid" \ "target option '$${target_option-}' specified" >&2; \ exit 1;; \ esac; \ has_opt=no; \ sane_makeflags=$$MAKEFLAGS; \ if $(am__is_gnu_make); then \ sane_makeflags=$$MFLAGS; \ else \ case $$MAKEFLAGS in \ *\\[\ \ ]*) \ bs=\\; \ sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ esac; \ fi; \ skip_next=no; \ strip_trailopt () \ { \ flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ }; \ for flg in $$sane_makeflags; do \ test $$skip_next = yes && { skip_next=no; continue; }; \ case $$flg in \ *=*|--*) continue;; \ -*I) strip_trailopt 'I'; skip_next=yes;; \ -*I?*) strip_trailopt 'I';; \ -*O) strip_trailopt 'O'; skip_next=yes;; \ -*O?*) strip_trailopt 'O';; \ -*l) strip_trailopt 'l'; skip_next=yes;; \ -*l?*) strip_trailopt 'l';; \ -[dEDm]) skip_next=yes;; \ -[JT]) skip_next=yes;; \ esac; \ case $$flg in \ *$$target_option*) has_opt=yes; break;; \ esac; \ done; \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ pkglibexecdir = $(libexecdir)/@PACKAGE@ am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd install_sh_DATA = $(install_sh) -c -m 644 install_sh_PROGRAM = $(install_sh) -c install_sh_SCRIPT = $(install_sh) -c INSTALL_HEADER = $(INSTALL_DATA) transform = $(program_transform_name) NORMAL_INSTALL = : PRE_INSTALL = : POST_INSTALL = : NORMAL_UNINSTALL = : PRE_UNINSTALL = : POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ subdir = src DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 am__aclocal_m4_deps = $(top_srcdir)/m4/acx_64bit.m4 \ $(top_srcdir)/m4/acx_botan.m4 \ $(top_srcdir)/m4/acx_botan_ecc.m4 \ $(top_srcdir)/m4/acx_botan_gnump.m4 \ $(top_srcdir)/m4/acx_botan_gost.m4 \ $(top_srcdir)/m4/acx_botan_rfc5649.m4 \ $(top_srcdir)/m4/acx_crypto_backend.m4 \ $(top_srcdir)/m4/acx_dlopen.m4 \ $(top_srcdir)/m4/acx_non_paged_memory.m4 \ $(top_srcdir)/m4/acx_openssl.m4 \ $(top_srcdir)/m4/acx_openssl_ecc.m4 \ $(top_srcdir)/m4/acx_openssl_fips.m4 \ $(top_srcdir)/m4/acx_openssl_gost.m4 \ $(top_srcdir)/m4/acx_openssl_rfc5649.m4 \ $(top_srcdir)/m4/acx_pedantic.m4 \ $(top_srcdir)/m4/acx_prefixhack.m4 \ $(top_srcdir)/m4/acx_sqlite3.m4 $(top_srcdir)/m4/acx_strict.m4 \ $(top_srcdir)/m4/acx_visibility.m4 \ $(top_srcdir)/m4/acx_yield.m4 \ $(top_srcdir)/m4/ax_cxx_compile_stdcxx_11.m4 \ $(top_srcdir)/m4/libtool.m4 $(top_srcdir)/m4/ltoptions.m4 \ $(top_srcdir)/m4/ltsugar.m4 $(top_srcdir)/m4/ltversion.m4 \ $(top_srcdir)/m4/lt~obsolete.m4 $(top_srcdir)/configure.ac am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ $(ACLOCAL_M4) mkinstalldirs = $(install_sh) -d CONFIG_HEADER = $(top_builddir)/config.h CONFIG_CLEAN_FILES = CONFIG_CLEAN_VPATH_FILES = AM_V_P = $(am__v_P_@AM_V@) am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) am__v_P_0 = false am__v_P_1 = : AM_V_GEN = $(am__v_GEN_@AM_V@) am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) am__v_GEN_0 = @echo " GEN " $@; am__v_GEN_1 = AM_V_at = $(am__v_at_@AM_V@) am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) am__v_at_0 = @ am__v_at_1 = SOURCES = DIST_SOURCES = RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \ ctags-recursive dvi-recursive html-recursive info-recursive \ install-data-recursive install-dvi-recursive \ install-exec-recursive install-html-recursive \ install-info-recursive install-pdf-recursive \ install-ps-recursive install-recursive installcheck-recursive \ installdirs-recursive pdf-recursive ps-recursive \ tags-recursive uninstall-recursive am__can_run_installinfo = \ case $$AM_UPDATE_INFO_DIR in \ n|no|NO) false;; \ *) (install-info --version) >/dev/null 2>&1;; \ esac RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ distclean-recursive maintainer-clean-recursive am__recursive_targets = \ $(RECURSIVE_TARGETS) \ $(RECURSIVE_CLEAN_TARGETS) \ $(am__extra_recursive_targets) AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \ distdir am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) # Read a list of newline-separated strings from the standard input, # and print each of them once, without duplicates. Input order is # *not* preserved. am__uniquify_input = $(AWK) '\ BEGIN { nonempty = 0; } \ { items[$$0] = 1; nonempty = 1; } \ END { if (nonempty) { for (i in items) print i; }; } \ ' # Make sure the list of sources is unique. This is necessary because, # e.g., the same source file might be shared among _SOURCES variables # for different programs/libraries. am__define_uniq_tagged_files = \ list='$(am__tagged_files)'; \ unique=`for i in $$list; do \ if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ done | $(am__uniquify_input)` ETAGS = etags CTAGS = ctags DIST_SUBDIRS = $(SUBDIRS) DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) am__relativize = \ dir0=`pwd`; \ sed_first='s,^\([^/]*\)/.*$$,\1,'; \ sed_rest='s,^[^/]*/*,,'; \ sed_last='s,^.*/\([^/]*\)$$,\1,'; \ sed_butlast='s,/*[^/]*$$,,'; \ while test -n "$$dir1"; do \ first=`echo "$$dir1" | sed -e "$$sed_first"`; \ if test "$$first" != "."; then \ if test "$$first" = ".."; then \ dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ else \ first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ if test "$$first2" = "$$first"; then \ dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ else \ dir2="../$$dir2"; \ fi; \ dir0="$$dir0"/"$$first"; \ fi; \ fi; \ dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ done; \ reldir="$$dir2" ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ AR = @AR@ AUTOCONF = @AUTOCONF@ AUTOHEADER = @AUTOHEADER@ AUTOMAKE = @AUTOMAKE@ AWK = @AWK@ BOTAN_INCLUDES = @BOTAN_INCLUDES@ BOTAN_LIBS = @BOTAN_LIBS@ BOTAN_VERSION_MINOR = @BOTAN_VERSION_MINOR@ CC = @CC@ CCDEPMODE = @CCDEPMODE@ CFLAGS = @CFLAGS@ CPP = @CPP@ CPPFLAGS = @CPPFLAGS@ CRYPTO_INCLUDES = @CRYPTO_INCLUDES@ CRYPTO_LIBS = @CRYPTO_LIBS@ CXX = @CXX@ CXXCPP = @CXXCPP@ CXXDEPMODE = @CXXDEPMODE@ CXXFLAGS = @CXXFLAGS@ CYGPATH_W = @CYGPATH_W@ DEFS = @DEFS@ DEPDIR = @DEPDIR@ DLLTOOL = @DLLTOOL@ DSYMUTIL = @DSYMUTIL@ DUMPBIN = @DUMPBIN@ ECHO_C = @ECHO_C@ ECHO_N = @ECHO_N@ ECHO_T = @ECHO_T@ EGREP = @EGREP@ EXEEXT = @EXEEXT@ FGREP = @FGREP@ GREP = @GREP@ HAVE_CXX11 = @HAVE_CXX11@ INSTALL = @INSTALL@ INSTALL_DATA = @INSTALL_DATA@ INSTALL_PROGRAM = @INSTALL_PROGRAM@ INSTALL_SCRIPT = @INSTALL_SCRIPT@ INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ LD = @LD@ LDFLAGS = @LDFLAGS@ LIBOBJS = @LIBOBJS@ LIBS = @LIBS@ LIBTOOL = @LIBTOOL@ LIPO = @LIPO@ LN_S = @LN_S@ LTLIBOBJS = @LTLIBOBJS@ MAKEINFO = @MAKEINFO@ MANIFEST_TOOL = @MANIFEST_TOOL@ MKDIR_P = @MKDIR_P@ NM = @NM@ NMEDIT = @NMEDIT@ OBJDUMP = @OBJDUMP@ OBJEXT = @OBJEXT@ OPENSSL_INCLUDES = @OPENSSL_INCLUDES@ OPENSSL_LIBS = @OPENSSL_LIBS@ OTOOL = @OTOOL@ OTOOL64 = @OTOOL64@ PACKAGE = @PACKAGE@ PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ PACKAGE_NAME = @PACKAGE_NAME@ PACKAGE_STRING = @PACKAGE_STRING@ PACKAGE_TARNAME = @PACKAGE_TARNAME@ PACKAGE_URL = @PACKAGE_URL@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ RANLIB = @RANLIB@ SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SQLITE3 = @SQLITE3@ SQLITE3_INCLUDES = @SQLITE3_INCLUDES@ SQLITE3_LIBS = @SQLITE3_LIBS@ STRIP = @STRIP@ VERSION = @VERSION@ VERSION_INFO = @VERSION_INFO@ YIELD_LIB = @YIELD_LIB@ abs_builddir = @abs_builddir@ abs_srcdir = @abs_srcdir@ abs_top_builddir = @abs_top_builddir@ abs_top_srcdir = @abs_top_srcdir@ ac_ct_AR = @ac_ct_AR@ ac_ct_CC = @ac_ct_CC@ ac_ct_CXX = @ac_ct_CXX@ ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ am__tar = @am__tar@ am__untar = @am__untar@ bindir = @bindir@ build = @build@ build_alias = @build_alias@ build_cpu = @build_cpu@ build_os = @build_os@ build_vendor = @build_vendor@ builddir = @builddir@ datadir = @datadir@ datarootdir = @datarootdir@ default_softhsm2_conf = @default_softhsm2_conf@ docdir = @docdir@ dvidir = @dvidir@ exec_prefix = @exec_prefix@ host = @host@ host_alias = @host_alias@ host_cpu = @host_cpu@ host_os = @host_os@ host_vendor = @host_vendor@ htmldir = @htmldir@ includedir = @includedir@ infodir = @infodir@ install_sh = @install_sh@ libdir = @libdir@ libexecdir = @libexecdir@ localedir = @localedir@ localstatedir = @localstatedir@ mandir = @mandir@ mkdir_p = @mkdir_p@ oldincludedir = @oldincludedir@ pdfdir = @pdfdir@ prefix = @prefix@ program_transform_name = @program_transform_name@ psdir = @psdir@ sbindir = @sbindir@ sharedstatedir = @sharedstatedir@ softhsmtokendir = @softhsmtokendir@ srcdir = @srcdir@ sysconfdir = @sysconfdir@ target_alias = @target_alias@ top_build_prefix = @top_build_prefix@ top_builddir = @top_builddir@ top_srcdir = @top_srcdir@ MAINTAINERCLEANFILES = $(srcdir)/Makefile.in SUBDIRS = bin lib all: all-recursive .SUFFIXES: $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) @for dep in $?; do \ case '$(am__configure_deps)' in \ *$$dep*) \ ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ && { if test -f $@; then exit 0; else break; fi; }; \ exit 1;; \ esac; \ done; \ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/Makefile'; \ $(am__cd) $(top_srcdir) && \ $(AUTOMAKE) --foreign src/Makefile .PRECIOUS: Makefile Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status @case '$?' in \ *config.status*) \ cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ *) \ echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ esac; $(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(top_srcdir)/configure: $(am__configure_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(ACLOCAL_M4): $(am__aclocal_m4_deps) cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh $(am__aclocal_m4_deps): mostlyclean-libtool: -rm -f *.lo clean-libtool: -rm -rf .libs _libs # This directory's subdirectories are mostly independent; you can cd # into them and run 'make' without going through this Makefile. # To change the values of 'make' variables: instead of editing Makefiles, # (1) if the variable is set in 'config.status', edit 'config.status' # (which will cause the Makefiles to be regenerated when you run 'make'); # (2) otherwise, pass the desired values on the 'make' command line. $(am__recursive_targets): @fail=; \ if $(am__make_keepgoing); then \ failcom='fail=yes'; \ else \ failcom='exit 1'; \ fi; \ dot_seen=no; \ target=`echo $@ | sed s/-recursive//`; \ case "$@" in \ distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ *) list='$(SUBDIRS)' ;; \ esac; \ for subdir in $$list; do \ echo "Making $$target in $$subdir"; \ if test "$$subdir" = "."; then \ dot_seen=yes; \ local_target="$$target-am"; \ else \ local_target="$$target"; \ fi; \ ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ || eval $$failcom; \ done; \ if test "$$dot_seen" = "no"; then \ $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ fi; test -z "$$fail" ID: $(am__tagged_files) $(am__define_uniq_tagged_files); mkid -fID $$unique tags: tags-recursive TAGS: tags tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) set x; \ here=`pwd`; \ if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ include_option=--etags-include; \ empty_fix=.; \ else \ include_option=--include; \ empty_fix=; \ fi; \ list='$(SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ test ! -f $$subdir/TAGS || \ set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ fi; \ done; \ $(am__define_uniq_tagged_files); \ shift; \ if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ test -n "$$unique" || unique=$$empty_fix; \ if test $$# -gt 0; then \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ "$$@" $$unique; \ else \ $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ $$unique; \ fi; \ fi ctags: ctags-recursive CTAGS: ctags ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) $(am__define_uniq_tagged_files); \ test -z "$(CTAGS_ARGS)$$unique" \ || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ $$unique GTAGS: here=`$(am__cd) $(top_builddir) && pwd` \ && $(am__cd) $(top_srcdir) \ && gtags -i $(GTAGS_ARGS) "$$here" cscopelist: cscopelist-recursive cscopelist-am: $(am__tagged_files) list='$(am__tagged_files)'; \ case "$(srcdir)" in \ [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ *) sdir=$(subdir)/$(srcdir) ;; \ esac; \ for i in $$list; do \ if test -f "$$i"; then \ echo "$(subdir)/$$i"; \ else \ echo "$$sdir/$$i"; \ fi; \ done >> $(top_builddir)/cscope.files distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags distdir: $(DISTFILES) @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ dist_files=`for file in $$list; do echo $$file; done | \ sed -e "s|^$$srcdirstrip/||;t" \ -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ case $$dist_files in \ */*) $(MKDIR_P) `echo "$$dist_files" | \ sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ sort -u` ;; \ esac; \ for file in $$dist_files; do \ if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ if test -d $$d/$$file; then \ dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ if test -d "$(distdir)/$$file"; then \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ fi; \ cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ else \ test -f "$(distdir)/$$file" \ || cp -p $$d/$$file "$(distdir)/$$file" \ || exit 1; \ fi; \ done @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ if test "$$subdir" = .; then :; else \ $(am__make_dryrun) \ || test -d "$(distdir)/$$subdir" \ || $(MKDIR_P) "$(distdir)/$$subdir" \ || exit 1; \ dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ $(am__relativize); \ new_distdir=$$reldir; \ dir1=$$subdir; dir2="$(top_distdir)"; \ $(am__relativize); \ new_top_distdir=$$reldir; \ echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ ($(am__cd) $$subdir && \ $(MAKE) $(AM_MAKEFLAGS) \ top_distdir="$$new_top_distdir" \ distdir="$$new_distdir" \ am__remove_distdir=: \ am__skip_length_check=: \ am__skip_mode_fix=: \ distdir) \ || exit 1; \ fi; \ done check-am: all-am check: check-recursive all-am: Makefile installdirs: installdirs-recursive installdirs-am: install: install-recursive install-exec: install-exec-recursive install-data: install-data-recursive uninstall: uninstall-recursive install-am: all-am @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am installcheck: installcheck-recursive install-strip: if test -z '$(STRIP)'; then \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ install; \ else \ $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ fi mostlyclean-generic: clean-generic: distclean-generic: -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @echo "it deletes files that may require special tools to rebuild." -test -z "$(MAINTAINERCLEANFILES)" || rm -f $(MAINTAINERCLEANFILES) clean: clean-recursive clean-am: clean-generic clean-libtool mostlyclean-am distclean: distclean-recursive -rm -f Makefile distclean-am: clean-am distclean-generic distclean-tags dvi: dvi-recursive dvi-am: html: html-recursive html-am: info: info-recursive info-am: install-data-am: install-dvi: install-dvi-recursive install-dvi-am: install-exec-am: install-html: install-html-recursive install-html-am: install-info: install-info-recursive install-info-am: install-man: install-pdf: install-pdf-recursive install-pdf-am: install-ps: install-ps-recursive install-ps-am: installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f Makefile maintainer-clean-am: distclean-am maintainer-clean-generic mostlyclean: mostlyclean-recursive mostlyclean-am: mostlyclean-generic mostlyclean-libtool pdf: pdf-recursive pdf-am: ps: ps-recursive ps-am: uninstall-am: .MAKE: $(am__recursive_targets) install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \ check-am clean clean-generic clean-libtool cscopelist-am ctags \ ctags-am distclean distclean-generic distclean-libtool \ distclean-tags distdir dvi dvi-am html html-am info info-am \ install install-am install-data install-data-am install-dvi \ install-dvi-am install-exec install-exec-am install-html \ install-html-am install-info install-info-am install-man \ install-pdf install-pdf-am install-ps install-ps-am \ install-strip installcheck installcheck-am installdirs \ installdirs-am maintainer-clean maintainer-clean-generic \ mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ ps ps-am tags tags-am uninstall uninstall-am # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: softhsm-2.0.0/config.guess0000755000175000017500000013036112552216620012442 00000000000000#! /bin/sh # Attempt to guess a canonical system name. # Copyright 1992-2013 Free Software Foundation, Inc. timestamp='2013-06-10' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see . # # As a special exception to the GNU General Public License, if you # distribute this file as part of a program that contains a # configuration script generated by Autoconf, you may include it under # the same distribution terms that you use for the rest of that # program. This Exception is an additional permission under section 7 # of the GNU General Public License, version 3 ("GPLv3"). # # Originally written by Per Bothner. # # You can get the latest version of this script from: # http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD # # Please send patches with a ChangeLog entry to config-patches@gnu.org. me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] Output the configuration name of the system \`$me' is run on. Operation modes: -h, --help print this help, then exit -t, --time-stamp print date of last modification, then exit -v, --version print version number, then exit Report bugs and patches to ." version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. Copyright 1992-2013 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" Try \`$me --help' for more information." # Parse command line while test $# -gt 0 ; do case $1 in --time-stamp | --time* | -t ) echo "$timestamp" ; exit ;; --version | -v ) echo "$version" ; exit ;; --help | --h* | -h ) echo "$usage"; exit ;; -- ) # Stop option processing shift; break ;; - ) # Use stdin as input. break ;; -* ) echo "$me: invalid option $1$help" >&2 exit 1 ;; * ) break ;; esac done if test $# != 0; then echo "$me: too many arguments$help" >&2 exit 1 fi trap 'exit 1' 1 2 15 # CC_FOR_BUILD -- compiler used by this script. Note that the use of a # compiler to aid in system detection is discouraged as it requires # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. # Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still # use `HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. set_cc_for_build=' trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; : ${TMPDIR=/tmp} ; { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; dummy=$tmp/dummy ; tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; case $CC_FOR_BUILD,$HOST_CC,$CC in ,,) echo "int x;" > $dummy.c ; for c in cc gcc c89 c99 ; do if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then CC_FOR_BUILD="$c"; break ; fi ; done ; if test x"$CC_FOR_BUILD" = x ; then CC_FOR_BUILD=no_compiler_found ; fi ;; ,,*) CC_FOR_BUILD=$CC ;; ,*,*) CC_FOR_BUILD=$HOST_CC ;; esac ; set_cc_for_build= ;' # This is needed to find uname on a Pyramid OSx when run in the BSD universe. # (ghazi@noc.rutgers.edu 1994-08-24) if (test -f /.attbin/uname) >/dev/null 2>&1 ; then PATH=$PATH:/.attbin ; export PATH fi UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown case "${UNAME_SYSTEM}" in Linux|GNU|GNU/*) # If the system lacks a compiler, then just pick glibc. # We could probably try harder. LIBC=gnu eval $set_cc_for_build cat <<-EOF > $dummy.c #include #if defined(__UCLIBC__) LIBC=uclibc #elif defined(__dietlibc__) LIBC=dietlibc #else LIBC=gnu #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` ;; esac # Note: order is significant - the case branches are not exclusive. case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in *:NetBSD:*:*) # NetBSD (nbsd) targets should (where applicable) match one or # more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*, # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently # switched to ELF, *-*-netbsd* would select the old # object file format. This provides both forward # compatibility and a consistent mechanism for selecting the # object file format. # # Note: NetBSD doesn't particularly care about the vendor # portion of the name. We always set it to "unknown". sysctl="sysctl -n hw.machine_arch" UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ /usr/sbin/$sysctl 2>/dev/null || echo unknown)` case "${UNAME_MACHINE_ARCH}" in armeb) machine=armeb-unknown ;; arm*) machine=arm-unknown ;; sh3el) machine=shl-unknown ;; sh3eb) machine=sh-unknown ;; sh5el) machine=sh5le-unknown ;; *) machine=${UNAME_MACHINE_ARCH}-unknown ;; esac # The Operating System including object format, if it has switched # to ELF recently, or will in the future. case "${UNAME_MACHINE_ARCH}" in arm*|i386|m68k|ns32k|sh3*|sparc|vax) eval $set_cc_for_build if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ELF__ then # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). # Return netbsd for either. FIX? os=netbsd else os=netbsdelf fi ;; *) os=netbsd ;; esac # The OS release # Debian GNU/NetBSD machines have a different userland, and # thus, need a distinct triplet. However, they do not need # kernel version information, so it can be replaced with a # suitable tag, in the style of linux-gnu. case "${UNAME_VERSION}" in Debian*) release='-gnu' ;; *) release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` ;; esac # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: # contains redundant information, the shorter form: # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. echo "${machine}-${os}${release}" exit ;; *:Bitrig:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'` echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE} exit ;; *:OpenBSD:*:*) UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} exit ;; *:ekkoBSD:*:*) echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} exit ;; *:SolidBSD:*:*) echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} exit ;; macppc:MirBSD:*:*) echo powerpc-unknown-mirbsd${UNAME_RELEASE} exit ;; *:MirBSD:*:*) echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} exit ;; alpha:OSF1:*:*) case $UNAME_RELEASE in *4.0) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` ;; *5.*) UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` ;; esac # According to Compaq, /usr/sbin/psrinfo has been available on # OSF/1 and Tru64 systems produced since 1995. I hope that # covers most systems running today. This code pipes the CPU # types through head -n 1, so we only detect the type of CPU 0. ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` case "$ALPHA_CPU_TYPE" in "EV4 (21064)") UNAME_MACHINE="alpha" ;; "EV4.5 (21064)") UNAME_MACHINE="alpha" ;; "LCA4 (21066/21068)") UNAME_MACHINE="alpha" ;; "EV5 (21164)") UNAME_MACHINE="alphaev5" ;; "EV5.6 (21164A)") UNAME_MACHINE="alphaev56" ;; "EV5.6 (21164PC)") UNAME_MACHINE="alphapca56" ;; "EV5.7 (21164PC)") UNAME_MACHINE="alphapca57" ;; "EV6 (21264)") UNAME_MACHINE="alphaev6" ;; "EV6.7 (21264A)") UNAME_MACHINE="alphaev67" ;; "EV6.8CB (21264C)") UNAME_MACHINE="alphaev68" ;; "EV6.8AL (21264B)") UNAME_MACHINE="alphaev68" ;; "EV6.8CX (21264D)") UNAME_MACHINE="alphaev68" ;; "EV6.9A (21264/EV69A)") UNAME_MACHINE="alphaev69" ;; "EV7 (21364)") UNAME_MACHINE="alphaev7" ;; "EV7.9 (21364A)") UNAME_MACHINE="alphaev79" ;; esac # A Pn.n version is a patched version. # A Vn.n version is a released version. # A Tn.n version is a released field test version. # A Xn.n version is an unreleased experimental baselevel. # 1.2 uses "1.2" for uname -r. echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` # Reset EXIT trap before exiting to avoid spurious non-zero exit code. exitcode=$? trap '' 0 exit $exitcode ;; Alpha\ *:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # Should we change UNAME_MACHINE based on the output of uname instead # of the specific Alpha model? echo alpha-pc-interix exit ;; 21064:Windows_NT:50:3) echo alpha-dec-winnt3.5 exit ;; Amiga*:UNIX_System_V:4.0:*) echo m68k-unknown-sysv4 exit ;; *:[Aa]miga[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-amigaos exit ;; *:[Mm]orph[Oo][Ss]:*:*) echo ${UNAME_MACHINE}-unknown-morphos exit ;; *:OS/390:*:*) echo i370-ibm-openedition exit ;; *:z/VM:*:*) echo s390-ibm-zvmoe exit ;; *:OS400:*:*) echo powerpc-ibm-os400 exit ;; arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) echo arm-acorn-riscix${UNAME_RELEASE} exit ;; arm*:riscos:*:*|arm*:RISCOS:*:*) echo arm-unknown-riscos exit ;; SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) echo hppa1.1-hitachi-hiuxmpp exit ;; Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. if test "`(/bin/universe) 2>/dev/null`" = att ; then echo pyramid-pyramid-sysv3 else echo pyramid-pyramid-bsd fi exit ;; NILE*:*:*:dcosx) echo pyramid-pyramid-svr4 exit ;; DRS?6000:unix:4.0:6*) echo sparc-icl-nx6 exit ;; DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) case `/usr/bin/uname -p` in sparc) echo sparc-icl-nx7; exit ;; esac ;; s390x:SunOS:*:*) echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4H:SunOS:5.*:*) echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) echo i386-pc-auroraux${UNAME_RELEASE} exit ;; i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) eval $set_cc_for_build SUN_ARCH="i386" # If there is a compiler, see if it is configured for 64-bit objects. # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. # This test works for both compilers. if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then SUN_ARCH="x86_64" fi fi echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:6*:*) # According to config.sub, this is the proper way to canonicalize # SunOS6. Hard to guess exactly what SunOS6 will be like, but # it's likely to be more like Solaris than SunOS4. echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; sun4*:SunOS:*:*) case "`/usr/bin/arch -k`" in Series*|S4*) UNAME_RELEASE=`uname -v` ;; esac # Japanese Language versions have a version number like `4.1.3-JL'. echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` exit ;; sun3*:SunOS:*:*) echo m68k-sun-sunos${UNAME_RELEASE} exit ;; sun*:*:4.2BSD:*) UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 case "`/bin/arch`" in sun3) echo m68k-sun-sunos${UNAME_RELEASE} ;; sun4) echo sparc-sun-sunos${UNAME_RELEASE} ;; esac exit ;; aushp:SunOS:*:*) echo sparc-auspex-sunos${UNAME_RELEASE} exit ;; # The situation for MiNT is a little confusing. The machine name # can be virtually everything (everything which is not # "atarist" or "atariste" at least should have a processor # > m68000). The system name ranges from "MiNT" over "FreeMiNT" # to the lowercase version "mint" (or "freemint"). Finally # the system name "TOS" denotes a system which is actually not # MiNT. But MiNT is downward compatible to TOS, so this should # be no problem. atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) echo m68k-atari-mint${UNAME_RELEASE} exit ;; milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) echo m68k-milan-mint${UNAME_RELEASE} exit ;; hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) echo m68k-hades-mint${UNAME_RELEASE} exit ;; *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) echo m68k-unknown-mint${UNAME_RELEASE} exit ;; m68k:machten:*:*) echo m68k-apple-machten${UNAME_RELEASE} exit ;; powerpc:machten:*:*) echo powerpc-apple-machten${UNAME_RELEASE} exit ;; RISC*:Mach:*:*) echo mips-dec-mach_bsd4.3 exit ;; RISC*:ULTRIX:*:*) echo mips-dec-ultrix${UNAME_RELEASE} exit ;; VAX*:ULTRIX*:*:*) echo vax-dec-ultrix${UNAME_RELEASE} exit ;; 2020:CLIX:*:* | 2430:CLIX:*:*) echo clipper-intergraph-clix${UNAME_RELEASE} exit ;; mips:*:*:UMIPS | mips:*:*:RISCos) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #ifdef __cplusplus #include /* for printf() prototype */ int main (int argc, char *argv[]) { #else int main (argc, argv) int argc; char *argv[]; { #endif #if defined (host_mips) && defined (MIPSEB) #if defined (SYSTYPE_SYSV) printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_SVR4) printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); #endif #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); #endif #endif exit (-1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && SYSTEM_NAME=`$dummy $dummyarg` && { echo "$SYSTEM_NAME"; exit; } echo mips-mips-riscos${UNAME_RELEASE} exit ;; Motorola:PowerMAX_OS:*:*) echo powerpc-motorola-powermax exit ;; Motorola:*:4.3:PL8-*) echo powerpc-harris-powermax exit ;; Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) echo powerpc-harris-powermax exit ;; Night_Hawk:Power_UNIX:*:*) echo powerpc-harris-powerunix exit ;; m88k:CX/UX:7*:*) echo m88k-harris-cxux7 exit ;; m88k:*:4*:R4*) echo m88k-motorola-sysv4 exit ;; m88k:*:3*:R3*) echo m88k-motorola-sysv3 exit ;; AViiON:dgux:*:*) # DG/UX returns AViiON for all architectures UNAME_PROCESSOR=`/usr/bin/uname -p` if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] then if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ [ ${TARGET_BINARY_INTERFACE}x = x ] then echo m88k-dg-dgux${UNAME_RELEASE} else echo m88k-dg-dguxbcs${UNAME_RELEASE} fi else echo i586-dg-dgux${UNAME_RELEASE} fi exit ;; M88*:DolphinOS:*:*) # DolphinOS (SVR3) echo m88k-dolphin-sysv3 exit ;; M88*:*:R3*:*) # Delta 88k system running SVR3 echo m88k-motorola-sysv3 exit ;; XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) echo m88k-tektronix-sysv3 exit ;; Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) echo m68k-tektronix-bsd exit ;; *:IRIX*:*:*) echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` exit ;; ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' i*86:AIX:*:*) echo i386-ibm-aix exit ;; ia64:AIX:*:*) if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} exit ;; *:AIX:2:3) if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include main() { if (!__power_pc()) exit(1); puts("powerpc-ibm-aix3.2.5"); exit(0); } EOF if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` then echo "$SYSTEM_NAME" else echo rs6000-ibm-aix3.2.5 fi elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then echo rs6000-ibm-aix3.2.4 else echo rs6000-ibm-aix3.2 fi exit ;; *:AIX:*:[4567]) IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then IBM_ARCH=rs6000 else IBM_ARCH=powerpc fi if [ -x /usr/bin/oslevel ] ; then IBM_REV=`/usr/bin/oslevel` else IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} fi echo ${IBM_ARCH}-ibm-aix${IBM_REV} exit ;; *:AIX:*:*) echo rs6000-ibm-aix exit ;; ibmrt:4.4BSD:*|romp-ibm:BSD:*) echo romp-ibm-bsd4.4 exit ;; ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to exit ;; # report: romp-ibm BSD 4.3 *:BOSX:*:*) echo rs6000-bull-bosx exit ;; DPX/2?00:B.O.S.:*:*) echo m68k-bull-sysv3 exit ;; 9000/[34]??:4.3bsd:1.*:*) echo m68k-hp-bsd exit ;; hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) echo m68k-hp-bsd4.4 exit ;; 9000/[34678]??:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` case "${UNAME_MACHINE}" in 9000/31? ) HP_ARCH=m68000 ;; 9000/[34]?? ) HP_ARCH=m68k ;; 9000/[678][0-9][0-9]) if [ -x /usr/bin/getconf ]; then sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` case "${sc_cpu_version}" in 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 532) # CPU_PA_RISC2_0 case "${sc_kernel_bits}" in 32) HP_ARCH="hppa2.0n" ;; 64) HP_ARCH="hppa2.0w" ;; '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 esac ;; esac fi if [ "${HP_ARCH}" = "" ]; then eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #define _HPUX_SOURCE #include #include int main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); #endif long cpu = sysconf (_SC_CPU_VERSION); switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0"); break; case CPU_PA_RISC1_1: puts ("hppa1.1"); break; case CPU_PA_RISC2_0: #if defined(_SC_KERNEL_BITS) switch (bits) { case 64: puts ("hppa2.0w"); break; case 32: puts ("hppa2.0n"); break; default: puts ("hppa2.0"); break; } break; #else /* !defined(_SC_KERNEL_BITS) */ puts ("hppa2.0"); break; #endif default: puts ("hppa1.0"); break; } exit (0); } EOF (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` test -z "$HP_ARCH" && HP_ARCH=hppa fi ;; esac if [ ${HP_ARCH} = "hppa2.0w" ] then eval $set_cc_for_build # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler # generating 64-bit code. GNU and HP use different nomenclature: # # $ CC_FOR_BUILD=cc ./config.guess # => hppa2.0w-hp-hpux11.23 # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess # => hppa64-hp-hpux11.23 if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | grep -q __LP64__ then HP_ARCH="hppa2.0w" else HP_ARCH="hppa64" fi fi echo ${HP_ARCH}-hp-hpux${HPUX_REV} exit ;; ia64:HP-UX:*:*) HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` echo ia64-hp-hpux${HPUX_REV} exit ;; 3050*:HI-UX:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #include int main () { long cpu = sysconf (_SC_CPU_VERSION); /* The order matters, because CPU_IS_HP_MC68K erroneously returns true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct results, however. */ if (CPU_IS_PA_RISC (cpu)) { switch (cpu) { case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; default: puts ("hppa-hitachi-hiuxwe2"); break; } } else if (CPU_IS_HP_MC68K (cpu)) puts ("m68k-hitachi-hiuxwe2"); else puts ("unknown-hitachi-hiuxwe2"); exit (0); } EOF $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } echo unknown-hitachi-hiuxwe2 exit ;; 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) echo hppa1.1-hp-bsd exit ;; 9000/8??:4.3bsd:*:*) echo hppa1.0-hp-bsd exit ;; *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) echo hppa1.0-hp-mpeix exit ;; hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) echo hppa1.1-hp-osf exit ;; hp8??:OSF1:*:*) echo hppa1.0-hp-osf exit ;; i*86:OSF1:*:*) if [ -x /usr/sbin/sysversion ] ; then echo ${UNAME_MACHINE}-unknown-osf1mk else echo ${UNAME_MACHINE}-unknown-osf1 fi exit ;; parisc*:Lites*:*:*) echo hppa1.1-hp-lites exit ;; C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) echo c1-convex-bsd exit ;; C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) echo c34-convex-bsd exit ;; C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) echo c38-convex-bsd exit ;; C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) echo c4-convex-bsd exit ;; CRAY*Y-MP:*:*:*) echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*[A-Z]90:*:*:*) echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ -e 's/\.[^.]*$/.X/' exit ;; CRAY*TS:*:*:*) echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*T3E:*:*:*) echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; CRAY*SV1:*:*:*) echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; *:UNICOS/mp:*:*) echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' exit ;; F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; 5000:UNIX_System_V:4.*:*) FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" exit ;; i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} exit ;; sparc*:BSD/OS:*:*) echo sparc-unknown-bsdi${UNAME_RELEASE} exit ;; *:BSD/OS:*:*) echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} exit ;; *:FreeBSD:*:*) UNAME_PROCESSOR=`/usr/bin/uname -p` case ${UNAME_PROCESSOR} in amd64) echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; *) echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; esac exit ;; i*:CYGWIN*:*) echo ${UNAME_MACHINE}-pc-cygwin exit ;; *:MINGW64*:*) echo ${UNAME_MACHINE}-pc-mingw64 exit ;; *:MINGW*:*) echo ${UNAME_MACHINE}-pc-mingw32 exit ;; i*:MSYS*:*) echo ${UNAME_MACHINE}-pc-msys exit ;; i*:windows32*:*) # uname -m includes "-pc" on this system. echo ${UNAME_MACHINE}-mingw32 exit ;; i*:PW*:*) echo ${UNAME_MACHINE}-pc-pw32 exit ;; *:Interix*:*) case ${UNAME_MACHINE} in x86) echo i586-pc-interix${UNAME_RELEASE} exit ;; authenticamd | genuineintel | EM64T) echo x86_64-unknown-interix${UNAME_RELEASE} exit ;; IA64) echo ia64-unknown-interix${UNAME_RELEASE} exit ;; esac ;; [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) echo i${UNAME_MACHINE}-pc-mks exit ;; 8664:Windows_NT:*) echo x86_64-pc-mks exit ;; i*:Windows_NT*:* | Pentium*:Windows_NT*:*) # How do we know it's Interix rather than the generic POSIX subsystem? # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we # UNAME_MACHINE based on the output of uname instead of i386? echo i586-pc-interix exit ;; i*:UWIN*:*) echo ${UNAME_MACHINE}-pc-uwin exit ;; amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) echo x86_64-unknown-cygwin exit ;; p*:CYGWIN*:*) echo powerpcle-unknown-cygwin exit ;; prep*:SunOS:5.*:*) echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` exit ;; *:GNU:*:*) # the GNU system echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` exit ;; *:GNU/*:*:*) # other systems with GNU libc and userland echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC} exit ;; i*86:Minix:*:*) echo ${UNAME_MACHINE}-pc-minix exit ;; aarch64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; alpha:Linux:*:*) case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in EV5) UNAME_MACHINE=alphaev5 ;; EV56) UNAME_MACHINE=alphaev56 ;; PCA56) UNAME_MACHINE=alphapca56 ;; PCA57) UNAME_MACHINE=alphapca56 ;; EV6) UNAME_MACHINE=alphaev6 ;; EV67) UNAME_MACHINE=alphaev67 ;; EV68*) UNAME_MACHINE=alphaev68 ;; esac objdump --private-headers /bin/sh | grep -q ld.so.1 if test "$?" = 0 ; then LIBC="gnulibc1" ; fi echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arc:Linux:*:* | arceb:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; arm*:Linux:*:*) eval $set_cc_for_build if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_EABI__ then echo ${UNAME_MACHINE}-unknown-linux-${LIBC} else if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \ | grep -q __ARM_PCS_VFP then echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi else echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf fi fi exit ;; avr32*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; cris:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; crisv32:Linux:*:*) echo ${UNAME_MACHINE}-axis-linux-${LIBC} exit ;; frv:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; hexagon:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:Linux:*:*) echo ${UNAME_MACHINE}-pc-linux-${LIBC} exit ;; ia64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m32r*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; m68*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; mips:Linux:*:* | mips64:Linux:*:*) eval $set_cc_for_build sed 's/^ //' << EOF >$dummy.c #undef CPU #undef ${UNAME_MACHINE} #undef ${UNAME_MACHINE}el #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) CPU=${UNAME_MACHINE}el #else #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) CPU=${UNAME_MACHINE} #else CPU= #endif #endif EOF eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; } ;; or1k:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; or32:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; padre:Linux:*:*) echo sparc-unknown-linux-${LIBC} exit ;; parisc64:Linux:*:* | hppa64:Linux:*:*) echo hppa64-unknown-linux-${LIBC} exit ;; parisc:Linux:*:* | hppa:Linux:*:*) # Look for CPU level case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in PA7*) echo hppa1.1-unknown-linux-${LIBC} ;; PA8*) echo hppa2.0-unknown-linux-${LIBC} ;; *) echo hppa-unknown-linux-${LIBC} ;; esac exit ;; ppc64:Linux:*:*) echo powerpc64-unknown-linux-${LIBC} exit ;; ppc:Linux:*:*) echo powerpc-unknown-linux-${LIBC} exit ;; ppc64le:Linux:*:*) echo powerpc64le-unknown-linux-${LIBC} exit ;; ppcle:Linux:*:*) echo powerpcle-unknown-linux-${LIBC} exit ;; s390:Linux:*:* | s390x:Linux:*:*) echo ${UNAME_MACHINE}-ibm-linux-${LIBC} exit ;; sh64*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sh*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; sparc:Linux:*:* | sparc64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; tile*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; vax:Linux:*:*) echo ${UNAME_MACHINE}-dec-linux-${LIBC} exit ;; x86_64:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; xtensa*:Linux:*:*) echo ${UNAME_MACHINE}-unknown-linux-${LIBC} exit ;; i*86:DYNIX/ptx:4*:*) # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. # earlier versions are messed up and put the nodename in both # sysname and nodename. echo i386-sequent-sysv4 exit ;; i*86:UNIX_SV:4.2MP:2.*) # Unixware is an offshoot of SVR4, but it has its own version # number series starting with 2... # I am not positive that other SVR4 systems won't match this, # I just have to hope. -- rms. # Use sysv4.2uw... so that sysv4* matches it. echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} exit ;; i*86:OS/2:*:*) # If we were able to find `uname', then EMX Unix compatibility # is probably installed. echo ${UNAME_MACHINE}-pc-os2-emx exit ;; i*86:XTS-300:*:STOP) echo ${UNAME_MACHINE}-unknown-stop exit ;; i*86:atheos:*:*) echo ${UNAME_MACHINE}-unknown-atheos exit ;; i*86:syllable:*:*) echo ${UNAME_MACHINE}-pc-syllable exit ;; i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) echo i386-unknown-lynxos${UNAME_RELEASE} exit ;; i*86:*DOS:*:*) echo ${UNAME_MACHINE}-pc-msdosdjgpp exit ;; i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} else echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} fi exit ;; i*86:*:5:[678]*) # UnixWare 7.x, OpenUNIX and OpenServer 6. case `/bin/uname -X | grep "^Machine"` in *486*) UNAME_MACHINE=i486 ;; *Pentium) UNAME_MACHINE=i586 ;; *Pent*|*Celeron) UNAME_MACHINE=i686 ;; esac echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} exit ;; i*86:*:3.2:*) if test -f /usr/options/cb.name; then UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ && UNAME_MACHINE=i586 (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ && UNAME_MACHINE=i686 (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ && UNAME_MACHINE=i686 echo ${UNAME_MACHINE}-pc-sco$UNAME_REL else echo ${UNAME_MACHINE}-pc-sysv32 fi exit ;; pc:*:*:*) # Left here for compatibility: # uname -m prints for DJGPP always 'pc', but it prints nothing about # the processor, so we play safe by assuming i586. # Note: whatever this is, it MUST be the same as what config.sub # prints for the "djgpp" host, or else GDB configury will decide that # this is a cross-build. echo i586-pc-msdosdjgpp exit ;; Intel:Mach:3*:*) echo i386-pc-mach3 exit ;; paragon:*:*:*) echo i860-intel-osf1 exit ;; i860:*:4.*:*) # i860-SVR4 if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 else # Add other i860-SVR4 vendors below as they are discovered. echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 fi exit ;; mini*:CTIX:SYS*5:*) # "miniframe" echo m68010-convergent-sysv exit ;; mc68k:UNIX:SYSTEM5:3.51m) echo m68k-convergent-sysv exit ;; M680?0:D-NIX:5.3:*) echo m68k-diab-dnix exit ;; M68*:*:R3V[5678]*:*) test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) OS_REL='' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4; exit; } ;; NCR*:*:4.2:* | MPRAS*:*:4.2:*) OS_REL='.3' test -r /etc/.relid \ && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ && { echo i486-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) echo m68k-unknown-lynxos${UNAME_RELEASE} exit ;; mc68030:UNIX_System_V:4.*:*) echo m68k-atari-sysv4 exit ;; TSUNAMI:LynxOS:2.*:*) echo sparc-unknown-lynxos${UNAME_RELEASE} exit ;; rs6000:LynxOS:2.*:*) echo rs6000-unknown-lynxos${UNAME_RELEASE} exit ;; PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) echo powerpc-unknown-lynxos${UNAME_RELEASE} exit ;; SM[BE]S:UNIX_SV:*:*) echo mips-dde-sysv${UNAME_RELEASE} exit ;; RM*:ReliantUNIX-*:*:*) echo mips-sni-sysv4 exit ;; RM*:SINIX-*:*:*) echo mips-sni-sysv4 exit ;; *:SINIX-*:*:*) if uname -p 2>/dev/null >/dev/null ; then UNAME_MACHINE=`(uname -p) 2>/dev/null` echo ${UNAME_MACHINE}-sni-sysv4 else echo ns32k-sni-sysv fi exit ;; PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort # says echo i586-unisys-sysv4 exit ;; *:UNIX_System_V:4*:FTX*) # From Gerald Hewes . # How about differentiating between stratus architectures? -djm echo hppa1.1-stratus-sysv4 exit ;; *:*:*:FTX*) # From seanf@swdc.stratus.com. echo i860-stratus-sysv4 exit ;; i*86:VOS:*:*) # From Paul.Green@stratus.com. echo ${UNAME_MACHINE}-stratus-vos exit ;; *:VOS:*:*) # From Paul.Green@stratus.com. echo hppa1.1-stratus-vos exit ;; mc68*:A/UX:*:*) echo m68k-apple-aux${UNAME_RELEASE} exit ;; news*:NEWS-OS:6*:*) echo mips-sony-newsos6 exit ;; R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) if [ -d /usr/nec ]; then echo mips-nec-sysv${UNAME_RELEASE} else echo mips-unknown-sysv${UNAME_RELEASE} fi exit ;; BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. echo powerpc-be-beos exit ;; BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. echo powerpc-apple-beos exit ;; BePC:BeOS:*:*) # BeOS running on Intel PC compatible. echo i586-pc-beos exit ;; BePC:Haiku:*:*) # Haiku running on Intel PC compatible. echo i586-pc-haiku exit ;; x86_64:Haiku:*:*) echo x86_64-unknown-haiku exit ;; SX-4:SUPER-UX:*:*) echo sx4-nec-superux${UNAME_RELEASE} exit ;; SX-5:SUPER-UX:*:*) echo sx5-nec-superux${UNAME_RELEASE} exit ;; SX-6:SUPER-UX:*:*) echo sx6-nec-superux${UNAME_RELEASE} exit ;; SX-7:SUPER-UX:*:*) echo sx7-nec-superux${UNAME_RELEASE} exit ;; SX-8:SUPER-UX:*:*) echo sx8-nec-superux${UNAME_RELEASE} exit ;; SX-8R:SUPER-UX:*:*) echo sx8r-nec-superux${UNAME_RELEASE} exit ;; Power*:Rhapsody:*:*) echo powerpc-apple-rhapsody${UNAME_RELEASE} exit ;; *:Rhapsody:*:*) echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} exit ;; *:Darwin:*:*) UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown eval $set_cc_for_build if test "$UNAME_PROCESSOR" = unknown ; then UNAME_PROCESSOR=powerpc fi if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ grep IS_64BIT_ARCH >/dev/null then case $UNAME_PROCESSOR in i386) UNAME_PROCESSOR=x86_64 ;; powerpc) UNAME_PROCESSOR=powerpc64 ;; esac fi fi echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} exit ;; *:procnto*:*:* | *:QNX:[0123456789]*:*) UNAME_PROCESSOR=`uname -p` if test "$UNAME_PROCESSOR" = "x86"; then UNAME_PROCESSOR=i386 UNAME_MACHINE=pc fi echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} exit ;; *:QNX:*:4*) echo i386-pc-qnx exit ;; NEO-?:NONSTOP_KERNEL:*:*) echo neo-tandem-nsk${UNAME_RELEASE} exit ;; NSE-*:NONSTOP_KERNEL:*:*) echo nse-tandem-nsk${UNAME_RELEASE} exit ;; NSR-?:NONSTOP_KERNEL:*:*) echo nsr-tandem-nsk${UNAME_RELEASE} exit ;; *:NonStop-UX:*:*) echo mips-compaq-nonstopux exit ;; BS2000:POSIX*:*:*) echo bs2000-siemens-sysv exit ;; DS/*:UNIX_System_V:*:*) echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} exit ;; *:Plan9:*:*) # "uname -m" is not consistent, so use $cputype instead. 386 # is converted to i386 for consistency with other x86 # operating systems. if test "$cputype" = "386"; then UNAME_MACHINE=i386 else UNAME_MACHINE="$cputype" fi echo ${UNAME_MACHINE}-unknown-plan9 exit ;; *:TOPS-10:*:*) echo pdp10-unknown-tops10 exit ;; *:TENEX:*:*) echo pdp10-unknown-tenex exit ;; KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) echo pdp10-dec-tops20 exit ;; XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) echo pdp10-xkl-tops20 exit ;; *:TOPS-20:*:*) echo pdp10-unknown-tops20 exit ;; *:ITS:*:*) echo pdp10-unknown-its exit ;; SEI:*:*:SEIUX) echo mips-sei-seiux${UNAME_RELEASE} exit ;; *:DragonFly:*:*) echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` exit ;; *:*VMS:*:*) UNAME_MACHINE=`(uname -p) 2>/dev/null` case "${UNAME_MACHINE}" in A*) echo alpha-dec-vms ; exit ;; I*) echo ia64-dec-vms ; exit ;; V*) echo vax-dec-vms ; exit ;; esac ;; *:XENIX:*:SysV) echo i386-pc-xenix exit ;; i*86:skyos:*:*) echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' exit ;; i*86:rdos:*:*) echo ${UNAME_MACHINE}-pc-rdos exit ;; i*86:AROS:*:*) echo ${UNAME_MACHINE}-pc-aros exit ;; x86_64:VMkernel:*:*) echo ${UNAME_MACHINE}-unknown-esx exit ;; esac eval $set_cc_for_build cat >$dummy.c < # include #endif main () { #if defined (sony) #if defined (MIPSEB) /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, I don't know.... */ printf ("mips-sony-bsd\n"); exit (0); #else #include printf ("m68k-sony-newsos%s\n", #ifdef NEWSOS4 "4" #else "" #endif ); exit (0); #endif #endif #if defined (__arm) && defined (__acorn) && defined (__unix) printf ("arm-acorn-riscix\n"); exit (0); #endif #if defined (hp300) && !defined (hpux) printf ("m68k-hp-bsd\n"); exit (0); #endif #if defined (NeXT) #if !defined (__ARCHITECTURE__) #define __ARCHITECTURE__ "m68k" #endif int version; version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; if (version < 4) printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); else printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); exit (0); #endif #if defined (MULTIMAX) || defined (n16) #if defined (UMAXV) printf ("ns32k-encore-sysv\n"); exit (0); #else #if defined (CMU) printf ("ns32k-encore-mach\n"); exit (0); #else printf ("ns32k-encore-bsd\n"); exit (0); #endif #endif #endif #if defined (__386BSD__) printf ("i386-pc-bsd\n"); exit (0); #endif #if defined (sequent) #if defined (i386) printf ("i386-sequent-dynix\n"); exit (0); #endif #if defined (ns32000) printf ("ns32k-sequent-dynix\n"); exit (0); #endif #endif #if defined (_SEQUENT_) struct utsname un; uname(&un); if (strncmp(un.version, "V2", 2) == 0) { printf ("i386-sequent-ptx2\n"); exit (0); } if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ printf ("i386-sequent-ptx1\n"); exit (0); } printf ("i386-sequent-ptx\n"); exit (0); #endif #if defined (vax) # if !defined (ultrix) # include # if defined (BSD) # if BSD == 43 printf ("vax-dec-bsd4.3\n"); exit (0); # else # if BSD == 199006 printf ("vax-dec-bsd4.3reno\n"); exit (0); # else printf ("vax-dec-bsd\n"); exit (0); # endif # endif # else printf ("vax-dec-bsd\n"); exit (0); # endif # else printf ("vax-dec-ultrix\n"); exit (0); # endif #endif #if defined (alliant) && defined (i860) printf ("i860-alliant-bsd\n"); exit (0); #endif exit (1); } EOF $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && { echo "$SYSTEM_NAME"; exit; } # Apollos put the system type in the environment. test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } # Convex versions that predate uname can use getsysinfo(1) if [ -x /usr/convex/getsysinfo ] then case `getsysinfo -f cpu_type` in c1*) echo c1-convex-bsd exit ;; c2*) if getsysinfo -f scalar_acc then echo c32-convex-bsd else echo c2-convex-bsd fi exit ;; c34*) echo c34-convex-bsd exit ;; c38*) echo c38-convex-bsd exit ;; c4*) echo c4-convex-bsd exit ;; esac fi cat >&2 < in order to provide the needed information to handle your system. config.guess timestamp = $timestamp uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` /bin/uname -X = `(/bin/uname -X) 2>/dev/null` hostinfo = `(hostinfo) 2>/dev/null` /bin/universe = `(/bin/universe) 2>/dev/null` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` /bin/arch = `(/bin/arch) 2>/dev/null` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` UNAME_MACHINE = ${UNAME_MACHINE} UNAME_RELEASE = ${UNAME_RELEASE} UNAME_SYSTEM = ${UNAME_SYSTEM} UNAME_VERSION = ${UNAME_VERSION} EOF exit 1 # Local variables: # eval: (add-hook 'write-file-hooks 'time-stamp) # time-stamp-start: "timestamp='" # time-stamp-format: "%:y-%02m-%02d" # time-stamp-end: "'" # End: softhsm-2.0.0/m4/0000775000175000017500000000000012552220146010516 500000000000000softhsm-2.0.0/m4/ltoptions.m40000644000175000017500000003007312552216615012742 00000000000000# Helper functions for option handling. -*- Autoconf -*- # # Copyright (C) 2004, 2005, 2007, 2008, 2009 Free Software Foundation, # Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 7 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) # _LT_MANGLE_OPTION(MACRO-NAME, OPTION-NAME) # ------------------------------------------ m4_define([_LT_MANGLE_OPTION], [[_LT_OPTION_]m4_bpatsubst($1__$2, [[^a-zA-Z0-9_]], [_])]) # _LT_SET_OPTION(MACRO-NAME, OPTION-NAME) # --------------------------------------- # Set option OPTION-NAME for macro MACRO-NAME, and if there is a # matching handler defined, dispatch to it. Other OPTION-NAMEs are # saved as a flag. m4_define([_LT_SET_OPTION], [m4_define(_LT_MANGLE_OPTION([$1], [$2]))dnl m4_ifdef(_LT_MANGLE_DEFUN([$1], [$2]), _LT_MANGLE_DEFUN([$1], [$2]), [m4_warning([Unknown $1 option `$2'])])[]dnl ]) # _LT_IF_OPTION(MACRO-NAME, OPTION-NAME, IF-SET, [IF-NOT-SET]) # ------------------------------------------------------------ # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. m4_define([_LT_IF_OPTION], [m4_ifdef(_LT_MANGLE_OPTION([$1], [$2]), [$3], [$4])]) # _LT_UNLESS_OPTIONS(MACRO-NAME, OPTION-LIST, IF-NOT-SET) # ------------------------------------------------------- # Execute IF-NOT-SET unless all options in OPTION-LIST for MACRO-NAME # are set. m4_define([_LT_UNLESS_OPTIONS], [m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [m4_ifdef(_LT_MANGLE_OPTION([$1], _LT_Option), [m4_define([$0_found])])])[]dnl m4_ifdef([$0_found], [m4_undefine([$0_found])], [$3 ])[]dnl ]) # _LT_SET_OPTIONS(MACRO-NAME, OPTION-LIST) # ---------------------------------------- # OPTION-LIST is a space-separated list of Libtool options associated # with MACRO-NAME. If any OPTION has a matching handler declared with # LT_OPTION_DEFINE, dispatch to that macro; otherwise complain about # the unknown option and exit. m4_defun([_LT_SET_OPTIONS], [# Set options m4_foreach([_LT_Option], m4_split(m4_normalize([$2])), [_LT_SET_OPTION([$1], _LT_Option)]) m4_if([$1],[LT_INIT],[ dnl dnl Simply set some default values (i.e off) if boolean options were not dnl specified: _LT_UNLESS_OPTIONS([LT_INIT], [dlopen], [enable_dlopen=no ]) _LT_UNLESS_OPTIONS([LT_INIT], [win32-dll], [enable_win32_dll=no ]) dnl dnl If no reference was made to various pairs of opposing options, then dnl we run the default mode handler for the pair. For example, if neither dnl `shared' nor `disable-shared' was passed, we enable building of shared dnl archives by default: _LT_UNLESS_OPTIONS([LT_INIT], [shared disable-shared], [_LT_ENABLE_SHARED]) _LT_UNLESS_OPTIONS([LT_INIT], [static disable-static], [_LT_ENABLE_STATIC]) _LT_UNLESS_OPTIONS([LT_INIT], [pic-only no-pic], [_LT_WITH_PIC]) _LT_UNLESS_OPTIONS([LT_INIT], [fast-install disable-fast-install], [_LT_ENABLE_FAST_INSTALL]) ]) ])# _LT_SET_OPTIONS ## --------------------------------- ## ## Macros to handle LT_INIT options. ## ## --------------------------------- ## # _LT_MANGLE_DEFUN(MACRO-NAME, OPTION-NAME) # ----------------------------------------- m4_define([_LT_MANGLE_DEFUN], [[_LT_OPTION_DEFUN_]m4_bpatsubst(m4_toupper([$1__$2]), [[^A-Z0-9_]], [_])]) # LT_OPTION_DEFINE(MACRO-NAME, OPTION-NAME, CODE) # ----------------------------------------------- m4_define([LT_OPTION_DEFINE], [m4_define(_LT_MANGLE_DEFUN([$1], [$2]), [$3])[]dnl ])# LT_OPTION_DEFINE # dlopen # ------ LT_OPTION_DEFINE([LT_INIT], [dlopen], [enable_dlopen=yes ]) AU_DEFUN([AC_LIBTOOL_DLOPEN], [_LT_SET_OPTION([LT_INIT], [dlopen]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `dlopen' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN], []) # win32-dll # --------- # Declare package support for building win32 dll's. LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) ;; esac test -z "$AS" && AS=as _LT_DECL([], [AS], [1], [Assembler program])dnl test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program])dnl test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [Object dumper program])dnl ])# win32-dll AU_DEFUN([AC_LIBTOOL_WIN32_DLL], [AC_REQUIRE([AC_CANONICAL_HOST])dnl _LT_SET_OPTION([LT_INIT], [win32-dll]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `win32-dll' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_WIN32_DLL], []) # _LT_ENABLE_SHARED([DEFAULT]) # ---------------------------- # implement the --enable-shared flag, and supports the `shared' and # `disable-shared' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_SHARED], [m4_define([_LT_ENABLE_SHARED_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([shared], [AS_HELP_STRING([--enable-shared@<:@=PKGS@:>@], [build shared libraries @<:@default=]_LT_ENABLE_SHARED_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_shared=yes ;; no) enable_shared=no ;; *) enable_shared=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_shared=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_shared=]_LT_ENABLE_SHARED_DEFAULT) _LT_DECL([build_libtool_libs], [enable_shared], [0], [Whether or not to build shared libraries]) ])# _LT_ENABLE_SHARED LT_OPTION_DEFINE([LT_INIT], [shared], [_LT_ENABLE_SHARED([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-shared], [_LT_ENABLE_SHARED([no])]) # Old names: AC_DEFUN([AC_ENABLE_SHARED], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[shared]) ]) AC_DEFUN([AC_DISABLE_SHARED], [_LT_SET_OPTION([LT_INIT], [disable-shared]) ]) AU_DEFUN([AM_ENABLE_SHARED], [AC_ENABLE_SHARED($@)]) AU_DEFUN([AM_DISABLE_SHARED], [AC_DISABLE_SHARED($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_SHARED], []) dnl AC_DEFUN([AM_DISABLE_SHARED], []) # _LT_ENABLE_STATIC([DEFAULT]) # ---------------------------- # implement the --enable-static flag, and support the `static' and # `disable-static' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_STATIC], [m4_define([_LT_ENABLE_STATIC_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([static], [AS_HELP_STRING([--enable-static@<:@=PKGS@:>@], [build static libraries @<:@default=]_LT_ENABLE_STATIC_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_static=yes ;; no) enable_static=no ;; *) enable_static=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_static=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_static=]_LT_ENABLE_STATIC_DEFAULT) _LT_DECL([build_old_libs], [enable_static], [0], [Whether or not to build static libraries]) ])# _LT_ENABLE_STATIC LT_OPTION_DEFINE([LT_INIT], [static], [_LT_ENABLE_STATIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-static], [_LT_ENABLE_STATIC([no])]) # Old names: AC_DEFUN([AC_ENABLE_STATIC], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[static]) ]) AC_DEFUN([AC_DISABLE_STATIC], [_LT_SET_OPTION([LT_INIT], [disable-static]) ]) AU_DEFUN([AM_ENABLE_STATIC], [AC_ENABLE_STATIC($@)]) AU_DEFUN([AM_DISABLE_STATIC], [AC_DISABLE_STATIC($@)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_ENABLE_STATIC], []) dnl AC_DEFUN([AM_DISABLE_STATIC], []) # _LT_ENABLE_FAST_INSTALL([DEFAULT]) # ---------------------------------- # implement the --enable-fast-install flag, and support the `fast-install' # and `disable-fast-install' LT_INIT options. # DEFAULT is either `yes' or `no'. If omitted, it defaults to `yes'. m4_define([_LT_ENABLE_FAST_INSTALL], [m4_define([_LT_ENABLE_FAST_INSTALL_DEFAULT], [m4_if($1, no, no, yes)])dnl AC_ARG_ENABLE([fast-install], [AS_HELP_STRING([--enable-fast-install@<:@=PKGS@:>@], [optimize for fast installation @<:@default=]_LT_ENABLE_FAST_INSTALL_DEFAULT[@:>@])], [p=${PACKAGE-default} case $enableval in yes) enable_fast_install=yes ;; no) enable_fast_install=no ;; *) enable_fast_install=no # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for pkg in $enableval; do IFS="$lt_save_ifs" if test "X$pkg" = "X$p"; then enable_fast_install=yes fi done IFS="$lt_save_ifs" ;; esac], [enable_fast_install=]_LT_ENABLE_FAST_INSTALL_DEFAULT) _LT_DECL([fast_install], [enable_fast_install], [0], [Whether or not to optimize for fast installation])dnl ])# _LT_ENABLE_FAST_INSTALL LT_OPTION_DEFINE([LT_INIT], [fast-install], [_LT_ENABLE_FAST_INSTALL([yes])]) LT_OPTION_DEFINE([LT_INIT], [disable-fast-install], [_LT_ENABLE_FAST_INSTALL([no])]) # Old names: AU_DEFUN([AC_ENABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], m4_if([$1], [no], [disable-])[fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `fast-install' option into LT_INIT's first parameter.]) ]) AU_DEFUN([AC_DISABLE_FAST_INSTALL], [_LT_SET_OPTION([LT_INIT], [disable-fast-install]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `disable-fast-install' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_ENABLE_FAST_INSTALL], []) dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_PIC([MODE]) # -------------------- # implement the --with-pic flag, and support the `pic-only' and `no-pic' # LT_INIT options. # MODE is either `yes' or `no'. If omitted, it defaults to `both'. m4_define([_LT_WITH_PIC], [AC_ARG_WITH([pic], [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} case $withval in yes|no) pic_mode=$withval ;; *) pic_mode=default # Look at the argument we got. We use all the common list separators. lt_save_ifs="$IFS"; IFS="${IFS}$PATH_SEPARATOR," for lt_pkg in $withval; do IFS="$lt_save_ifs" if test "X$lt_pkg" = "X$lt_p"; then pic_mode=yes fi done IFS="$lt_save_ifs" ;; esac], [pic_mode=default]) test -z "$pic_mode" && pic_mode=m4_default([$1], [default]) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC LT_OPTION_DEFINE([LT_INIT], [pic-only], [_LT_WITH_PIC([yes])]) LT_OPTION_DEFINE([LT_INIT], [no-pic], [_LT_WITH_PIC([no])]) # Old name: AU_DEFUN([AC_LIBTOOL_PICMODE], [_LT_SET_OPTION([LT_INIT], [pic-only]) AC_DIAGNOSE([obsolete], [$0: Remove this warning and the call to _LT_SET_OPTION when you put the `pic-only' option into LT_INIT's first parameter.]) ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_PICMODE], []) ## ----------------- ## ## LTDL_INIT Options ## ## ----------------- ## m4_define([_LTDL_MODE], []) LT_OPTION_DEFINE([LTDL_INIT], [nonrecursive], [m4_define([_LTDL_MODE], [nonrecursive])]) LT_OPTION_DEFINE([LTDL_INIT], [recursive], [m4_define([_LTDL_MODE], [recursive])]) LT_OPTION_DEFINE([LTDL_INIT], [subproject], [m4_define([_LTDL_MODE], [subproject])]) m4_define([_LTDL_TYPE], []) LT_OPTION_DEFINE([LTDL_INIT], [installable], [m4_define([_LTDL_TYPE], [installable])]) LT_OPTION_DEFINE([LTDL_INIT], [convenience], [m4_define([_LTDL_TYPE], [convenience])]) softhsm-2.0.0/m4/acx_strict.m40000664000175000017500000000044212533040716013045 00000000000000AC_DEFUN([ACX_STRICT],[ AC_ARG_ENABLE( [strict], [AS_HELP_STRING([--enable-strict],[enable strict compile mode @<:@enabled@:>@])], , [enable_strict="yes"] ) if test "${enable_strict}" = "yes"; then CFLAGS="${CFLAGS} -Wall -Wextra" CXXFLAGS="${CXXFLAGS} -Wall -Wextra" fi ]) softhsm-2.0.0/m4/acx_prefixhack.m40000664000175000017500000000114312533040716013660 00000000000000# Special processing of paths depending on whether --prefix, # --sysconfdir or --localstatedir arguments were given. AC_DEFUN([ACX_PREFIXHACK],[ case "$prefix" in NONE) case "$sysconfdir" in '${prefix}/etc') sysconfdir=/etc ac_configure_args="$ac_configure_args --sysconfdir=$sysconfdir" AC_MSG_NOTICE([sysconfdir set to $sysconfdir]) ;; esac case "$localstatedir" in '${prefix}/var') localstatedir=/var ac_configure_args="$ac_configure_args --localstatedir=$localstatedir" AC_MSG_NOTICE([localstate set to $localstatedir]) ;; esac ;; esac ]) softhsm-2.0.0/m4/acx_openssl_gost.m40000664000175000017500000000133412533040716014255 00000000000000AC_DEFUN([ACX_OPENSSL_GOST],[ AC_MSG_CHECKING(for OpenSSL GOST support) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" AC_LANG_PUSH([C]) AC_RUN_IFELSE([ AC_LANG_SOURCE([[ #include #include int main() { ENGINE *e; EC_KEY *ek; ek = NULL; OPENSSL_config(NULL); e = ENGINE_by_id("gost"); if (e == NULL) return 1; if (ENGINE_init(e) <= 0) return 1; return 0; } ]]) ],[ AC_MSG_RESULT([Found GOST engine]) ],[ AC_MSG_RESULT([Cannot GOST engine]) AC_MSG_ERROR([OpenSSL library has no GOST support]) ],[]) AC_LANG_POP([C]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/acx_non_paged_memory.m40000664000175000017500000000341512533040716015062 00000000000000AC_DEFUN([ACX_NON_PAGED_MEMORY],[ AC_ARG_ENABLE(non-paged-memory, AC_HELP_STRING([--disable-non-paged-memory], [Disable non-paged memory for secure storage (default enabled)] ), [enable_non_paged_memory="${enableval}"], [enable_non_paged_memory="yes"] ) AC_MSG_CHECKING(for non-paged memory for secure storage) if test "x${enable_non_paged_memory}" = "xyes"; then AC_MSG_RESULT(enabled) AC_DEFINE_UNQUOTED( [SENSITIVE_NON_PAGE], [], [Non-paged memory for secure storage] ) AC_CHECK_HEADERS([sys/mman.h]) AC_MSG_CHECKING(the maximum size that may be locked into memory) MLOCK_SIZE="`ulimit -l`" AC_MSG_RESULT($MLOCK_SIZE) if test "x${MLOCK_SIZE}" != "xunlimited"; then AC_MSG_WARN([ ====================================================================== SoftHSM has been configured to store sensitive data in non-page RAM (i.e. memory that is not swapped out to disk). This is the default and most secure configuration. Your system, however, is not configured to support this model in non-privileged accounts (i.e. user accounts). You can check the setting on your system by running the following command in a shell: ulimit -l If this does not return "unlimited" and you plan to run SoftHSM from non-privileged accounts then you should edit the configuration file /etc/security/limits.conf (on most systems). You will need to add the following lines to this file: # * - memlock unlimited Alternatively, you can elect to disable this feature of SoftHSM by re-running configure with the option "--disable-non-paged-memory". Please be advised that this may seriously degrade the security of SoftHSM. ======================================================================]) fi else AC_MSG_RESULT(disabled) fi ]) softhsm-2.0.0/m4/acx_botan_ecc.m40000664000175000017500000000224212533040716013452 00000000000000AC_DEFUN([ACX_BOTAN_ECC],[ AC_MSG_CHECKING(for Botan ECC support) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" AC_LANG_PUSH([C++]) AC_RUN_IFELSE([ AC_LANG_SOURCE([[ #include #include #include int main() { Botan::LibraryInitializer::initialize(); const std::string name("secp256r1"); const Botan::OID oid(Botan::OIDS::lookup(name)); const Botan::EC_Group ecg(oid); try { #if BOTAN_VERSION_MINOR == 11 const std::vector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #else const Botan::SecureVector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #endif } catch(...) { return 1; } return 0; } ]]) ],[ AC_MSG_RESULT([Found P256]) ],[ AC_MSG_RESULT([Cannot find P256]) AC_MSG_ERROR([ Botan library has no valid ECC support. Please upgrade to a later version of Botan, above or including version 1.10.6 or 1.11.5. Alternatively disable ECC support in SoftHSM with --disable-ecc ]) ],[]) AC_LANG_POP([C++]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/acx_botan_rfc5649.m40000664000175000017500000000165512533040716014031 00000000000000AC_DEFUN([ACX_BOTAN_RFC5649],[ AC_MSG_CHECKING(for Botan RFC5649 support) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" AC_DEFINE([HAVE_AES_KEY_WRAP], [1], [Define if advanced AES key wrap without pad is supported]) AC_LANG_PUSH([C++]) AC_LINK_IFELSE([ AC_LANG_SOURCE([[ #include #include int main() { using namespace Botan; SecureVector key(10); SymmetricKey kek("AABB"); Algorithm_Factory& af = global_state().algorithm_factory(); SecureVector x = rfc5649_keywrap(key, kek, af); return 1; } ]]) ],[ AC_MSG_RESULT([Found AES key wrap with pad]) AC_DEFINE([HAVE_AES_KEY_WRAP_PAD], [1], [Define if advanced AES key wrap with pad is supported]) ],[ AC_MSG_RESULT([Cannot find AES key wrap with pad]) ]) AC_LANG_POP([C++]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/acx_openssl_ecc.m40000664000175000017500000000136112533040716014033 00000000000000AC_DEFUN([ACX_OPENSSL_ECC],[ AC_MSG_CHECKING(for OpenSSL ECC support) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" AC_LANG_PUSH([C]) AC_RUN_IFELSE([ AC_LANG_SOURCE([[ #include #include int main() { EC_KEY *ec256, *ec384; ec256 = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); ec384 = EC_KEY_new_by_curve_name(NID_secp384r1); if (ec256 == NULL || ec384 == NULL) return 1; return 0; } ]]) ],[ AC_MSG_RESULT([Found P256 and P384]) ],[ AC_MSG_RESULT([Cannot find P256 or P384]) AC_MSG_ERROR([OpenSSL library has no ECC support]) ],[]) AC_LANG_POP([C]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/ax_cxx_compile_stdcxx_11.m40000664000175000017500000001127512533040716015610 00000000000000# ============================================================================ # http://www.gnu.org/software/autoconf-archive/ax_cxx_compile_stdcxx_11.html # ============================================================================ # # SYNOPSIS # # AX_CXX_COMPILE_STDCXX_11([ext|noext],[mandatory|optional]) # # DESCRIPTION # # Check for baseline language coverage in the compiler for the C++11 # standard; if necessary, add switches to CXXFLAGS to enable support. # # The first argument, if specified, indicates whether you insist on an # extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. # -std=c++11). If neither is specified, you get whatever works, with # preference for an extended mode. # # The second argument, if specified 'mandatory' or if left unspecified, # indicates that baseline C++11 support is required and that the macro # should error out if no mode with that support is found. If specified # 'optional', then configuration proceeds regardless, after defining # HAVE_CXX11 if and only if a supporting mode is found. # # LICENSE # # Copyright (c) 2008 Benjamin Kosnik # Copyright (c) 2012 Zack Weinberg # Copyright (c) 2013 Roy Stogner # Copyright (c) 2014 Alexey Sokolov # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 4 m4_define([_AX_CXX_COMPILE_STDCXX_11_testbody], [[ template struct check { static_assert(sizeof(int) <= sizeof(T), "not big enough"); }; struct Base { virtual void f() {} }; struct Child : public Base { virtual void f() override {} }; typedef check> right_angle_brackets; int a; decltype(a) b; typedef check check_type; check_type c; check_type&& cr = static_cast(c); auto d = a; auto l = [](){}; ]]) AC_DEFUN([AX_CXX_COMPILE_STDCXX_11], [dnl m4_if([$1], [], [], [$1], [ext], [], [$1], [noext], [], [m4_fatal([invalid argument `$1' to AX_CXX_COMPILE_STDCXX_11])])dnl m4_if([$2], [], [ax_cxx_compile_cxx11_required=true], [$2], [mandatory], [ax_cxx_compile_cxx11_required=true], [$2], [optional], [ax_cxx_compile_cxx11_required=false], [m4_fatal([invalid second argument `$2' to AX_CXX_COMPILE_STDCXX_11])]) AC_LANG_PUSH([C++])dnl ac_success=no AC_CACHE_CHECK(whether $CXX supports C++11 features by default, ax_cv_cxx_compile_cxx11, [AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], [ax_cv_cxx_compile_cxx11=yes], [ax_cv_cxx_compile_cxx11=no])]) if test x$ax_cv_cxx_compile_cxx11 = xyes; then ac_success=yes fi m4_if([$1], [noext], [], [dnl if test x$ac_success = xno; then for switch in -std=gnu++11 -std=gnu++0x; do cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, $cachevar, [ac_save_CXXFLAGS="$CXXFLAGS" CXXFLAGS="$CXXFLAGS $switch" AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], [eval $cachevar=yes], [eval $cachevar=no]) CXXFLAGS="$ac_save_CXXFLAGS"]) if eval test x\$$cachevar = xyes; then CXXFLAGS="$CXXFLAGS $switch" ac_success=yes break fi done fi]) m4_if([$1], [ext], [], [dnl if test x$ac_success = xno; then for switch in -std=c++11 -std=c++0x; do cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx11_$switch]) AC_CACHE_CHECK(whether $CXX supports C++11 features with $switch, $cachevar, [ac_save_CXXFLAGS="$CXXFLAGS" CXXFLAGS="$CXXFLAGS $switch" AC_COMPILE_IFELSE([AC_LANG_SOURCE([_AX_CXX_COMPILE_STDCXX_11_testbody])], [eval $cachevar=yes], [eval $cachevar=no]) CXXFLAGS="$ac_save_CXXFLAGS"]) if eval test x\$$cachevar = xyes; then CXXFLAGS="$CXXFLAGS $switch" ac_success=yes break fi done fi]) AC_LANG_POP([C++]) if test x$ax_cxx_compile_cxx11_required = xtrue; then if test x$ac_success = xno; then AC_MSG_ERROR([*** A compiler with support for C++11 language features is required.]) fi else if test x$ac_success = xno; then HAVE_CXX11=0 AC_MSG_NOTICE([No compiler with C++11 support was found]) else HAVE_CXX11=1 AC_DEFINE(HAVE_CXX11,1, [define if the compiler supports basic C++11 syntax]) fi AC_SUBST(HAVE_CXX11) fi ]) softhsm-2.0.0/m4/ltsugar.m40000644000175000017500000001042412552216615012366 00000000000000# ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2008 Free Software Foundation, Inc. # Written by Gary V. Vaughan, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 6 ltsugar.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTSUGAR_VERSION], [m4_if([0.1])]) # lt_join(SEP, ARG1, [ARG2...]) # ----------------------------- # Produce ARG1SEPARG2...SEPARGn, omitting [] arguments and their # associated separator. # Needed until we can rely on m4_join from Autoconf 2.62, since all earlier # versions in m4sugar had bugs. m4_define([lt_join], [m4_if([$#], [1], [], [$#], [2], [[$2]], [m4_if([$2], [], [], [[$2]_])$0([$1], m4_shift(m4_shift($@)))])]) m4_define([_lt_join], [m4_if([$#$2], [2], [], [m4_if([$2], [], [], [[$1$2]])$0([$1], m4_shift(m4_shift($@)))])]) # lt_car(LIST) # lt_cdr(LIST) # ------------ # Manipulate m4 lists. # These macros are necessary as long as will still need to support # Autoconf-2.59 which quotes differently. m4_define([lt_car], [[$1]]) m4_define([lt_cdr], [m4_if([$#], 0, [m4_fatal([$0: cannot be called without arguments])], [$#], 1, [], [m4_dquote(m4_shift($@))])]) m4_define([lt_unquote], $1) # lt_append(MACRO-NAME, STRING, [SEPARATOR]) # ------------------------------------------ # Redefine MACRO-NAME to hold its former content plus `SEPARATOR'`STRING'. # Note that neither SEPARATOR nor STRING are expanded; they are appended # to MACRO-NAME as is (leaving the expansion for when MACRO-NAME is invoked). # No SEPARATOR is output if MACRO-NAME was previously undefined (different # than defined and empty). # # This macro is needed until we can rely on Autoconf 2.62, since earlier # versions of m4sugar mistakenly expanded SEPARATOR but not STRING. m4_define([lt_append], [m4_define([$1], m4_ifdef([$1], [m4_defn([$1])[$3]])[$2])]) # lt_combine(SEP, PREFIX-LIST, INFIX, SUFFIX1, [SUFFIX2...]) # ---------------------------------------------------------- # Produce a SEP delimited list of all paired combinations of elements of # PREFIX-LIST with SUFFIX1 through SUFFIXn. Each element of the list # has the form PREFIXmINFIXSUFFIXn. # Needed until we can rely on m4_combine added in Autoconf 2.62. m4_define([lt_combine], [m4_if(m4_eval([$# > 3]), [1], [m4_pushdef([_Lt_sep], [m4_define([_Lt_sep], m4_defn([lt_car]))])]]dnl [[m4_foreach([_Lt_prefix], [$2], [m4_foreach([_Lt_suffix], ]m4_dquote(m4_dquote(m4_shift(m4_shift(m4_shift($@)))))[, [_Lt_sep([$1])[]m4_defn([_Lt_prefix])[$3]m4_defn([_Lt_suffix])])])])]) # lt_if_append_uniq(MACRO-NAME, VARNAME, [SEPARATOR], [UNIQ], [NOT-UNIQ]) # ----------------------------------------------------------------------- # Iff MACRO-NAME does not yet contain VARNAME, then append it (delimited # by SEPARATOR if supplied) and expand UNIQ, else NOT-UNIQ. m4_define([lt_if_append_uniq], [m4_ifdef([$1], [m4_if(m4_index([$3]m4_defn([$1])[$3], [$3$2$3]), [-1], [lt_append([$1], [$2], [$3])$4], [$5])], [lt_append([$1], [$2], [$3])$4])]) # lt_dict_add(DICT, KEY, VALUE) # ----------------------------- m4_define([lt_dict_add], [m4_define([$1($2)], [$3])]) # lt_dict_add_subkey(DICT, KEY, SUBKEY, VALUE) # -------------------------------------------- m4_define([lt_dict_add_subkey], [m4_define([$1($2:$3)], [$4])]) # lt_dict_fetch(DICT, KEY, [SUBKEY]) # ---------------------------------- m4_define([lt_dict_fetch], [m4_ifval([$3], m4_ifdef([$1($2:$3)], [m4_defn([$1($2:$3)])]), m4_ifdef([$1($2)], [m4_defn([$1($2)])]))]) # lt_if_dict_fetch(DICT, KEY, [SUBKEY], VALUE, IF-TRUE, [IF-FALSE]) # ----------------------------------------------------------------- m4_define([lt_if_dict_fetch], [m4_if(lt_dict_fetch([$1], [$2], [$3]), [$4], [$5], [$6])]) # lt_dict_filter(DICT, [SUBKEY], VALUE, [SEPARATOR], KEY, [...]) # -------------------------------------------------------------- m4_define([lt_dict_filter], [m4_if([$5], [], [], [lt_join(m4_quote(m4_default([$4], [[, ]])), lt_unquote(m4_split(m4_normalize(m4_foreach(_Lt_key, lt_car([m4_shiftn(4, $@)]), [lt_if_dict_fetch([$1], _Lt_key, [$2], [$3], [_Lt_key ])])))))])[]dnl ]) softhsm-2.0.0/m4/acx_botan.m40000664000175000017500000000305512533040716012643 00000000000000AC_DEFUN([ACX_BOTAN],[ AC_ARG_WITH(botan, AC_HELP_STRING([--with-botan=PATH],[Specify prefix of path of Botan]), [ BOTAN_PATH="$withval" ], [ BOTAN_PATH="/usr/local" ]) BOTAN_VERSION_MINOR=10 AC_CHECK_FILE($BOTAN_PATH/include/botan-1.10/botan/init.h, BOTAN_VERSION_MINOR=10, AC_CHECK_FILE($BOTAN_PATH/include/botan-1.11/botan/init.h, BOTAN_VERSION_MINOR=11, AC_MSG_ERROR([Cannot find Botan includes]))) AC_MSG_CHECKING(what are the Botan includes) BOTAN_INCLUDES="-I$BOTAN_PATH/include/botan-1.$BOTAN_VERSION_MINOR" AC_MSG_RESULT($BOTAN_INCLUDES) AC_MSG_CHECKING(what are the Botan libs) BOTAN_LIBS="-L$BOTAN_PATH/lib -lbotan-1.$BOTAN_VERSION_MINOR" AC_MSG_RESULT($BOTAN_LIBS) if test "x${BOTAN_VERSION_MINOR}" = "x11"; then AX_CXX_COMPILE_STDCXX_11([noext],[mandatory]) fi tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $BOTAN_INCLUDES" LIBS="$LIBS $BOTAN_LIBS" AC_LANG_PUSH([C++]) AC_LINK_IFELSE( [AC_LANG_PROGRAM( [#include #include ], [using namespace Botan; LibraryInitializer::initialize(); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR($1,$2,$3) #error "Botan version too old"; #endif])], [AC_MSG_RESULT([checking for Botan >= v$1.$2.$3 ... yes])], [AC_MSG_RESULT([checking for Botan >= v$1.$2.$3 ... no]) AC_MSG_ERROR([Missing the correct version of the Botan library])] ) AC_LANG_POP([C++]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS AC_SUBST(BOTAN_INCLUDES) AC_SUBST(BOTAN_LIBS) AC_SUBST(BOTAN_VERSION_MINOR) ]) softhsm-2.0.0/m4/libtool.m40000644000175000017500000106011112552216615012350 00000000000000# libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl # Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, # 2006, 2007, 2008, 2009, 2010, 2011 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # # This file is part of GNU Libtool. # # GNU Libtool is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # As a special exception to the GNU General Public License, # if you distribute this file as part of a program or library that # is built using GNU Libtool, you may include this file under the # same distribution terms that you use for the rest of that program. # # GNU Libtool is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Libtool; see the file COPYING. If not, a copy # can be downloaded from http://www.gnu.org/licenses/gpl.html, or # obtained by writing to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]) # serial 57 LT_INIT # LT_PREREQ(VERSION) # ------------------ # Complain and exit if this libtool version is less that VERSION. m4_defun([LT_PREREQ], [m4_if(m4_version_compare(m4_defn([LT_PACKAGE_VERSION]), [$1]), -1, [m4_default([$3], [m4_fatal([Libtool version $1 or higher is required], 63)])], [$2])]) # _LT_CHECK_BUILDDIR # ------------------ # Complain if the absolute build directory name contains unusual characters m4_defun([_LT_CHECK_BUILDDIR], [case `pwd` in *\ * | *\ *) AC_MSG_WARN([Libtool does not cope well with whitespace in `pwd`]) ;; esac ]) # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], [AC_PREREQ([2.58])dnl We use AC_INCLUDES_DEFAULT AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl AC_BEFORE([$0], [LTDL_INIT])dnl m4_require([_LT_CHECK_BUILDDIR])dnl dnl Autoconf doesn't catch unexpanded LT_ macros by default: m4_pattern_forbid([^_?LT_[A-Z_]+$])dnl m4_pattern_allow([^(_LT_EOF|LT_DLGLOBAL|LT_DLLAZY_OR_NOW|LT_MULTI_MODULE)$])dnl dnl aclocal doesn't pull ltoptions.m4, ltsugar.m4, or ltversion.m4 dnl unless we require an AC_DEFUNed macro: AC_REQUIRE([LTOPTIONS_VERSION])dnl AC_REQUIRE([LTSUGAR_VERSION])dnl AC_REQUIRE([LTVERSION_VERSION])dnl AC_REQUIRE([LTOBSOLETE_VERSION])dnl m4_require([_LT_PROG_LTMAIN])dnl _LT_SHELL_INIT([SHELL=${CONFIG_SHELL-/bin/sh}]) dnl Parse OPTIONS _LT_SET_OPTIONS([$0], [$1]) # This can be used to rebuild libtool when needed LIBTOOL_DEPS="$ltmain" # Always use our own libtool. LIBTOOL='$(SHELL) $(top_builddir)/libtool' AC_SUBST(LIBTOOL)dnl _LT_SETUP # Only expand once: m4_define([LT_INIT]) ])# LT_INIT # Old names: AU_ALIAS([AC_PROG_LIBTOOL], [LT_INIT]) AU_ALIAS([AM_PROG_LIBTOOL], [LT_INIT]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PROG_LIBTOOL], []) dnl AC_DEFUN([AM_PROG_LIBTOOL], []) # _LT_CC_BASENAME(CC) # ------------------- # Calculate cc_basename. Skip known compiler wrappers and cross-prefix. m4_defun([_LT_CC_BASENAME], [for cc_temp in $1""; do case $cc_temp in compile | *[[\\/]]compile | ccache | *[[\\/]]ccache ) ;; distcc | *[[\\/]]distcc | purify | *[[\\/]]purify ) ;; \-*) ;; *) break;; esac done cc_basename=`$ECHO "$cc_temp" | $SED "s%.*/%%; s%^$host_alias-%%"` ]) # _LT_FILEUTILS_DEFAULTS # ---------------------- # It is okay to use these file commands and assume they have been set # sensibly after `m4_require([_LT_FILEUTILS_DEFAULTS])'. m4_defun([_LT_FILEUTILS_DEFAULTS], [: ${CP="cp -f"} : ${MV="mv -f"} : ${RM="rm -f"} ])# _LT_FILEUTILS_DEFAULTS # _LT_SETUP # --------- m4_defun([_LT_SETUP], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_REQUIRE([_LT_PREPARE_SED_QUOTE_VARS])dnl AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH])dnl _LT_DECL([], [PATH_SEPARATOR], [1], [The PATH separator for the build system])dnl dnl _LT_DECL([], [host_alias], [0], [The host system])dnl _LT_DECL([], [host], [0])dnl _LT_DECL([], [host_os], [0])dnl dnl _LT_DECL([], [build_alias], [0], [The build system])dnl _LT_DECL([], [build], [0])dnl _LT_DECL([], [build_os], [0])dnl dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl dnl AC_REQUIRE([AC_PROG_LN_S])dnl test -z "$LN_S" && LN_S="ln -s" _LT_DECL([], [LN_S], [1], [Whether we need soft or hard links])dnl dnl AC_REQUIRE([LT_CMD_MAX_LEN])dnl _LT_DECL([objext], [ac_objext], [0], [Object file suffix (normally "o")])dnl _LT_DECL([], [exeext], [0], [Executable file suffix (normally "")])dnl dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl m4_require([_LT_PATH_CONVERSION_FUNCTIONS])dnl m4_require([_LT_CMD_RELOAD])dnl m4_require([_LT_CHECK_MAGIC_METHOD])dnl m4_require([_LT_CHECK_SHAREDLIB_FROM_LINKLIB])dnl m4_require([_LT_CMD_OLD_ARCHIVE])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_WITH_SYSROOT])dnl _LT_CONFIG_LIBTOOL_INIT([ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes INIT. if test -n "\${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi ]) if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi _LT_CHECK_OBJDIR m4_require([_LT_TAG_COMPILER])dnl case $host_os in aix3*) # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi ;; esac # Global variables: ofile=libtool can_build_shared=yes # All known linkers require a `.a' archive for static linking (except MSVC, # which needs '.lib'). libext=a with_gnu_ld="$lt_cv_prog_gnu_ld" old_CC="$CC" old_CFLAGS="$CFLAGS" # Set sane defaults for various variables test -z "$CC" && CC=cc test -z "$LTCC" && LTCC=$CC test -z "$LTCFLAGS" && LTCFLAGS=$CFLAGS test -z "$LD" && LD=ld test -z "$ac_objext" && ac_objext=o _LT_CC_BASENAME([$compiler]) # Only perform the check for file, if the check method requires it test -z "$MAGIC_CMD" && MAGIC_CMD=file case $deplibs_check_method in file_magic*) if test "$file_magic_cmd" = '$MAGIC_CMD'; then _LT_PATH_MAGIC fi ;; esac # Use C for the default configuration in the libtool script LT_SUPPORTED_TAG([CC]) _LT_LANG_C_CONFIG _LT_LANG_DEFAULT_CONFIG _LT_CONFIG_COMMANDS ])# _LT_SETUP # _LT_PREPARE_SED_QUOTE_VARS # -------------------------- # Define a few sed substitution that help us do robust quoting. m4_defun([_LT_PREPARE_SED_QUOTE_VARS], [# Backslashify metacharacters that are still active within # double-quoted strings. sed_quote_subst='s/\([["`$\\]]\)/\\\1/g' # Same as above, but do not quote variable references. double_quote_subst='s/\([["`\\]]\)/\\\1/g' # Sed substitution to delay expansion of an escaped shell variable in a # double_quote_subst'ed string. delay_variable_subst='s/\\\\\\\\\\\$/\\\\\\$/g' # Sed substitution to delay expansion of an escaped single quote. delay_single_quote_subst='s/'\''/'\'\\\\\\\'\''/g' # Sed substitution to avoid accidental globbing in evaled expressions no_glob_subst='s/\*/\\\*/g' ]) # _LT_PROG_LTMAIN # --------------- # Note that this code is called both from `configure', and `config.status' # now that we use AC_CONFIG_COMMANDS to generate libtool. Notably, # `config.status' has no value for ac_aux_dir unless we are using Automake, # so we pass a copy along to make sure it has a sensible value anyway. m4_defun([_LT_PROG_LTMAIN], [m4_ifdef([AC_REQUIRE_AUX_FILE], [AC_REQUIRE_AUX_FILE([ltmain.sh])])dnl _LT_CONFIG_LIBTOOL_INIT([ac_aux_dir='$ac_aux_dir']) ltmain="$ac_aux_dir/ltmain.sh" ])# _LT_PROG_LTMAIN ## ------------------------------------- ## ## Accumulate code for creating libtool. ## ## ------------------------------------- ## # So that we can recreate a full libtool script including additional # tags, we accumulate the chunks of code to send to AC_CONFIG_COMMANDS # in macros and then make a single call at the end using the `libtool' # label. # _LT_CONFIG_LIBTOOL_INIT([INIT-COMMANDS]) # ---------------------------------------- # Register INIT-COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL_INIT], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_INIT], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_INIT]) # _LT_CONFIG_LIBTOOL([COMMANDS]) # ------------------------------ # Register COMMANDS to be passed to AC_CONFIG_COMMANDS later. m4_define([_LT_CONFIG_LIBTOOL], [m4_ifval([$1], [m4_append([_LT_OUTPUT_LIBTOOL_COMMANDS], [$1 ])])]) # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS]) # _LT_CONFIG_SAVE_COMMANDS([COMMANDS], [INIT_COMMANDS]) # ----------------------------------------------------- m4_defun([_LT_CONFIG_SAVE_COMMANDS], [_LT_CONFIG_LIBTOOL([$1]) _LT_CONFIG_LIBTOOL_INIT([$2]) ]) # _LT_FORMAT_COMMENT([COMMENT]) # ----------------------------- # Add leading comment marks to the start of each line, and a trailing # full-stop to the whole comment if one is not present already. m4_define([_LT_FORMAT_COMMENT], [m4_ifval([$1], [ m4_bpatsubst([m4_bpatsubst([$1], [^ *], [# ])], [['`$\]], [\\\&])]m4_bmatch([$1], [[!?.]$], [], [.]) )]) ## ------------------------ ## ## FIXME: Eliminate VARNAME ## ## ------------------------ ## # _LT_DECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION], [IS-TAGGED?]) # ------------------------------------------------------------------- # CONFIGNAME is the name given to the value in the libtool script. # VARNAME is the (base) name used in the configure script. # VALUE may be 0, 1 or 2 for a computed quote escaped value based on # VARNAME. Any other value will be used directly. m4_define([_LT_DECL], [lt_if_append_uniq([lt_decl_varnames], [$2], [, ], [lt_dict_add_subkey([lt_decl_dict], [$2], [libtool_name], [m4_ifval([$1], [$1], [$2])]) lt_dict_add_subkey([lt_decl_dict], [$2], [value], [$3]) m4_ifval([$4], [lt_dict_add_subkey([lt_decl_dict], [$2], [description], [$4])]) lt_dict_add_subkey([lt_decl_dict], [$2], [tagged?], [m4_ifval([$5], [yes], [no])])]) ]) # _LT_TAGDECL([CONFIGNAME], VARNAME, VALUE, [DESCRIPTION]) # -------------------------------------------------------- m4_define([_LT_TAGDECL], [_LT_DECL([$1], [$2], [$3], [$4], [yes])]) # lt_decl_tag_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_tag_varnames], [_lt_decl_filter([tagged?], [yes], $@)]) # _lt_decl_filter(SUBKEY, VALUE, [SEPARATOR], [VARNAME1..]) # --------------------------------------------------------- m4_define([_lt_decl_filter], [m4_case([$#], [0], [m4_fatal([$0: too few arguments: $#])], [1], [m4_fatal([$0: too few arguments: $#: $1])], [2], [lt_dict_filter([lt_decl_dict], [$1], [$2], [], lt_decl_varnames)], [3], [lt_dict_filter([lt_decl_dict], [$1], [$2], [$3], lt_decl_varnames)], [lt_dict_filter([lt_decl_dict], $@)])[]dnl ]) # lt_decl_quote_varnames([SEPARATOR], [VARNAME1...]) # -------------------------------------------------- m4_define([lt_decl_quote_varnames], [_lt_decl_filter([value], [1], $@)]) # lt_decl_dquote_varnames([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_dquote_varnames], [_lt_decl_filter([value], [2], $@)]) # lt_decl_varnames_tagged([SEPARATOR], [VARNAME1...]) # --------------------------------------------------- m4_define([lt_decl_varnames_tagged], [m4_assert([$# <= 2])dnl _$0(m4_quote(m4_default([$1], [[, ]])), m4_ifval([$2], [[$2]], [m4_dquote(lt_decl_tag_varnames)]), m4_split(m4_normalize(m4_quote(_LT_TAGS)), [ ]))]) m4_define([_lt_decl_varnames_tagged], [m4_ifval([$3], [lt_combine([$1], [$2], [_], $3)])]) # lt_decl_all_varnames([SEPARATOR], [VARNAME1...]) # ------------------------------------------------ m4_define([lt_decl_all_varnames], [_$0(m4_quote(m4_default([$1], [[, ]])), m4_if([$2], [], m4_quote(lt_decl_varnames), m4_quote(m4_shift($@))))[]dnl ]) m4_define([_lt_decl_all_varnames], [lt_join($@, lt_decl_varnames_tagged([$1], lt_decl_tag_varnames([[, ]], m4_shift($@))))dnl ]) # _LT_CONFIG_STATUS_DECLARE([VARNAME]) # ------------------------------------ # Quote a variable value, and forward it to `config.status' so that its # declaration there will have the same value as in `configure'. VARNAME # must have a single quote delimited value for this to work. m4_define([_LT_CONFIG_STATUS_DECLARE], [$1='`$ECHO "$][$1" | $SED "$delay_single_quote_subst"`']) # _LT_CONFIG_STATUS_DECLARATIONS # ------------------------------ # We delimit libtool config variables with single quotes, so when # we write them to config.status, we have to be sure to quote all # embedded single quotes properly. In configure, this macro expands # each variable declared with _LT_DECL (and _LT_TAGDECL) into: # # ='`$ECHO "$" | $SED "$delay_single_quote_subst"`' m4_defun([_LT_CONFIG_STATUS_DECLARATIONS], [m4_foreach([_lt_var], m4_quote(lt_decl_all_varnames), [m4_n([_LT_CONFIG_STATUS_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAGS # ---------------- # Output comment and list of tags supported by the script m4_defun([_LT_LIBTOOL_TAGS], [_LT_FORMAT_COMMENT([The names of the tagged configurations supported by this script])dnl available_tags="_LT_TAGS"dnl ]) # _LT_LIBTOOL_DECLARE(VARNAME, [TAG]) # ----------------------------------- # Extract the dictionary values for VARNAME (optionally with TAG) and # expand to a commented shell variable setting: # # # Some comment about what VAR is for. # visible_name=$lt_internal_name m4_define([_LT_LIBTOOL_DECLARE], [_LT_FORMAT_COMMENT(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [description])))[]dnl m4_pushdef([_libtool_name], m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [libtool_name])))[]dnl m4_case(m4_quote(lt_dict_fetch([lt_decl_dict], [$1], [value])), [0], [_libtool_name=[$]$1], [1], [_libtool_name=$lt_[]$1], [2], [_libtool_name=$lt_[]$1], [_libtool_name=lt_dict_fetch([lt_decl_dict], [$1], [value])])[]dnl m4_ifval([$2], [_$2])[]m4_popdef([_libtool_name])[]dnl ]) # _LT_LIBTOOL_CONFIG_VARS # ----------------------- # Produce commented declarations of non-tagged libtool config variables # suitable for insertion in the LIBTOOL CONFIG section of the `libtool' # script. Tagged libtool config variables (even for the LIBTOOL CONFIG # section) are produced by _LT_LIBTOOL_TAG_VARS. m4_defun([_LT_LIBTOOL_CONFIG_VARS], [m4_foreach([_lt_var], m4_quote(_lt_decl_filter([tagged?], [no], [], lt_decl_varnames)), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var)])])]) # _LT_LIBTOOL_TAG_VARS(TAG) # ------------------------- m4_define([_LT_LIBTOOL_TAG_VARS], [m4_foreach([_lt_var], m4_quote(lt_decl_tag_varnames), [m4_n([_LT_LIBTOOL_DECLARE(_lt_var, [$1])])])]) # _LT_TAGVAR(VARNAME, [TAGNAME]) # ------------------------------ m4_define([_LT_TAGVAR], [m4_ifval([$2], [$1_$2], [$1])]) # _LT_CONFIG_COMMANDS # ------------------- # Send accumulated output to $CONFIG_STATUS. Thanks to the lists of # variables for single and double quote escaping we saved from calls # to _LT_DECL, we can put quote escaped variables declarations # into `config.status', and then the shell code to quote escape them in # for loops in `config.status'. Finally, any additional code accumulated # from calls to _LT_CONFIG_LIBTOOL_INIT is expanded. m4_defun([_LT_CONFIG_COMMANDS], [AC_PROVIDE_IFELSE([LT_OUTPUT], dnl If the libtool generation code has been placed in $CONFIG_LT, dnl instead of duplicating it all over again into config.status, dnl then we will have config.status run $CONFIG_LT later, so it dnl needs to know what name is stored there: [AC_CONFIG_COMMANDS([libtool], [$SHELL $CONFIG_LT || AS_EXIT(1)], [CONFIG_LT='$CONFIG_LT'])], dnl If the libtool generation code is destined for config.status, dnl expand the accumulated commands and init code now: [AC_CONFIG_COMMANDS([libtool], [_LT_OUTPUT_LIBTOOL_COMMANDS], [_LT_OUTPUT_LIBTOOL_COMMANDS_INIT])]) ])#_LT_CONFIG_COMMANDS # Initialize. m4_define([_LT_OUTPUT_LIBTOOL_COMMANDS_INIT], [ # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH sed_quote_subst='$sed_quote_subst' double_quote_subst='$double_quote_subst' delay_variable_subst='$delay_variable_subst' _LT_CONFIG_STATUS_DECLARATIONS LTCC='$LTCC' LTCFLAGS='$LTCFLAGS' compiler='$compiler_DEFAULT' # A function that is used when there is no print builtin or printf. func_fallback_echo () { eval 'cat <<_LTECHO_EOF \$[]1 _LTECHO_EOF' } # Quote evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_quote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED \\"\\\$sed_quote_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done # Double-quote double-evaled strings. for var in lt_decl_all_varnames([[ \ ]], lt_decl_dquote_varnames); do case \`eval \\\\\$ECHO \\\\""\\\\\$\$var"\\\\"\` in *[[\\\\\\\`\\"\\\$]]*) eval "lt_\$var=\\\\\\"\\\`\\\$ECHO \\"\\\$\$var\\" | \\\$SED -e \\"\\\$double_quote_subst\\" -e \\"\\\$sed_quote_subst\\" -e \\"\\\$delay_variable_subst\\"\\\`\\\\\\"" ;; *) eval "lt_\$var=\\\\\\"\\\$\$var\\\\\\"" ;; esac done _LT_OUTPUT_LIBTOOL_INIT ]) # _LT_GENERATED_FILE_INIT(FILE, [COMMENT]) # ------------------------------------ # Generate a child script FILE with all initialization necessary to # reuse the environment learned by the parent script, and make the # file executable. If COMMENT is supplied, it is inserted after the # `#!' sequence but before initialization text begins. After this # macro, additional text can be appended to FILE to form the body of # the child script. The macro ends with non-zero status if the # file could not be fully written (such as if the disk is full). m4_ifdef([AS_INIT_GENERATED], [m4_defun([_LT_GENERATED_FILE_INIT],[AS_INIT_GENERATED($@)])], [m4_defun([_LT_GENERATED_FILE_INIT], [m4_require([AS_PREPARE])]dnl [m4_pushdef([AS_MESSAGE_LOG_FD])]dnl [lt_write_fail=0 cat >$1 <<_ASEOF || lt_write_fail=1 #! $SHELL # Generated by $as_me. $2 SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$1 <<\_ASEOF || lt_write_fail=1 AS_SHELL_SANITIZE _AS_PREPARE exec AS_MESSAGE_FD>&1 _ASEOF test $lt_write_fail = 0 && chmod +x $1[]dnl m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before # AC_OUTPUT is called), incase it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} AC_MSG_NOTICE([creating $CONFIG_LT]) _LT_GENERATED_FILE_INIT(["$CONFIG_LT"], [# Run this file to recreate a libtool stub with the current configuration.]) cat >>"$CONFIG_LT" <<\_LTEOF lt_cl_silent=false exec AS_MESSAGE_LOG_FD>>config.log { echo AS_BOX([Running $as_me.]) } >&AS_MESSAGE_LOG_FD lt_cl_help="\ \`$as_me' creates a local libtool stub from the current configuration, for use in further configure time tests before the real libtool is generated. Usage: $[0] [[OPTIONS]] -h, --help print this help, then exit -V, --version print version number, then exit -q, --quiet do not print progress messages -d, --debug don't remove temporary files Report bugs to ." lt_cl_version="\ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. Copyright (C) 2011 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation gives unlimited permision to copy, distribute and modify it." while test $[#] != 0 do case $[1] in --version | --v* | -V ) echo "$lt_cl_version"; exit 0 ;; --help | --h* | -h ) echo "$lt_cl_help"; exit 0 ;; --debug | --d* | -d ) debug=: ;; --quiet | --q* | --silent | --s* | -q ) lt_cl_silent=: ;; -*) AC_MSG_ERROR([unrecognized option: $[1] Try \`$[0] --help' for more information.]) ;; *) AC_MSG_ERROR([unrecognized argument: $[1] Try \`$[0] --help' for more information.]) ;; esac shift done if $lt_cl_silent; then exec AS_MESSAGE_FD>/dev/null fi _LTEOF cat >>"$CONFIG_LT" <<_LTEOF _LT_OUTPUT_LIBTOOL_COMMANDS_INIT _LTEOF cat >>"$CONFIG_LT" <<\_LTEOF AC_MSG_NOTICE([creating $ofile]) _LT_OUTPUT_LIBTOOL_COMMANDS AS_EXIT(0) _LTEOF chmod +x "$CONFIG_LT" # configure is writing to config.log, but config.lt does its own redirection, # appending to config.log, which fails on DOS, as config.log is still kept # open by configure. Here we exec the FD to /dev/null, effectively closing # config.log, so it can be properly (re)opened and appended to by config.lt. lt_cl_success=: test "$silent" = yes && lt_config_lt_args="$lt_config_lt_args --quiet" exec AS_MESSAGE_LOG_FD>/dev/null $SHELL "$CONFIG_LT" $lt_config_lt_args || lt_cl_success=false exec AS_MESSAGE_LOG_FD>>config.log $lt_cl_success || AS_EXIT(1) ])# LT_OUTPUT # _LT_CONFIG(TAG) # --------------- # If TAG is the built-in tag, create an initial libtool script with a # default configuration from the untagged config vars. Otherwise add code # to config.status for appending the configuration named by TAG from the # matching tagged config vars. m4_defun([_LT_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_CONFIG_SAVE_COMMANDS([ m4_define([_LT_TAG], m4_if([$1], [], [C], [$1]))dnl m4_if(_LT_TAG, [C], [ # See if we are running on zsh, and set the options which allow our # commands through without removal of \ escapes. if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST fi cfgfile="${ofile}T" trap "$RM \"$cfgfile\"; exit 1" 1 2 15 $RM "$cfgfile" cat <<_LT_EOF >> "$cfgfile" #! $SHELL # `$ECHO "$ofile" | sed 's%^.*/%%'` - Provide generalized library-building support services. # Generated automatically by $as_me ($PACKAGE$TIMESTAMP) $VERSION # Libtool was configured on host `(hostname || uname -n) 2>/dev/null | sed 1q`: # NOTE: Changes made to this file will be lost: look at ltmain.sh. # _LT_COPYING _LT_LIBTOOL_TAGS # ### BEGIN LIBTOOL CONFIG _LT_LIBTOOL_CONFIG_VARS _LT_LIBTOOL_TAG_VARS # ### END LIBTOOL CONFIG _LT_EOF case $host_os in aix3*) cat <<\_LT_EOF >> "$cfgfile" # AIX sometimes has problems with the GCC collect2 program. For some # reason, if we set the COLLECT_NAMES environment variable, the problems # vanish in a puff of smoke. if test "X${COLLECT_NAMES+set}" != Xset; then COLLECT_NAMES= export COLLECT_NAMES fi _LT_EOF ;; esac _LT_PROG_LTMAIN # We use sed instead of cat because bash on DJGPP gets confused if # if finds mixed CR/LF and LF-only lines. Since sed operates in # text mode, it properly converts lines to CR/LF. This bash problem # is reportedly fixed, but why not run on old versions too? sed '$q' "$ltmain" >> "$cfgfile" \ || (rm -f "$cfgfile"; exit 1) _LT_PROG_REPLACE_SHELLFNS mv -f "$cfgfile" "$ofile" || (rm -f "$ofile" && cp "$cfgfile" "$ofile" && rm -f "$cfgfile") chmod +x "$ofile" ], [cat <<_LT_EOF >> "$ofile" dnl Unfortunately we have to use $1 here, since _LT_TAG is not expanded dnl in a comment (ie after a #). # ### BEGIN LIBTOOL TAG CONFIG: $1 _LT_LIBTOOL_TAG_VARS(_LT_TAG) # ### END LIBTOOL TAG CONFIG: $1 _LT_EOF ])dnl /m4_if ], [m4_if([$1], [], [ PACKAGE='$PACKAGE' VERSION='$VERSION' TIMESTAMP='$TIMESTAMP' RM='$RM' ofile='$ofile'], []) ])dnl /_LT_CONFIG_SAVE_COMMANDS ])# _LT_CONFIG # LT_SUPPORTED_TAG(TAG) # --------------------- # Trace this macro to discover what tags are supported by the libtool # --tag option, using: # autoconf --trace 'LT_SUPPORTED_TAG:$1' AC_DEFUN([LT_SUPPORTED_TAG], []) # C support is built-in for now m4_define([_LT_LANG_C_enabled], []) m4_define([_LT_TAGS], []) # LT_LANG(LANG) # ------------- # Enable libtool support for the given language if not already enabled. AC_DEFUN([LT_LANG], [AC_BEFORE([$0], [LT_OUTPUT])dnl m4_case([$1], [C], [_LT_LANG(C)], [C++], [_LT_LANG(CXX)], [Go], [_LT_LANG(GO)], [Java], [_LT_LANG(GCJ)], [Fortran 77], [_LT_LANG(F77)], [Fortran], [_LT_LANG(FC)], [Windows Resource], [_LT_LANG(RC)], [m4_ifdef([_LT_LANG_]$1[_CONFIG], [_LT_LANG($1)], [m4_fatal([$0: unsupported language: "$1"])])])dnl ])# LT_LANG # _LT_LANG(LANGNAME) # ------------------ m4_defun([_LT_LANG], [m4_ifdef([_LT_LANG_]$1[_enabled], [], [LT_SUPPORTED_TAG([$1])dnl m4_append([_LT_TAGS], [$1 ])dnl m4_define([_LT_LANG_]$1[_enabled], [])dnl _LT_LANG_$1_CONFIG($1)])dnl ])# _LT_LANG m4_ifndef([AC_PROG_GO], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_GO. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_GO], [AC_LANG_PUSH(Go)dnl AC_ARG_VAR([GOC], [Go compiler command])dnl AC_ARG_VAR([GOFLAGS], [Go compiler flags])dnl _AC_ARG_VAR_LDFLAGS()dnl AC_CHECK_TOOL(GOC, gccgo) if test -z "$GOC"; then if test -n "$ac_tool_prefix"; then AC_CHECK_PROG(GOC, [${ac_tool_prefix}gccgo], [${ac_tool_prefix}gccgo]) fi fi if test -z "$GOC"; then AC_CHECK_PROG(GOC, gccgo, gccgo, false) fi ])#m4_defun ])#m4_ifndef # _LT_LANG_DEFAULT_CONFIG # ----------------------- m4_defun([_LT_LANG_DEFAULT_CONFIG], [AC_PROVIDE_IFELSE([AC_PROG_CXX], [LT_LANG(CXX)], [m4_define([AC_PROG_CXX], defn([AC_PROG_CXX])[LT_LANG(CXX)])]) AC_PROVIDE_IFELSE([AC_PROG_F77], [LT_LANG(F77)], [m4_define([AC_PROG_F77], defn([AC_PROG_F77])[LT_LANG(F77)])]) AC_PROVIDE_IFELSE([AC_PROG_FC], [LT_LANG(FC)], [m4_define([AC_PROG_FC], defn([AC_PROG_FC])[LT_LANG(FC)])]) dnl The call to [A][M_PROG_GCJ] is quoted like that to stop aclocal dnl pulling things in needlessly. AC_PROVIDE_IFELSE([AC_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([A][M_PROG_GCJ], [LT_LANG(GCJ)], [AC_PROVIDE_IFELSE([LT_PROG_GCJ], [LT_LANG(GCJ)], [m4_ifdef([AC_PROG_GCJ], [m4_define([AC_PROG_GCJ], defn([AC_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([A][M_PROG_GCJ], [m4_define([A][M_PROG_GCJ], defn([A][M_PROG_GCJ])[LT_LANG(GCJ)])]) m4_ifdef([LT_PROG_GCJ], [m4_define([LT_PROG_GCJ], defn([LT_PROG_GCJ])[LT_LANG(GCJ)])])])])]) AC_PROVIDE_IFELSE([AC_PROG_GO], [LT_LANG(GO)], [m4_define([AC_PROG_GO], defn([AC_PROG_GO])[LT_LANG(GO)])]) AC_PROVIDE_IFELSE([LT_PROG_RC], [LT_LANG(RC)], [m4_define([LT_PROG_RC], defn([LT_PROG_RC])[LT_LANG(RC)])]) ])# _LT_LANG_DEFAULT_CONFIG # Obsolete macros: AU_DEFUN([AC_LIBTOOL_CXX], [LT_LANG(C++)]) AU_DEFUN([AC_LIBTOOL_F77], [LT_LANG(Fortran 77)]) AU_DEFUN([AC_LIBTOOL_FC], [LT_LANG(Fortran)]) AU_DEFUN([AC_LIBTOOL_GCJ], [LT_LANG(Java)]) AU_DEFUN([AC_LIBTOOL_RC], [LT_LANG(Windows Resource)]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_CXX], []) dnl AC_DEFUN([AC_LIBTOOL_F77], []) dnl AC_DEFUN([AC_LIBTOOL_FC], []) dnl AC_DEFUN([AC_LIBTOOL_GCJ], []) dnl AC_DEFUN([AC_LIBTOOL_RC], []) # _LT_TAG_COMPILER # ---------------- m4_defun([_LT_TAG_COMPILER], [AC_REQUIRE([AC_PROG_CC])dnl _LT_DECL([LTCC], [CC], [1], [A C compiler])dnl _LT_DECL([LTCFLAGS], [CFLAGS], [1], [LTCC compiler flags])dnl _LT_TAGDECL([CC], [compiler], [1], [A language specific compiler])dnl _LT_TAGDECL([with_gcc], [GCC], [0], [Is the compiler the GNU compiler?])dnl # If no C compiler was specified, use CC. LTCC=${LTCC-"$CC"} # If no C compiler flags were specified, use CFLAGS. LTCFLAGS=${LTCFLAGS-"$CFLAGS"} # Allow CC to be a program name with arguments. compiler=$CC ])# _LT_TAG_COMPILER # _LT_COMPILER_BOILERPLATE # ------------------------ # Check for compiler boilerplate output or warnings with # the simple compiler test code. m4_defun([_LT_COMPILER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" >conftest.$ac_ext eval "$ac_compile" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_compiler_boilerplate=`cat conftest.err` $RM conftest* ])# _LT_COMPILER_BOILERPLATE # _LT_LINKER_BOILERPLATE # ---------------------- # Check for linker boilerplate output or warnings with # the simple link test code. m4_defun([_LT_LINKER_BOILERPLATE], [m4_require([_LT_DECL_SED])dnl ac_outfile=conftest.$ac_objext echo "$lt_simple_link_test_code" >conftest.$ac_ext eval "$ac_link" 2>&1 >/dev/null | $SED '/^$/d; /^ *+/d' >conftest.err _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ case $host_os in rhapsody* | darwin*) AC_CHECK_TOOL([DSYMUTIL], [dsymutil], [:]) AC_CHECK_TOOL([NMEDIT], [nmedit], [:]) AC_CHECK_TOOL([LIPO], [lipo], [:]) AC_CHECK_TOOL([OTOOL], [otool], [:]) AC_CHECK_TOOL([OTOOL64], [otool64], [:]) _LT_DECL([], [DSYMUTIL], [1], [Tool to manipulate archived DWARF debug symbol files on Mac OS X]) _LT_DECL([], [NMEDIT], [1], [Tool to change global to local symbols on Mac OS X]) _LT_DECL([], [LIPO], [1], [Tool to manipulate fat objects and archives on Mac OS X]) _LT_DECL([], [OTOOL], [1], [ldd/readelf like tool for Mach-O binaries on Mac OS X]) _LT_DECL([], [OTOOL64], [1], [ldd/readelf like tool for 64 bit Mach-O binaries on Mac OS X 10.4]) AC_CACHE_CHECK([for -single_module linker flag],[lt_cv_apple_cc_single_mod], [lt_cv_apple_cc_single_mod=no if test -z "${LT_MULTI_MODULE}"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE # non-empty at configure time, or by adding -multi_module to the # link flags. rm -rf libconftest.dylib* echo "int foo(void){return 1;}" > conftest.c echo "$LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o libconftest.dylib \ -dynamiclib -Wl,-single_module conftest.c 2>conftest.err _lt_result=$? # If there is a non-empty error log, and "single_module" # appears in it, assume the flag caused a linker warning if test -s conftest.err && $GREP single_module conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD # Otherwise, if the output was created with a 0 exit code from # the compiler, it worked. elif test -f libconftest.dylib && test $_lt_result -eq 0; then lt_cv_apple_cc_single_mod=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -rf libconftest.dylib* rm -f conftest.* fi]) AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [lt_cv_ld_exported_symbols_list=yes], [lt_cv_ld_exported_symbols_list=no]) LDFLAGS="$save_LDFLAGS" ]) AC_CACHE_CHECK([for -force_load linker flag],[lt_cv_ld_force_load], [lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF echo "$LTCC $LTCFLAGS -c -o conftest.o conftest.c" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS -c -o conftest.o conftest.c 2>&AS_MESSAGE_LOG_FD echo "$AR cru libconftest.a conftest.o" >&AS_MESSAGE_LOG_FD $AR cru libconftest.a conftest.o 2>&AS_MESSAGE_LOG_FD echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF int main() { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err _lt_result=$? if test -s conftest.err && $GREP force_load conftest.err; then cat conftest.err >&AS_MESSAGE_LOG_FD elif test -f conftest && test $_lt_result -eq 0 && $GREP forced_load conftest >/dev/null 2>&1 ; then lt_cv_ld_force_load=yes else cat conftest.err >&AS_MESSAGE_LOG_FD fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM ]) case $host_os in rhapsody* | darwin1.[[012]]) _lt_dar_allow_undefined='${wl}-undefined ${wl}suppress' ;; darwin1.*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; darwin*) # darwin 5.x on # if running on 10.5 or later, the deployment target defaults # to the OS version, if on x86, and 10.4, the deployment # target defaults to 10.4. Don't you love it? case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in 10.0,*86*-darwin8*|10.0,*-darwin[[91]]*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; 10.[[012]]*) _lt_dar_allow_undefined='${wl}-flat_namespace ${wl}-undefined ${wl}suppress' ;; 10.*) _lt_dar_allow_undefined='${wl}-undefined ${wl}dynamic_lookup' ;; esac ;; esac if test "$lt_cv_apple_cc_single_mod" = "yes"; then _lt_dar_single_mod='$single_module' fi if test "$lt_cv_ld_exported_symbols_list" = "yes"; then _lt_dar_export_syms=' ${wl}-exported_symbols_list,$output_objdir/${libname}-symbols.expsym' else _lt_dar_export_syms='~$NMEDIT -s $output_objdir/${libname}-symbols.expsym ${lib}' fi if test "$DSYMUTIL" != ":" && test "$lt_cv_ld_force_load" = "no"; then _lt_dsymutil='~$DSYMUTIL $lib || :' else _lt_dsymutil= fi ;; esac ]) # _LT_DARWIN_LINKER_FEATURES([TAG]) # --------------------------------- # Checks for linker and compiler features on darwin m4_defun([_LT_DARWIN_LINKER_FEATURES], [ m4_require([_LT_REQUIRED_DARWIN_CHECKS]) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported if test "$lt_cv_ld_force_load" = "yes"; then _LT_TAGVAR(whole_archive_flag_spec, $1)='`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience ${wl}-force_load,$conv\"; done; func_echo_all \"$new_convenience\"`' m4_case([$1], [F77], [_LT_TAGVAR(compiler_needs_object, $1)=yes], [FC], [_LT_TAGVAR(compiler_needs_object, $1)=yes]) else _LT_TAGVAR(whole_archive_flag_spec, $1)='' fi _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)="$_lt_dar_allow_undefined" case $cc_basename in ifort*) _lt_dar_can_shared=yes ;; *) _lt_dar_can_shared=$GCC ;; esac if test "$_lt_dar_can_shared" = "yes"; then output_verbose_link_cmd=func_echo_all _LT_TAGVAR(archive_cmds, $1)="\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod${_lt_dsymutil}" _LT_TAGVAR(module_cmds, $1)="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring ${_lt_dar_single_mod}${_lt_dar_export_syms}${_lt_dsymutil}" _LT_TAGVAR(module_expsym_cmds, $1)="sed -e 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags${_lt_dar_export_syms}${_lt_dsymutil}" m4_if([$1], [CXX], [ if test "$lt_cv_apple_cc_single_mod" != "yes"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dsymutil}" _LT_TAGVAR(archive_expsym_cmds, $1)="sed 's,^,_,' < \$export_symbols > \$output_objdir/\${libname}-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \${lib}-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \${lib}-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring${_lt_dar_export_syms}${_lt_dsymutil}" fi ],[]) else _LT_TAGVAR(ld_shlibs, $1)=no fi ]) # _LT_SYS_MODULE_PATH_AIX([TAGNAME]) # ---------------------------------- # Links a minimal program and checks the executable # for the system default hardcoded library path. In most cases, # this is /usr/lib:/lib, but when the MPI compilers are used # the location of the communication and MPI libs are included too. # If we don't find anything, use the default library path according # to the aix ld manual. # Store the results from the different compilers for each TAGNAME. # Allow to override them for all tags through lt_cv_aix_libpath. m4_defun([_LT_SYS_MODULE_PATH_AIX], [m4_require([_LT_DECL_SED])dnl if test "${lt_cv_aix_libpath+set}" = set; then aix_libpath=$lt_cv_aix_libpath else AC_CACHE_VAL([_LT_TAGVAR([lt_cv_aix_libpath_], [$1])], [AC_LINK_IFELSE([AC_LANG_PROGRAM],[ lt_aix_libpath_sed='[ /Import File Strings/,/^$/ { /^0/ { s/^0 *\([^ ]*\) *$/\1/ p } }]' _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -H conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` # Check for a 64-bit object if we didn't find anything. if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])=`dump -HX64 conftest$ac_exeext 2>/dev/null | $SED -n -e "$lt_aix_libpath_sed"` fi],[]) if test -z "$_LT_TAGVAR([lt_cv_aix_libpath_], [$1])"; then _LT_TAGVAR([lt_cv_aix_libpath_], [$1])="/usr/lib:/lib" fi ]) aix_libpath=$_LT_TAGVAR([lt_cv_aix_libpath_], [$1]) fi ])# _LT_SYS_MODULE_PATH_AIX # _LT_SHELL_INIT(ARG) # ------------------- m4_define([_LT_SHELL_INIT], [m4_divert_text([M4SH-INIT], [$1 ])])# _LT_SHELL_INIT # _LT_PROG_ECHO_BACKSLASH # ----------------------- # Find how we can fake an echo command that does not interpret backslash. # In particular, with Autoconf 2.60 or later we add some code to the start # of the generated configure script which will find a shell with a builtin # printf (which we can use as an echo command). m4_defun([_LT_PROG_ECHO_BACKSLASH], [ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO AC_MSG_CHECKING([how to print strings]) # Test print first, because it will be a builtin if present. if test "X`( print -r -- -n ) 2>/dev/null`" = X-n && \ test "X`print -r -- $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='print -r --' elif test "X`printf %s $ECHO 2>/dev/null`" = "X$ECHO"; then ECHO='printf %s\n' else # Use this function as a fallback that always works. func_fallback_echo () { eval 'cat <<_LTECHO_EOF $[]1 _LTECHO_EOF' } ECHO='func_fallback_echo' fi # func_echo_all arg... # Invoke $ECHO with all args, space-separated. func_echo_all () { $ECHO "$*" } case "$ECHO" in printf*) AC_MSG_RESULT([printf]) ;; print*) AC_MSG_RESULT([print -r]) ;; *) AC_MSG_RESULT([cat]) ;; esac m4_ifdef([_AS_DETECT_SUGGESTED], [_AS_DETECT_SUGGESTED([ test -n "${ZSH_VERSION+set}${BASH_VERSION+set}" || ( ECHO='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO ECHO=$ECHO$ECHO$ECHO$ECHO$ECHO$ECHO PATH=/empty FPATH=/empty; export PATH FPATH test "X`printf %s $ECHO`" = "X$ECHO" \ || test "X`print -r -- $ECHO`" = "X$ECHO" )])]) _LT_DECL([], [SHELL], [1], [Shell to use when invoking shell scripts]) _LT_DECL([], [ECHO], [1], [An echo program that protects backslashes]) ])# _LT_PROG_ECHO_BACKSLASH # _LT_WITH_SYSROOT # ---------------- AC_DEFUN([_LT_WITH_SYSROOT], [AC_MSG_CHECKING([for sysroot]) AC_ARG_WITH([sysroot], [ --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified).], [], [with_sysroot=no]) dnl lt_sysroot will always be passed unquoted. We quote it here dnl in case the user passed a directory name. lt_sysroot= case ${with_sysroot} in #( yes) if test "$GCC" = yes; then lt_sysroot=`$CC --print-sysroot 2>/dev/null` fi ;; #( /*) lt_sysroot=`echo "$with_sysroot" | sed -e "$sed_quote_subst"` ;; #( no|'') ;; #( *) AC_MSG_RESULT([${with_sysroot}]) AC_MSG_ERROR([The sysroot must be an absolute path.]) ;; esac AC_MSG_RESULT([${lt_sysroot:-no}]) _LT_DECL([], [lt_sysroot], [0], [The root where to search for ]dnl [dependent libraries, and in which our libraries should be installed.])]) # _LT_ENABLE_LOCK # --------------- m4_defun([_LT_ENABLE_LOCK], [AC_ARG_ENABLE([libtool-lock], [AS_HELP_STRING([--disable-libtool-lock], [avoid locking (might break parallel builds)])]) test "x$enable_libtool_lock" != xno && enable_libtool_lock=yes # Some flags need to be propagated to the compiler or linker for good # libtool support. case $host in ia64-*-hpux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.$ac_objext` in *ELF-32*) HPUX_IA64_MODE="32" ;; *ELF-64*) HPUX_IA64_MODE="64" ;; esac fi rm -rf conftest* ;; *-*-irix6*) # Find out which ABI we are using. echo '[#]line '$LINENO' "configure"' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then if test "$lt_cv_prog_gnu_ld" = yes; then case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -melf32bsmip" ;; *N32*) LD="${LD-ld} -melf32bmipn32" ;; *64-bit*) LD="${LD-ld} -melf64bmip" ;; esac else case `/usr/bin/file conftest.$ac_objext` in *32-bit*) LD="${LD-ld} -32" ;; *N32*) LD="${LD-ld} -n32" ;; *64-bit*) LD="${LD-ld} -64" ;; esac fi fi rm -rf conftest* ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *32-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; x86_64-*linux*) case `/usr/bin/file conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" ;; *) LD="${LD-ld} -m elf_i386" ;; esac ;; powerpc64le-*) LD="${LD-ld} -m elf32lppclinux" ;; powerpc64-*) LD="${LD-ld} -m elf32ppclinux" ;; s390x-*linux*) LD="${LD-ld} -m elf_s390" ;; sparc64-*linux*) LD="${LD-ld} -m elf32_sparc" ;; esac ;; *64-bit*) case $host in x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; x86_64-*linux*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*) LD="${LD-ld} -m elf64lppc" ;; powerpc-*) LD="${LD-ld} -m elf64ppc" ;; s390*-*linux*|s390*-*tpf*) LD="${LD-ld} -m elf64_s390" ;; sparc*-*linux*) LD="${LD-ld} -m elf64_sparc" ;; esac ;; esac fi rm -rf conftest* ;; *-*-sco3.2v5*) # On SCO OpenServer 5, we need -belf to get full-featured binaries. SAVE_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS -belf" AC_CACHE_CHECK([whether the C compiler needs -belf], lt_cv_cc_needs_belf, [AC_LANG_PUSH(C) AC_LINK_IFELSE([AC_LANG_PROGRAM([[]],[[]])],[lt_cv_cc_needs_belf=yes],[lt_cv_cc_needs_belf=no]) AC_LANG_POP]) if test x"$lt_cv_cc_needs_belf" != x"yes"; then # this is probably gcc 2.8.0, egcs 1.0 or newer; no need for -belf CFLAGS="$SAVE_CFLAGS" fi ;; *-*solaris*) # Find out which ABI we are using. echo 'int i;' > conftest.$ac_ext if AC_TRY_EVAL(ac_compile); then case `/usr/bin/file conftest.o` in *64-bit*) case $lt_cv_prog_gnu_ld in yes*) case $host in i?86-*-solaris*) LD="${LD-ld} -m elf_x86_64" ;; sparc*-*-solaris*) LD="${LD-ld} -m elf64_sparc" ;; esac # GNU ld 2.21 introduced _sol2 emulations. Use them if available. if ${LD-ld} -V | grep _sol2 >/dev/null 2>&1; then LD="${LD-ld}_sol2" fi ;; *) if ${LD-ld} -64 -r -o conftest2.o conftest.o >/dev/null 2>&1; then LD="${LD-ld} -64" fi ;; esac ;; esac fi rm -rf conftest* ;; esac need_locks="$enable_libtool_lock" ])# _LT_ENABLE_LOCK # _LT_PROG_AR # ----------- m4_defun([_LT_PROG_AR], [AC_CHECK_TOOLS(AR, [ar], false) : ${AR=ar} : ${AR_FLAGS=cru} _LT_DECL([], [AR], [1], [The archiver]) _LT_DECL([], [AR_FLAGS], [1], [Flags to create an archive]) AC_CACHE_CHECK([for archiver @FILE support], [lt_cv_ar_at_file], [lt_cv_ar_at_file=no AC_COMPILE_IFELSE([AC_LANG_PROGRAM], [echo conftest.$ac_objext > conftest.lst lt_ar_try='$AR $AR_FLAGS libconftest.a @conftest.lst >&AS_MESSAGE_LOG_FD' AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -eq 0; then # Ensure the archiver fails upon bogus file names. rm -f conftest.$ac_objext libconftest.a AC_TRY_EVAL([lt_ar_try]) if test "$ac_status" -ne 0; then lt_cv_ar_at_file=@ fi fi rm -f conftest.* libconftest.a ]) ]) if test "x$lt_cv_ar_at_file" = xno; then archiver_list_spec= else archiver_list_spec=$lt_cv_ar_at_file fi _LT_DECL([], [archiver_list_spec], [1], [How to feed a file listing to the archiver]) ])# _LT_PROG_AR # _LT_CMD_OLD_ARCHIVE # ------------------- m4_defun([_LT_CMD_OLD_ARCHIVE], [_LT_PROG_AR AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) AC_CHECK_TOOL(RANLIB, ranlib, :) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) # Determine commands to create old-style static archives. old_archive_cmds='$AR $AR_FLAGS $oldlib$oldobjs' old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then case $host_os in openbsd*) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" ;; *) old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" ;; esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in darwin*) lock_old_archive_extraction=yes ;; *) lock_old_archive_extraction=no ;; esac _LT_DECL([], [old_postinstall_cmds], [2]) _LT_DECL([], [old_postuninstall_cmds], [2]) _LT_TAGDECL([], [old_archive_cmds], [2], [Commands used to build an old-style archive]) _LT_DECL([], [lock_old_archive_extraction], [0], [Whether to use a lock for old archive extraction]) ])# _LT_CMD_OLD_ARCHIVE # _LT_COMPILER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [OUTPUT-FILE], [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------------------- # Check whether the given compiler option works AC_DEFUN([_LT_COMPILER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no m4_if([$4], , [ac_outfile=conftest.$ac_objext], [ac_outfile=$4]) echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$3" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. # The option is referenced via a variable to avoid confusing sed. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi fi $RM conftest* ]) if test x"[$]$2" = xyes; then m4_if([$5], , :, [$5]) else m4_if([$6], , :, [$6]) fi ])# _LT_COMPILER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_COMPILER_OPTION], [_LT_COMPILER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_COMPILER_OPTION], []) # _LT_LINKER_OPTION(MESSAGE, VARIABLE-NAME, FLAGS, # [ACTION-SUCCESS], [ACTION-FAILURE]) # ---------------------------------------------------- # Check whether the given linker option works AC_DEFUN([_LT_LINKER_OPTION], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_SED])dnl AC_CACHE_CHECK([$1], [$2], [$2=no save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS $3" echo "$lt_simple_link_test_code" > conftest.$ac_ext if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then # The linker can only warn and ignore the option if not recognized # So say no if there are warnings if test -s conftest.err; then # Append any errors to the config.log. cat conftest.err 1>&AS_MESSAGE_LOG_FD $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 if diff conftest.exp conftest.er2 >/dev/null; then $2=yes fi else $2=yes fi fi $RM -r conftest* LDFLAGS="$save_LDFLAGS" ]) if test x"[$]$2" = xyes; then m4_if([$4], , :, [$4]) else m4_if([$5], , :, [$5]) fi ])# _LT_LINKER_OPTION # Old name: AU_ALIAS([AC_LIBTOOL_LINKER_OPTION], [_LT_LINKER_OPTION]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_LINKER_OPTION], []) # LT_CMD_MAX_LEN #--------------- AC_DEFUN([LT_CMD_MAX_LEN], [AC_REQUIRE([AC_CANONICAL_HOST])dnl # find the maximum length of command line arguments AC_MSG_CHECKING([the maximum length of command line arguments]) AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl i=0 teststring="ABCD" case $build_os in msdosdjgpp*) # On DJGPP, this test can blow up pretty badly due to problems in libc # (any single argument exceeding 2000 bytes causes a buffer overrun # during glob expansion). Even if it were fixed, the result of this # check would be larger than it should be. lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; gnu*) # Under GNU Hurd, this test is not required because there is # no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; cygwin* | mingw* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, # you end up with a "frozen" computer, even though with patience # the test eventually succeeds (with a max line length of 256k). # Instead, let's just punt: use the minimum linelength reported by # all of the supported platforms: 8192 (on NT/2K/XP). lt_cv_sys_max_cmd_len=8192; ;; mint*) # On MiNT this can take a long time and run out of memory. lt_cv_sys_max_cmd_len=8192; ;; amigaos*) # On AmigaOS with pdksh, this test takes hours, literally. # So we just punt and use a minimum line length of 8192. lt_cv_sys_max_cmd_len=8192; ;; netbsd* | freebsd* | openbsd* | darwin* | dragonfly*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` elif test -x /usr/sbin/sysctl; then lt_cv_sys_max_cmd_len=`/usr/sbin/sysctl -n kern.argmax` else lt_cv_sys_max_cmd_len=65536 # usable default for all BSDs fi # And add a safety zone lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` ;; interix*) # We know the value 262144 and hardcode it with a safety zone (like BSD) lt_cv_sys_max_cmd_len=196608 ;; os2*) # The test takes a long time on OS/2. lt_cv_sys_max_cmd_len=8192 ;; osf*) # Dr. Hans Ekkehard Plesser reports seeing a kernel panic running configure # due to this test when exec_disable_arg_limit is 1 on Tru64. It is not # nice to cause kernel panics so lets avoid the loop below. # First set a reasonable default. lt_cv_sys_max_cmd_len=16384 # if test -x /sbin/sysconfig; then case `/sbin/sysconfig -q proc exec_disable_arg_limit` in *1*) lt_cv_sys_max_cmd_len=-1 ;; esac fi ;; sco3.2v5*) lt_cv_sys_max_cmd_len=102400 ;; sysv5* | sco5v6* | sysv4.2uw2*) kargmax=`grep ARG_MAX /etc/conf/cf.d/stune 2>/dev/null` if test -n "$kargmax"; then lt_cv_sys_max_cmd_len=`echo $kargmax | sed 's/.*[[ ]]//'` else lt_cv_sys_max_cmd_len=32768 fi ;; *) lt_cv_sys_max_cmd_len=`(getconf ARG_MAX) 2> /dev/null` if test -n "$lt_cv_sys_max_cmd_len" && \ test undefined != "$lt_cv_sys_max_cmd_len"; then lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 4` lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \* 3` else # Make teststring a little bigger before we do anything with it. # a 1K string should be a reasonable start. for i in 1 2 3 4 5 6 7 8 ; do teststring=$teststring$teststring done SHELL=${SHELL-${CONFIG_SHELL-/bin/sh}} # If test is not a shell built-in, we'll probably end up computing a # maximum length that is only half of the actual maximum length, but # we can't tell. while { test "X"`env echo "$teststring$teststring" 2>/dev/null` \ = "X$teststring$teststring"; } >/dev/null 2>&1 && test $i != 17 # 1/2 MB should be enough do i=`expr $i + 1` teststring=$teststring$teststring done # Only check the string length outside the loop. lt_cv_sys_max_cmd_len=`expr "X$teststring" : ".*" 2>&1` teststring= # Add a significant safety factor because C++ compilers can tack on # massive amounts of additional arguments before passing them to the # linker. It appears as though 1/2 is a usable value. lt_cv_sys_max_cmd_len=`expr $lt_cv_sys_max_cmd_len \/ 2` fi ;; esac ]) if test -n $lt_cv_sys_max_cmd_len ; then AC_MSG_RESULT($lt_cv_sys_max_cmd_len) else AC_MSG_RESULT(none) fi max_cmd_len=$lt_cv_sys_max_cmd_len _LT_DECL([], [max_cmd_len], [0], [What is the maximum length of a command?]) ])# LT_CMD_MAX_LEN # Old name: AU_ALIAS([AC_LIBTOOL_SYS_MAX_CMD_LEN], [LT_CMD_MAX_LEN]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_SYS_MAX_CMD_LEN], []) # _LT_HEADER_DLFCN # ---------------- m4_defun([_LT_HEADER_DLFCN], [AC_CHECK_HEADERS([dlfcn.h], [], [], [AC_INCLUDES_DEFAULT])dnl ])# _LT_HEADER_DLFCN # _LT_TRY_DLOPEN_SELF (ACTION-IF-TRUE, ACTION-IF-TRUE-W-USCORE, # ACTION-IF-FALSE, ACTION-IF-CROSS-COMPILING) # ---------------------------------------------------------------- m4_defun([_LT_TRY_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "$cross_compiling" = yes; then : [$4] else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<_LT_EOF [#line $LINENO "configure" #include "confdefs.h" #if HAVE_DLFCN_H #include #endif #include #ifdef RTLD_GLOBAL # define LT_DLGLOBAL RTLD_GLOBAL #else # ifdef DL_GLOBAL # define LT_DLGLOBAL DL_GLOBAL # else # define LT_DLGLOBAL 0 # endif #endif /* We may have to define LT_DLLAZY_OR_NOW in the command line if we find out it does not work in some platform. */ #ifndef LT_DLLAZY_OR_NOW # ifdef RTLD_LAZY # define LT_DLLAZY_OR_NOW RTLD_LAZY # else # ifdef DL_LAZY # define LT_DLLAZY_OR_NOW DL_LAZY # else # ifdef RTLD_NOW # define LT_DLLAZY_OR_NOW RTLD_NOW # else # ifdef DL_NOW # define LT_DLLAZY_OR_NOW DL_NOW # else # define LT_DLLAZY_OR_NOW 0 # endif # endif # endif # endif #endif /* When -fvisbility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined(__GNUC__) && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) int fnord () __attribute__((visibility("default"))); #endif int fnord () { return 42; } int main () { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; if (self) { if (dlsym (self,"fnord")) status = $lt_dlno_uscore; else { if (dlsym( self,"_fnord")) status = $lt_dlneed_uscore; else puts (dlerror ()); } /* dlclose (self); */ } else puts (dlerror ()); return status; }] _LT_EOF if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext} 2>/dev/null; then (./conftest; exit; ) >&AS_MESSAGE_LOG_FD 2>/dev/null lt_status=$? case x$lt_status in x$lt_dlno_uscore) $1 ;; x$lt_dlneed_uscore) $2 ;; x$lt_dlunknown|x*) $3 ;; esac else : # compilation failed $3 fi fi rm -fr conftest* ])# _LT_TRY_DLOPEN_SELF # LT_SYS_DLOPEN_SELF # ------------------ AC_DEFUN([LT_SYS_DLOPEN_SELF], [m4_require([_LT_HEADER_DLFCN])dnl if test "x$enable_dlopen" != xyes; then enable_dlopen=unknown enable_dlopen_self=unknown enable_dlopen_self_static=unknown else lt_cv_dlopen=no lt_cv_dlopen_libs= case $host_os in beos*) lt_cv_dlopen="load_add_on" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ;; mingw* | pw32* | cegcc*) lt_cv_dlopen="LoadLibrary" lt_cv_dlopen_libs= ;; cygwin*) lt_cv_dlopen="dlopen" lt_cv_dlopen_libs= ;; darwin*) # if libdl is installed we need to link against it AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"],[ lt_cv_dlopen="dyld" lt_cv_dlopen_libs= lt_cv_dlopen_self=yes ]) ;; *) AC_CHECK_FUNC([shl_load], [lt_cv_dlopen="shl_load"], [AC_CHECK_LIB([dld], [shl_load], [lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"], [AC_CHECK_FUNC([dlopen], [lt_cv_dlopen="dlopen"], [AC_CHECK_LIB([dl], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"], [AC_CHECK_LIB([svld], [dlopen], [lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"], [AC_CHECK_LIB([dld], [dld_link], [lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"]) ]) ]) ]) ]) ]) ;; esac if test "x$lt_cv_dlopen" != xno; then enable_dlopen=yes else enable_dlopen=no fi case $lt_cv_dlopen in dlopen) save_CPPFLAGS="$CPPFLAGS" test "x$ac_cv_header_dlfcn_h" = xyes && CPPFLAGS="$CPPFLAGS -DHAVE_DLFCN_H" save_LDFLAGS="$LDFLAGS" wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\" save_LIBS="$LIBS" LIBS="$lt_cv_dlopen_libs $LIBS" AC_CACHE_CHECK([whether a program can dlopen itself], lt_cv_dlopen_self, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self=yes, lt_cv_dlopen_self=yes, lt_cv_dlopen_self=no, lt_cv_dlopen_self=cross) ]) if test "x$lt_cv_dlopen_self" = xyes; then wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\" AC_CACHE_CHECK([whether a statically linked program can dlopen itself], lt_cv_dlopen_self_static, [dnl _LT_TRY_DLOPEN_SELF( lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=yes, lt_cv_dlopen_self_static=no, lt_cv_dlopen_self_static=cross) ]) fi CPPFLAGS="$save_CPPFLAGS" LDFLAGS="$save_LDFLAGS" LIBS="$save_LIBS" ;; esac case $lt_cv_dlopen_self in yes|no) enable_dlopen_self=$lt_cv_dlopen_self ;; *) enable_dlopen_self=unknown ;; esac case $lt_cv_dlopen_self_static in yes|no) enable_dlopen_self_static=$lt_cv_dlopen_self_static ;; *) enable_dlopen_self_static=unknown ;; esac fi _LT_DECL([dlopen_support], [enable_dlopen], [0], [Whether dlopen is supported]) _LT_DECL([dlopen_self], [enable_dlopen_self], [0], [Whether dlopen of programs is supported]) _LT_DECL([dlopen_self_static], [enable_dlopen_self_static], [0], [Whether dlopen of statically linked programs is supported]) ])# LT_SYS_DLOPEN_SELF # Old name: AU_ALIAS([AC_LIBTOOL_DLOPEN_SELF], [LT_SYS_DLOPEN_SELF]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LIBTOOL_DLOPEN_SELF], []) # _LT_COMPILER_C_O([TAGNAME]) # --------------------------- # Check to see if options -c and -o are simultaneously supported by compiler. # This macro does not hard code the compiler like AC_PROG_CC_C_O. m4_defun([_LT_COMPILER_C_O], [m4_require([_LT_DECL_SED])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_CACHE_CHECK([if $compiler supports -c -o file.$ac_objext], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest mkdir out echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-o out/conftest2.$ac_objext" # Insert the option either (1) after the last *FLAGS variable, or # (2) before a word containing "conftest.", or (3) at the end. # Note that $ac_compile itself does not contain backslashes and begins # with a dollar sign (not a hyphen), so the echo should work correctly. lt_compile=`echo "$ac_compile" | $SED \ -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [[^ ]]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&AS_MESSAGE_LOG_FD echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' > out/conftest.exp $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2 if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes fi fi chmod u+w . 2>&AS_MESSAGE_LOG_FD $RM conftest* # SGI C++ compiler will create directory out/ii_files/ for # template instantiation test -d out/ii_files && $RM out/ii_files/* && rmdir out/ii_files $RM out/* && rmdir out cd .. $RM -r conftest $RM conftest* ]) _LT_TAGDECL([compiler_c_o], [lt_cv_prog_compiler_c_o], [1], [Does compiler simultaneously support -c and -o options?]) ])# _LT_COMPILER_C_O # _LT_COMPILER_FILE_LOCKS([TAGNAME]) # ---------------------------------- # Check to see if we can do hard links to lock some files if needed m4_defun([_LT_COMPILER_FILE_LOCKS], [m4_require([_LT_ENABLE_LOCK])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl _LT_COMPILER_C_O([$1]) hard_links="nottested" if test "$_LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)" = no && test "$need_locks" != no; then # do not overwrite the value of need_locks provided by the user AC_MSG_CHECKING([if we can lock with hard links]) hard_links=yes $RM conftest* ln conftest.a conftest.b 2>/dev/null && hard_links=no touch conftest.a ln conftest.a conftest.b 2>&5 || hard_links=no ln conftest.a conftest.b 2>/dev/null && hard_links=no AC_MSG_RESULT([$hard_links]) if test "$hard_links" = no; then AC_MSG_WARN([`$CC' does not support `-c -o', so `make -j' may be unsafe]) need_locks=warn fi else need_locks=no fi _LT_DECL([], [need_locks], [1], [Must we lock files when doing compilation?]) ])# _LT_COMPILER_FILE_LOCKS # _LT_CHECK_OBJDIR # ---------------- m4_defun([_LT_CHECK_OBJDIR], [AC_CACHE_CHECK([for objdir], [lt_cv_objdir], [rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi rmdir .libs 2>/dev/null]) objdir=$lt_cv_objdir _LT_DECL([], [objdir], [0], [The name of the directory that contains temporary libtool files])dnl m4_pattern_allow([LT_OBJDIR])dnl AC_DEFINE_UNQUOTED(LT_OBJDIR, "$lt_cv_objdir/", [Define to the sub-directory in which libtool stores uninstalled libraries.]) ])# _LT_CHECK_OBJDIR # _LT_LINKER_HARDCODE_LIBPATH([TAGNAME]) # -------------------------------------- # Check hardcoding attributes. m4_defun([_LT_LINKER_HARDCODE_LIBPATH], [AC_MSG_CHECKING([how to hardcode library paths into programs]) _LT_TAGVAR(hardcode_action, $1)= if test -n "$_LT_TAGVAR(hardcode_libdir_flag_spec, $1)" || test -n "$_LT_TAGVAR(runpath_var, $1)" || test "X$_LT_TAGVAR(hardcode_automatic, $1)" = "Xyes" ; then # We can hardcode non-existent directories. if test "$_LT_TAGVAR(hardcode_direct, $1)" != no && # If the only mechanism to avoid hardcoding is shlibpath_var, we # have to relink, otherwise we might link with an installed library # when we should be linking with a yet-to-be-installed one ## test "$_LT_TAGVAR(hardcode_shlibpath_var, $1)" != no && test "$_LT_TAGVAR(hardcode_minus_L, $1)" != no; then # Linking always hardcodes the temporary library directory. _LT_TAGVAR(hardcode_action, $1)=relink else # We can link without hardcoding, and we can hardcode nonexisting dirs. _LT_TAGVAR(hardcode_action, $1)=immediate fi else # We cannot hardcode anything, or else we can only hardcode existing # directories. _LT_TAGVAR(hardcode_action, $1)=unsupported fi AC_MSG_RESULT([$_LT_TAGVAR(hardcode_action, $1)]) if test "$_LT_TAGVAR(hardcode_action, $1)" = relink || test "$_LT_TAGVAR(inherit_rpath, $1)" = yes; then # Fast installation is not supported enable_fast_install=no elif test "$shlibpath_overrides_runpath" = yes || test "$enable_shared" = no; then # Fast installation is not necessary enable_fast_install=needless fi _LT_TAGDECL([], [hardcode_action], [0], [How to hardcode a shared library path into an executable]) ])# _LT_LINKER_HARDCODE_LIBPATH # _LT_CMD_STRIPLIB # ---------------- m4_defun([_LT_CMD_STRIPLIB], [m4_require([_LT_DECL_EGREP]) striplib= old_striplib= AC_MSG_CHECKING([whether stripping libraries is possible]) if test -n "$STRIP" && $STRIP -V 2>&1 | $GREP "GNU strip" >/dev/null; then test -z "$old_striplib" && old_striplib="$STRIP --strip-debug" test -z "$striplib" && striplib="$STRIP --strip-unneeded" AC_MSG_RESULT([yes]) else # FIXME - insert some real tests, host_os isn't really good enough case $host_os in darwin*) if test -n "$STRIP" ; then striplib="$STRIP -x" old_striplib="$STRIP -S" AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) fi ;; *) AC_MSG_RESULT([no]) ;; esac fi _LT_DECL([], [old_striplib], [1], [Commands to strip libraries]) _LT_DECL([], [striplib], [1]) ])# _LT_CMD_STRIPLIB # _LT_SYS_DYNAMIC_LINKER([TAG]) # ----------------------------- # PORTME Fill in your ld.so characteristics m4_defun([_LT_SYS_DYNAMIC_LINKER], [AC_REQUIRE([AC_CANONICAL_HOST])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_OBJDUMP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CHECK_SHELL_FEATURES])dnl AC_MSG_CHECKING([dynamic linker characteristics]) m4_if([$1], [], [ if test "$GCC" = yes; then case $host_os in darwin*) lt_awk_arg="/^libraries:/,/LR/" ;; *) lt_awk_arg="/^libraries:/" ;; esac case $host_os in mingw* | cegcc*) lt_sed_strip_eq="s,=\([[A-Za-z]]:\),\1,g" ;; *) lt_sed_strip_eq="s,=/,/,g" ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` case $lt_search_path_spec in *\;*) # if the path contains ";" then we assume it to be the separator # otherwise default to the standard path separator (i.e. ":") - it is # assumed that no part of a normal pathname contains ";" but that should # okay in the real world where ";" in dirpaths is itself problematic. lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED 's/;/ /g'` ;; *) lt_search_path_spec=`$ECHO "$lt_search_path_spec" | $SED "s/$PATH_SEPARATOR/ /g"` ;; esac # Ok, now we have the path, separated by spaces, we can step through it # and add multilib dir if necessary. lt_tmp_lt_search_path_spec= lt_multi_os_dir=`$CC $CPPFLAGS $CFLAGS $LDFLAGS -print-multi-os-directory 2>/dev/null` for lt_sys_path in $lt_search_path_spec; do if test -d "$lt_sys_path/$lt_multi_os_dir"; then lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path/$lt_multi_os_dir" else test -d "$lt_sys_path" && \ lt_tmp_lt_search_path_spec="$lt_tmp_lt_search_path_spec $lt_sys_path" fi done lt_search_path_spec=`$ECHO "$lt_tmp_lt_search_path_spec" | awk ' BEGIN {RS=" "; FS="/|\n";} { lt_foo=""; lt_count=0; for (lt_i = NF; lt_i > 0; lt_i--) { if ($lt_i != "" && $lt_i != ".") { if ($lt_i == "..") { lt_count++; } else { if (lt_count == 0) { lt_foo="/" $lt_i lt_foo; } else { lt_count--; } } } } if (lt_foo != "") { lt_freq[[lt_foo]]++; } if (lt_freq[[lt_foo]] == 1) { print lt_foo; } }'` # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's,/\([[A-Za-z]]:\),\1,g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` else sys_lib_search_path_spec="/lib /usr/lib /usr/local/lib" fi]) library_names_spec= libname_spec='lib$name' soname_spec= shrext_cmds=".so" postinstall_cmds= postuninstall_cmds= finish_cmds= finish_eval= shlibpath_var= shlibpath_overrides_runpath=unknown version_type=none dynamic_linker="$host_os ld.so" sys_lib_dlsearch_path_spec="/lib /usr/lib" need_lib_prefix=unknown hardcode_into_libs=no # when you set need_version to no, make sure it does not cause -set_version # flags to be left without arguments need_version=unknown case $host_os in aix3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix $libname.a' shlibpath_var=LIBPATH # AIX 3 has no versioning support, so we append a major version to the name. soname_spec='${libname}${release}${shared_ext}$major' ;; aix[[4-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no hardcode_into_libs=yes if test "$host_cpu" = ia64; then # AIX 5 supports IA64 library_names_spec='${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext}$versuffix $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH else # With GCC up to 2.95.x, collect2 would create an import file # for dependence libraries. The import file would start with # the line `#! .'. This would cause the generated library to # depend on `.', always an invalid library. This was fixed in # development snapshots of GCC prior to 3.0. case $host_os in aix4 | aix4.[[01]] | aix4.[[01]].*) if { echo '#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 97)' echo ' yes ' echo '#endif'; } | ${CC} -E - | $GREP yes > /dev/null; then : else can_build_shared=no fi ;; esac # AIX (on Power*) has no versioning support, so currently we can not hardcode correct # soname into executable. Probably we can add versioning support to # collect2, so additional links can be useful in future. if test "$aix_use_runtimelinking" = yes; then # If using run time linking (on AIX 4.2 or later) use lib.so # instead of lib.a to let people know that these are not # typical AIX shared libraries. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' else # We preserve .a as extension for shared libraries through AIX4.2 # and later when we are not doing run time linking. library_names_spec='${libname}${release}.a $libname.a' soname_spec='${libname}${release}${shared_ext}$major' fi shlibpath_var=LIBPATH fi ;; amigaos*) case $host_cpu in powerpc) # Since July 2007 AmigaOS4 officially supports .so libraries. # When compiling the executable, add -use-dynld -Lsobjs: to the compileline. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' ;; m68k) library_names_spec='$libname.ixlibrary $libname.a' # Create ${libname}_ixlibrary.a entries in /sys/libs. finish_eval='for lib in `ls $libdir/*.ixlibrary 2>/dev/null`; do libname=`func_echo_all "$lib" | $SED '\''s%^.*/\([[^/]]*\)\.ixlibrary$%\1%'\''`; test $RM /sys/libs/${libname}_ixlibrary.a; $show "cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a"; cd /sys/libs && $LN_S $lib ${libname}_ixlibrary.a || exit 1; done' ;; esac ;; beos*) library_names_spec='${libname}${shared_ext}' dynamic_linker="$host_os ld.so" shlibpath_var=LIBRARY_PATH ;; bsdi[[45]]*) version_type=linux # correct to gnu/linux during the next big refactor need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/shlib /usr/lib /usr/X11/lib /usr/contrib/lib /lib /usr/local/lib" sys_lib_dlsearch_path_spec="/shlib /usr/lib /usr/local/lib" # the default ld.so.conf also contains /usr/contrib/lib and # /usr/X11R6/lib (/usr/X11 is a link to /usr/X11R6), but let us allow # libtool to hard-code these into programs ;; cygwin* | mingw* | pw32* | cegcc*) version_type=windows shrext_cmds=".dll" need_version=no need_lib_prefix=no case $GCC,$cc_basename in yes,*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname~ chmod a+x \$dldir/$dlname~ if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; fi' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes case $host_os in cygwin*) # Cygwin DLLs use 'cyg' prefix rather than 'lib' soname_spec='`echo ${libname} | sed -e 's/^lib/cyg/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; mingw* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; pw32*) # pw32 DLLs use 'pw' prefix rather than 'lib' library_names_spec='`echo ${libname} | sed -e 's/^lib/pw/'``echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' ;; esac dynamic_linker='Win32 ld.exe' ;; *,cl*) # Native MSVC libname_spec='$name' soname_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext}' library_names_spec='${libname}.dll.lib' case $build_os in mingw*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' for lt_path in $LIB do IFS=$lt_save_ifs # Let DOS variable expansion print the short 8.3 style file name. lt_path=`cd "$lt_path" 2>/dev/null && cmd //C "for %i in (".") do @echo %~si"` sys_lib_search_path_spec="$sys_lib_search_path_spec $lt_path" done IFS=$lt_save_ifs # Convert to MSYS style. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | sed -e 's|\\\\|/|g' -e 's| \\([[a-zA-Z]]\\):| /\\1|g' -e 's|^ ||'` ;; cygwin*) # Convert to unix form, then to dos form, then back to unix form # but this time dos style (no spaces!) so that the unix form looks # like /cygdrive/c/PROGRA~1:/cygdr... sys_lib_search_path_spec=`cygpath --path --unix "$LIB"` sys_lib_search_path_spec=`cygpath --path --dos "$sys_lib_search_path_spec" 2>/dev/null` sys_lib_search_path_spec=`cygpath --path --unix "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` ;; *) sys_lib_search_path_spec="$LIB" if $ECHO "$sys_lib_search_path_spec" | [$GREP ';[c-zC-Z]:/' >/dev/null]; then # It is most probably a Windows format PATH. sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e 's/;/ /g'` else sys_lib_search_path_spec=`$ECHO "$sys_lib_search_path_spec" | $SED -e "s/$PATH_SEPARATOR/ /g"` fi # FIXME: find the short name or the path components, as spaces are # common. (e.g. "Program Files" -> "PROGRA~1") ;; esac # DLL is installed to $(libdir)/../bin by postinstall_cmds postinstall_cmds='base_file=`basename \${file}`~ dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\${base_file}'\''i; echo \$dlname'\''`~ dldir=$destdir/`dirname \$dlpath`~ test -d \$dldir || mkdir -p \$dldir~ $install_prog $dir/$dlname \$dldir/$dlname' postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' shlibpath_overrides_runpath=yes dynamic_linker='Win32 link.exe' ;; *) # Assume MSVC wrapper library_names_spec='${libname}`echo ${release} | $SED -e 's/[[.]]/-/g'`${versuffix}${shared_ext} $libname.lib' dynamic_linker='Win32 ld.exe' ;; esac # FIXME: first we should search . and the directory the executable is in shlibpath_var=PATH ;; darwin* | rhapsody*) dynamic_linker="$host_os dyld" version_type=darwin need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${major}$shared_ext ${libname}$shared_ext' soname_spec='${libname}${release}${major}$shared_ext' shlibpath_overrides_runpath=yes shlibpath_var=DYLD_LIBRARY_PATH shrext_cmds='`test .$module = .yes && echo .so || echo .dylib`' m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/local/lib"]) sys_lib_dlsearch_path_spec='/usr/local/lib /lib /usr/lib' ;; dgux*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname$shared_ext' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; freebsd* | dragonfly*) # DragonFly does not have aout. When/if they implement a new # versioning mechanism, adjust this. if test -x /usr/bin/objformat; then objformat=`/usr/bin/objformat` else case $host_os in freebsd[[23]].*) objformat=aout ;; *) objformat=elf ;; esac fi version_type=freebsd-$objformat case $version_type in freebsd-elf*) library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' need_version=no need_lib_prefix=no ;; freebsd-*) library_names_spec='${libname}${release}${shared_ext}$versuffix $libname${shared_ext}$versuffix' need_version=yes ;; esac shlibpath_var=LD_LIBRARY_PATH case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes ;; freebsd3.[[01]]* | freebsdelf3.[[01]]*) shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; freebsd3.[[2-9]]* | freebsdelf3.[[2-9]]* | \ freebsd4.[[0-5]] | freebsdelf4.[[0-5]] | freebsd4.1.1 | freebsdelf4.1.1) shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; *) # from 4.6 on, and DragonFly shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; esac ;; haiku*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no dynamic_linker="$host_os runtime_loader" library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}${major} ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=yes sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' hardcode_into_libs=yes ;; hpux9* | hpux10* | hpux11*) # Give a soname corresponding to the major version so that dld.sl refuses to # link against other versions. version_type=sunos need_lib_prefix=no need_version=no case $host_cpu in ia64*) shrext_cmds='.so' hardcode_into_libs=yes dynamic_linker="$host_os dld.so" shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' if test "X$HPUX_IA64_MODE" = X32; then sys_lib_search_path_spec="/usr/lib/hpux32 /usr/local/lib/hpux32 /usr/local/lib" else sys_lib_search_path_spec="/usr/lib/hpux64 /usr/local/lib/hpux64" fi sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; hppa*64*) shrext_cmds='.sl' hardcode_into_libs=yes dynamic_linker="$host_os dld.sl" shlibpath_var=LD_LIBRARY_PATH # How should we handle SHLIB_PATH shlibpath_overrides_runpath=yes # Unless +noenvvar is specified. library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' sys_lib_search_path_spec="/usr/lib/pa20_64 /usr/ccs/lib/pa20_64" sys_lib_dlsearch_path_spec=$sys_lib_search_path_spec ;; *) shrext_cmds='.sl' dynamic_linker="$host_os dld.sl" shlibpath_var=SHLIB_PATH shlibpath_overrides_runpath=no # +s is required to enable SHLIB_PATH library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' ;; esac # HP-UX runs *really* slowly unless shared libraries are mode 555, ... postinstall_cmds='chmod 555 $lib' # or fails outright, so override atomically: install_override_mode=555 ;; interix[[3-9]]*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='Interix 3.x ld.so.1 (PE, like ELF)' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; irix5* | irix6* | nonstopux*) case $host_os in nonstopux*) version_type=nonstopux ;; *) if test "$lt_cv_prog_gnu_ld" = yes; then version_type=linux # correct to gnu/linux during the next big refactor else version_type=irix fi ;; esac need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${release}${shared_ext} $libname${shared_ext}' case $host_os in irix5* | nonstopux*) libsuff= shlibsuff= ;; *) case $LD in # libtool.m4 will add one of these switches to LD *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= libmagic=32-bit;; *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 libmagic=N32;; *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 libmagic=64-bit;; *) libsuff= shlibsuff= libmagic=never-match;; esac ;; esac shlibpath_var=LD_LIBRARY${shlibsuff}_PATH shlibpath_overrides_runpath=no sys_lib_search_path_spec="/usr/lib${libsuff} /lib${libsuff} /usr/local/lib${libsuff}" sys_lib_dlsearch_path_spec="/usr/lib${libsuff} /lib${libsuff}" hardcode_into_libs=yes ;; # No shared lib support for Linux oldld, aout, or coff. linux*oldld* | linux*aout* | linux*coff*) dynamic_linker=no ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' finish_cmds='PATH="\$PATH:/sbin" ldconfig -n $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no # Some binutils ld are patched to set DT_RUNPATH AC_CACHE_VAL([lt_cv_shlibpath_overrides_runpath], [lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$_LT_TAGVAR(lt_prog_compiler_wl, $1)\"; \ LDFLAGS=\"\$LDFLAGS $_LT_TAGVAR(hardcode_libdir_flag_spec, $1)\"" AC_LINK_IFELSE([AC_LANG_PROGRAM([],[])], [AS_IF([ ($OBJDUMP -p conftest$ac_exeext) 2>/dev/null | grep "RUNPATH.*$libdir" >/dev/null], [lt_cv_shlibpath_overrides_runpath=yes])]) LDFLAGS=$save_LDFLAGS libdir=$save_libdir ]) shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath # This implies no fast_install, which is unacceptable. # Some rework will be needed to allow for fast_install # before this can be enabled. hardcode_into_libs=yes # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;/^[ ]*hwcap[ ]/d;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;s/"//g;/^$/d' | tr '\n' ' '` sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on # powerpc, because MkLinux only supported shared libraries with the # GNU dynamic linker. Since this was broken with cross compilers, # most powerpc-linux boxes support dynamic linking these days and # people can always --disable-shared, the test was removed, and we # assume the GNU/Linux dynamic linker is in use. dynamic_linker='GNU/Linux ld.so' ;; netbsdelf*-gnu) version_type=linux need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='NetBSD ld.elf_so' ;; netbsd*) version_type=sunos need_lib_prefix=no need_version=no if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' dynamic_linker='NetBSD (a.out) ld.so' else library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major ${libname}${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' dynamic_linker='NetBSD ld.elf_so' fi shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes ;; newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes ;; *nto* | *qnx*) version_type=qnx need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes dynamic_linker='ldqnx.so' ;; openbsd*) version_type=sunos sys_lib_dlsearch_path_spec="/usr/lib" need_lib_prefix=no # Some older versions of OpenBSD (3.3 at least) *do* need versioned libs. case $host_os in openbsd3.3 | openbsd3.3.*) need_version=yes ;; *) need_version=no ;; esac library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/sbin" ldconfig -m $libdir' shlibpath_var=LD_LIBRARY_PATH if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then case $host_os in openbsd2.[[89]] | openbsd2.[[89]].*) shlibpath_overrides_runpath=no ;; *) shlibpath_overrides_runpath=yes ;; esac else shlibpath_overrides_runpath=yes fi ;; os2*) libname_spec='$name' shrext_cmds=".dll" need_lib_prefix=no library_names_spec='$libname${shared_ext} $libname.a' dynamic_linker='OS/2 ld.exe' shlibpath_var=LIBPATH ;; osf3* | osf4* | osf5*) version_type=osf need_lib_prefix=no need_version=no soname_spec='${libname}${release}${shared_ext}$major' library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH sys_lib_search_path_spec="/usr/shlib /usr/ccs/lib /usr/lib/cmplrs/cc /usr/lib /usr/local/lib /var/shlib" sys_lib_dlsearch_path_spec="$sys_lib_search_path_spec" ;; rdos*) dynamic_linker=no ;; solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes # ldd complains unless libraries are executable postinstall_cmds='chmod +x $lib' ;; sunos4*) version_type=sunos library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${shared_ext}$versuffix' finish_cmds='PATH="\$PATH:/usr/etc" ldconfig $libdir' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes if test "$with_gnu_ld" = yes; then need_lib_prefix=no fi need_version=yes ;; sysv4 | sysv4.3*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH case $host_vendor in sni) shlibpath_overrides_runpath=no need_lib_prefix=no runpath_var=LD_RUN_PATH ;; siemens) need_lib_prefix=no ;; motorola) need_lib_prefix=no need_version=no shlibpath_overrides_runpath=no sys_lib_search_path_spec='/lib /usr/lib /usr/ccs/lib' ;; esac ;; sysv4*MP*) if test -d /usr/nec ;then version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname${shared_ext}.$versuffix $libname${shared_ext}.$major $libname${shared_ext}' soname_spec='$libname${shared_ext}.$major' shlibpath_var=LD_LIBRARY_PATH fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) version_type=freebsd-elf need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext} $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=yes hardcode_into_libs=yes if test "$with_gnu_ld" = yes; then sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' else sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' case $host_os in sco3.2v5*) sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" ;; esac fi sys_lib_dlsearch_path_spec='/usr/lib' ;; tpf*) # TPF is a cross-target only. Preferred cross-host = GNU/Linux. version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no need_version=no library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' shlibpath_var=LD_LIBRARY_PATH shlibpath_overrides_runpath=no hardcode_into_libs=yes ;; uts4*) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='${libname}${release}${shared_ext}$versuffix ${libname}${release}${shared_ext}$major $libname${shared_ext}' soname_spec='${libname}${release}${shared_ext}$major' shlibpath_var=LD_LIBRARY_PATH ;; *) dynamic_linker=no ;; esac AC_MSG_RESULT([$dynamic_linker]) test "$dynamic_linker" = no && can_build_shared=no variables_saved_for_relink="PATH $shlibpath_var $runpath_var" if test "$GCC" = yes; then variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" fi if test "${lt_cv_sys_lib_search_path_spec+set}" = set; then sys_lib_search_path_spec="$lt_cv_sys_lib_search_path_spec" fi if test "${lt_cv_sys_lib_dlsearch_path_spec+set}" = set; then sys_lib_dlsearch_path_spec="$lt_cv_sys_lib_dlsearch_path_spec" fi _LT_DECL([], [variables_saved_for_relink], [1], [Variables whose values should be saved in libtool wrapper scripts and restored at link time]) _LT_DECL([], [need_lib_prefix], [0], [Do we need the "lib" prefix for modules?]) _LT_DECL([], [need_version], [0], [Do we need a version for libraries?]) _LT_DECL([], [version_type], [0], [Library versioning type]) _LT_DECL([], [runpath_var], [0], [Shared library runtime path variable]) _LT_DECL([], [shlibpath_var], [0],[Shared library path variable]) _LT_DECL([], [shlibpath_overrides_runpath], [0], [Is shlibpath searched before the hard-coded library search path?]) _LT_DECL([], [libname_spec], [1], [Format of library name prefix]) _LT_DECL([], [library_names_spec], [1], [[List of archive names. First name is the real one, the rest are links. The last name is the one that the linker finds with -lNAME]]) _LT_DECL([], [soname_spec], [1], [[The coded name of the library, if different from the real name]]) _LT_DECL([], [install_override_mode], [1], [Permission mode override for installation of shared libraries]) _LT_DECL([], [postinstall_cmds], [2], [Command to use after installation of a shared archive]) _LT_DECL([], [postuninstall_cmds], [2], [Command to use after uninstallation of a shared archive]) _LT_DECL([], [finish_cmds], [2], [Commands used to finish a libtool library installation in a directory]) _LT_DECL([], [finish_eval], [1], [[As "finish_cmds", except a single script fragment to be evaled but not shown]]) _LT_DECL([], [hardcode_into_libs], [0], [Whether we should hardcode library paths into libraries]) _LT_DECL([], [sys_lib_search_path_spec], [2], [Compile-time system search path for libraries]) _LT_DECL([], [sys_lib_dlsearch_path_spec], [2], [Run-time system search path for libraries]) ])# _LT_SYS_DYNAMIC_LINKER # _LT_PATH_TOOL_PREFIX(TOOL) # -------------------------- # find a file program which can recognize shared library AC_DEFUN([_LT_PATH_TOOL_PREFIX], [m4_require([_LT_DECL_EGREP])dnl AC_MSG_CHECKING([for $1]) AC_CACHE_VAL(lt_cv_path_MAGIC_CMD, [case $MAGIC_CMD in [[\\/*] | ?:[\\/]*]) lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path. ;; *) lt_save_MAGIC_CMD="$MAGIC_CMD" lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR dnl $ac_dummy forces splitting on constant user-supplied paths. dnl POSIX.2 word splitting is done only on the output of word expansions, dnl not every word. This closes a longstanding sh security hole. ac_dummy="m4_if([$2], , $PATH, [$2])" for ac_dir in $ac_dummy; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f $ac_dir/$1; then lt_cv_path_MAGIC_CMD="$ac_dir/$1" if test -n "$file_magic_test_file"; then case $deplibs_check_method in "file_magic "*) file_magic_regex=`expr "$deplibs_check_method" : "file_magic \(.*\)"` MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if eval $file_magic_cmd \$file_magic_test_file 2> /dev/null | $EGREP "$file_magic_regex" > /dev/null; then : else cat <<_LT_EOF 1>&2 *** Warning: the command libtool uses to detect shared libraries, *** $file_magic_cmd, produces output that libtool cannot recognize. *** The result is that libtool may fail to recognize shared libraries *** as such. This will affect the creation of libtool libraries that *** depend on shared libraries, but programs linked with such libtool *** libraries will work regardless of this problem. Nevertheless, you *** may want to report the problem to your system manager and/or to *** bug-libtool@gnu.org _LT_EOF fi ;; esac fi break fi done IFS="$lt_save_ifs" MAGIC_CMD="$lt_save_MAGIC_CMD" ;; esac]) MAGIC_CMD="$lt_cv_path_MAGIC_CMD" if test -n "$MAGIC_CMD"; then AC_MSG_RESULT($MAGIC_CMD) else AC_MSG_RESULT(no) fi _LT_DECL([], [MAGIC_CMD], [0], [Used to examine libraries when file_magic_cmd begins with "file"])dnl ])# _LT_PATH_TOOL_PREFIX # Old name: AU_ALIAS([AC_PATH_TOOL_PREFIX], [_LT_PATH_TOOL_PREFIX]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_PATH_TOOL_PREFIX], []) # _LT_PATH_MAGIC # -------------- # find a file program which can recognize a shared library m4_defun([_LT_PATH_MAGIC], [_LT_PATH_TOOL_PREFIX(${ac_tool_prefix}file, /usr/bin$PATH_SEPARATOR$PATH) if test -z "$lt_cv_path_MAGIC_CMD"; then if test -n "$ac_tool_prefix"; then _LT_PATH_TOOL_PREFIX(file, /usr/bin$PATH_SEPARATOR$PATH) else MAGIC_CMD=: fi fi ])# _LT_PATH_MAGIC # LT_PATH_LD # ---------- # find the pathname to the GNU or non-GNU linker AC_DEFUN([LT_PATH_LD], [AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PROG_ECHO_BACKSLASH])dnl AC_ARG_WITH([gnu-ld], [AS_HELP_STRING([--with-gnu-ld], [assume the C compiler uses GNU ld @<:@default=no@:>@])], [test "$withval" = no || with_gnu_ld=yes], [with_gnu_ld=no])dnl ac_prog=ld if test "$GCC" = yes; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in *-*-mingw*) # gcc leaves a trailing carriage return which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) ac_prog=`($CC -print-prog-name=ld) 2>&5` ;; esac case $ac_prog in # Accept absolute paths. [[\\/]]* | ?:[[\\/]]*) re_direlt='/[[^/]][[^/]]*/\.\./' # Canonicalize the pathname of ld ac_prog=`$ECHO "$ac_prog"| $SED 's%\\\\%/%g'` while $ECHO "$ac_prog" | $GREP "$re_direlt" > /dev/null 2>&1; do ac_prog=`$ECHO $ac_prog| $SED "s%$re_direlt%/%"` done test -z "$LD" && LD="$ac_prog" ;; "") # If it fails, then pretend we aren't using GCC. ac_prog=ld ;; *) # If it is relative, then search for the first ld in PATH. with_gnu_ld=unknown ;; esac elif test "$with_gnu_ld" = yes; then AC_MSG_CHECKING([for GNU ld]) else AC_MSG_CHECKING([for non-GNU ld]) fi AC_CACHE_VAL(lt_cv_path_LD, [if test -z "$LD"; then lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then lt_cv_path_LD="$ac_dir/$ac_prog" # Check to see if the program is GNU ld. I'd rather use --version, # but apparently some variants of GNU ld only accept -v. # Break only if it was the GNU/non-GNU ld that we prefer. case `"$lt_cv_path_LD" -v 2>&1 &1 /dev/null 2>&1; then lt_cv_deplibs_check_method='file_magic ^x86 archive import|^x86 DLL' lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; cegcc*) # use the weaker test based on 'objdump'. See mingw*. lt_cv_deplibs_check_method='file_magic file format pe-arm-.*little(.*architecture: arm)?' lt_cv_file_magic_cmd='$OBJDUMP -f' ;; darwin* | rhapsody*) lt_cv_deplibs_check_method=pass_all ;; freebsd* | dragonfly*) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then case $host_cpu in i*86 ) # Not sure whether the presence of OpenBSD here was a mistake. # Let's accept both of them until this is cleared up. lt_cv_deplibs_check_method='file_magic (FreeBSD|OpenBSD|DragonFly)/i[[3-9]]86 (compact )?demand paged shared library' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=`echo /usr/lib/libc.so.*` ;; esac else lt_cv_deplibs_check_method=pass_all fi ;; haiku*) lt_cv_deplibs_check_method=pass_all ;; hpux10.20* | hpux11*) lt_cv_file_magic_cmd=/usr/bin/file case $host_cpu in ia64*) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|ELF-[[0-9]][[0-9]]) shared object file - IA64' lt_cv_file_magic_test_file=/usr/lib/hpux32/libc.so ;; hppa*64*) [lt_cv_deplibs_check_method='file_magic (s[0-9][0-9][0-9]|ELF[ -][0-9][0-9])(-bit)?( [LM]SB)? shared object( file)?[, -]* PA-RISC [0-9]\.[0-9]'] lt_cv_file_magic_test_file=/usr/lib/pa20_64/libc.sl ;; *) lt_cv_deplibs_check_method='file_magic (s[[0-9]][[0-9]][[0-9]]|PA-RISC[[0-9]]\.[[0-9]]) shared library' lt_cv_file_magic_test_file=/usr/lib/libc.sl ;; esac ;; interix[[3-9]]*) # PIC code is broken on Interix 3.x, that's why |\.a not |_pic\.a here lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|\.a)$' ;; irix5* | irix6* | nonstopux*) case $LD in *-32|*"-32 ") libmagic=32-bit;; *-n32|*"-n32 ") libmagic=N32;; *-64|*"-64 ") libmagic=64-bit;; *) libmagic=never-match;; esac lt_cv_deplibs_check_method=pass_all ;; # This must be glibc/ELF. linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so|_pic\.a)$' fi ;; newos6*) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (executable|dynamic lib)' lt_cv_file_magic_cmd=/usr/bin/file lt_cv_file_magic_test_file=/usr/lib/libnls.so ;; *nto* | *qnx*) lt_cv_deplibs_check_method=pass_all ;; openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' fi ;; osf3* | osf4* | osf5*) lt_cv_deplibs_check_method=pass_all ;; rdos*) lt_cv_deplibs_check_method=pass_all ;; solaris*) lt_cv_deplibs_check_method=pass_all ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) lt_cv_deplibs_check_method=pass_all ;; sysv4 | sysv4.3*) case $host_vendor in motorola) lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[ML]]SB (shared object|dynamic lib) M[[0-9]][[0-9]]* Version [[0-9]]' lt_cv_file_magic_test_file=`echo /usr/lib/libc.so*` ;; ncr) lt_cv_deplibs_check_method=pass_all ;; sequent) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method='file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB (shared object|dynamic lib )' ;; sni) lt_cv_file_magic_cmd='/bin/file' lt_cv_deplibs_check_method="file_magic ELF [[0-9]][[0-9]]*-bit [[LM]]SB dynamic lib" lt_cv_file_magic_test_file=/lib/libc.so ;; siemens) lt_cv_deplibs_check_method=pass_all ;; pc) lt_cv_deplibs_check_method=pass_all ;; esac ;; tpf*) lt_cv_deplibs_check_method=pass_all ;; esac ]) file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in mingw* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else file_magic_glob=`echo aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ | $SED -e "s/\(..\)/s\/[[\1]]\/[[\1]]\/g;/g"` fi ;; esac fi file_magic_cmd=$lt_cv_file_magic_cmd deplibs_check_method=$lt_cv_deplibs_check_method test -z "$deplibs_check_method" && deplibs_check_method=unknown _LT_DECL([], [deplibs_check_method], [1], [Method to check whether dependent libraries are shared objects]) _LT_DECL([], [file_magic_cmd], [1], [Command to use when deplibs_check_method = "file_magic"]) _LT_DECL([], [file_magic_glob], [1], [How to find potential files when deplibs_check_method = "file_magic"]) _LT_DECL([], [want_nocaseglob], [1], [Find potential files using nocaseglob when deplibs_check_method = "file_magic"]) ])# _LT_CHECK_MAGIC_METHOD # LT_PATH_NM # ---------- # find the pathname to a BSD- or MS-compatible name lister AC_DEFUN([LT_PATH_NM], [AC_REQUIRE([AC_PROG_CC])dnl AC_CACHE_CHECK([for BSD- or MS-compatible name lister (nm)], lt_cv_path_NM, [if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM="$NM" else lt_nm_to_check="${ac_tool_prefix}nm" if test -n "$ac_tool_prefix" && test "$build" = "$host"; then lt_nm_to_check="$lt_nm_to_check nm" fi for lt_tmp_nm in $lt_nm_to_check; do lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR for ac_dir in $PATH /usr/ccs/bin/elf /usr/ccs/bin /usr/ucb /bin; do IFS="$lt_save_ifs" test -z "$ac_dir" && ac_dir=. tmp_nm="$ac_dir/$lt_tmp_nm" if test -f "$tmp_nm" || test -f "$tmp_nm$ac_exeext" ; then # Check to see if the nm accepts a BSD-compat flag. # Adding the `sed 1q' prevents false positives on HP-UX, which says: # nm: unknown option "B" ignored # Tru64's nm complains that /dev/null is an invalid object file case `"$tmp_nm" -B /dev/null 2>&1 | sed '1q'` in */dev/null* | *'Invalid file or object type'*) lt_cv_path_NM="$tmp_nm -B" break ;; *) case `"$tmp_nm" -p /dev/null 2>&1 | sed '1q'` in */dev/null*) lt_cv_path_NM="$tmp_nm -p" break ;; *) lt_cv_path_NM=${lt_cv_path_NM="$tmp_nm"} # keep the first match, but continue # so that we can try to find one that supports BSD flags ;; esac ;; esac fi done IFS="$lt_save_ifs" done : ${lt_cv_path_NM=no} fi]) if test "$lt_cv_path_NM" != "no"; then NM="$lt_cv_path_NM" else # Didn't find any BSD compatible name lister, look for dumpbin. if test -n "$DUMPBIN"; then : # Let the user override the test. else AC_CHECK_TOOLS(DUMPBIN, [dumpbin "link -dump"], :) case `$DUMPBIN -symbols /dev/null 2>&1 | sed '1q'` in *COFF*) DUMPBIN="$DUMPBIN -symbols" ;; *) DUMPBIN=: ;; esac fi AC_SUBST([DUMPBIN]) if test "$DUMPBIN" != ":"; then NM="$DUMPBIN" fi fi test -z "$NM" && NM=nm AC_SUBST([NM]) _LT_DECL([], [NM], [1], [A BSD- or MS-compatible name lister])dnl AC_CACHE_CHECK([the name lister ($NM) interface], [lt_cv_nm_interface], [lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&AS_MESSAGE_LOG_FD) (eval "$ac_compile" 2>conftest.err) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: $NM \\\"conftest.$ac_objext\\\"\"" >&AS_MESSAGE_LOG_FD) (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out) cat conftest.err >&AS_MESSAGE_LOG_FD (eval echo "\"\$as_me:$LINENO: output\"" >&AS_MESSAGE_LOG_FD) cat conftest.out >&AS_MESSAGE_LOG_FD if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi rm -f conftest*]) ])# LT_PATH_NM # Old names: AU_ALIAS([AM_PROG_NM], [LT_PATH_NM]) AU_ALIAS([AC_PROG_NM], [LT_PATH_NM]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AM_PROG_NM], []) dnl AC_DEFUN([AC_PROG_NM], []) # _LT_CHECK_SHAREDLIB_FROM_LINKLIB # -------------------------------- # how to determine the name of the shared library # associated with a specific link library. # -- PORTME fill in with the dynamic library characteristics m4_defun([_LT_CHECK_SHAREDLIB_FROM_LINKLIB], [m4_require([_LT_DECL_EGREP]) m4_require([_LT_DECL_OBJDUMP]) m4_require([_LT_DECL_DLLTOOL]) AC_CACHE_CHECK([how to associate runtime and link libraries], lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in cygwin* | mingw* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh # decide which to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in *--identify-strict*) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib ;; *) lt_cv_sharedlib_from_linklib_cmd=func_cygming_dll_for_implib_fallback ;; esac ;; *) # fallback: assume linklib IS sharedlib lt_cv_sharedlib_from_linklib_cmd="$ECHO" ;; esac ]) sharedlib_from_linklib_cmd=$lt_cv_sharedlib_from_linklib_cmd test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO _LT_DECL([], [sharedlib_from_linklib_cmd], [1], [Command to associate shared and link libraries]) ])# _LT_CHECK_SHAREDLIB_FROM_LINKLIB # _LT_PATH_MANIFEST_TOOL # ---------------------- # locate the manifest tool m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], [lt_cv_path_mainfest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then lt_cv_path_mainfest_tool=yes fi rm -f conftest*]) if test "x$lt_cv_path_mainfest_tool" != xyes; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl ])# _LT_PATH_MANIFEST_TOOL # LT_LIB_M # -------- # check for math library AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in *-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) AC_CHECK_LIB(mw, _mwvalidcheckl, LIBM="-lmw") AC_CHECK_LIB(m, cos, LIBM="$LIBM -lm") ;; *) AC_CHECK_LIB(m, cos, LIBM="-lm") ;; esac AC_SUBST([LIBM]) ])# LT_LIB_M # Old name: AU_ALIAS([AC_CHECK_LIBM], [LT_LIB_M]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_CHECK_LIBM], []) # _LT_COMPILER_NO_RTTI([TAGNAME]) # ------------------------------- m4_defun([_LT_COMPILER_NO_RTTI], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= if test "$GCC" = yes; then case $cc_basename in nvcc*) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -Xcompiler -fno-builtin' ;; *) _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' ;; esac _LT_COMPILER_OPTION([if $compiler supports -fno-rtti -fno-exceptions], lt_cv_prog_compiler_rtti_exceptions, [-fno-rtti -fno-exceptions], [], [_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)="$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1) -fno-rtti -fno-exceptions"]) fi _LT_TAGDECL([no_builtin_flag], [lt_prog_compiler_no_builtin_flag], [1], [Compiler flag to turn off builtin functions]) ])# _LT_COMPILER_NO_RTTI # _LT_CMD_GLOBAL_SYMBOLS # ---------------------- m4_defun([_LT_CMD_GLOBAL_SYMBOLS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_PROG_CC])dnl AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([LT_PATH_NM])dnl AC_REQUIRE([LT_PATH_LD])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_TAG_COMPILER])dnl # Check for command to grab the raw symbol name followed by C symbol from nm. AC_MSG_CHECKING([command to parse $NM output from $compiler object]) AC_CACHE_VAL([lt_cv_sys_global_symbol_pipe], [ # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] # Character class describing NM global symbol codes. symcode='[[BCDEGRST]]' # Regexp to match symbols that can be accessed directly from C. sympat='\([[_A-Za-z]][[_A-Za-z0-9]]*\)' # Define system-specific variables. case $host_os in aix*) symcode='[[BCDT]]' ;; cygwin* | mingw* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) if test "$host_cpu" = ia64; then symcode='[[ABCDEGRST]]' fi ;; irix* | nonstopux*) symcode='[[BCDEGRST]]' ;; osf*) symcode='[[BCDEGQRST]]' ;; solaris*) symcode='[[BDRT]]' ;; sco3.2v5*) symcode='[[DT]]' ;; sysv4.2uw2*) symcode='[[DT]]' ;; sysv5* | sco5v6* | unixware* | OpenUNIX*) symcode='[[ABDT]]' ;; sysv4) symcode='[[DFNSTU]]' ;; esac # If we're using GNU nm, then use its standard symbol codes. case `$NM -V 2>&1` in *GNU* | *'with BFD'*) symcode='[[ABCDGIRSTW]]' ;; esac # Transform an extracted symbol line into a proper C declaration. # Some systems (esp. on ia64) link data and code symbols differently, # so use this general approach. lt_cv_sys_global_symbol_to_cdecl="sed -n -e 's/^T .* \(.*\)$/extern int \1();/p' -e 's/^$symcode* .* \(.*\)$/extern char \1;/p'" # Transform an extracted symbol line into symbol name and symbol address lt_cv_sys_global_symbol_to_c_name_address="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p'" lt_cv_sys_global_symbol_to_c_name_address_lib_prefix="sed -n -e 's/^: \([[^ ]]*\)[[ ]]*$/ {\\\"\1\\\", (void *) 0},/p' -e 's/^$symcode* \([[^ ]]*\) \(lib[[^ ]]*\)$/ {\"\2\", (void *) \&\2},/p' -e 's/^$symcode* \([[^ ]]*\) \([[^ ]]*\)$/ {\"lib\2\", (void *) \&\2},/p'" # Handle CRLF in mingw tool chain opt_cr= case $build_os in mingw*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac # Try without a prefix underscore, then with it. for ac_symprfx in "" "_"; do # Transform symcode, sympat, and symprfx into a raw symbol and a C symbol. symxfrm="\\1 $ac_symprfx\\2 \\2" # Write the raw and C identifiers. if test "$lt_cv_nm_interface" = "MS dumpbin"; then # Fake it for dumpbin and say T for any non-static function # and D for any global variable. # Also find C++ and __fastcall symbols from MSVC++, # which start with @ or ?. lt_cv_sys_global_symbol_pipe="$AWK ['"\ " {last_section=section; section=\$ 3};"\ " /^COFF SYMBOL TABLE/{for(i in hide) delete hide[i]};"\ " /Section length .*#relocs.*(pick any)/{hide[last_section]=1};"\ " \$ 0!~/External *\|/{next};"\ " / 0+ UNDEF /{next}; / UNDEF \([^|]\)*()/{next};"\ " {if(hide[section]) next};"\ " {f=0}; \$ 0~/\(\).*\|/{f=1}; {printf f ? \"T \" : \"D \"};"\ " {split(\$ 0, a, /\||\r/); split(a[2], s)};"\ " s[1]~/^[@?]/{print s[1], s[1]; next};"\ " s[1]~prfx {split(s[1],t,\"@\"); print t[1], substr(t[1],length(prfx))}"\ " ' prfx=^$ac_symprfx]" else lt_cv_sys_global_symbol_pipe="sed -n -e 's/^.*[[ ]]\($symcode$symcode*\)[[ ]][[ ]]*$ac_symprfx$sympat$opt_cr$/$symxfrm/p'" fi lt_cv_sys_global_symbol_pipe="$lt_cv_sys_global_symbol_pipe | sed '/ __gnu_lto/d'" # Check to see that the pipe works correctly. pipe_works=no rm -f conftest* cat > conftest.$ac_ext <<_LT_EOF #ifdef __cplusplus extern "C" { #endif char nm_test_var; void nm_test_func(void); void nm_test_func(void){} #ifdef __cplusplus } #endif int main(){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. nlist=conftest.nm if AC_TRY_EVAL(NM conftest.$ac_objext \| "$lt_cv_sys_global_symbol_pipe" \> $nlist) && test -s "$nlist"; then # Try sorting and uniquifying the output. if sort "$nlist" | uniq > "$nlist"T; then mv -f "$nlist"T "$nlist" else rm -f "$nlist"T fi # Make sure that we snagged all the symbols we need. if $GREP ' nm_test_var$' "$nlist" >/dev/null; then if $GREP ' nm_test_func$' "$nlist" >/dev/null; then cat <<_LT_EOF > conftest.$ac_ext /* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ #if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) /* DATA imports from DLLs on WIN32 con't be const, because runtime relocations are performed -- see ld's documentation on pseudo-relocs. */ # define LT@&t@_DLSYM_CONST #elif defined(__osf__) /* This system does not cope well with relocations in const data. */ # define LT@&t@_DLSYM_CONST #else # define LT@&t@_DLSYM_CONST const #endif #ifdef __cplusplus extern "C" { #endif _LT_EOF # Now generate the symbol file. eval "$lt_cv_sys_global_symbol_to_cdecl"' < "$nlist" | $GREP -v main >> conftest.$ac_ext' cat <<_LT_EOF >> conftest.$ac_ext /* The mapping between symbol names and symbols. */ LT@&t@_DLSYM_CONST struct { const char *name; void *address; } lt__PROGRAM__LTX_preloaded_symbols[[]] = { { "@PROGRAM@", (void *) 0 }, _LT_EOF $SED "s/^$symcode$symcode* \(.*\) \(.*\)$/ {\"\2\", (void *) \&\2},/" < "$nlist" | $GREP -v main >> conftest.$ac_ext cat <<\_LT_EOF >> conftest.$ac_ext {0, (void *) 0} }; /* This works around a problem in FreeBSD linker */ #ifdef FREEBSD_WORKAROUND static const void *lt_preloaded_setup() { return lt__PROGRAM__LTX_preloaded_symbols; } #endif #ifdef __cplusplus } #endif _LT_EOF # Now try linking the two files. mv conftest.$ac_objext conftstm.$ac_objext lt_globsym_save_LIBS=$LIBS lt_globsym_save_CFLAGS=$CFLAGS LIBS="conftstm.$ac_objext" CFLAGS="$CFLAGS$_LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)" if AC_TRY_EVAL(ac_link) && test -s conftest${ac_exeext}; then pipe_works=yes fi LIBS=$lt_globsym_save_LIBS CFLAGS=$lt_globsym_save_CFLAGS else echo "cannot find nm_test_func in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot find nm_test_var in $nlist" >&AS_MESSAGE_LOG_FD fi else echo "cannot run $lt_cv_sys_global_symbol_pipe" >&AS_MESSAGE_LOG_FD fi else echo "$progname: failed program was:" >&AS_MESSAGE_LOG_FD cat conftest.$ac_ext >&5 fi rm -rf conftest* conftst* # Do not use the global_symbol_pipe unless it works. if test "$pipe_works" = yes; then break else lt_cv_sys_global_symbol_pipe= fi done ]) if test -z "$lt_cv_sys_global_symbol_pipe"; then lt_cv_sys_global_symbol_to_cdecl= fi if test -z "$lt_cv_sys_global_symbol_pipe$lt_cv_sys_global_symbol_to_cdecl"; then AC_MSG_RESULT(failed) else AC_MSG_RESULT(ok) fi # Response file support. if test "$lt_cv_nm_interface" = "MS dumpbin"; then nm_file_list_spec='@' elif $NM --help 2>/dev/null | grep '[[@]]FILE' >/dev/null; then nm_file_list_spec='@' fi _LT_DECL([global_symbol_pipe], [lt_cv_sys_global_symbol_pipe], [1], [Take the output of nm and produce a listing of raw symbols and C names]) _LT_DECL([global_symbol_to_cdecl], [lt_cv_sys_global_symbol_to_cdecl], [1], [Transform the output of nm in a proper C declaration]) _LT_DECL([global_symbol_to_c_name_address], [lt_cv_sys_global_symbol_to_c_name_address], [1], [Transform the output of nm in a C name address pair]) _LT_DECL([global_symbol_to_c_name_address_lib_prefix], [lt_cv_sys_global_symbol_to_c_name_address_lib_prefix], [1], [Transform the output of nm in a C name address pair when lib prefix is needed]) _LT_DECL([], [nm_file_list_spec], [1], [Specify filename containing input files for $NM]) ]) # _LT_CMD_GLOBAL_SYMBOLS # _LT_COMPILER_PIC([TAGNAME]) # --------------------------- m4_defun([_LT_COMPILER_PIC], [m4_require([_LT_TAG_COMPILER])dnl _LT_TAGVAR(lt_prog_compiler_wl, $1)= _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)= m4_if([$1], [CXX], [ # C++ specific cases for pic, static, wl, etc. if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; *djgpp*) # DJGPP does not support shared libraries at all _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac else case $host_os in aix[[4-9]]*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; chorus*) case $cc_basename in cxch68*) # Green Hills C++ Compiler # _LT_TAGVAR(lt_prog_compiler_static, $1)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" ;; esac ;; mingw* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; dgux*) case $cc_basename in ec++*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; ghcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; freebsd* | dragonfly*) # FreeBSD uses GNU C++ ;; hpux9* | hpux10* | hpux11*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' if test "$host_cpu" != ia64; then _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' fi ;; aCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac ;; *) ;; esac ;; interix*) # This is c89, which is MS Visual C++ (no shared libs) # Anyone wants to do a port? ;; irix5* | irix6* | nonstopux*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' # CC pic flag -KPIC is the default. ;; *) ;; esac ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # KAI C++ Compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; ecpc* ) # old Intel C++ for x86_64 which still supported -KPIC. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; icpc* ) # Intel C++, used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; pgCC* | pgcpp*) # Portland Group C++ compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; cxx*) # Compaq C++ # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xlc* | xlC* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL 8.0, 9.0 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; esac ;; esac ;; lynxos*) ;; m88k*) ;; mvs*) case $cc_basename in cxx*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-W c,exportall' ;; *) ;; esac ;; netbsd* | netbsdelf*-gnu) ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='--backend -Wl,' ;; RCC*) # Rational C++ 2.4.1 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; cxx*) # Digital/Compaq C++ _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # Make sure the PIC flag is empty. It appears that all Alpha # Linux and Compaq Tru64 Unix objects are PIC. _LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; *) ;; esac ;; psos*) ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' ;; *) ;; esac ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; lcc*) # Lucid _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' ;; *) ;; esac ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) case $cc_basename in CC*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' ;; *) ;; esac ;; vxworks*) ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ], [ if test "$GCC" = yes; then _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' case $host_os in aix*) # All AIX code is PIC. if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; m68k) # FIXME: we need at least 68020 code to build shared libraries, but # adding the `-m68020' flag to GCC prevents building anything better, # like `-m68040'. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-m68020 -resident32 -malways-restore-a4' ;; esac ;; beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style # (--disable-auto-import) libraries m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; darwin* | rhapsody*) # PIC is the default on this platform # Common symbols not allowed in MH_DYLIB files _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fno-common' ;; haiku*) # PIC is the default for Haiku. # The "-static" flag exists, but is broken. _LT_TAGVAR(lt_prog_compiler_static, $1)= ;; hpux*) # PIC is the default for 64-bit PA HP-UX, but not for 32-bit # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag # sets the default TLS model and affects inlining. case $host_cpu in hppa*64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac ;; interix[[3-9]]*) # Interix 3.x gcc -fpic/-fPIC options generate broken code. # Instead, we relocate shared libraries at runtime. ;; msdosdjgpp*) # Just because we use GCC doesn't mean we suddenly get shared libraries # on systems that don't support them. _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no enable_shared=no ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(lt_prog_compiler_pic, $1)=-Kconform_pic fi ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' ;; esac case $cc_basename in nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Xlinker ' if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_TAGVAR(lt_prog_compiler_pic, $1)="-Xcompiler $_LT_TAGVAR(lt_prog_compiler_pic, $1)" fi ;; esac else # PORTME Check for flag to pass linker flags through the system compiler. case $host_os in aix*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' if test "$host_cpu" = ia64; then # AIX 5 now supports IA64 processor _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' else _LT_TAGVAR(lt_prog_compiler_static, $1)='-bnso -bI:/lib/syscalls.exp' fi ;; mingw* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], [_LT_TAGVAR(lt_prog_compiler_pic, $1)='-DDLL_EXPORT']) ;; hpux9* | hpux10* | hpux11*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but # not for PA HP-UX. case $host_cpu in hppa*64*|ia64*) # +Z the default ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)='+Z' ;; esac # Is there a better lt_prog_compiler_static that works with the bundled CC? _LT_TAGVAR(lt_prog_compiler_static, $1)='${wl}-a ${wl}archive' ;; irix5* | irix6* | nonstopux*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # PIC (with -KPIC) is the default. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in # old Intel for x86_64 which still supported -KPIC. ecc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # icc used to be incompatible with GCC. # ICC 10 doesn't accept -KPIC any more. icc* | ifort*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; # Lahey Fortran 8.1. lf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='--shared' _LT_TAGVAR(lt_prog_compiler_static, $1)='--static' ;; nagfor*) # NAG Fortran compiler _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,-Wl,,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group compilers (*not* the Pentium gcc compiler, # which looks to be a dead project) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; ccc*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All Alpha code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; xl* | bgxl* | bgf* | mpixl*) # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-qpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-qstaticlink' ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [[1-7]].* | *Sun*Fortran*\ 8.[[0-3]]*) # Sun Fortran 8.3 passes all unrecognized flags to the linker _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='' ;; *Sun\ F* | *Sun*Fortran*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' ;; *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' ;; *Intel*\ [[CF]]*Compiler*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; *Portland\ Group*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fpic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; esac ;; esac ;; newsos6) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC -shared' ;; osf3* | osf4* | osf5*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' # All OSF/1 code is PIC. _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; rdos*) _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' case $cc_basename in f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ';; *) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,';; esac ;; sunos4*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Qoption ld ' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-PIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4 | sysv4.2uw2* | sysv4.3*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; sysv4*MP*) if test -d /usr/nec ;then _LT_TAGVAR(lt_prog_compiler_pic, $1)='-Kconform_pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' fi ;; sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; unicos*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; uts4*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-pic' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; *) _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no ;; esac fi ]) case $host_os in # For platforms which do not support PIC, -DPIC is meaningless: *djgpp*) _LT_TAGVAR(lt_prog_compiler_pic, $1)= ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)="$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])" ;; esac AC_CACHE_CHECK([for $compiler option to produce PIC], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)], [_LT_TAGVAR(lt_cv_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_prog_compiler_pic, $1)]) _LT_TAGVAR(lt_prog_compiler_pic, $1)=$_LT_TAGVAR(lt_cv_prog_compiler_pic, $1) # # Check to make sure the PIC flag actually works. # if test -n "$_LT_TAGVAR(lt_prog_compiler_pic, $1)"; then _LT_COMPILER_OPTION([if $compiler PIC flag $_LT_TAGVAR(lt_prog_compiler_pic, $1) works], [_LT_TAGVAR(lt_cv_prog_compiler_pic_works, $1)], [$_LT_TAGVAR(lt_prog_compiler_pic, $1)@&t@m4_if([$1],[],[ -DPIC],[m4_if([$1],[CXX],[ -DPIC],[])])], [], [case $_LT_TAGVAR(lt_prog_compiler_pic, $1) in "" | " "*) ;; *) _LT_TAGVAR(lt_prog_compiler_pic, $1)=" $_LT_TAGVAR(lt_prog_compiler_pic, $1)" ;; esac], [_LT_TAGVAR(lt_prog_compiler_pic, $1)= _LT_TAGVAR(lt_prog_compiler_can_build_shared, $1)=no]) fi _LT_TAGDECL([pic_flag], [lt_prog_compiler_pic], [1], [Additional compiler flags for building library objects]) _LT_TAGDECL([wl], [lt_prog_compiler_wl], [1], [How to pass a linker flag through the compiler]) # # Check to make sure the static flag actually works. # wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) eval lt_tmp_static_flag=\"$_LT_TAGVAR(lt_prog_compiler_static, $1)\" _LT_LINKER_OPTION([if $compiler static flag $lt_tmp_static_flag works], _LT_TAGVAR(lt_cv_prog_compiler_static_works, $1), $lt_tmp_static_flag, [], [_LT_TAGVAR(lt_prog_compiler_static, $1)=]) _LT_TAGDECL([link_static_flag], [lt_prog_compiler_static], [1], [Compiler flag to prevent dynamic linking]) ])# _LT_COMPILER_PIC # _LT_LINKER_SHLIBS([TAGNAME]) # ---------------------------- # See if the linker supports building shared libraries. m4_defun([_LT_LINKER_SHLIBS], [AC_REQUIRE([LT_PATH_LD])dnl AC_REQUIRE([LT_PATH_NM])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_DECL_SED])dnl m4_require([_LT_CMD_GLOBAL_SYMBOLS])dnl m4_require([_LT_TAG_COMPILER])dnl AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) m4_if([$1], [CXX], [ _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] case $host_os in aix[[4-9]]*) # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global defined # symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi ;; pw32*) _LT_TAGVAR(export_symbols_cmds, $1)="$ltdll_cmds" ;; cygwin* | mingw* | cegcc*) case $cc_basename in cl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] ;; esac ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; *) _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' ;; esac ], [ runpath_var= _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_cmds, $1)= _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED '\''s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(old_archive_from_new_cmds, $1)= _LT_TAGVAR(old_archive_from_expsyms_cmds, $1)= _LT_TAGVAR(thread_safe_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= # include_expsyms should be a list of space-separated symbols to be *always* # included in the symbol list _LT_TAGVAR(include_expsyms, $1)= # exclude_expsyms can be an extended regexp of symbols to exclude # it will be wrapped by ` (' and `)$', so one must not match beginning or # end of line. Example: `a|bc|.*d.*' will exclude the symbols `a' and `bc', # as well as any symbol that contains `d'. _LT_TAGVAR(exclude_expsyms, $1)=['_GLOBAL_OFFSET_TABLE_|_GLOBAL__F[ID]_.*'] # Although _GLOBAL_OFFSET_TABLE_ is a valid symbol C name, most a.out # platforms (ab)use it in PIC code, but their linkers get confused if # the symbol is explicitly referenced. Since portable code cannot # rely on this symbol name, it's probably fine to never include it in # preloaded symbol tables. # Exclude shared library initialization/finalization symbols. dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in cygwin* | mingw* | pw32* | cegcc*) # FIXME: the MSVC++ port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++. if test "$GCC" != yes; then with_gnu_ld=no fi ;; interix*) # we just hope/assume this is gcc and not c89 (= MSVC++) with_gnu_ld=yes ;; openbsd*) with_gnu_ld=no ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; esac _LT_TAGVAR(ld_shlibs, $1)=yes # On some targets, GNU ld is compatible enough with the native linker # that we're better off using the native interface for both. lt_use_gnu_ld_interface=no if test "$with_gnu_ld" = yes; then case $host_os in aix*) # The AIX port of GNU ld has always aspired to compatibility # with the native linker. However, as the warning in the GNU ld # block says, versions before 2.19.5* couldn't really create working # shared libraries, regardless of the interface used. case `$LD -v 2>&1` in *\ \(GNU\ Binutils\)\ 2.19.5*) ;; *\ \(GNU\ Binutils\)\ 2.[[2-9]]*) ;; *\ \(GNU\ Binutils\)\ [[3-9]]*) ;; *) lt_use_gnu_ld_interface=yes ;; esac ;; *) lt_use_gnu_ld_interface=yes ;; esac fi if test "$lt_use_gnu_ld_interface" = yes; then # If archive_cmds runs LD, not CC, wlarc should be empty wlarc='${wl}' # Set some defaults for GNU ld with shared library support. These # are reset later if shared libraries are not supported. Putting them # here allows them to be overridden if necessary. runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # ancient GNU ld didn't support --whole-archive et. al. if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi supports_anon_versioning=no case `$LD -v 2>&1` in *GNU\ gold*) supports_anon_versioning=yes ;; *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.10.*) ;; # catch versions < 2.11 *\ 2.11.93.0.2\ *) supports_anon_versioning=yes ;; # RH7.3 ... *\ 2.11.92.0.12\ *) supports_anon_versioning=yes ;; # Mandrake 8.2 ... *\ 2.11.*) ;; # other 2.11 versions *) supports_anon_versioning=yes ;; esac # See if GNU ld supports shared libraries. case $host_os in aix[[3-9]]*) # On AIX/PPC, the GNU linker is very broken if test "$host_cpu" != ia64; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: the GNU linker, at least up to release 2.19, is reported *** to be unable to reliably create shared libraries on AIX. *** Therefore, libtool is disabling shared libraries support. If you *** really care for shared libraries, you may want to install binutils *** 2.20 or above, or modify your PATH so that a non-GNU linker is found. *** You will then need to restart the configuration process. _LT_EOF fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; cygwin* | mingw* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared $output_objdir/$soname.def $libobjs $deplibs $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; gnu* | linux* | tpf* | k*bsd*-gnu | kopensolaris*-gnu) tmp_diet=no if test "$host_os" = linux-dietlibc; then case $cc_basename in diet\ *) tmp_diet=yes;; # linux-dietlibc with static linking (!diet-dyn) esac fi if $LD --help 2>&1 | $EGREP ': supported targets:.* elf' > /dev/null \ && test "$tmp_diet" = no then tmp_addflag=' $pic_flag' tmp_sharedflag='-shared' case $cc_basename,$host_cpu in pgcc*) # Portland Group C compiler _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag' ;; pgf77* | pgf90* | pgf95* | pgfortran*) # Portland Group f77 and f90 compilers _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' tmp_addflag=' $pic_flag -Mnomain' ;; ecc*,ia64* | icc*,ia64*) # Intel C compiler on ia64 tmp_addflag=' -i_dynamic' ;; efc*,ia64* | ifort*,ia64*) # Intel Fortran compiler on ia64 tmp_addflag=' -i_dynamic -nofor_main' ;; ifc* | ifort*) # Intel Fortran compiler tmp_addflag=' -nofor_main' ;; lf95*) # Lahey Fortran 8.1 _LT_TAGVAR(whole_archive_flag_spec, $1)= tmp_sharedflag='--shared' ;; xl[[cC]]* | bgxl[[cC]]* | mpixl[[cC]]*) # IBM XL C 8.0 on PPC (deal with xlf below) tmp_sharedflag='-qmkshrobj' tmp_addflag= ;; nvcc*) # Cuda Compiler Driver 2.2 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes ;; esac case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C 5.9 _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes tmp_sharedflag='-G' ;; *Sun\ F*) # Sun Fortran 8.3 tmp_sharedflag='-G' ;; esac _LT_TAGVAR(archive_cmds, $1)='$CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC '"$tmp_sharedflag""$tmp_addflag"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi case $cc_basename in xlf* | bgf* | bgxlf* | mpixlf*) # IBM XL Fortran 10.1 on PPC cannot create shared libs itself _LT_TAGVAR(whole_archive_flag_spec, $1)='--whole-archive$convenience --no-whole-archive' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$LD -shared $libobjs $deplibs $linker_flags -soname $soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $LD -shared $libobjs $deplibs $linker_flags -soname $soname -version-script $output_objdir/$libname.ver -o $lib' fi ;; esac else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' wlarc= else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' fi ;; solaris*) if $LD -v 2>&1 | $GREP 'BFD 2\.8' > /dev/null; then _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: The releases 2.8.* of the GNU linker cannot reliably *** create shared libraries on Solaris systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.9.1 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF elif $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) case `$LD -v 2>&1` in *\ [[01]].* | *\ 2.[[0-9]].* | *\ 2.1[[0-5]].*) _LT_TAGVAR(ld_shlibs, $1)=no cat <<_LT_EOF 1>&2 *** Warning: Releases of the GNU linker prior to 2.16.91.0.3 can not *** reliably create shared libraries on SCO systems. Therefore, libtool *** is disabling shared libraries support. We urge you to upgrade GNU *** binutils to release 2.16.91.0.3 or newer. Another option is to modify *** your PATH or compiler configuration so that the native linker is *** used, and then restart. _LT_EOF ;; *) # For security reasons, it is highly recommended that you always # use absolute paths for naming shared libraries, and exclude the # DT_RUNPATH tag from executables and libraries. But doing so # requires that you compile everything twice, which is a pain. if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; sunos4*) _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bshareable -o $lib $libobjs $deplibs $linker_flags' wlarc= _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac if test "$_LT_TAGVAR(ld_shlibs, $1)" = no; then runpath_var= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else # PORTME fill in a description of your system's linker (not GNU ld) case $host_os in aix3*) _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(archive_expsym_cmds, $1)='$LD -o $output_objdir/$soname $libobjs $deplibs $linker_flags -bE:$export_symbols -T512 -H512 -bM:SRE~$AR $AR_FLAGS $lib $output_objdir/$soname' # Note: this linker hardcodes the directories in LIBPATH if there # are no directories specified by -L. _LT_TAGVAR(hardcode_minus_L, $1)=yes if test "$GCC" = yes && test -z "$lt_prog_compiler_static"; then # Neither direct hardcoding nor static linking is supported with a # broken collect2. _LT_TAGVAR(hardcode_direct, $1)=unsupported fi ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else # If we're using GNU nm, then we don't want the "-C" option. # -C means demangle to AIX nm, but means don't demangle with GNU nm # Also, AIX nm treats weak defined symbols like other global # defined symbols, whereas GNU nm marks them as "W". if $NM -V 2>&1 | $GREP 'GNU' > /dev/null; then _LT_TAGVAR(export_symbols_cmds, $1)='$NM -Bpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B") || (\$ 2 == "W")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' else _LT_TAGVAR(export_symbols_cmds, $1)='$NM -BCpg $libobjs $convenience | awk '\''{ if (((\$ 2 == "T") || (\$ 2 == "D") || (\$ 2 == "B")) && ([substr](\$ 3,1,1) != ".")) { print \$ 3 } }'\'' | sort -u > $export_symbols' fi aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then aix_use_runtimelinking=yes break fi done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GCC" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi ;; esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi _LT_TAGVAR(link_all_deplibs, $1)=no else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; amigaos*) case $host_cpu in powerpc) # see comment about AmigaOS4 .so support _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='' ;; m68k) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/a2ixlibrary.data~$ECHO "#define NAME $libname" > $output_objdir/a2ixlibrary.data~$ECHO "#define LIBRARY_ID 1" >> $output_objdir/a2ixlibrary.data~$ECHO "#define VERSION $major" >> $output_objdir/a2ixlibrary.data~$ECHO "#define REVISION $revision" >> $output_objdir/a2ixlibrary.data~$AR $AR_FLAGS $lib $libobjs~$RANLIB $lib~(cd $output_objdir && a2ixlibrary -32)' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac ;; bsdi[[45]]*) _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; cygwin* | mingw* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++. # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. case $cc_basename in cl*) # Native MSVC _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then sed -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else sed -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1,DATA/'\'' | $SED -e '\''/^[[AITW]][[ ]]/s/.*[[ ]]//'\'' | sort | uniq > $export_symbols' # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # Assume MSVC wrapper _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $lib $libobjs $compiler_flags `func_echo_all "$deplibs" | $SED '\''s/ -lc$//'\''` -link -dll~linknames=' # The linker will automatically build a .lib file if we build a DLL. _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' # FIXME: Should let the user specify the lib program. _LT_TAGVAR(old_archive_cmds, $1)='lib -OUT:$oldlib$oldobjs$old_deplibs' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 2.2.[012] allows us to include c++rt0.o to get C++ constructor # support. Future versions do this automatically, but an explicit c++rt0.o # does not break anything, and helps significantly (at the cost of a little # extra space). freebsd2.2*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags /usr/lib/c++rt0.o' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # Unfortunately, older versions of FreeBSD 2 do not have this feature. freebsd2.*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; # FreeBSD 3 and greater uses gcc -shared to do shared libraries. freebsd* | dragonfly*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; hpux9*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $libobjs $deplibs $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$LD -b +b $install_libdir -o $output_objdir/$soname $libobjs $deplibs $linker_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; hpux10*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags' fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes fi ;; hpux11*) if test "$GCC" = yes && test "$with_gnu_ld" = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags' ;; esac else case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $libobjs $deplibs $compiler_flags' ;; *) m4_if($1, [], [ # Older versions of the 11.00 compiler do not understand -b yet # (HP92453-01 A.11.01.20 doesn't, HP92453-01 B.11.X.35175-35176.GP does) _LT_LINKER_OPTION([if $CC understands -b], _LT_TAGVAR(lt_cv_prog_compiler__b, $1), [-b], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags'], [_LT_TAGVAR(archive_cmds, $1)='$LD -b +h $soname +b $install_libdir -o $lib $libobjs $deplibs $linker_flags'])], [_LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $libobjs $deplibs $compiler_flags']) ;; esac fi if test "$with_gnu_ld" = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # hardcode_minus_L: Not really in the search PATH, # but as the default location of the library. _LT_TAGVAR(hardcode_minus_L, $1)=yes ;; esac fi ;; irix5* | irix6* | nonstopux*) if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' # Try to use the -exported_symbol ld option, if it does not # work, assume that -exports_file does not work either and # implicitly export all symbols. # This should be the same for all languages, so no per-tag cache variable. AC_CACHE_CHECK([whether the $host_os linker accepts -exported_symbol], [lt_cv_irix_exported_symbol], [save_LDFLAGS="$LDFLAGS" LDFLAGS="$LDFLAGS -shared ${wl}-exported_symbol ${wl}foo ${wl}-update_registry ${wl}/dev/null" AC_LINK_IFELSE( [AC_LANG_SOURCE( [AC_LANG_CASE([C], [[int foo (void) { return 0; }]], [C++], [[int foo (void) { return 0; }]], [Fortran 77], [[ subroutine foo end]], [Fortran], [[ subroutine foo end]])])], [lt_cv_irix_exported_symbol=yes], [lt_cv_irix_exported_symbol=no]) LDFLAGS="$save_LDFLAGS"]) if test "$lt_cv_irix_exported_symbol" = yes; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations ${wl}-exports_file ${wl}$export_symbols -o $lib' fi else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -exports_file $export_symbols -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes _LT_TAGVAR(link_all_deplibs, $1)=yes ;; netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out else _LT_TAGVAR(archive_cmds, $1)='$LD -shared -o $lib $libobjs $deplibs $linker_flags' # ELF fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; newsos6) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *nto* | *qnx*) ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags ${wl}-retain-symbols-file,$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' else case $host_os in openbsd[[01]].* | openbsd2.[[0-7]] | openbsd2.[[0-7]].*) _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' ;; esac fi else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; os2*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(archive_cmds, $1)='$ECHO "LIBRARY $libname INITINSTANCE" > $output_objdir/$libname.def~$ECHO "DESCRIPTION \"$libname\"" >> $output_objdir/$libname.def~echo DATA >> $output_objdir/$libname.def~echo " SINGLE NONSHARED" >> $output_objdir/$libname.def~echo EXPORTS >> $output_objdir/$libname.def~emxexp $libobjs >> $output_objdir/$libname.def~$CC -Zdll -Zcrtdll -o $lib $libobjs $deplibs $compiler_flags $output_objdir/$libname.def' _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/$libname.a $output_objdir/$libname.def' ;; osf3*) if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; osf4* | osf5*) # as osf3* with the addition of -msym flag if test "$GCC" = yes; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $pic_flag $libobjs $deplibs $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' else _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $libobjs $deplibs $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done; printf "%s\\n" "-hidden">> $lib.exp~ $CC -shared${allow_undefined_flag} ${wl}-input ${wl}$lib.exp $compiler_flags $libobjs $deplibs -soname $soname `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~$RM $lib.exp' # Both c and cxx compiler support -rpath directly _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' fi _LT_TAGVAR(archive_cmds_need_lc, $1)='no' _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test "$GCC" = yes; then wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag ${wl}-z ${wl}text ${wl}-M ${wl}$lib.exp ${wl}-h ${wl}$soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' else case `$CC -V 2>&1` in *"Compilers 5.0"*) wlarc='' _LT_TAGVAR(archive_cmds, $1)='$LD -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $LD -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $linker_flags~$RM $lib.exp' ;; *) wlarc='${wl}' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h $soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} -M $lib.exp -h $soname -o $lib $libobjs $deplibs $compiler_flags~$RM $lib.exp' ;; esac fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. GCC discards it without `$wl', # but is careful enough not to reorder. # Supported since Solaris 2.6 (maybe 2.5.1?) if test "$GCC" = yes; then _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' else _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' fi ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes ;; sunos4*) if test "x$host_vendor" = xsequent; then # Use $CC to link under sequent, because it throws in some extra .o # files that make .init and .fini sections work. _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h $soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$LD -assert pure-text -Bstatic -o $lib $libobjs $deplibs $linker_flags' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4) case $host_vendor in sni) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=yes # is this really true??? ;; siemens) ## LD is ld it makes a PLAMLIB ## CC just makes a GrossModule. _LT_TAGVAR(archive_cmds, $1)='$LD -G -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(reload_cmds, $1)='$CC -r -o $output$reload_objs' _LT_TAGVAR(hardcode_direct, $1)=no ;; motorola) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_direct, $1)=no #Motorola manual says yes, but my tests say they lie ;; esac runpath_var='LD_RUN_PATH' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; sysv4.3*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)='-Bexport' ;; sysv4*MP*) if test -d /usr/nec; then _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var=LD_RUN_PATH hardcode_runpath_var=yes _LT_TAGVAR(ld_shlibs, $1)=yes fi ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' if test "$GCC" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' else _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' fi ;; uts4*) _LT_TAGVAR(archive_cmds, $1)='$LD -G -h $soname -o $lib $libobjs $deplibs $linker_flags' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(ld_shlibs, $1)=no ;; esac if test x$host_vendor = xsni; then case $host in sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Blargedynsym' ;; esac fi fi ]) AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(with_gnu_ld, $1)=$with_gnu_ld _LT_DECL([], [libext], [0], [Old archive suffix (normally "a")])dnl _LT_DECL([], [shrext_cmds], [1], [Shared library suffix (normally ".so")])dnl _LT_DECL([], [extract_expsyms_cmds], [2], [The commands to extract the exported symbol list from a shared archive]) # # Do we need to explicitly link libc? # case "x$_LT_TAGVAR(archive_cmds_need_lc, $1)" in x|xyes) # Assume -lc should be added _LT_TAGVAR(archive_cmds_need_lc, $1)=yes if test "$enable_shared" = yes && test "$GCC" = yes; then case $_LT_TAGVAR(archive_cmds, $1) in *'~'*) # FIXME: we may have to deal with multi-command sequences. ;; '$CC '*) # Test whether the compiler implicitly links with -lc since on some # systems, -lgcc has to come before -lc. If gcc already passes -lc # to ld, don't add -lc before -lgcc. AC_CACHE_CHECK([whether -lc should be explicitly linked in], [lt_cv_]_LT_TAGVAR(archive_cmds_need_lc, $1), [$RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if AC_TRY_EVAL(ac_compile) 2>conftest.err; then soname=conftest lib=conftest libobjs=conftest.$ac_objext deplibs= wl=$_LT_TAGVAR(lt_prog_compiler_wl, $1) pic_flag=$_LT_TAGVAR(lt_prog_compiler_pic, $1) compiler_flags=-v linker_flags=-v verstring= output_objdir=. libname=conftest lt_save_allow_undefined_flag=$_LT_TAGVAR(allow_undefined_flag, $1) _LT_TAGVAR(allow_undefined_flag, $1)= if AC_TRY_EVAL(_LT_TAGVAR(archive_cmds, $1) 2\>\&1 \| $GREP \" -lc \" \>/dev/null 2\>\&1) then lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=no else lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1)=yes fi _LT_TAGVAR(allow_undefined_flag, $1)=$lt_save_allow_undefined_flag else cat conftest.err 1>&5 fi $RM conftest* ]) _LT_TAGVAR(archive_cmds_need_lc, $1)=$lt_cv_[]_LT_TAGVAR(archive_cmds_need_lc, $1) ;; esac fi ;; esac _LT_TAGDECL([build_libtool_need_lc], [archive_cmds_need_lc], [0], [Whether or not to add -lc for building shared libraries]) _LT_TAGDECL([allow_libtool_libs_with_static_runtimes], [enable_shared_with_static_runtimes], [0], [Whether or not to disallow shared libs when runtime libs are static]) _LT_TAGDECL([], [export_dynamic_flag_spec], [1], [Compiler flag to allow reflexive dlopens]) _LT_TAGDECL([], [whole_archive_flag_spec], [1], [Compiler flag to generate shared objects directly from archives]) _LT_TAGDECL([], [compiler_needs_object], [1], [Whether the compiler copes with passing no objects directly]) _LT_TAGDECL([], [old_archive_from_new_cmds], [2], [Create an old-style archive from a shared archive]) _LT_TAGDECL([], [old_archive_from_expsyms_cmds], [2], [Create a temporary old-style archive to link instead of a shared archive]) _LT_TAGDECL([], [archive_cmds], [2], [Commands used to build a shared archive]) _LT_TAGDECL([], [archive_expsym_cmds], [2]) _LT_TAGDECL([], [module_cmds], [2], [Commands used to build a loadable module if different from building a shared archive.]) _LT_TAGDECL([], [module_expsym_cmds], [2]) _LT_TAGDECL([], [with_gnu_ld], [1], [Whether we are building with GNU ld or not]) _LT_TAGDECL([], [allow_undefined_flag], [1], [Flag that allows shared libraries with undefined symbols to be built]) _LT_TAGDECL([], [no_undefined_flag], [1], [Flag that enforces no undefined symbols]) _LT_TAGDECL([], [hardcode_libdir_flag_spec], [1], [Flag to hardcode $libdir into a binary during linking. This must work even if $libdir does not exist]) _LT_TAGDECL([], [hardcode_libdir_separator], [1], [Whether we need a single "-rpath" flag with a separated argument]) _LT_TAGDECL([], [hardcode_direct], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME${shared_ext} during linking hardcodes DIR into the resulting binary and the resulting library dependency is "absolute", i.e impossible to change by setting ${shlibpath_var} if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_shlibpath_var], [0], [Set to "yes" if using SHLIBPATH_VAR=DIR during linking hardcodes DIR into the resulting binary]) _LT_TAGDECL([], [hardcode_automatic], [0], [Set to "yes" if building a shared library automatically hardcodes DIR into the library and all subsequent libraries and executables linked against it]) _LT_TAGDECL([], [inherit_rpath], [0], [Set to yes if linker adds runtime paths of dependent libraries to runtime path list]) _LT_TAGDECL([], [link_all_deplibs], [0], [Whether libtool must link a program against all its dependency libraries]) _LT_TAGDECL([], [always_export_symbols], [0], [Set to "yes" if exported symbols are required]) _LT_TAGDECL([], [export_symbols_cmds], [2], [The commands to list exported symbols]) _LT_TAGDECL([], [exclude_expsyms], [1], [Symbols that should not be listed in the preloaded symbols]) _LT_TAGDECL([], [include_expsyms], [1], [Symbols that must always be exported]) _LT_TAGDECL([], [prelink_cmds], [2], [Commands necessary for linking programs (against libraries) with templates]) _LT_TAGDECL([], [postlink_cmds], [2], [Commands necessary for finishing linking programs]) _LT_TAGDECL([], [file_list_spec], [1], [Specify filename containing input files]) dnl FIXME: Not yet implemented dnl _LT_TAGDECL([], [thread_safe_flag_spec], [1], dnl [Compiler flag to generate thread safe objects]) ])# _LT_LINKER_SHLIBS # _LT_LANG_C_CONFIG([TAG]) # ------------------------ # Ensure that the configuration variables for a C compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_C_CONFIG], [m4_require([_LT_DECL_EGREP])dnl lt_save_CC="$CC" AC_LANG_PUSH(C) # Source file extension for C test sources. ac_ext=c # Object file extension for compiled C test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other # tags are being tested, and _LT_TAGVAR(compiler, []) is a NOP. compiler_DEFAULT=$CC # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) LT_SYS_DLOPEN_SELF _LT_CMD_STRIPLIB # Report which library types will actually be built AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_CONFIG($1) fi AC_LANG_POP CC="$lt_save_CC" ])# _LT_LANG_C_CONFIG # _LT_LANG_CXX_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a C++ compiler are suitably # defined. These variables are subsequently used by _LT_CONFIG to write # the compiler configuration to `libtool'. m4_defun([_LT_LANG_CXX_CONFIG], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl m4_require([_LT_DECL_EGREP])dnl m4_require([_LT_PATH_MANIFEST_TOOL])dnl if test -n "$CXX" && ( test "X$CXX" != "Xno" && ( (test "X$CXX" = "Xg++" && `g++ -v >/dev/null 2>&1` ) || (test "X$CXX" != "Xg++"))) ; then AC_PROG_CXXCPP else _lt_caught_CXX_error=yes fi AC_LANG_PUSH(C++) _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(compiler_needs_object, $1)=no _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=unsupported _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for C++ test sources. ac_ext=cpp # Object file extension for compiled C++ test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the CXX compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_caught_CXX_error" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests lt_simple_link_test_code='int main(int, char *[[]]) { return(0); }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_LD=$LD lt_save_GCC=$GCC GCC=$GXX lt_save_with_gnu_ld=$with_gnu_ld lt_save_path_LD=$lt_cv_path_LD if test -n "${lt_cv_prog_gnu_ldcxx+set}"; then lt_cv_prog_gnu_ld=$lt_cv_prog_gnu_ldcxx else $as_unset lt_cv_prog_gnu_ld fi if test -n "${lt_cv_path_LDCXX+set}"; then lt_cv_path_LD=$lt_cv_path_LDCXX else $as_unset lt_cv_path_LD fi test -z "${LDCXX+set}" || LD=$LDCXX CC=${CXX-"c++"} CFLAGS=$CXXFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then # We don't want -fno-exception when compiling C++ code, so set the # no_builtin_flag separately if test "$GXX" = yes; then _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)=' -fno-builtin' else _LT_TAGVAR(lt_prog_compiler_no_builtin_flag, $1)= fi if test "$GXX" = yes; then # Set up default GNU C++ configuration LT_PATH_LD # Check if GNU C++ uses GNU ld as the underlying linker, since the # archiving commands below assume that GNU ld is being used. if test "$with_gnu_ld" = yes; then _LT_TAGVAR(archive_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC $pic_flag -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # If archive_cmds runs LD, not CC, wlarc should be empty # XXX I think wlarc can be eliminated in ltcf-cxx, but I need to # investigate it a little bit more. (MM) wlarc='${wl}' # ancient GNU ld didn't support --whole-archive et. al. if eval "`$CC -print-prog-name=ld` --help 2>&1" | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= fi else with_gnu_ld=no wlarc= # A generic and very simple default shared library creation # command for GNU C++ for the case where it uses the native # linker, instead of GNU ld. If possible, this setting should # overridden to take advantage of the native linker features on # the platform it is being used on. _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else GXX=no with_gnu_ld=no wlarc= fi # PORTME: fill in a description of your system's C++ link characteristics AC_MSG_CHECKING([whether the $compiler linker ($LD) supports shared libraries]) _LT_TAGVAR(ld_shlibs, $1)=yes case $host_os in aix3*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aix[[4-9]]*) if test "$host_cpu" = ia64; then # On IA64, the linker does run time linking by default, so we don't # have to do anything special. aix_use_runtimelinking=no exp_sym_flag='-Bexport' no_entry_flag="" else aix_use_runtimelinking=no # Test if we are trying to use run time linking or normal # AIX style linking. If -brtl is somewhere in LDFLAGS, we # need to do runtime linking. case $host_os in aix4.[[23]]|aix4.[[23]].*|aix[[5-9]]*) for ld_flag in $LDFLAGS; do case $ld_flag in *-brtl*) aix_use_runtimelinking=yes break ;; esac done ;; esac exp_sym_flag='-bexport' no_entry_flag='-bnoentry' fi # When large executables or shared objects are built, AIX ld can # have problems creating the table of contents. If linking a library # or program results in "error TOC overflow" add -mminimal-toc to # CXXFLAGS/CFLAGS for g++/gcc. In the cases where that is not # enough to fix the problem, add -Wl,-bbigtoc to LDFLAGS. _LT_TAGVAR(archive_cmds, $1)='' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(file_list_spec, $1)='${wl}-f,' if test "$GXX" = yes; then case $host_os in aix4.[[012]]|aix4.[[012]].*) # We only want to do this on AIX 4.2 and lower, the check # below for broken collect2 doesn't work under 4.3+ collect2name=`${CC} -print-prog-name=collect2` if test -f "$collect2name" && strings "$collect2name" | $GREP resolve_lib_name >/dev/null then # We have reworked collect2 : else # We have old collect2 _LT_TAGVAR(hardcode_direct, $1)=unsupported # It fails to find uninstalled libraries when the uninstalled # path is not listed in the libpath. Setting hardcode_minus_L # to unsupported forces relinking _LT_TAGVAR(hardcode_minus_L, $1)=yes _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)= fi esac shared_flag='-shared' if test "$aix_use_runtimelinking" = yes; then shared_flag="$shared_flag "'${wl}-G' fi else # not using gcc if test "$host_cpu" = ia64; then # VisualAge C++, Version 5.5 for AIX 5L for IA-64, Beta 3 Release # chokes on -Wl,-G. The following line is correct: shared_flag='-G' else if test "$aix_use_runtimelinking" = yes; then shared_flag='${wl}-G' else shared_flag='${wl}-bM:SRE' fi fi fi _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-bexpall' # It seems that -bexpall does not export symbols beginning with # underscore (_), so it is better to generate a list of symbols to # export. _LT_TAGVAR(always_export_symbols, $1)=yes if test "$aix_use_runtimelinking" = yes; then # Warning - without using the other runtime loading flags (-brtl), # -berok will link without error, but may produce a broken library. _LT_TAGVAR(allow_undefined_flag, $1)='-berok' # Determine the default libpath from the value encoded in an empty # executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags `if test "x${allow_undefined_flag}" != "x"; then func_echo_all "${wl}${allow_undefined_flag}"; else :; fi` '"\${wl}$exp_sym_flag:\$export_symbols $shared_flag" else if test "$host_cpu" = ia64; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $libdir:/usr/lib:/lib' _LT_TAGVAR(allow_undefined_flag, $1)="-z nodefs" _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs '"\${wl}$no_entry_flag"' $compiler_flags ${wl}${allow_undefined_flag} '"\${wl}$exp_sym_flag:\$export_symbols" else # Determine the default libpath from the value encoded in an # empty executable. _LT_SYS_MODULE_PATH_AIX([$1]) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-blibpath:$libdir:'"$aix_libpath" # Warning - without using the other run time loading flags, # -berok will link without error, but may produce a broken library. _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-bernotok' _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-berok' if test "$with_gnu_ld" = yes; then # We only use this code for GNU lds that support --whole-archive. _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' else # Exported symbols can be pulled into shared objects from archives _LT_TAGVAR(whole_archive_flag_spec, $1)='$convenience' fi _LT_TAGVAR(archive_cmds_need_lc, $1)=yes # This is similar to how AIX traditionally builds its shared # libraries. _LT_TAGVAR(archive_expsym_cmds, $1)="\$CC $shared_flag"' -o $output_objdir/$soname $libobjs $deplibs ${wl}-bnoentry $compiler_flags ${wl}-bE:$export_symbols${allow_undefined_flag}~$AR $AR_FLAGS $output_objdir/$libname$release.a $output_objdir/$soname' fi fi ;; beos*) if $LD --help 2>&1 | $GREP ': supported targets:.* elf' > /dev/null; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported # Joseph Beckenbach says some releases of gcc # support --undefined. This deserves some investigation. FIXME _LT_TAGVAR(archive_cmds, $1)='$CC -nostart $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; chorus*) case $cc_basename in *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; cygwin* | mingw* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl*) # Native MSVC # hardcode_libdir_flag_spec is actually meaningless, as there is # no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)=' ' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' # Tell ltmain to make .lib files, not .a files. libext=lib # Tell ltmain to make .dll files, not .so files. shrext_cmds=".dll" # FIXME: Setting linknames here is a bad hack. _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-dll~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then $SED -n -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' -e '1\\\!p' < $export_symbols > $output_objdir/$soname.exp; else $SED -e 's/\\\\\\\(.*\\\\\\\)/-link\\\ -EXPORT:\\\\\\\1/' < $export_symbols > $output_objdir/$soname.exp; fi~ $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes # Don't use ranlib _LT_TAGVAR(old_postinstall_cmds, $1)='chmod 644 $oldlib' _LT_TAGVAR(postlink_cmds, $1)='lt_outputfile="@OUTPUT@"~ lt_tool_outputfile="@TOOL_OUTPUT@"~ case $lt_outputfile in *.exe|*.EXE) ;; *) lt_outputfile="$lt_outputfile.exe" lt_tool_outputfile="$lt_tool_outputfile.exe" ;; esac~ func_to_tool_file "$lt_outputfile"~ if test "$MANIFEST_TOOL" != ":" && test -f "$lt_outputfile.manifest"; then $MANIFEST_TOOL -manifest "$lt_tool_outputfile.manifest" -outputresource:"$lt_tool_outputfile" || exit 1; $RM "$lt_outputfile.manifest"; fi' ;; *) # g++ # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-all-symbols' _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' # If the export-symbols file already is a .def file (1st line # is EXPORTS), use it as is; otherwise, prepend... _LT_TAGVAR(archive_expsym_cmds, $1)='if test "x`$SED 1q $export_symbols`" = xEXPORTS; then cp $export_symbols $output_objdir/$soname.def; else echo EXPORTS > $output_objdir/$soname.def; cat $export_symbols >> $output_objdir/$soname.def; fi~ $CC -shared -nostdlib $output_objdir/$soname.def $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname ${wl}--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; darwin* | rhapsody*) _LT_DARWIN_LINKER_FEATURES($1) ;; dgux*) case $cc_basename in ec++*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; ghcx*) # Green Hills C++ Compiler # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; freebsd2.*) # C++ shared libraries reported to be fairly broken before # switch to ELF _LT_TAGVAR(ld_shlibs, $1)=no ;; freebsd-elf*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; freebsd* | dragonfly*) # FreeBSD 3 and later use GNU C++ and GNU ld with standard ELF # conventions _LT_TAGVAR(ld_shlibs, $1)=yes ;; haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(link_all_deplibs, $1)=yes ;; hpux9*) _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -b ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then _LT_TAGVAR(archive_cmds, $1)='$RM $output_objdir/$soname~$CC -shared -nostdlib $pic_flag ${wl}+b ${wl}$install_libdir -o $output_objdir/$soname $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~test $output_objdir/$soname = $lib || mv $output_objdir/$soname $lib' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; hpux10*|hpux11*) if test $with_gnu_ld = no; then _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}+b ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: case $host_cpu in hppa*64*|ia64*) ;; *) _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' ;; esac fi case $host_cpu in hppa*64*|ia64*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no ;; *) _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(hardcode_minus_L, $1)=yes # Not in the search PATH, # but as the default # location of the library. ;; esac case $cc_basename in CC*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; aCC*) case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -b ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP "\-L"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes; then if test $with_gnu_ld = no; then case $host_cpu in hppa*64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib -fPIC ${wl}+h ${wl}$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; ia64*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+nodefaultrpath -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $pic_flag ${wl}+h ${wl}$soname ${wl}+b ${wl}$install_libdir -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' ;; esac fi else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; interix[[3-9]]*) _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' # Hack: On Interix 3.x, we cannot compile PIC because of a broken gcc. # Instead, shared libraries are loaded at an image base (0x10000000 by # default) and relocated if they conflict, which is a slow very memory # consuming and fragmenting process. To avoid this, we pick a random, # 256 KiB-aligned image base between 0x50000000 and 0x6FFC0000 at link # time. Moving up from 0x10000000 also allows more sbrk(2) space. _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='sed "s,^,_," $export_symbols >$output_objdir/$soname.expsym~$CC -shared $pic_flag $libobjs $deplibs $compiler_flags ${wl}-h,$soname ${wl}--retain-symbols-file,$output_objdir/$soname.expsym ${wl}--image-base,`expr ${RANDOM-$$} % 4096 / 2 \* 262144 + 1342177280` -o $lib' ;; irix5* | irix6*) case $cc_basename in CC*) # SGI C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared -all -multigot $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' # Archives containing C++ object files must be created using # "CC -ar", where "CC" is the IRIX C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -ar -WR,-u -o $oldlib $oldobjs' ;; *) if test "$GXX" = yes; then if test "$with_gnu_ld" = no; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' else _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` -o $lib' fi fi _LT_TAGVAR(link_all_deplibs, $1)=yes ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: _LT_TAGVAR(inherit_rpath, $1)=yes ;; linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo $lib | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib ${wl}-retain-symbols-file,$export_symbols; mv \$templib $lib' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 | $GREP "ld"`; rm -f libconftest$shared_ext; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' # Archives containing C++ object files must be created using # "CC -Bstatic", where "CC" is the KAI C++ compiler. _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; icpc* | ecpc* ) # Intel C++ with_gnu_ld=yes # version 8.0 and above of icpc choke on multiply defined symbols # if we add $predep_objects and $postdep_objects, however 7.1 and # earlier do not add the objects themselves. case `$CC -V 2>&1` in *"Version 7."*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; *) # Version 8.0 or newer tmp_idyn= case $host_cpu in ia64*) tmp_idyn=' -i_dynamic';; esac _LT_TAGVAR(archive_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared'"$tmp_idyn"' $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-retain-symbols-file $wl$export_symbols -o $lib' ;; esac _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive$convenience ${wl}--no-whole-archive' ;; pgCC* | pgcpp*) # Portland Group C++ compiler case `$CC -V` in *pgCC\ [[1-5]].* | *pgcpp\ [[1-5]].*) _LT_TAGVAR(prelink_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $objs $libobjs $compile_deplibs~ compile_command="$compile_command `find $tpldir -name \*.o | sort | $NL2SP`"' _LT_TAGVAR(old_archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $oldobjs$old_deplibs~ $AR $AR_FLAGS $oldlib$oldobjs$old_deplibs `find $tpldir -name \*.o | sort | $NL2SP`~ $RANLIB $oldlib' _LT_TAGVAR(archive_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='tpldir=Template.dir~ rm -rf $tpldir~ $CC --prelink_objects --instantiation_dir $tpldir $predep_objects $libobjs $deplibs $convenience $postdep_objects~ $CC -shared $pic_flag $predep_objects $libobjs $deplibs `find $tpldir -name \*.o | sort | $NL2SP` $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; *) # Version 6 and above use weak symbols _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname ${wl}-retain-symbols-file ${wl}$export_symbols -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}--rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`for conv in $convenience\"\"; do test -n \"$conv\" && new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' ;; cxx*) # Compaq C++ _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $wl$soname -o $lib ${wl}-retain-symbols-file $wl$export_symbols' runpath_var=LD_RUN_PATH _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld .*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "X$list" | $Xsed' ;; xl* | mpixl* | bgxl*) # IBM XL 8.0 on PPC, with GNU ld _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}--export-dynamic' _LT_TAGVAR(archive_cmds, $1)='$CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname -o $lib' if test "x$supports_anon_versioning" = xyes; then _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $output_objdir/$libname.ver~ cat $export_symbols | sed -e "s/\(.*\)/\1;/" >> $output_objdir/$libname.ver~ echo "local: *; };" >> $output_objdir/$libname.ver~ $CC -qmkshrobj $libobjs $deplibs $compiler_flags ${wl}-soname $wl$soname ${wl}-version-script ${wl}$output_objdir/$libname.ver -o $lib' fi ;; *) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file ${wl}$export_symbols' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}--whole-archive`new_convenience=; for conv in $convenience\"\"; do test -z \"$conv\" || new_convenience=\"$new_convenience,$conv\"; done; func_echo_all \"$new_convenience\"` ${wl}--no-whole-archive' _LT_TAGVAR(compiler_needs_object, $1)=yes # Not sure whether something based on # $CC $CFLAGS -v conftest.$objext -o libconftest$shared_ext 2>&1 # would be better. output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; esac ;; esac ;; lynxos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; m88k*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; mvs*) case $cc_basename in cxx*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' wlarc= _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no fi # Workaround some broken pre-1.5 toolchains output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP conftest.$objext | $SED -e "s:-lgcc -lc -lgcc::"' ;; *nto* | *qnx*) _LT_TAGVAR(ld_shlibs, $1)=yes ;; openbsd2*) # C++ shared libraries are fairly broken _LT_TAGVAR(ld_shlibs, $1)=no ;; openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=yes _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-retain-symbols-file,$export_symbols -o $lib' _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-E' _LT_TAGVAR(whole_archive_flag_spec, $1)="$wlarc"'--whole-archive$convenience '"$wlarc"'--no-whole-archive' fi output_verbose_link_cmd=func_echo_all else _LT_TAGVAR(ld_shlibs, $1)=no fi ;; osf3* | osf4* | osf5*) case $cc_basename in KCC*) # Kuck and Associates, Inc. (KAI) C++ Compiler # KCC will only create a shared library if the output file # ends with ".so" (or ".sl" for HP-UX), so rename the library # to its proper name (with version) after linking. _LT_TAGVAR(archive_cmds, $1)='tempext=`echo $shared_ext | $SED -e '\''s/\([[^()0-9A-Za-z{}]]\)/\\\\\1/g'\''`; templib=`echo "$lib" | $SED -e "s/\${tempext}\..*/.so/"`; $CC $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags --soname $soname -o \$templib; mv \$templib $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Archives containing C++ object files must be created using # the KAI C++ compiler. case $host in osf3*) _LT_TAGVAR(old_archive_cmds, $1)='$CC -Bstatic -o $oldlib $oldobjs' ;; *) _LT_TAGVAR(old_archive_cmds, $1)='$CC -o $oldlib $oldobjs' ;; esac ;; RCC*) # Rational C++ 2.4.1 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; cxx*) case $host in osf3*) _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname $soname `test -n "$verstring" && func_echo_all "${wl}-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' ;; *) _LT_TAGVAR(allow_undefined_flag, $1)=' -expect_unresolved \*' _LT_TAGVAR(archive_cmds, $1)='$CC -shared${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname `test -n "$verstring" && func_echo_all "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='for i in `cat $export_symbols`; do printf "%s %s\\n" -exported_symbol "\$i" >> $lib.exp; done~ echo "-hidden">> $lib.exp~ $CC -shared$allow_undefined_flag $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -msym -soname $soname ${wl}-input ${wl}$lib.exp `test -n "$verstring" && $ECHO "-set_version $verstring"` -update_registry ${output_objdir}/so_locations -o $lib~ $RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-rpath $libdir' ;; esac _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. # # There doesn't appear to be a way to prevent this compiler from # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. output_verbose_link_cmd='templist=`$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP "ld" | $GREP -v "ld:"`; templist=`func_echo_all "$templist" | $SED "s/\(^.*ld.*\)\( .*ld.*$\)/\1/"`; list=""; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(allow_undefined_flag, $1)=' ${wl}-expect_unresolved ${wl}\*' case $host in osf3*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib ${allow_undefined_flag} $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-msym ${wl}-soname ${wl}$soname `test -n "$verstring" && func_echo_all "${wl}-set_version ${wl}$verstring"` ${wl}-update_registry ${wl}${output_objdir}/so_locations -o $lib' ;; esac _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-rpath ${wl}$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=: # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no fi ;; esac ;; psos*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; sunos4*) case $cc_basename in CC*) # Sun C++ 4.x # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; lcc*) # Lucid # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # Sun C++ 4.2, 5.x and Centerline C++ _LT_TAGVAR(archive_cmds_need_lc,$1)=yes _LT_TAGVAR(no_undefined_flag, $1)=' -zdefs' _LT_TAGVAR(archive_cmds, $1)='$CC -G${allow_undefined_flag} -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G${allow_undefined_flag} ${wl}-M ${wl}$lib.exp -h$soname -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-R$libdir' _LT_TAGVAR(hardcode_shlibpath_var, $1)=no case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) # The compiler driver will combine and reorder linker options, # but understands `-z linker_flag'. # Supported since Solaris 2.6 (maybe 2.5.1?) _LT_TAGVAR(whole_archive_flag_spec, $1)='-z allextract$convenience -z defaultextract' ;; esac _LT_TAGVAR(link_all_deplibs, $1)=yes output_verbose_link_cmd='func_echo_all' # Archives containing C++ object files must be created using # "CC -xar", where "CC" is the Sun C++ compiler. This is # necessary to make sure instantiated templates are included # in the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC -xar -o $oldlib $oldobjs' ;; gcx*) # Green Hills C++ Compiler _LT_TAGVAR(archive_cmds, $1)='$CC -shared $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' # The C++ compiler must be used to create the archive. _LT_TAGVAR(old_archive_cmds, $1)='$CC $LDFLAGS -archive -o $oldlib $oldobjs' ;; *) # GNU C++ compiler with Solaris linker if test "$GXX" = yes && test "$with_gnu_ld" = no; then _LT_TAGVAR(no_undefined_flag, $1)=' ${wl}-z ${wl}defs' if $CC --version | $GREP -v '^2\.7' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -shared $pic_flag -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' else # g++ 2.7 appears to require `-G' NOT `-shared' on this # platform. _LT_TAGVAR(archive_cmds, $1)='$CC -G -nostdlib $LDFLAGS $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags ${wl}-h $wl$soname -o $lib' _LT_TAGVAR(archive_expsym_cmds, $1)='echo "{ global:" > $lib.exp~cat $export_symbols | $SED -e "s/\(.*\)/\1;/" >> $lib.exp~echo "local: *; };" >> $lib.exp~ $CC -G -nostdlib ${wl}-M $wl$lib.exp -o $lib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags~$RM $lib.exp' # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP "\-L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R $wl$libdir' case $host_os in solaris2.[[0-5]] | solaris2.[[0-5]].*) ;; *) _LT_TAGVAR(whole_archive_flag_spec, $1)='${wl}-z ${wl}allextract$convenience ${wl}-z ${wl}defaultextract' ;; esac fi ;; esac ;; sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[[01]].[[10]]* | unixware7* | sco3.2v5.0.[[024]]*) _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; sysv5* | sco3.2v5* | sco5v6*) # Note: We can NOT use -z defs as we might desire, because we do not # link with -lc, and that would cause any symbols used from libc to # always be unresolved, which means just about no library would # ever link correctly. If we're not using GNU ld we use -z text # though, which does catch some bad symbols but isn't as heavy-handed # as -z defs. _LT_TAGVAR(no_undefined_flag, $1)='${wl}-z,text' _LT_TAGVAR(allow_undefined_flag, $1)='${wl}-z,nodefs' _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(hardcode_shlibpath_var, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='${wl}-R,$libdir' _LT_TAGVAR(hardcode_libdir_separator, $1)=':' _LT_TAGVAR(link_all_deplibs, $1)=yes _LT_TAGVAR(export_dynamic_flag_spec, $1)='${wl}-Bexport' runpath_var='LD_RUN_PATH' case $cc_basename in CC*) _LT_TAGVAR(archive_cmds, $1)='$CC -G ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -G ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(old_archive_cmds, $1)='$CC -Tprelink_objects $oldobjs~ '"$_LT_TAGVAR(old_archive_cmds, $1)" _LT_TAGVAR(reload_cmds, $1)='$CC -Tprelink_objects $reload_objs~ '"$_LT_TAGVAR(reload_cmds, $1)" ;; *) _LT_TAGVAR(archive_cmds, $1)='$CC -shared ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared ${wl}-Bexport:$export_symbols ${wl}-h,$soname -o $lib $libobjs $deplibs $compiler_flags' ;; esac ;; tandem*) case $cc_basename in NCC*) # NonStop-UX NCC 3.20 # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac ;; vxworks*) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; *) # FIXME: insert proper C++ library support _LT_TAGVAR(ld_shlibs, $1)=no ;; esac AC_MSG_RESULT([$_LT_TAGVAR(ld_shlibs, $1)]) test "$_LT_TAGVAR(ld_shlibs, $1)" = no && can_build_shared=no _LT_TAGVAR(GCC, $1)="$GXX" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS LDCXX=$LD LD=$lt_save_LD GCC=$lt_save_GCC with_gnu_ld=$lt_save_with_gnu_ld lt_cv_path_LDCXX=$lt_cv_path_LD lt_cv_path_LD=$lt_save_path_LD lt_cv_prog_gnu_ldcxx=$lt_cv_prog_gnu_ld lt_cv_prog_gnu_ld=$lt_save_with_gnu_ld fi # test "$_lt_caught_CXX_error" != yes AC_LANG_POP ])# _LT_LANG_CXX_CONFIG # _LT_FUNC_STRIPNAME_CNF # ---------------------- # func_stripname_cnf prefix suffix name # strip PREFIX and SUFFIX off of NAME. # PREFIX and SUFFIX must not contain globbing or regex special # characters, hashes, percent signs, but SUFFIX may contain a leading # dot (in which case that matches only a dot). # # This function is identical to the (non-XSI) version of func_stripname, # except this one can be used by m4 code that may be executed by configure, # rather than the libtool script. m4_defun([_LT_FUNC_STRIPNAME_CNF],[dnl AC_REQUIRE([_LT_DECL_SED]) AC_REQUIRE([_LT_PROG_ECHO_BACKSLASH]) func_stripname_cnf () { case ${2} in .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; esac } # func_stripname_cnf ])# _LT_FUNC_STRIPNAME_CNF # _LT_SYS_HIDDEN_LIBDEPS([TAGNAME]) # --------------------------------- # Figure out "hidden" library dependencies from verbose # compiler output when linking a shared library. # Parse the compiler output and extract the necessary # objects, libraries and library flags. m4_defun([_LT_SYS_HIDDEN_LIBDEPS], [m4_require([_LT_FILEUTILS_DEFAULTS])dnl AC_REQUIRE([_LT_FUNC_STRIPNAME_CNF])dnl # Dependencies to place before and after the object being linked: _LT_TAGVAR(predep_objects, $1)= _LT_TAGVAR(postdep_objects, $1)= _LT_TAGVAR(predeps, $1)= _LT_TAGVAR(postdeps, $1)= _LT_TAGVAR(compiler_lib_search_path, $1)= dnl we can't use the lt_simple_compile_test_code here, dnl because it contains code intended for an executable, dnl not a library. It's possible we should let each dnl tag define a new lt_????_link_test_code variable, dnl but it's only used here... m4_if([$1], [], [cat > conftest.$ac_ext <<_LT_EOF int a; void foo (void) { a = 0; } _LT_EOF ], [$1], [CXX], [cat > conftest.$ac_ext <<_LT_EOF class Foo { public: Foo (void) { a = 0; } private: int a; }; _LT_EOF ], [$1], [F77], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer*4 a a=0 return end _LT_EOF ], [$1], [FC], [cat > conftest.$ac_ext <<_LT_EOF subroutine foo implicit none integer a a=0 return end _LT_EOF ], [$1], [GCJ], [cat > conftest.$ac_ext <<_LT_EOF public class foo { private int a; public void bar (void) { a = 0; } }; _LT_EOF ], [$1], [GO], [cat > conftest.$ac_ext <<_LT_EOF package foo func foo() { } _LT_EOF ]) _lt_libdeps_save_CFLAGS=$CFLAGS case "$CC $CFLAGS " in #( *\ -flto*\ *) CFLAGS="$CFLAGS -fno-lto" ;; *\ -fwhopr*\ *) CFLAGS="$CFLAGS -fno-whopr" ;; *\ -fuse-linker-plugin*\ *) CFLAGS="$CFLAGS -fno-use-linker-plugin" ;; esac dnl Parse the compiler output and extract the necessary dnl objects, libraries and library flags. if AC_TRY_EVAL(ac_compile); then # Parse the compiler output and extract the necessary # objects, libraries and library flags. # Sentinel used to keep track of whether or not we are before # the conftest object file. pre_test_object_deps_done=no for p in `eval "$output_verbose_link_cmd"`; do case ${prev}${p} in -L* | -R* | -l*) # Some compilers place space between "-{L,R}" and the path. # Remove the space. if test $p = "-L" || test $p = "-R"; then prev=$p continue fi # Expand the sysroot to ease extracting the directories later. if test -z "$prev"; then case $p in -L*) func_stripname_cnf '-L' '' "$p"; prev=-L; p=$func_stripname_result ;; -R*) func_stripname_cnf '-R' '' "$p"; prev=-R; p=$func_stripname_result ;; -l*) func_stripname_cnf '-l' '' "$p"; prev=-l; p=$func_stripname_result ;; esac fi case $p in =*) func_stripname_cnf '=' '' "$p"; p=$lt_sysroot$func_stripname_result ;; esac if test "$pre_test_object_deps_done" = no; then case ${prev} in -L | -R) # Internal compiler library paths should come after those # provided the user. The postdeps already come after the # user supplied libs so there is no need to process them. if test -z "$_LT_TAGVAR(compiler_lib_search_path, $1)"; then _LT_TAGVAR(compiler_lib_search_path, $1)="${prev}${p}" else _LT_TAGVAR(compiler_lib_search_path, $1)="${_LT_TAGVAR(compiler_lib_search_path, $1)} ${prev}${p}" fi ;; # The "-l" case would never come before the object being # linked, so don't bother handling this case. esac else if test -z "$_LT_TAGVAR(postdeps, $1)"; then _LT_TAGVAR(postdeps, $1)="${prev}${p}" else _LT_TAGVAR(postdeps, $1)="${_LT_TAGVAR(postdeps, $1)} ${prev}${p}" fi fi prev= ;; *.lto.$objext) ;; # Ignore GCC LTO objects *.$objext) # This assumes that the test object file only shows up # once in the compiler output. if test "$p" = "conftest.$objext"; then pre_test_object_deps_done=yes continue fi if test "$pre_test_object_deps_done" = no; then if test -z "$_LT_TAGVAR(predep_objects, $1)"; then _LT_TAGVAR(predep_objects, $1)="$p" else _LT_TAGVAR(predep_objects, $1)="$_LT_TAGVAR(predep_objects, $1) $p" fi else if test -z "$_LT_TAGVAR(postdep_objects, $1)"; then _LT_TAGVAR(postdep_objects, $1)="$p" else _LT_TAGVAR(postdep_objects, $1)="$_LT_TAGVAR(postdep_objects, $1) $p" fi fi ;; *) ;; # Ignore the rest. esac done # Clean up. rm -f a.out a.exe else echo "libtool.m4: error: problem compiling $1 test program" fi $RM -f confest.$objext CFLAGS=$_lt_libdeps_save_CFLAGS # PORTME: override above test on systems where it is broken m4_if([$1], [CXX], [case $host_os in interix[[3-9]]*) # Interix 3.5 installs completely hosed .la files for C++, so rather than # hack all around it, let's just trust "g++" to DTRT. _LT_TAGVAR(predep_objects,$1)= _LT_TAGVAR(postdep_objects,$1)= _LT_TAGVAR(postdeps,$1)= ;; linux*) case `$CC -V 2>&1 | sed 5q` in *Sun\ C*) # Sun C++ 5.9 # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; solaris*) case $cc_basename in CC* | sunCC*) # The more standards-conforming stlport4 library is # incompatible with the Cstd library. Avoid specifying # it if it's in CXXFLAGS. Ignore libCrun as # -library=stlport4 depends on it. case " $CXX $CXXFLAGS " in *" -library=stlport4 "*) solaris_use_stlport4=yes ;; esac # Adding this requires a known-good setup of shared libraries for # Sun compiler versions before 5.6, else PIC objects from an old # archive will be linked into the output, leading to subtle bugs. if test "$solaris_use_stlport4" != yes; then _LT_TAGVAR(postdeps,$1)='-library=Cstd -library=Crun' fi ;; esac ;; esac ]) case " $_LT_TAGVAR(postdeps, $1) " in *" -lc "*) _LT_TAGVAR(archive_cmds_need_lc, $1)=no ;; esac _LT_TAGVAR(compiler_lib_search_dirs, $1)= if test -n "${_LT_TAGVAR(compiler_lib_search_path, $1)}"; then _LT_TAGVAR(compiler_lib_search_dirs, $1)=`echo " ${_LT_TAGVAR(compiler_lib_search_path, $1)}" | ${SED} -e 's! -L! !g' -e 's!^ !!'` fi _LT_TAGDECL([], [compiler_lib_search_dirs], [1], [The directories searched by this compiler when creating a shared library]) _LT_TAGDECL([], [predep_objects], [1], [Dependencies to place before and after the objects being linked to create a shared library]) _LT_TAGDECL([], [postdep_objects], [1]) _LT_TAGDECL([], [predeps], [1]) _LT_TAGDECL([], [postdeps], [1]) _LT_TAGDECL([], [compiler_lib_search_path], [1], [The library search path used internally by the compiler when linking a shared library]) ])# _LT_SYS_HIDDEN_LIBDEPS # _LT_LANG_F77_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for a Fortran 77 compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_F77_CONFIG], [AC_LANG_PUSH(Fortran 77) if test -z "$F77" || test "X$F77" = "Xno"; then _lt_disable_F77=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for f77 test sources. ac_ext=f # Object file extension for compiled f77 test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the F77 compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_F77" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${F77-"f77"} CFLAGS=$FFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) GCC=$G77 if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$G77" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC="$lt_save_CC" CFLAGS="$lt_save_CFLAGS" fi # test "$_lt_disable_F77" != yes AC_LANG_POP ])# _LT_LANG_F77_CONFIG # _LT_LANG_FC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for a Fortran compiler are # suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_FC_CONFIG], [AC_LANG_PUSH(Fortran) if test -z "$FC" || test "X$FC" = "Xno"; then _lt_disable_FC=yes fi _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(allow_undefined_flag, $1)= _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(archive_expsym_cmds, $1)= _LT_TAGVAR(export_dynamic_flag_spec, $1)= _LT_TAGVAR(hardcode_direct, $1)=no _LT_TAGVAR(hardcode_direct_absolute, $1)=no _LT_TAGVAR(hardcode_libdir_flag_spec, $1)= _LT_TAGVAR(hardcode_libdir_separator, $1)= _LT_TAGVAR(hardcode_minus_L, $1)=no _LT_TAGVAR(hardcode_automatic, $1)=no _LT_TAGVAR(inherit_rpath, $1)=no _LT_TAGVAR(module_cmds, $1)= _LT_TAGVAR(module_expsym_cmds, $1)= _LT_TAGVAR(link_all_deplibs, $1)=unknown _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds _LT_TAGVAR(no_undefined_flag, $1)= _LT_TAGVAR(whole_archive_flag_spec, $1)= _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=no # Source file extension for fc test sources. ac_ext=${ac_fc_srcext-f} # Object file extension for compiled fc test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # No sense in running all these tests if we already determined that # the FC compiler isn't working. Some variables (like enable_shared) # are currently assumed to apply to all compilers on this platform, # and will be corrupted by setting them based on a non-working compiler. if test "$_lt_disable_FC" != yes; then # Code to be used in simple compile tests lt_simple_compile_test_code="\ subroutine t return end " # Code to be used in simple link tests lt_simple_link_test_code="\ program t end " # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_GCC=$GCC lt_save_CFLAGS=$CFLAGS CC=${FC-"f95"} CFLAGS=$FCFLAGS compiler=$CC GCC=$ac_cv_fc_compiler_gnu _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) if test -n "$compiler"; then AC_MSG_CHECKING([if libtool supports shared libraries]) AC_MSG_RESULT([$can_build_shared]) AC_MSG_CHECKING([whether to build shared libraries]) test "$can_build_shared" = "no" && enable_shared=no # On AIX, shared libraries and static libraries use the same namespace, and # are all built from PIC. case $host_os in aix3*) test "$enable_shared" = yes && enable_static=no if test -n "$RANLIB"; then archive_cmds="$archive_cmds~\$RANLIB \$lib" postinstall_cmds='$RANLIB $lib' fi ;; aix[[4-9]]*) if test "$host_cpu" != ia64 && test "$aix_use_runtimelinking" = no ; then test "$enable_shared" = yes && enable_static=no fi ;; esac AC_MSG_RESULT([$enable_shared]) AC_MSG_CHECKING([whether to build static libraries]) # Make sure either enable_shared or enable_static is yes. test "$enable_shared" = yes || enable_static=yes AC_MSG_RESULT([$enable_static]) _LT_TAGVAR(GCC, $1)="$ac_cv_fc_compiler_gnu" _LT_TAGVAR(LD, $1)="$LD" ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... _LT_SYS_HIDDEN_LIBDEPS($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_SYS_DYNAMIC_LINKER($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi # test -n "$compiler" GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS fi # test "$_lt_disable_FC" != yes AC_LANG_POP ])# _LT_LANG_FC_CONFIG # _LT_LANG_GCJ_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Java Compiler compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GCJ_CONFIG], [AC_REQUIRE([LT_PROG_GCJ])dnl AC_LANG_SAVE # Source file extension for Java test sources. ac_ext=java # Object file extension for compiled Java test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="class foo {}" # Code to be used in simple link tests lt_simple_link_test_code='public class conftest { public static void main(String[[]] argv) {}; }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GCJ-"gcj"} CFLAGS=$GCJFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # GCJ did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GCJ_CONFIG # _LT_LANG_GO_CONFIG([TAG]) # -------------------------- # Ensure that the configuration variables for the GNU Go compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_GO_CONFIG], [AC_REQUIRE([LT_PROG_GO])dnl AC_LANG_SAVE # Source file extension for Go test sources. ac_ext=go # Object file extension for compiled Go test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code="package main; func main() { }" # Code to be used in simple link tests lt_simple_link_test_code='package main; func main() { }' # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC=$CC lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC=yes CC=${GOC-"gccgo"} CFLAGS=$GOFLAGS compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_TAGVAR(LD, $1)="$LD" _LT_CC_BASENAME([$compiler]) # Go did not exist at the time GCC didn't implicitly link libc in. _LT_TAGVAR(archive_cmds_need_lc, $1)=no _LT_TAGVAR(old_archive_cmds, $1)=$old_archive_cmds _LT_TAGVAR(reload_flag, $1)=$reload_flag _LT_TAGVAR(reload_cmds, $1)=$reload_cmds ## CAVEAT EMPTOR: ## There is no encapsulation within the following macros, do not change ## the running order or otherwise move them around unless you know exactly ## what you are doing... if test -n "$compiler"; then _LT_COMPILER_NO_RTTI($1) _LT_COMPILER_PIC($1) _LT_COMPILER_C_O($1) _LT_COMPILER_FILE_LOCKS($1) _LT_LINKER_SHLIBS($1) _LT_LINKER_HARDCODE_LIBPATH($1) _LT_CONFIG($1) fi AC_LANG_RESTORE GCC=$lt_save_GCC CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_GO_CONFIG # _LT_LANG_RC_CONFIG([TAG]) # ------------------------- # Ensure that the configuration variables for the Windows resource compiler # are suitably defined. These variables are subsequently used by _LT_CONFIG # to write the compiler configuration to `libtool'. m4_defun([_LT_LANG_RC_CONFIG], [AC_REQUIRE([LT_PROG_RC])dnl AC_LANG_SAVE # Source file extension for RC test sources. ac_ext=rc # Object file extension for compiled RC test sources. objext=o _LT_TAGVAR(objext, $1)=$objext # Code to be used in simple compile tests lt_simple_compile_test_code='sample MENU { MENUITEM "&Soup", 100, CHECKED }' # Code to be used in simple link tests lt_simple_link_test_code="$lt_simple_compile_test_code" # ltmain only uses $CC for tagged configurations so make sure $CC is set. _LT_TAG_COMPILER # save warnings/boilerplate of simple test code _LT_COMPILER_BOILERPLATE _LT_LINKER_BOILERPLATE # Allow CC to be a program name with arguments. lt_save_CC="$CC" lt_save_CFLAGS=$CFLAGS lt_save_GCC=$GCC GCC= CC=${RC-"windres"} CFLAGS= compiler=$CC _LT_TAGVAR(compiler, $1)=$CC _LT_CC_BASENAME([$compiler]) _LT_TAGVAR(lt_cv_prog_compiler_c_o, $1)=yes if test -n "$compiler"; then : _LT_CONFIG($1) fi GCC=$lt_save_GCC AC_LANG_RESTORE CC=$lt_save_CC CFLAGS=$lt_save_CFLAGS ])# _LT_LANG_RC_CONFIG # LT_PROG_GCJ # ----------- AC_DEFUN([LT_PROG_GCJ], [m4_ifdef([AC_PROG_GCJ], [AC_PROG_GCJ], [m4_ifdef([A][M_PROG_GCJ], [A][M_PROG_GCJ], [AC_CHECK_TOOL(GCJ, gcj,) test "x${GCJFLAGS+set}" = xset || GCJFLAGS="-g -O2" AC_SUBST(GCJFLAGS)])])[]dnl ]) # Old name: AU_ALIAS([LT_AC_PROG_GCJ], [LT_PROG_GCJ]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_GCJ], []) # LT_PROG_GO # ---------- AC_DEFUN([LT_PROG_GO], [AC_CHECK_TOOL(GOC, gccgo,) ]) # LT_PROG_RC # ---------- AC_DEFUN([LT_PROG_RC], [AC_CHECK_TOOL(RC, windres,) ]) # Old name: AU_ALIAS([LT_AC_PROG_RC], [LT_PROG_RC]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_RC], []) # _LT_DECL_EGREP # -------------- # If we don't have a new enough Autoconf to choose the best grep # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_EGREP], [AC_REQUIRE([AC_PROG_EGREP])dnl AC_REQUIRE([AC_PROG_FGREP])dnl test -z "$GREP" && GREP=grep _LT_DECL([], [GREP], [1], [A grep program that handles long lines]) _LT_DECL([], [EGREP], [1], [An ERE matcher]) _LT_DECL([], [FGREP], [1], [A literal string matcher]) dnl Non-bleeding-edge autoconf doesn't subst GREP, so do it here too AC_SUBST([GREP]) ]) # _LT_DECL_OBJDUMP # -------------- # If we don't have a new enough Autoconf to choose the best objdump # available, choose the one first in the user's PATH. m4_defun([_LT_DECL_OBJDUMP], [AC_CHECK_TOOL(OBJDUMP, objdump, false) test -z "$OBJDUMP" && OBJDUMP=objdump _LT_DECL([], [OBJDUMP], [1], [An object symbol dumper]) AC_SUBST([OBJDUMP]) ]) # _LT_DECL_DLLTOOL # ---------------- # Ensure DLLTOOL variable is set. m4_defun([_LT_DECL_DLLTOOL], [AC_CHECK_TOOL(DLLTOOL, dlltool, false) test -z "$DLLTOOL" && DLLTOOL=dlltool _LT_DECL([], [DLLTOOL], [1], [DLL creation program]) AC_SUBST([DLLTOOL]) ]) # _LT_DECL_SED # ------------ # Check for a fully-functional sed program, that truncates # as few characters as possible. Prefer GNU sed if found. m4_defun([_LT_DECL_SED], [AC_PROG_SED test -z "$SED" && SED=sed Xsed="$SED -e 1s/^X//" _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED m4_ifndef([AC_PROG_SED], [ ############################################################ # NOTE: This macro has been submitted for inclusion into # # GNU Autoconf as AC_PROG_SED. When it is available in # # a released version of Autoconf we should remove this # # macro and use it instead. # ############################################################ m4_defun([AC_PROG_SED], [AC_MSG_CHECKING([for a sed that does not truncate output]) AC_CACHE_VAL(lt_cv_path_SED, [# Loop through the user's path and test for sed and gsed. # Then use that list of sed's as ones to test for truncation. as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for lt_ac_prog in sed gsed; do for ac_exec_ext in '' $ac_executable_extensions; do if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" fi done done done IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris # along with /bin/sed that truncates output. for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do test ! -f $lt_ac_sed && continue cat /dev/null > conftest.in lt_ac_count=0 echo $ECHO_N "0123456789$ECHO_C" >conftest.in # Check for GNU sed and select it if it is found. if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then lt_cv_path_SED=$lt_ac_sed break fi while true; do cat conftest.in conftest.in >conftest.tmp mv conftest.tmp conftest.in cp conftest.in conftest.nl echo >>conftest.nl $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break cmp -s conftest.out conftest.nl || break # 10000 chars as input seems more than enough test $lt_ac_count -gt 10 && break lt_ac_count=`expr $lt_ac_count + 1` if test $lt_ac_count -gt $lt_ac_max; then lt_ac_max=$lt_ac_count lt_cv_path_SED=$lt_ac_sed fi done done ]) SED=$lt_cv_path_SED AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ])#AC_PROG_SED ])#m4_ifndef # Old name: AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) # _LT_CHECK_SHELL_FEATURES # ------------------------ # Find out whether the shell is Bourne or XSI compatible, # or has some other useful features. m4_defun([_LT_CHECK_SHELL_FEATURES], [AC_MSG_CHECKING([whether the shell understands some XSI constructs]) # Try some XSI features xsi_shell=no ( _lt_dummy="a/b/c" test "${_lt_dummy##*/},${_lt_dummy%/*},${_lt_dummy#??}"${_lt_dummy%"$_lt_dummy"}, \ = c,a/b,b/c, \ && eval 'test $(( 1 + 1 )) -eq 2 \ && test "${#_lt_dummy}" -eq 5' ) >/dev/null 2>&1 \ && xsi_shell=yes AC_MSG_RESULT([$xsi_shell]) _LT_CONFIG_LIBTOOL_INIT([xsi_shell='$xsi_shell']) AC_MSG_CHECKING([whether the shell understands "+="]) lt_shell_append=no ( foo=bar; set foo baz; eval "$[1]+=\$[2]" && test "$foo" = barbaz ) \ >/dev/null 2>&1 \ && lt_shell_append=yes AC_MSG_RESULT([$lt_shell_append]) _LT_CONFIG_LIBTOOL_INIT([lt_shell_append='$lt_shell_append']) if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then lt_unset=unset else lt_unset=false fi _LT_DECL([], [lt_unset], [0], [whether the shell understands "unset"])dnl # test EBCDIC or ASCII case `echo X|tr X '\101'` in A) # ASCII based system # \n is not interpreted correctly by Solaris 8 /usr/ucb/tr lt_SP2NL='tr \040 \012' lt_NL2SP='tr \015\012 \040\040' ;; *) # EBCDIC based system lt_SP2NL='tr \100 \n' lt_NL2SP='tr \r\n \100\100' ;; esac _LT_DECL([SP2NL], [lt_SP2NL], [1], [turn spaces into newlines])dnl _LT_DECL([NL2SP], [lt_NL2SP], [1], [turn newlines into spaces])dnl ])# _LT_CHECK_SHELL_FEATURES # _LT_PROG_FUNCTION_REPLACE (FUNCNAME, REPLACEMENT-BODY) # ------------------------------------------------------ # In `$cfgfile', look for function FUNCNAME delimited by `^FUNCNAME ()$' and # '^} FUNCNAME ', and replace its body with REPLACEMENT-BODY. m4_defun([_LT_PROG_FUNCTION_REPLACE], [dnl { sed -e '/^$1 ()$/,/^} # $1 /c\ $1 ()\ {\ m4_bpatsubsts([$2], [$], [\\], [^\([ ]\)], [\\\1]) } # Extended-shell $1 implementation' "$cfgfile" > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: ]) # _LT_PROG_REPLACE_SHELLFNS # ------------------------- # Replace existing portable implementations of several shell functions with # equivalent extended shell implementations where those features are available.. m4_defun([_LT_PROG_REPLACE_SHELLFNS], [if test x"$xsi_shell" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_dirname], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_basename], [dnl func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_dirname_and_basename], [dnl case ${1} in */*) func_dirname_result="${1%/*}${2}" ;; * ) func_dirname_result="${3}" ;; esac func_basename_result="${1##*/}"]) _LT_PROG_FUNCTION_REPLACE([func_stripname], [dnl # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are # positional parameters, so assign one to ordinary parameter first. func_stripname_result=${3} func_stripname_result=${func_stripname_result#"${1}"} func_stripname_result=${func_stripname_result%"${2}"}]) _LT_PROG_FUNCTION_REPLACE([func_split_long_opt], [dnl func_split_long_opt_name=${1%%=*} func_split_long_opt_arg=${1#*=}]) _LT_PROG_FUNCTION_REPLACE([func_split_short_opt], [dnl func_split_short_opt_arg=${1#??} func_split_short_opt_name=${1%"$func_split_short_opt_arg"}]) _LT_PROG_FUNCTION_REPLACE([func_lo2o], [dnl case ${1} in *.lo) func_lo2o_result=${1%.lo}.${objext} ;; *) func_lo2o_result=${1} ;; esac]) _LT_PROG_FUNCTION_REPLACE([func_xform], [ func_xform_result=${1%.*}.lo]) _LT_PROG_FUNCTION_REPLACE([func_arith], [ func_arith_result=$(( $[*] ))]) _LT_PROG_FUNCTION_REPLACE([func_len], [ func_len_result=${#1}]) fi if test x"$lt_shell_append" = xyes; then _LT_PROG_FUNCTION_REPLACE([func_append], [ eval "${1}+=\\${2}"]) _LT_PROG_FUNCTION_REPLACE([func_append_quoted], [dnl func_quote_for_eval "${2}" dnl m4 expansion turns \\\\ into \\, and then the shell eval turns that into \ eval "${1}+=\\\\ \\$func_quote_for_eval_result"]) # Save a `func_append' function call where possible by direct use of '+=' sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1+="%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: else # Save a `func_append' function call even when '+=' is not available sed -e 's%func_append \([[a-zA-Z_]]\{1,\}\) "%\1="$\1%g' $cfgfile > $cfgfile.tmp \ && mv -f "$cfgfile.tmp" "$cfgfile" \ || (rm -f "$cfgfile" && cp "$cfgfile.tmp" "$cfgfile" && rm -f "$cfgfile.tmp") test 0 -eq $? || _lt_function_replace_fail=: fi if test x"$_lt_function_replace_fail" = x":"; then AC_MSG_WARN([Unable to substitute extended shell functions in $ofile]) fi ]) # _LT_PATH_CONVERSION_FUNCTIONS # ----------------------------- # Determine which file name conversion functions should be used by # func_to_host_file (and, implicitly, by func_to_host_path). These are needed # for certain cross-compile configurations and native mingw. m4_defun([_LT_PATH_CONVERSION_FUNCTIONS], [AC_REQUIRE([AC_CANONICAL_HOST])dnl AC_REQUIRE([AC_CANONICAL_BUILD])dnl AC_MSG_CHECKING([how to convert $build file names to $host format]) AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_cygwin_to_w32 ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_w32 ;; esac ;; *-*-cygwin* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) lt_cv_to_host_file_cmd=func_convert_file_noop ;; * ) # otherwise, assume *nix lt_cv_to_host_file_cmd=func_convert_file_nix_to_cygwin ;; esac ;; * ) # unhandled hosts (and "normal" native builds) lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac ]) to_host_file_cmd=$lt_cv_to_host_file_cmd AC_MSG_RESULT([$lt_cv_to_host_file_cmd]) _LT_DECL([to_host_file_cmd], [lt_cv_to_host_file_cmd], [0], [convert $build file names to $host format])dnl AC_MSG_CHECKING([how to convert $build file names to toolchain format]) AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in *-*-mingw* ) case $build in *-*-mingw* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac ]) to_tool_file_cmd=$lt_cv_to_tool_file_cmd AC_MSG_RESULT([$lt_cv_to_tool_file_cmd]) _LT_DECL([to_tool_file_cmd], [lt_cv_to_tool_file_cmd], [0], [convert $build files to toolchain format])dnl ])# _LT_PATH_CONVERSION_FUNCTIONS softhsm-2.0.0/m4/acx_botan_gost.m40000664000175000017500000000225112533040716013674 00000000000000AC_DEFUN([ACX_BOTAN_GOST],[ AC_MSG_CHECKING(for Botan GOST support) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" AC_LANG_PUSH([C++]) AC_RUN_IFELSE([ AC_LANG_SOURCE([[ #include #include #include int main() { Botan::LibraryInitializer::initialize(); const std::string name("gost_256A"); const Botan::OID oid(Botan::OIDS::lookup(name)); const Botan::EC_Group ecg(oid); try { #if BOTAN_VERSION_MINOR == 11 const std::vector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #else const Botan::SecureVector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); #endif } catch(...) { return 1; } return 0; } ]]) ],[ AC_MSG_RESULT([Found GOST]) ],[ AC_MSG_RESULT([Cannot find GOST]) AC_MSG_ERROR([ Botan library has no valid GOST support. Please upgrade to a later version of Botan, above or including version 1.10.6 or 1.11.5. Alternatively disable GOST support in SoftHSM with --disable-gost ]) ],[]) AC_LANG_POP([C++]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/acx_openssl.m40000664000175000017500000000257012533040716013224 00000000000000AC_DEFUN([ACX_OPENSSL],[ AC_ARG_WITH(openssl, AC_HELP_STRING([--with-openssl=PATH],[Specify prefix of path of OpenSSL]), [ OPENSSL_PATH="$withval" ], [ OPENSSL_PATH="/usr/local" ]) AC_MSG_CHECKING(what are the OpenSSL includes) OPENSSL_INCLUDES="-I$OPENSSL_PATH/include" AC_MSG_RESULT($OPENSSL_INCLUDES) AC_MSG_CHECKING(what are the OpenSSL libs) OPENSSL_LIBS="-L$OPENSSL_PATH/lib -lcrypto" AC_MSG_RESULT($OPENSSL_LIBS) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $OPENSSL_INCLUDES" LIBS="$LIBS $OPENSSL_LIBS" AC_CHECK_HEADERS([openssl/ssl.h],,[AC_MSG_ERROR([Can't find OpenSSL headers])]) AC_CHECK_LIB(crypto, BN_init,,[AC_MSG_ERROR([Can't find OpenSSL library])]) AC_MSG_CHECKING([for OpenSSL version]) CHECK_OPENSSL_VERSION=m4_format(0x%02x%02x%02x000L, $1, $2, $3) AC_LANG_PUSH([C]) AC_RUN_IFELSE([ AC_LANG_SOURCE([[ #include #include int main() { #ifndef OPENSSL_VERSION_NUMBER return -1; #endif #if OPENSSL_VERSION_NUMBER >= $CHECK_OPENSSL_VERSION return 0; #else return 1; #endif } ]]) ],[ AC_MSG_RESULT([>= $1.$2.$3]) ],[ AC_MSG_RESULT([< $1.$2.$3]) AC_MSG_ERROR([OpenSSL library too old ($1.$2.$3 or later required)]) ],[]) AC_LANG_POP([C]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS AC_SUBST(OPENSSL_INCLUDES) AC_SUBST(OPENSSL_LIBS) ]) softhsm-2.0.0/m4/acx_openssl_rfc5649.m40000664000175000017500000000207712533040716014410 00000000000000AC_DEFUN([ACX_OPENSSL_EVPAESWRAP],[ AC_MSG_CHECKING(OpenSSL EVP interface for AES key wrapping) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$LIBS $CRYPTO_LIBS" AC_LANG_PUSH([C]) AC_LINK_IFELSE([ AC_LANG_SOURCE([[ #include int main() { EVP_aes_128_wrap(); return 1; } ]]) ],[ AC_MSG_RESULT([RFC 3394 is supported]) AC_DEFINE([HAVE_AES_KEY_WRAP], [1], [Define if advanced AES key wrap without pad is supported in EVP interface]) ],[ AC_MSG_RESULT([RFC 3394 is not supported]) ]) AC_MSG_CHECKING(OpenSSL EVP interface for AES key wrapping with pad) AC_LINK_IFELSE([ AC_LANG_SOURCE([[ #include int main() { EVP_aes_128_wrap_pad(); return 1; } ]]) ],[ AC_MSG_RESULT([RFC 5649 is supported]) AC_DEFINE([HAVE_AES_KEY_WRAP_PAD], [1], [Define if advanced AES key wrap with pad is supported in EVP interface]) ],[ AC_MSG_RESULT([RFC 5649 is not supported]) ]) AC_LANG_POP([C]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/acx_botan_gnump.m40000664000175000017500000000132512533040716014047 00000000000000AC_DEFUN([ACX_BOTAN_GNUMP],[ tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $BOTAN_INCLUDES" LIBS="$LIBS $BOTAN_LIBS" AC_LANG_PUSH([C++]) AC_LINK_IFELSE( [AC_LANG_PROGRAM( [#include ], [#ifndef BOTAN_HAS_ENGINE_GNU_MP #error "No GNU MP support"; #endif])], [AC_MSG_RESULT([checking for Botan GNU MP support... yes])], [AC_MSG_RESULT([checking for Botan GNU MP support... no]) AC_MSG_WARN([ ==================================================== Botan has not been built with GNU MP (--with-gnump). This will give negative impact on the performance. ====================================================])] ) AC_LANG_POP([C++]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/acx_crypto_backend.m40000664000175000017500000000630712533040716014532 00000000000000AC_DEFUN([ACX_CRYPTO_BACKEND],[ # First check if we want to support ECC and GOST AC_ARG_ENABLE(ecc, AC_HELP_STRING([--enable-ecc], [Enable support for ECC (default enabled)] ), [enable_ecc="${enableval}"], [enable_ecc="yes"] ) AC_MSG_CHECKING(for ECC support) if test "x${enable_ecc}" = "xyes"; then AC_MSG_RESULT(yes) AC_DEFINE_UNQUOTED( [WITH_ECC], [], [Compile with ECC support] ) else AC_MSG_RESULT(no) fi AM_CONDITIONAL([WITH_ECC], [test "x${enable_ecc}" = "xyes"]) AC_ARG_ENABLE(gost, AC_HELP_STRING([--enable-gost], [Enable support for GOST (default enabled)] ), [enable_gost="${enableval}"], [enable_gost="yes"] ) AC_MSG_CHECKING(for GOST support) if test "x${enable_gost}" = "xyes"; then AC_MSG_RESULT(yes) AC_DEFINE_UNQUOTED( [WITH_GOST], [], [Compile with GOST support] ) else AC_MSG_RESULT(no) fi AM_CONDITIONAL([WITH_GOST], [test "x${enable_gost}" = "xyes"]) # Second check for the FIPS 140-2 mode AC_ARG_ENABLE(fips, AC_HELP_STRING([--enable-fips], [Enable support for FIPS 140-2 mode (default disabled)] ), [enable_fips="${enableval}"], [enable_fips="no"] ) AC_MSG_CHECKING(for FIPS 140-2 mode) if test "x${enable_fips}" = "xyes"; then AC_MSG_RESULT(yes) AC_DEFINE_UNQUOTED( [WITH_FIPS], [], [Compile with FIPS 140-2 mode] ) else AC_MSG_RESULT(no) fi AM_CONDITIONAL([WITH_GOST], [test "x${enable_fips}" = "xyes"]) # Then check what crypto library we want to use AC_ARG_WITH(crypto-backend, AC_HELP_STRING([--with-crypto-backend], [Select crypto backend (openssl|botan)] ), [crypto_backend="${withval}"], [crypto_backend="openssl"] ) AC_MSG_CHECKING(for crypto backend) if test "x${crypto_backend}" = "xopenssl"; then AC_MSG_RESULT(OpenSSL) if test "x${enable_fips}" = "xyes"; then ACX_OPENSSL(1,0,1) else ACX_OPENSSL(1,0,0) fi CRYPTO_INCLUDES=$OPENSSL_INCLUDES CRYPTO_LIBS=$OPENSSL_LIBS if test "x${enable_ecc}" = "xyes"; then ACX_OPENSSL_ECC fi if test "x${enable_gost}" = "xyes"; then if test "x${enable_fips}" = "xyes"; then AC_MSG_ERROR([GOST is not FIPS approved]) fi ACX_OPENSSL_GOST fi if test "x${enable_fips}" = "xyes"; then ACX_OPENSSL_FIPS else ACX_OPENSSL_EVPAESWRAP fi AC_DEFINE_UNQUOTED( [WITH_OPENSSL], [], [Compile with OpenSSL support] ) elif test "x${crypto_backend}" = "xbotan"; then AC_MSG_RESULT(Botan) ACX_BOTAN(1,10,0) CRYPTO_INCLUDES=$BOTAN_INCLUDES CRYPTO_LIBS=$BOTAN_LIBS if test "x${enable_ecc}" = "xyes"; then ACX_BOTAN_ECC fi if test "x${enable_fips}" = "xyes"; then AC_MSG_ERROR([Botan does not support FIPS 140-2 mode]) fi if test "x${enable_gost}" = "xyes"; then ACX_BOTAN_GOST fi if test "x${BOTAN_VERSION_MINOR}" = "x10"; then ACX_BOTAN_GNUMP fi ACX_BOTAN_RFC5649 AC_DEFINE_UNQUOTED( [WITH_BOTAN], [], [Compile with Botan support] ) else AC_MSG_RESULT(Unknown) AC_MSG_ERROR([Crypto backend ${crypto_backend} not supported. Use openssl or botan.]) fi AC_SUBST(CRYPTO_INCLUDES) AC_SUBST(CRYPTO_LIBS) AM_CONDITIONAL([WITH_OPENSSL], [test "x${crypto_backend}" = "xopenssl"]) AM_CONDITIONAL([WITH_BOTAN], [test "x${crypto_backend}" = "xbotan"]) ]) softhsm-2.0.0/m4/acx_dlopen.m40000664000175000017500000000075012533040716013020 00000000000000AC_DEFUN([ACX_DLOPEN],[ AC_CHECK_FUNC(dlopen, [AC_DEFINE(HAVE_DLOPEN,1,[Define if you have dlopen])], [ AC_CHECK_LIB([dl],[dlopen], [AC_DEFINE(HAVE_DLOPEN,1,[Define if you have dlopen]) LIBS="$LIBS -ldl"], [AC_CHECK_FUNC(LoadLibrary, [if test $ac_cv_func_LoadLibrary = yes; then AC_DEFINE(HAVE_LOADLIBRARY, 1, [Whether LoadLibrary is available]) fi ], [AC_MSG_ERROR(No dynamic library loading support)] )] ) ]) ]) softhsm-2.0.0/m4/acx_openssl_fips.m40000664000175000017500000000231412533040716014241 00000000000000AC_DEFUN([ACX_OPENSSL_FIPS],[ AC_MSG_CHECKING(for OpenSSL FIPS capable library) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $CRYPTO_INCLUDES" LIBS="$CRYPTO_LIBS $LIBS" # check whether we can build an application which can # "reference the OpenSSL FIPS object module" AC_LANG_PUSH([C]) AC_RUN_IFELSE([ AC_LANG_SOURCE([[ #include int main() { return !FIPS_mode_set(1); } ]]) ],[ AC_MSG_RESULT([Found working FIPS_mode_set()]) ],[ AC_MSG_RESULT([FIPS_mode_set(1) failed]) AC_MSG_ERROR([OpenSSL library is not FIPS capable]) ],[]) AC_LANG_POP([C]) # build missing fips_premain_dso tool if test "x${FIPSLD_CC}" != "x"; then THERE="`echo $CC | sed -e 's|[[^/]]*$||'`".. if test "x${FIPSLIBDIR}" != "x"; then PREMAIN_C="${FIPSLIBDIR}/fips_premain.c" elif test -f "${THERE}/fips/fips_premain.c"; then PREMAIN_C="${THERE}/fips/fips_premain.c" elif test -f "${THERE}/lib/fips_premain.c"; then PREMAIN_C="${THERE}/lib/fips_premain.c" else AC_MSG_WARN([can't find fips_premain.c]) fi $FIPSLD_CC $CPPFLAGS -DFINGERPRINT_PREMAIN_DSO_LOAD \ -o src/lib/fips_premain_dso $PREMAIN_C $LIBS fi CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS ]) softhsm-2.0.0/m4/lt~obsolete.m40000644000175000017500000001375612552216615013272 00000000000000# lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # # Copyright (C) 2004, 2005, 2007, 2009 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004. # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # serial 5 lt~obsolete.m4 # These exist entirely to fool aclocal when bootstrapping libtool. # # In the past libtool.m4 has provided macros via AC_DEFUN (or AU_DEFUN) # which have later been changed to m4_define as they aren't part of the # exported API, or moved to Autoconf or Automake where they belong. # # The trouble is, aclocal is a bit thick. It'll see the old AC_DEFUN # in /usr/share/aclocal/libtool.m4 and remember it, then when it sees us # using a macro with the same name in our local m4/libtool.m4 it'll # pull the old libtool.m4 in (it doesn't see our shiny new m4_define # and doesn't know about Autoconf macros at all.) # # So we provide this file, which has a silly filename so it's always # included after everything else. This provides aclocal with the # AC_DEFUNs it wants, but when m4 processes it, it doesn't do anything # because those macros already exist, or will be overwritten later. # We use AC_DEFUN over AU_DEFUN for compatibility with aclocal-1.6. # # Anytime we withdraw an AC_DEFUN or AU_DEFUN, remember to add it here. # Yes, that means every name once taken will need to remain here until # we give up compatibility with versions before 1.7, at which point # we need to keep only those names which we still refer to. # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOBSOLETE_VERSION], [m4_if([1])]) m4_ifndef([AC_LIBTOOL_LINKER_OPTION], [AC_DEFUN([AC_LIBTOOL_LINKER_OPTION])]) m4_ifndef([AC_PROG_EGREP], [AC_DEFUN([AC_PROG_EGREP])]) m4_ifndef([_LT_AC_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_AC_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_AC_SHELL_INIT], [AC_DEFUN([_LT_AC_SHELL_INIT])]) m4_ifndef([_LT_AC_SYS_LIBPATH_AIX], [AC_DEFUN([_LT_AC_SYS_LIBPATH_AIX])]) m4_ifndef([_LT_PROG_LTMAIN], [AC_DEFUN([_LT_PROG_LTMAIN])]) m4_ifndef([_LT_AC_TAGVAR], [AC_DEFUN([_LT_AC_TAGVAR])]) m4_ifndef([AC_LTDL_ENABLE_INSTALL], [AC_DEFUN([AC_LTDL_ENABLE_INSTALL])]) m4_ifndef([AC_LTDL_PREOPEN], [AC_DEFUN([AC_LTDL_PREOPEN])]) m4_ifndef([_LT_AC_SYS_COMPILER], [AC_DEFUN([_LT_AC_SYS_COMPILER])]) m4_ifndef([_LT_AC_LOCK], [AC_DEFUN([_LT_AC_LOCK])]) m4_ifndef([AC_LIBTOOL_SYS_OLD_ARCHIVE], [AC_DEFUN([AC_LIBTOOL_SYS_OLD_ARCHIVE])]) m4_ifndef([_LT_AC_TRY_DLOPEN_SELF], [AC_DEFUN([_LT_AC_TRY_DLOPEN_SELF])]) m4_ifndef([AC_LIBTOOL_PROG_CC_C_O], [AC_DEFUN([AC_LIBTOOL_PROG_CC_C_O])]) m4_ifndef([AC_LIBTOOL_SYS_HARD_LINK_LOCKS], [AC_DEFUN([AC_LIBTOOL_SYS_HARD_LINK_LOCKS])]) m4_ifndef([AC_LIBTOOL_OBJDIR], [AC_DEFUN([AC_LIBTOOL_OBJDIR])]) m4_ifndef([AC_LTDL_OBJDIR], [AC_DEFUN([AC_LTDL_OBJDIR])]) m4_ifndef([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH], [AC_DEFUN([AC_LIBTOOL_PROG_LD_HARDCODE_LIBPATH])]) m4_ifndef([AC_LIBTOOL_SYS_LIB_STRIP], [AC_DEFUN([AC_LIBTOOL_SYS_LIB_STRIP])]) m4_ifndef([AC_PATH_MAGIC], [AC_DEFUN([AC_PATH_MAGIC])]) m4_ifndef([AC_PROG_LD_GNU], [AC_DEFUN([AC_PROG_LD_GNU])]) m4_ifndef([AC_PROG_LD_RELOAD_FLAG], [AC_DEFUN([AC_PROG_LD_RELOAD_FLAG])]) m4_ifndef([AC_DEPLIBS_CHECK_METHOD], [AC_DEFUN([AC_DEPLIBS_CHECK_METHOD])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_NO_RTTI], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_NO_RTTI])]) m4_ifndef([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE], [AC_DEFUN([AC_LIBTOOL_SYS_GLOBAL_SYMBOL_PIPE])]) m4_ifndef([AC_LIBTOOL_PROG_COMPILER_PIC], [AC_DEFUN([AC_LIBTOOL_PROG_COMPILER_PIC])]) m4_ifndef([AC_LIBTOOL_PROG_LD_SHLIBS], [AC_DEFUN([AC_LIBTOOL_PROG_LD_SHLIBS])]) m4_ifndef([AC_LIBTOOL_POSTDEP_PREDEP], [AC_DEFUN([AC_LIBTOOL_POSTDEP_PREDEP])]) m4_ifndef([LT_AC_PROG_EGREP], [AC_DEFUN([LT_AC_PROG_EGREP])]) m4_ifndef([LT_AC_PROG_SED], [AC_DEFUN([LT_AC_PROG_SED])]) m4_ifndef([_LT_CC_BASENAME], [AC_DEFUN([_LT_CC_BASENAME])]) m4_ifndef([_LT_COMPILER_BOILERPLATE], [AC_DEFUN([_LT_COMPILER_BOILERPLATE])]) m4_ifndef([_LT_LINKER_BOILERPLATE], [AC_DEFUN([_LT_LINKER_BOILERPLATE])]) m4_ifndef([_AC_PROG_LIBTOOL], [AC_DEFUN([_AC_PROG_LIBTOOL])]) m4_ifndef([AC_LIBTOOL_SETUP], [AC_DEFUN([AC_LIBTOOL_SETUP])]) m4_ifndef([_LT_AC_CHECK_DLFCN], [AC_DEFUN([_LT_AC_CHECK_DLFCN])]) m4_ifndef([AC_LIBTOOL_SYS_DYNAMIC_LINKER], [AC_DEFUN([AC_LIBTOOL_SYS_DYNAMIC_LINKER])]) m4_ifndef([_LT_AC_TAGCONFIG], [AC_DEFUN([_LT_AC_TAGCONFIG])]) m4_ifndef([AC_DISABLE_FAST_INSTALL], [AC_DEFUN([AC_DISABLE_FAST_INSTALL])]) m4_ifndef([_LT_AC_LANG_CXX], [AC_DEFUN([_LT_AC_LANG_CXX])]) m4_ifndef([_LT_AC_LANG_F77], [AC_DEFUN([_LT_AC_LANG_F77])]) m4_ifndef([_LT_AC_LANG_GCJ], [AC_DEFUN([_LT_AC_LANG_GCJ])]) m4_ifndef([AC_LIBTOOL_LANG_C_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_C_CONFIG])]) m4_ifndef([_LT_AC_LANG_C_CONFIG], [AC_DEFUN([_LT_AC_LANG_C_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_CXX_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_CXX_CONFIG])]) m4_ifndef([_LT_AC_LANG_CXX_CONFIG], [AC_DEFUN([_LT_AC_LANG_CXX_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_F77_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_F77_CONFIG])]) m4_ifndef([_LT_AC_LANG_F77_CONFIG], [AC_DEFUN([_LT_AC_LANG_F77_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_GCJ_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_GCJ_CONFIG])]) m4_ifndef([_LT_AC_LANG_GCJ_CONFIG], [AC_DEFUN([_LT_AC_LANG_GCJ_CONFIG])]) m4_ifndef([AC_LIBTOOL_LANG_RC_CONFIG], [AC_DEFUN([AC_LIBTOOL_LANG_RC_CONFIG])]) m4_ifndef([_LT_AC_LANG_RC_CONFIG], [AC_DEFUN([_LT_AC_LANG_RC_CONFIG])]) m4_ifndef([AC_LIBTOOL_CONFIG], [AC_DEFUN([AC_LIBTOOL_CONFIG])]) m4_ifndef([_LT_AC_FILE_LTDLL_C], [AC_DEFUN([_LT_AC_FILE_LTDLL_C])]) m4_ifndef([_LT_REQUIRED_DARWIN_CHECKS], [AC_DEFUN([_LT_REQUIRED_DARWIN_CHECKS])]) m4_ifndef([_LT_AC_PROG_CXXCPP], [AC_DEFUN([_LT_AC_PROG_CXXCPP])]) m4_ifndef([_LT_PREPARE_SED_QUOTE_VARS], [AC_DEFUN([_LT_PREPARE_SED_QUOTE_VARS])]) m4_ifndef([_LT_PROG_ECHO_BACKSLASH], [AC_DEFUN([_LT_PROG_ECHO_BACKSLASH])]) m4_ifndef([_LT_PROG_F77], [AC_DEFUN([_LT_PROG_F77])]) m4_ifndef([_LT_PROG_FC], [AC_DEFUN([_LT_PROG_FC])]) m4_ifndef([_LT_PROG_CXX], [AC_DEFUN([_LT_PROG_CXX])]) softhsm-2.0.0/m4/acx_visibility.m40000664000175000017500000000072112533040716013724 00000000000000AC_DEFUN([ACX_VISIBILITY],[ AC_ARG_ENABLE( [visibility], [AS_HELP_STRING([--disable-visibility],[disable hidden visibilty link mode @<:@enabled@:>@])], [enable_visibility="${enableval}"], [enable_visibility="yes"] ) if test "${enable_visibility}" = "yes"; then CFLAGS="${CFLAGS} -fvisibility=hidden" CXXFLAGS="${CXXFLAGS} -fvisibility=hidden" AC_DEFINE(CRYPTOKI_VISIBILITY, 1, [Define to default visibility of PKCS@%:@11 entry points]) fi ]) softhsm-2.0.0/m4/ltversion.m40000644000175000017500000000126212552216615012732 00000000000000# ltversion.m4 -- version numbers -*- Autoconf -*- # # Copyright (C) 2004 Free Software Foundation, Inc. # Written by Scott James Remnant, 2004 # # This file is free software; the Free Software Foundation gives # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. # @configure_input@ # serial 3337 ltversion.m4 # This file is part of GNU Libtool m4_define([LT_PACKAGE_VERSION], [2.4.2]) m4_define([LT_PACKAGE_REVISION], [1.3337]) AC_DEFUN([LTVERSION_VERSION], [macro_version='2.4.2' macro_revision='1.3337' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) softhsm-2.0.0/m4/acx_sqlite3.m40000664000175000017500000000201512533040716013117 00000000000000AC_DEFUN([ACX_SQLITE3],[ AC_ARG_WITH(sqlite3, AC_HELP_STRING([--with-sqlite3=PATH],[Specify prefix of path of SQLite3]), [ SQLITE3_PATH="$withval" AC_PATH_PROGS(SQLITE3, sqlite3, sqlite3, $withval/bin) ],[ SQLITE3_PATH="/usr/local" AC_PATH_PROGS(SQLITE3, sqlite3, sqlite3, $PATH) ]) if ! test -x "$SQLITE3"; then AC_MSG_ERROR([sqlite3 command not found]) fi AC_MSG_CHECKING(what are the SQLite3 includes) SQLITE3_INCLUDES="-I$SQLITE3_PATH/include" AC_MSG_RESULT($SQLITE3_INCLUDES) AC_MSG_CHECKING(what are the SQLite3 libs) SQLITE3_LIBS="-L$SQLITE3_PATH/lib -lsqlite3" AC_MSG_RESULT($SQLITE3_LIBS) tmp_CPPFLAGS=$CPPFLAGS tmp_LIBS=$LIBS CPPFLAGS="$CPPFLAGS $SQLITE3_INCLUDES" LIBS="$LIBS $SQLITE3_LIBS" AC_CHECK_HEADERS(sqlite3.h,,[AC_MSG_ERROR([Can't find SQLite3 headers])]) AC_CHECK_LIB(sqlite3, sqlite3_prepare_v2, [], [AC_MSG_ERROR([Missing SQLite3 library v3.4.2 or greater])]) CPPFLAGS=$tmp_CPPFLAGS LIBS=$tmp_LIBS AC_SUBST(SQLITE3_INCLUDES) AC_SUBST(SQLITE3_LIBS) ]) softhsm-2.0.0/m4/acx_pedantic.m40000664000175000017500000000043212533040716013323 00000000000000AC_DEFUN([ACX_PEDANTIC],[ AC_ARG_ENABLE( [pedantic], [AS_HELP_STRING([--enable-pedantic],[enable pedantic compile mode @<:@enabled@:>@])], , [enable_pedantic="yes"] ) if test "${enable_pedantic}" = "yes"; then enable_strict="yes"; CFLAGS="${CFLAGS} -pedantic" fi ]) softhsm-2.0.0/m4/acx_64bit.m40000664000175000017500000000157112533040716012471 00000000000000AC_DEFUN([ACX_64BIT],[ AC_ARG_ENABLE( [64bit], [AS_HELP_STRING([--enable-64bit],[enable 64-bit compiling @<:@disabled@:>@])], [enable_64bit="${enableval}"], [enable_64bit="no"]) if test "x$enable_64bit" = "xyes" then AC_MSG_CHECKING(if we can compile in 64-bit mode) tmp_CFLAGS=$CFLAGS CFLAGS="-m64" AC_RUN_IFELSE( [ AC_LANG_PROGRAM([],[return sizeof(void*) == 8 ? 0 : 1;]) ], [ AC_MSG_RESULT(yes) CXXFLAGS="-m64 $CXXFLAGS" LDFLAGS="-m64 $LDFLAGS" CFLAGS="-m64 $tmp_CFLAGS" ],[ AC_MSG_RESULT(no) AC_MSG_ERROR([Don't know how to compile in 64-bit mode.]) CFLAGS=$tmp_CFLAGS ] ) fi ]) softhsm-2.0.0/m4/acx_yield.m40000664000175000017500000000050712533040716012645 00000000000000AC_DEFUN([ACX_YIELD],[ YIELD_LIB= # Solaris has sched_yield in librt, not in libpthread or libc. # Solaris 2.5.1, 2.6 has sched_yield in libposix4, not librt. AC_CHECK_LIB(rt, sched_yield, [YIELD_LIB=-lrt], [AC_CHECK_LIB(posix4, sched_yield, [YIELD_LIB=-lposix4])]) AC_SUBST([YIELD_LIB]) AC_CHECK_HEADER([sched.h]) ]) softhsm-2.0.0/win32/0000775000175000017500000000000012552220146011140 500000000000000softhsm-2.0.0/win32/sessionmgrtest/0000775000175000017500000000000012552220146014231 500000000000000softhsm-2.0.0/win32/sessionmgrtest/sessionmgrtest.vcxproj.user0000664000175000017500000000021712533040716021636 00000000000000 softhsm-2.0.0/win32/sessionmgrtest/sessionmgrtest.vcxproj.filters0000664000175000017500000000261112533040716022330 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Source Files Source Files softhsm-2.0.0/win32/sessionmgrtest/sessionmgrtest.vcxproj.in0000664000175000017500000001260512533040716021272 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {45E2ABF6-91A7-4AA5-A82B-0C8E54BCCCB9} Win32Proj sessionmgrtest Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\session_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\data_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\object_store;..\..\src\lib\win32;@CUINCPATH@;@DEBUGINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\session_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\data_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\object_store;..\..\src\lib\win32;@CUINCPATH@;@INCLUDEPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;%(AdditionalDependencies) softhsm-2.0.0/win32/util/0000775000175000017500000000000012552220146012115 500000000000000softhsm-2.0.0/win32/util/util.vcxproj.in0000664000175000017500000001376312533040716015050 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {05901466-4184-47C8-9D6C-3BB99BBF5378} Win32Proj util Application true Unicode Application false true Unicode true softhsm2-util false softhsm2-util Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\bin\common;..\..\src\bin\win32;..\..\src\lib\cryptoki_compat;@DEBUGINCPATH@;%(AdditionalIncludeDirectories) Console true @DEBUGLIBPATH@;%(AdditionalLibraryDirectories) @LIBNAME@;%(AdditionalDependencies) if exist @DEBUGDLLPATH@ copy @DEBUGDLLPATH@ ..\@PLATFORMDIR@$(Configuration) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\bin\common;..\..\src\bin\win32;..\..\src\lib\cryptoki_compat;@INCLUDEPATH@;%(AdditionalIncludeDirectories) Console true true true @LIBPATH@;%(AdditionalLibraryDirectories) @LIBNAME@;%(AdditionalDependencies) if exist @DLLPATH@ copy @DLLPATH@ ..\@PLATFORMDIR@$(Configuration) @IF BOTAN @END BOTAN @IF OPENSSL @END OPENSSL @IF BOTAN @END BOTAN @IF OPENSSL @END OPENSSL softhsm-2.0.0/win32/util/util.vcxproj.filters.in0000664000175000017500000000667312533040716016521 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {21eda3a1-8da0-4a99-967c-f218e4eecd08} h;hpp;hxx;hm;inl;inc;xsd {fd946626-7e24-4f78-834b-a4c0ac6dc2f5} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {f3a7acce-323d-4465-95bf-a326189dcdd5} h;hpp;hxx;hm;inl;inc;xsd {2b77905a-99da-49cf-9cac-aa72e7e3182b} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx Common Header Files Common Header Files Header Files @IF BOTAN Header Files @END BOTAN @IF OPENSSL Header Files @END OPENSSL Header Files Win32 Header Files Common Source Files Common Source Files Source Files @IF BOTAN Source Files @END BOTAN @IF OPENSSL Source Files @END OPENSSL Win32 Source Files Win32 Source Files softhsm-2.0.0/win32/util/util.vcxproj.user0000664000175000017500000000021712533040716015406 00000000000000 softhsm-2.0.0/win32/slotmgrtest/0000775000175000017500000000000012552220146013527 500000000000000softhsm-2.0.0/win32/slotmgrtest/slotmgrtest.vcxproj.in0000664000175000017500000001255112533040716020066 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {F62E31E5-0F8D-4B70-8F26-44AFA1A9E645} Win32Proj slotmgrtest Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\slot_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\data_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\slot_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\data_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) softhsm-2.0.0/win32/slotmgrtest/slotmgrtest.vcxproj.user0000664000175000017500000000021712533040716020432 00000000000000 softhsm-2.0.0/win32/slotmgrtest/slotmgrtest.vcxproj.filters0000664000175000017500000000256712533040716021136 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Source Files Source Files softhsm-2.0.0/win32/objstoretest/0000775000175000017500000000000012552220146013667 500000000000000softhsm-2.0.0/win32/objstoretest/objstoretest.vcxproj.filters0000664000175000017500000000630012533040716021423 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files softhsm-2.0.0/win32/objstoretest/objstoretest.vcxproj.in0000664000175000017500000001471512533040716020372 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {44F77533-A4A1-4175-8C4C-07106B3F9C08} Win32Proj objstoretest Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\object_store;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\data_mgr;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\object_store;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\data_mgr;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) softhsm-2.0.0/win32/objstoretest/objstoretest.vcxproj.user0000664000175000017500000000021712533040716020732 00000000000000 softhsm-2.0.0/win32/cryptotest/0000775000175000017500000000000012552220146013360 500000000000000softhsm-2.0.0/win32/cryptotest/cryptotest.vcxproj.filters0000664000175000017500000001077312533040716020616 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files softhsm-2.0.0/win32/cryptotest/cryptotest.vcxproj.user0000664000175000017500000000021712533040716020114 00000000000000 softhsm-2.0.0/win32/cryptotest/cryptotest.vcxproj.in0000664000175000017500000001616312533040716017553 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {07E03E0B-C525-4A72-88C6-2238896A4D8C} Win32Proj cryptotest Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\crypto;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\data_mgr;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\win32;@CUINCPATH@;@DEBUGINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\crypto;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\data_mgr;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\win32;@CUINCPATH@;@INCLUDEPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) softhsm-2.0.0/win32/config.h.in0000664000175000017500000000706612533040716013116 00000000000000/* config.h for WIN32 */ /* The default log level */ #define DEFAULT_LOG_LEVEL "INFO" /* Default storage backend for token objects */ #define DEFAULT_OBJECTSTORE_BACKEND "file" /* The default PKCS#11 library */ #define DEFAULT_PKCS11_LIB "softhsm2.dll" /* The default location of softhsm2.conf */ #define DEFAULT_SOFTHSM2_CONF "softhsm2.conf" /* The default location of the token directory */ #define DEFAULT_TOKENDIR "tokens" /* Define if advanced AES key wrap without pad is supported */ @IF RFC3394 #define HAVE_AES_KEY_WRAP 1 @ELSE RFC3394 #undef HAVE_AES_KEY_WRAP @END RFC3394 /* Define if advanced AES key wrap with pad is supported */ @IF RFC5649 #define HAVE_AES_KEY_WRAP_PAD 1 @ELSE RFC5649 #undef HAVE_AES_KEY_WRAP_PAD @END RFC5649 /* Whether LoadLibrary is available */ #define HAVE_LOADLIBRARY 1 /* Define to 1 if you have the header file. */ #undef HAVE_SQLITE3_H /* Define to 1 if you have the header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Maximum PIN length */ #define MAX_PIN_LEN 255 /* Minimum PIN length */ #define MIN_PIN_LEN 4 /* Name of package */ #define PACKAGE "softhsm" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "" /* Define to the full name of this package. */ #define PACKAGE_NAME "SoftHSM" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "SoftHSM 2.0.0b2" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "softhsm" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "2.0.0b2" /* Non-paged memory for secure storage */ @IF NONPAGE #define SENSITIVE_NON_PAGE 1 @ELSE NONPAGE #undef SENSITIVE_NON_PAGE @END NONPAGE /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Version number of package */ #define VERSION "2.0.0b2" /* SoftHSM major version number via PKCS#11 */ #define VERSION_MAJOR 2 /* SoftHSM minor version number via PKCS#11 */ #define VERSION_MINOR 0 /* Compile with Botan support */ @IF BOTAN #define WITH_BOTAN 1 @ELSE BOTAN #undef WITH_BOTAN @END BOTAN /* Compile with ECC support */ @IF ECC #define WITH_ECC 1 @ELSE ECC #undef WITH_ECC @END ECC /* Compile with GOST support */ @IF GOST #define WITH_GOST 1 @ELSE GOST #undef WITH_GOST @END GOST /* Compile with OpenSSL support */ @IF OPENSSL #define WITH_OPENSSL 1 @ELSE OPENSSL #undef WITH_OPENSSL @END OPENSSL /* Define to 1 if you have getpassphrase(). */ #define HAVE_GETPASSPHRASE /* Addition things */ char *getpassphrase(const char *prompt); int setenv(const char *name, const char *value, int overwrite); /* At least Vista */ #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0600 #endif #if _MSC_VER < 1900 #define snprintf _snprintf #endif #define strcasecmp _stricmp #define strncasecmp _strnicmp /* Prevent inclusion of winsock.h in windows.h */ #define WIN32_LEAN_AND_MEAN 1 #include /* avoid collision from min and max macros */ #undef min #undef max @IF BOTAN /* For Botan */ #pragma warning(disable: 4275 4267) @END BOTAN /* Temporary for debug */ #undef DEBUG_LOG_STDERR // #define DEBUG_LOG_STDERR 1 /* To avoid unsafe warnings (off) */ // #pragma warning(disable: 4996) softhsm-2.0.0/win32/p11test/0000775000175000017500000000000012552220146012441 500000000000000softhsm-2.0.0/win32/p11test/p11test.vcxproj.user0000664000175000017500000000021712533040716016256 00000000000000 softhsm-2.0.0/win32/p11test/p11test.vcxproj.in0000664000175000017500000002100312533040716015702 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {7C5EE7FC-B5FC-47BF-8164-A452FE689472} Win32Proj p11test Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\cryptoki_compat;..\..\src\lib\common;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\data_mgr;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\handle_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) copy ..\..\src\lib\test\softhsm2.conf.win32 ..\..\softhsm2.conf mkdir ..\..\tokens 2> nul copy ..\..\src\lib\test\tokens\dummy.in ..\..\tokens\dummy copy ..\..\src\lib\test\softhsm2.conf.win32 ..\..\win32\p11test\softhsm2.conf mkdir ..\..\win32\p11test\tokens 2> nul copy ..\..\src\lib\test\tokens\dummy.in ..\..\win32\p11test\tokens\dummy Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\cryptoki_compat;..\..\src\lib\common;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\data_mgr;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\handle_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) copy ..\..\src\lib\test\softhsm2.conf.win32 ..\..\softhsm2.conf mkdir ..\..\tokens 2> nul copy ..\..\src\lib\test\tokens\dummy.in ..\..\tokens\dummy copy ..\..\src\lib\test\softhsm2.conf.win32 ..\..\win32\p11test\softhsm2.conf mkdir ..\..\win32\p11test\tokens 2> nul copy ..\..\src\lib\test\tokens\dummy.in ..\..\win32\p11test\tokens\dummy softhsm-2.0.0/win32/p11test/p11test.vcxproj.filters0000664000175000017500000001474412533040716016762 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {8440d7eb-5530-4f5e-a355-a43435742c60} h;hpp;hxx;hm;inl;inc;xsd {3c33d54e-4bd1-43e0-bcc7-0d6adcfd5dc7} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {ff435d2e-c67a-4f47-9731-28d88617e559} h;hpp;hxx;hm;inl;inc;xsd {5df8b0a3-ecc7-4876-aea2-8421c0846535} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Other Header Files Lib Header Files Lib Header Files Other Header Files Lib Header Files Lib Header Files Lib Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Other Source Files Other Source Files Lib Source Files Lib Source Files Lib Source Files Lib Source Files Lib Source Files Source Files softhsm-2.0.0/win32/softhsm2.sln.in0000664000175000017500000001744112533040716013761 00000000000000 Microsoft Visual Studio Solution File, Format Version 11.00 # Visual C++ Express 2010 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "softhsm2", "softhsm2\softhsm2.vcxproj", "{801F5AB2-7A62-4085-B129-D15E2D717219}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "convarch", "convarch\convarch.vcxproj", "{F64541B6-FFBF-4368-B93A-A5CA8ADAD795}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "keyconv", "keyconv\keyconv.vcxproj", "{9B003E52-F02A-47EA-9942-2D9AE8738161}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "util", "util\util.vcxproj", "{05901466-4184-47C8-9D6C-3BB99BBF5378}" ProjectSection(ProjectDependencies) = postProject {801F5AB2-7A62-4085-B129-D15E2D717219} = {801F5AB2-7A62-4085-B129-D15E2D717219} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "dump", "dump\dump.vcxproj", "{F60ACB12-7D05-4A89-B2D1-DD16E1F3566B}" EndProject @IF TESTS Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "p11test", "p11test\p11test.vcxproj", "{7C5EE7FC-B5FC-47BF-8164-A452FE689472}" ProjectSection(ProjectDependencies) = postProject {801F5AB2-7A62-4085-B129-D15E2D717219} = {801F5AB2-7A62-4085-B129-D15E2D717219} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cryptotest", "cryptotest\cryptotest.vcxproj", "{07E03E0B-C525-4A72-88C6-2238896A4D8C}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datamgrtest", "datamgrtest\datamgrtest.vcxproj", "{E20315B5-B49E-46D7-B7EC-1A439F347C95}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "handlemgrtest", "handlemgrtest\handlemgrtest.vcxproj", "{014B1E10-EC68-4BEC-B992-F92CA2B6816F}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "objstoretest", "objstoretest\objstoretest.vcxproj", "{44F77533-A4A1-4175-8C4C-07106B3F9C08}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sessionmgrtest", "sessionmgrtest\sessionmgrtest.vcxproj", "{45E2ABF6-91A7-4AA5-A82B-0C8E54BCCCB9}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "slotmgrtest", "slotmgrtest\slotmgrtest.vcxproj", "{F62E31E5-0F8D-4B70-8F26-44AFA1A9E645}" ProjectSection(ProjectDependencies) = postProject {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} = {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} EndProjectSection EndProject @END TESTS Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|@PLATFORM@ = Debug|@PLATFORM@ Release|@PLATFORM@ = Release|@PLATFORM@ EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {801F5AB2-7A62-4085-B129-D15E2D717219}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {801F5AB2-7A62-4085-B129-D15E2D717219}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {801F5AB2-7A62-4085-B129-D15E2D717219}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {801F5AB2-7A62-4085-B129-D15E2D717219}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {F64541B6-FFBF-4368-B93A-A5CA8ADAD795}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {F64541B6-FFBF-4368-B93A-A5CA8ADAD795}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {F64541B6-FFBF-4368-B93A-A5CA8ADAD795}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {F64541B6-FFBF-4368-B93A-A5CA8ADAD795}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {9B003E52-F02A-47EA-9942-2D9AE8738161}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {9B003E52-F02A-47EA-9942-2D9AE8738161}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {9B003E52-F02A-47EA-9942-2D9AE8738161}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {9B003E52-F02A-47EA-9942-2D9AE8738161}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {05901466-4184-47C8-9D6C-3BB99BBF5378}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {05901466-4184-47C8-9D6C-3BB99BBF5378}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {05901466-4184-47C8-9D6C-3BB99BBF5378}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {05901466-4184-47C8-9D6C-3BB99BBF5378}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {F60ACB12-7D05-4A89-B2D1-DD16E1F3566B}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {F60ACB12-7D05-4A89-B2D1-DD16E1F3566B}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {F60ACB12-7D05-4A89-B2D1-DD16E1F3566B}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {F60ACB12-7D05-4A89-B2D1-DD16E1F3566B}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ @IF TESTS {7C5EE7FC-B5FC-47BF-8164-A452FE689472}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {7C5EE7FC-B5FC-47BF-8164-A452FE689472}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {7C5EE7FC-B5FC-47BF-8164-A452FE689472}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {7C5EE7FC-B5FC-47BF-8164-A452FE689472}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {07E03E0B-C525-4A72-88C6-2238896A4D8C}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {07E03E0B-C525-4A72-88C6-2238896A4D8C}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {07E03E0B-C525-4A72-88C6-2238896A4D8C}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {07E03E0B-C525-4A72-88C6-2238896A4D8C}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {E20315B5-B49E-46D7-B7EC-1A439F347C95}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {E20315B5-B49E-46D7-B7EC-1A439F347C95}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {E20315B5-B49E-46D7-B7EC-1A439F347C95}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {E20315B5-B49E-46D7-B7EC-1A439F347C95}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {014B1E10-EC68-4BEC-B992-F92CA2B6816F}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {014B1E10-EC68-4BEC-B992-F92CA2B6816F}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {014B1E10-EC68-4BEC-B992-F92CA2B6816F}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {014B1E10-EC68-4BEC-B992-F92CA2B6816F}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {44F77533-A4A1-4175-8C4C-07106B3F9C08}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {44F77533-A4A1-4175-8C4C-07106B3F9C08}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {44F77533-A4A1-4175-8C4C-07106B3F9C08}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {44F77533-A4A1-4175-8C4C-07106B3F9C08}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {45E2ABF6-91A7-4AA5-A82B-0C8E54BCCCB9}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {45E2ABF6-91A7-4AA5-A82B-0C8E54BCCCB9}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {45E2ABF6-91A7-4AA5-A82B-0C8E54BCCCB9}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {45E2ABF6-91A7-4AA5-A82B-0C8E54BCCCB9}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ {F62E31E5-0F8D-4B70-8F26-44AFA1A9E645}.Debug|@PLATFORM@.ActiveCfg = Debug|@PLATFORM@ {F62E31E5-0F8D-4B70-8F26-44AFA1A9E645}.Debug|@PLATFORM@.Build.0 = Debug|@PLATFORM@ {F62E31E5-0F8D-4B70-8F26-44AFA1A9E645}.Release|@PLATFORM@.ActiveCfg = Release|@PLATFORM@ {F62E31E5-0F8D-4B70-8F26-44AFA1A9E645}.Release|@PLATFORM@.Build.0 = Release|@PLATFORM@ @END TESTS EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal softhsm-2.0.0/win32/dump/0000775000175000017500000000000012552220146012105 500000000000000softhsm-2.0.0/win32/dump/dump.vcxproj.in0000664000175000017500000001103712533040716015020 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {F60ACB12-7D05-4A89-B2D1-DD16E1F3566B} Win32Proj dump Application true Unicode Application false true Unicode true softhsm2-dump-file false softhsm2-dump-file Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib\cryptoki_compat;..\..\src\lib\object_store;..\..\src\lib;%(AdditionalIncludeDirectories) Console true Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib\cryptoki_compat;..\..\src\lib\object_store;..\..\src\lib;%(AdditionalIncludeDirectories) Console true true true softhsm-2.0.0/win32/dump/dump.vcxproj.filters0000664000175000017500000000246512533040716016067 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Source Files softhsm-2.0.0/win32/dump/dump.vcxproj.user0000664000175000017500000000021712533040716015366 00000000000000 softhsm-2.0.0/win32/handlemgrtest/0000775000175000017500000000000012552220146014001 500000000000000softhsm-2.0.0/win32/handlemgrtest/handlemgrtest.vcxproj.user0000664000175000017500000000021712533040716021156 00000000000000 softhsm-2.0.0/win32/handlemgrtest/handlemgrtest.vcxproj.in0000664000175000017500000001262312533040716020612 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {014B1E10-EC68-4BEC-B992-F92CA2B6816F} Win32Proj handlemgrtest Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\handle_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\data_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\handle_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\data_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;%(AdditionalDependencies) softhsm-2.0.0/win32/handlemgrtest/handlemgrtest.vcxproj.filters0000664000175000017500000000260312533040716021651 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Source Files Source Files softhsm-2.0.0/win32/keyconv/0000775000175000017500000000000012552220146012616 500000000000000softhsm-2.0.0/win32/keyconv/keyconv.vcxproj.in0000664000175000017500000001313212533040716016240 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {9B003E52-F02A-47EA-9942-2D9AE8738161} Win32Proj keyconv Application true Unicode Application false true Unicode true softhsm2-keyconv false softhsm2-keyconv Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\bin\common;..\..\src\bin\win32;..\..\src\lib\cryptoki_compat;@DEBUGINCPATH@;%(AdditionalIncludeDirectories) Console true @DEBUGLIBPATH@;%(AdditionalLibraryDirectories) @LIBNAME@;%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\bin\common;..\..\src\bin\win32;..\..\src\lib\cryptoki_compat;@INCLUDEPATH@;%(AdditionalIncludeDirectories) Console true true true @LIBPATH@;%(AdditionalLibraryDirectories) @LIBNAME@;%(AdditionalDependencies) @IF BOTAN @END BOTAN @IF OPENSSL @END OPENSSL softhsm-2.0.0/win32/keyconv/keyconv.vcxproj.user0000664000175000017500000000021712533040716016610 00000000000000 softhsm-2.0.0/win32/keyconv/keyconv.vcxproj.filters.in0000664000175000017500000000640212533040716017711 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {6f8944db-01c2-47c3-a4b4-265d91e99ba0} h;hpp;hxx;hm;inl;inc;xsd {b6a2e68c-2518-456b-8592-561c011e0390} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {14914ba7-3ec3-4f58-a83a-4596a7f52075} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {3253c2c0-ca7a-4902-8b31-87ab6c4c754f} h;hpp;hxx;hm;inl;inc;xsd Common Header Files Common Header Files Header Files Header Files Win32 Header Files Source Files @IF BOTAN Source Files @END BOTAN @IF OPENSSL Source Files @END OPENSSL Common Source Files Common Source Files Source Files Win32 Source Files Win32 Source Files softhsm-2.0.0/win32/softhsm2/0000775000175000017500000000000012552220146012705 500000000000000softhsm-2.0.0/win32/softhsm2/softhsm2.vcxproj.user0000664000175000017500000000021712533040716016766 00000000000000 softhsm-2.0.0/win32/softhsm2/softhsm2.vcxproj.in0000664000175000017500000001341212533040716016417 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {801F5AB2-7A62-4085-B129-D15E2D717219} Win32Proj softhsm2 DynamicLibrary true Unicode DynamicLibrary false true Unicode true false Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;SOFTHSM2_EXPORTS;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\cryptoki_compat;..\..\src\lib\common;..\..\src\lib\object_store;..\..\src\lib\slot_mgr;..\..\src\lib\session_mgr;..\..\src\lib\data_mgr;..\..\src\lib\handle_mgr;..\..\src\lib\crypto;..\..\src\lib\win32;%(AdditionalIncludeDirectories) Windows true ..\@PLATFORMDIR@$(Configuration);@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;SOFTHSM2_EXPORTS;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\cryptoki_compat;..\..\src\lib\common;..\..\src\lib\object_store;..\..\src\lib\slot_mgr;..\..\src\lib\session_mgr;..\..\src\lib\data_mgr;..\..\src\lib\handle_mgr;..\..\src\lib\crypto;..\..\src\lib\win32;%(AdditionalIncludeDirectories) Windows true true true ..\@PLATFORMDIR@$(Configuration);@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) softhsm-2.0.0/win32/softhsm2/softhsm2.vcxproj.filters0000664000175000017500000000424512533040716017465 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files softhsm-2.0.0/win32/datamgrtest/0000775000175000017500000000000012552220146013457 500000000000000softhsm-2.0.0/win32/datamgrtest/datamgrtest.vcxproj.in0000664000175000017500000001322712533040716017747 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ {E20315B5-B49E-46D7-B7EC-1A439F347C95} Win32Proj datamgrtest Application true Unicode Application false true Unicode true false Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\data_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@DEBUGLIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunitd.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\data_mgr;..\..\src\lib\common;..\..\src\lib\cryptoki_compat;..\..\src\lib\crypto;..\..\src\lib\object_store;..\..\src\lib\session_mgr;..\..\src\lib\slot_mgr;..\..\src\lib\win32;@CUINCPATH@;%(AdditionalIncludeDirectories) Console true true true ..\@PLATFORMDIR@$(Configuration);@CULIBPATH@;@LIBPATH@;%(AdditionalLibraryDirectories) convarch.lib;cppunit.lib;@LIBNAME@;@EXTRALIBS@%(AdditionalDependencies) softhsm-2.0.0/win32/datamgrtest/datamgrtest.vcxproj.filters0000664000175000017500000000357112533040716021012 00000000000000 {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files softhsm-2.0.0/win32/datamgrtest/datamgrtest.vcxproj.user0000664000175000017500000000021712533040716020312 00000000000000 softhsm-2.0.0/win32/Configure.pl0000664000175000017500000006600612533040716013350 00000000000000#!perl # Configure -- perl version # # this script builds Visual Studio files require 5.000; use strict; use File::Spec; use Cwd; # files to configure my @filelist = ("config.h", "softhsm2.sln", "convarch\\convarch.vcxproj.filters", "convarch\\convarch.vcxproj", "cryptotest\\cryptotest.vcxproj", "datamgrtest\\datamgrtest.vcxproj", "dump\\dump.vcxproj", "handlemgrtest\\handlemgrtest.vcxproj", "keyconv\\keyconv.vcxproj.filters", "keyconv\\keyconv.vcxproj", "objstoretest\\objstoretest.vcxproj", "p11test\\p11test.vcxproj", "sessionmgrtest\\sessionmgrtest.vcxproj", "slotmgrtest\\slotmgrtest.vcxproj", "softhsm2\\softhsm2.vcxproj", "util\\util.vcxproj.filters", "util\\util.vcxproj"); # test files my @testlist = ("botan", "ecc", "gnump", "gost", "ossl", "osslv", "rfc3394", "rfc5649"); # variables to expand my %varvals; my @varnames = ("CUINCPATH", "CULIBPATH", "DEBUGDLLPATH", "DEBUGINCPATH", "DEBUGLIBPATH", "DLLPATH", "EXTRALIBS", "INCLUDEPATH", "LIBNAME", "LIBPATH", "PLATFORM", "PLATFORMDIR"); # conditions to stack my %condvals; my @condnames = ("BOTAN", "ECC", "GOST", "NONPAGE", "OPENSSL", "RFC3394", "RFC5649", "TESTS"); # enable-xxx/disable-xxx arguments my @enablelist = ("64bit", "debug", "ecc", "gost", "keep", "non-paged-memory", "verbose"); # with-xxx/without-xxx arguments my @withlist = ("botan", "cppunit", "crypto-backend", "debug-botan", "debug-openssl", "openssl"); # general commands my @commandlist = ("help", "clean"); # verbose, keep # usage my @usage = ("Usage: perl Configure.pl help\n", " perl Configure.pl options*\n", " perl Configure.pl clean\n"); # help my @help = ( "'perl Configure.pl' configures SoftHSMv2 build files.\n\n", @usage, "\nGeneral Commands:\n", " help print this help\n", " clean clean up generated files\n", " print a summary of the configuration\n", "\nOptional Features:\n", " enable-verbose print messages [default=no]\n", " enable-keep keep test files after config [default=no]\n", " enable-64bit enable 64-bit compiling [default=no]\n", " enable-debug enable build of Debug config [default=yes]\n", " enable-ecc enable support for ECC [default=yes]\n", " enable-gost enable support for GOST [default=yes]\n", " enable-non-paged-memory enable non-paged memory [default=yes]\n", "\nOptional Packages:\n", " with-crypto-backend select the crypto backend [openssl|botan]\n", " with-botan=PATH speficy prefix of path of Botan (Release)\n", " with-debug-botan=PATH speficy prefix of path of Botan (Debug)\n", " with-openssl=PATH speficy prefix of path of OpenSSL (Release)\n", " with-debug-openssl=PATH speficy prefix of path of OpenSSL (Debug)\n", " with-cppunit=PATH specify prefix of path of CppUnit\n"); # variables for parsing my $verbose = 0; my $configargs; my $want_help = "no"; my $want_clean = "no"; my $want_unknown = "no"; my $unknown_value; my $enable_keep = "no"; my $enable_debug = "yes"; my $enable_ecc = "yes"; my $enable_gost = "yes"; my $enable_non_paged = "yes"; my $platform = "win32"; my $crypto_backend = "openssl"; my $botan_path = "..\\..\\btn"; my $debug_botan_path; my $openssl_path = "..\\..\\ssl"; my $debug_openssl_path; my $want_tests = "yes"; my $cppunit_path = "..\\..\\cu"; # no arguments -> usage if ($#ARGV < 0) { foreach (@usage) { print $_; } exit 1; } # parse arguments foreach (@ARGV) { if (/^verbose$/i) { $verbose = 1; } elsif (/^keep$/i) { appargs($_); $enable_keep = "yes"; } elsif (/^help$/i) { $want_help = "yes"; } elsif (/^disable-(.*)$/i) { appargs($_); myenable($1, "no"); } elsif (/^enable-(.*)$/i) { appargs($_); myenable($1, "yes"); } elsif (/^without-(.*)$/i) { appargs($_); mywith($1, "no"); } elsif (/^with-(.*)=(.*)$/i) { appargs($_); mywith($1, $2); } elsif (/^with-(.*)$/i) { appargs($_); mywith($1, "yes"); } elsif (/^clean$/i) { $want_clean = "yes"; } else { $want_unknown = "yes"; $unknown_value = $_; } } # append seen arguments to configargs sub appargs { my $arg = $_[0]; # escape backslashes, spaces and double quotes $arg =~ s/([\\ "])/\\$1/g; if (defined($configargs)) { $configargs .= " " . $arg; } else { $configargs = $arg; } } # parse enable/disable sub myenable { my $key = $_[0]; my $val = $_[1]; if ($key =~ /^64bit$/i) { if ($val =~ /^yes$/i) { $platform = "x64"; } } elsif ($key =~ /^debug$/i) { if ($val =~ /^no$/i) { $enable_debug = "no"; } } elsif ($key =~ /^ecc$/i) { if ($val =~ /^no$/i) { $enable_ecc = "no"; } } elsif ($key =~ /^gost$/i) { if ($val =~ /^no$/i) { $enable_gost = "no"; } } elsif ($key =~ /^non-paged-memory$/i) { if ($val =~ /^no$/i) { $enable_non_paged = "no"; } } elsif ($key =~ /^keep$/i) { if ($val =~ /^yes$/i) { $enable_keep = "yes"; } } elsif ($key =~ /^verbose$/i) { if ($val =~ /^yes$/i) { $verbose = 1; } } else { $want_unknown = "yes"; if ($val eq "no") { $unknown_value = "disable-" . $key; } else { $unknown_value = "enable-" . $key; } } } # parse with/without sub mywith { my $key = $_[0]; my $val = $_[1]; if ($key =~ /^crypto-backend$/i) { if ($val =~ /^openssl$/i) { $crypto_backend = "openssl"; } elsif ($val =~ /^botan$/i) { $crypto_backend = "botan"; } else { $want_unknown = "yes"; $unknown_value = "with-crypto-backend=" . $val; } } elsif ($key =~ /^botan$/i) { if ($val =~ /^no$/i) { $want_unknown = "yes"; $unknown_value = "without-botan doesn't make sense\n"; } elsif ($val !~ /^yes$/i) { $botan_path = $val; } } elsif ($key =~ /^debug-botan$/i) { if ($val =~ /^no$/i) { $want_unknown = "yes"; $unknown_value = "without-debug-botan doesn't make sense\n"; } elsif ($val !~ /^yes$/i) { $debug_botan_path = $val; } } elsif ($key =~ /^openssl$/i) { if ($val =~ /^no$/i) { $want_unknown = "yes"; $unknown_value = "without-openssl doesn't make sense\n"; } elsif ($val !~ /^yes$/i) { $openssl_path = $val; } } elsif ($key =~ /^debug-openssl$/i) { if ($val =~ /^no$/i) { $want_unknown = "yes"; $unknown_value = "without-debug-openssl doesn't make sense\n"; } elsif ($val !~ /^yes$/i) { $debug_openssl_path = $val; } } elsif ($key =~ /^cppunit$/i) { if ($val =~ /^no$/i) { $want_tests = "no"; } elsif ($val !~ /^yes$/i) { $cppunit_path = $val; } } else { $want_unknown = "yes"; if ($val eq "no") { $unknown_value = "without-" . $key; } else { $unknown_value = "with-" . $key; } } } # help if ($want_help ne "no") { foreach (@help) { print $_; } exit 1; } # clean sub cleantest { my $file; foreach $file (@testlist) { unlink("test" . $file . ".c"); unlink("test" . $file . ".cpp"); unlink("test" . $file . ".obj"); unlink("test" . $file . ".exe"); } unlink("botan.dll"); unlink("libeay32.dll"); } if ($want_clean eq "yes") { my $file; cleantest(); foreach $file (@filelist) { unlink($file); } exit 0; } # parsing error if ($want_unknown ne "no") { print STDERR "can't parse $unknown_value\n"; exit 1; } # debug if ($enable_debug eq "yes") { if (!defined($debug_botan_path)) { $debug_botan_path = $botan_path . "_d"; } if (!defined($debug_openssl_path)) { $debug_openssl_path = $openssl_path . "_d"; } } # verbose if ($verbose) { if ($enable_keep eq "yes") { print "keep: enabled\n"; } else { print "keep: disabled\n"; } if ($platform eq "x64") { print "64bit: enabled\n"; } else { print "64bit: disabled\n"; } if ($enable_debug eq "yes") { print "debug: enabled\n"; } else { print "debug: disabled\n"; } if ($enable_ecc eq "yes") { print "ecc: enabled\n"; } else { print "ecc: disabled\n"; } if ($enable_gost eq "yes") { print "gost: enabled\n"; } else { print "gost: disabled\n"; } if ($enable_non_paged eq "yes") { print "non-paged-memory: enabled\n"; } else { print "non-paged-memory: disabled\n"; } print "crypto-backend: $crypto_backend\n"; if ($crypto_backend eq "botan") { print "botan-path: $botan_path\n"; if ($enable_debug eq "yes") { print "debug-botan-path: $debug_botan_path\n"; } } else { print "openssl-path: $openssl_path\n"; if ($enable_debug eq "yes") { print "debug-openssl-path: $debug_openssl_path\n"; } } if ($want_tests eq "yes") { print "cppunit-path: $cppunit_path\n"; } } # configure the platform if ($platform eq "win32") { $varvals{"PLATFORM"} = "Win32"; } else { $varvals{"PLATFORM"} = "x64"; $varvals{"PLATFORMDIR"} = "x64\\"; } # configure ECC and GOST if ($enable_ecc eq "yes") { $condvals{"ECC"} = 1; } if ($enable_gost eq "yes") { $condvals{"GOST"} = 1; } # configure the crypto if ($crypto_backend eq "botan") { $condvals{"BOTAN"} = 1; $varvals{"LIBNAME"} = "botan.lib"; $botan_path = File::Spec->rel2abs($botan_path); my $botan_dll = File::Spec->catfile($botan_path, "botan.dll"); $varvals{"DLLPATH"} = $botan_dll; my $botan_inc = File::Spec->catfile($botan_path, "include"); if (!-f File::Spec->catfile($botan_inc, "botan\\init.h")) { die "can't find Botan includes\n"; } $varvals{"INCLUDEPATH"} = $botan_inc; if (!-f File::Spec->catfile($botan_path, "botan.lib")) { die "can't find Botan library\n"; } $varvals{"LIBPATH"} = $botan_path; if ($enable_debug eq "yes") { $debug_botan_path = File::Spec->rel2abs($debug_botan_path); $varvals{"DEBUGDLLPATH"} = File::Spec->catfile($debug_botan_path, "botan.dll"); my $debug_botan_inc = File::Spec->catfile($debug_botan_path, "include"); if (!-f File::Spec->catfile($debug_botan_inc, "botan\\init.h")) { die "can't find debug Botan includes\n"; } $varvals{"DEBUGINCPATH"} = $debug_botan_inc; if (!-f File::Spec->catfile($debug_botan_path, "botan.lib")) { die "can't find debug Botan library\n"; } $varvals{"DEBUGLIBPATH"} = $debug_botan_path; } else { $varvals{"DEBUGDLLPATH"} = $varvals{"DLLPATH"}; $varvals{"DEBUGINCPATH"} = $varvals{"INCLUDEPATH"}; $varvals{"DEBUGLIBPATH"} = $varvals{"LIBPATH"}; } # Botan version if ($verbose) { print "checking Botan version\n"; } my $botan_version_minor = 0; my $system_libs = ""; if (-f $botan_dll) { `copy "$botan_dll" .`; } else { $system_libs = " user32.lib advapi32.lib"; } my $inc = $botan_inc; my $lib = File::Spec->catfile($botan_path, "botan.lib"); open F, ">testbotan.cpp" || die $!; print F << 'EOF'; #include #include int main() { using namespace Botan; LibraryInitializer::initialize(); #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,10,0) return 1; #endif #if BOTAN_VERSION_CODE > BOTAN_VERSION_CODE_FOR(1,11,0) return 2; #endif return 0; } EOF close F; my $compret = `cl /nologo /MD /I "$inc" testbotan.cpp "$lib"$system_libs`; if (grep { -f and -x } ".\\testbotan.exe") { `.\\testbotan.exe`; if ($? == 1) { die "Botan version too old\n"; } elsif ($? == 2) { $botan_version_minor = 11; die "Botan version 11 not yet supported\n"; } elsif ($? != 0) { die "Botan test failed\n"; } else { $botan_version_minor = 10; } } else { die "can't compile Botan test: $compret\n"; } # Botan ECC support if ($enable_ecc eq "yes") { if ($verbose) { print "checking Botan ECC support\n"; } open F, ">testecc.cpp" || die $!; print F << 'EOF'; #include #include #include int main() { Botan::LibraryInitializer::initialize(); const std::string name("secp256r1"); const Botan::OID oid(Botan::OIDS::lookup(name)); const Botan::EC_Group ecg(oid); try { const Botan::SecureVector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); } catch(...) { return 1; } return 0; } EOF close F; $compret = `cl /nologo /MD /I "$inc" testecc.cpp "$lib"$system_libs`; if (grep { -f and -x } ".\\testecc.exe") { `.\\testecc.exe`; if ($? != 0) { die "can't find P256: upgrade to Botan >= 1.10.6\n"; } } else { die "can't compile ECC test: $compret\n"; } } # Botan GOST support if ($enable_gost eq "yes") { if ($verbose) { print "checking Botan GOST support\n"; } open F, ">testgost.cpp" || die $!; print F << 'EOF'; #include #include #include int main() { Botan::LibraryInitializer::initialize(); const std::string name("gost_256A"); const Botan::OID oid(Botan::OIDS::lookup(name)); const Botan::EC_Group ecg(oid); try { const Botan::SecureVector der = ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID); } catch(...) { return 1; } return 0; } EOF close F; $compret = `cl /nologo /MD /I "$inc" testgost.cpp "$lib"$system_libs`; if (grep { -f and -x } ".\\testgost.exe") { `.\\testgost.exe`; if ($? != 0) { die "can't find GOST: upgrade to Botan >= 1.10.6\n"; } } else { die "can't compile GOST test: $compret\n"; } } # no check for Botan RFC3394 support $condvals{"RFC3394"} = 1; # Botan RFC5649 support if ($verbose) { print "checking Botan RFC5649 support\n"; } open F, ">testrfc5649.cpp" || die $!; print F << 'EOF'; #include #include int main() { using namespace Botan; SecureVector key(10); SymmetricKey kek("AABB"); Algorithm_Factory& af = global_state().algorithm_factory(); SecureVector x = rfc5649_keywrap(key, kek, af); return 1; } EOF close F; `cl /nologo /MD /I "$inc" testrfc5649.cpp "$lib"$system_libs`; if (grep { -f and -x } ".\\testrfc5649.exe") { if ($verbose) { print "Found AES key wrap with pad\n"; } $condvals{"RFC5649"} = 1; } else { if ($verbose) { print "can't compile Botan AES key wrap with pad\n"; } } # Botan GNU MP support if ($botan_version_minor == 10) { if ($verbose) { print "checking Botan GNU MP support\n"; } open F, ">testgnump.cpp" || die $!; print F << 'EOF'; #include int main() { #ifndef BOTAN_HAS_ENGINE_GNU_MP #error "No GNU MP support"; #endif } EOF close F; `cl /nologo /MD /I "$inc" testgnump.cpp "$lib"$system_libs`; if (grep { -f and -x } ".\\testgnump.exe") { if ($verbose) { print "Botan GNU MP is supported\n"; } } else { if ($verbose) { print "Botan GNU MP is not supported\n"; } } } } else { $condvals{"OPENSSL"} = 1; $varvals{"LIBNAME"} = "libeay32.lib"; $varvals{"EXTRALIBS"} = "crypt32.lib;"; $openssl_path = File::Spec->rel2abs($openssl_path); my $openssl_dll = File::Spec->catfile($openssl_path, "bin\\libeay32.dll"); $varvals{"DLLPATH"} = $openssl_dll; my $openssl_inc = File::Spec->catfile($openssl_path, "include"); if (!-f File::Spec->catfile($openssl_inc, "openssl\\ssl.h")) { die "can't find OpenSSL headers\n"; } $varvals{"INCLUDEPATH"} = $openssl_inc; my $openssl_lib = File::Spec->catfile($openssl_path, "lib"); if (!-f File::Spec->catfile($openssl_lib, "libeay32.lib")) { die "can't find OpenSSL library\n"; } $varvals{"LIBPATH"} = $openssl_lib; if ($enable_debug eq "yes") { $debug_openssl_path = File::Spec->rel2abs($debug_openssl_path); $varvals{"DEBUGDLLPATH"} = File::Spec->catfile($debug_openssl_path, "bin\\libeay32.dll"); my $debug_openssl_inc = File::Spec->catfile($debug_openssl_path, "include"); if (!-f File::Spec->catfile($debug_openssl_inc, "openssl\\ssl.h")) { die "can't find debug OpenSSL headers\n"; } $varvals{"DEBUGINCPATH"} = $debug_openssl_inc; my $debug_openssl_lib = File::Spec->catfile($debug_openssl_path, "lib"); if (!-f File::Spec->catfile($debug_openssl_lib, "libeay32.lib")) { die "can't find debug OpenSSL library\n"; } $varvals{"DEBUGLIBPATH"} = $debug_openssl_lib; } else { $varvals{"DEBUGDLLPATH"} = $varvals{"DLLPATH"}; $varvals{"DEBUGINCPATH"} = $varvals{"INCLUDEPATH"}; $varvals{"DEBUGLIBPATH"} = $varvals{"LIBPATH"}; } # OpenSSL support if ($verbose) { print "checking OpenSSL\n"; } my $system_libs = ""; if (-f $openssl_dll) { `copy "$openssl_dll" .`; } else { $system_libs = " user32.lib advapi32.lib gdi32.lib crypt32.lib"; } my $inc = $openssl_inc; my $lib = File::Spec->catfile($openssl_lib, "libeay32.lib"); open F, ">testossl.c" || die $!; print F << 'EOF'; #include int main() { ERR_clear_error(); return 0; } EOF close F; my $compret = `cl /nologo /MD /I "$inc" testossl.c "$lib"$system_libs`; if (grep { -f and -x } ".\\testossl.exe") { `.\\testossl.exe`; if ($? != 0) { die "OpenSSL test failed\n"; } } else { die "can't compile OpenSSL test: $compret\n"; } # OpenSSL version if ($verbose) { print "checking OpenSSL version\n"; } open F, ">testosslv.c" || die $!; print F << 'EOF'; #include #include int main() { #ifndef OPENSSL_VERSION_NUMBER return -1; #endif #if OPENSSL_VERSION_NUMBER >= 0x010000000L return 0; #else return 1; #endif } EOF close F; $compret = `cl /nologo /MD /I "$inc" testosslv.c "$lib"$system_libs`; if (grep { -f and -x } ".\\testosslv.exe") { `.\\testosslv.exe`; if ($? != 0) { die "OpenSLL version too old (1.0.0 or later required)\n"; } } else { die "can't compile OpenSSL version test: $compret\n"; } # OpenSSL ECC support if ($enable_ecc eq "yes") { if ($verbose) { print "checking OpenSSL ECC support\n"; } open F, ">testecc.c" || die $!; print F << 'EOF'; #include #include int main() { EC_KEY *ec256, *ec384; ec256 = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); ec384 = EC_KEY_new_by_curve_name(NID_secp384r1); if (ec256 == NULL || ec384 == NULL) return 1; return 0; } EOF close F; $compret = `cl /nologo /MD /I "$inc" testecc.c "$lib"$system_libs`; if (grep { -f and -x } ".\\testecc.exe") { `.\\testecc.exe`; if ($? != 0) { die "can't find P256 or P384: no ECC support\n"; } } else { die "can't compile ECC test: $compret\n"; } } # OpenSSL GOST support if ($enable_gost eq "yes") { if ($verbose) { print "checking OpenSSL GOST support\n"; } open F, ">testgost.c" || die $!; print F << 'EOF'; #include #include int main() { ENGINE *e; EC_KEY *ek; ek = NULL; OPENSSL_config(NULL); e = ENGINE_by_id("gost"); if (e == NULL) return 1; if (ENGINE_init(e) <= 0) return 1; return 0; } EOF close F; $compret = `cl /nologo /MD /I "$inc" testgost.c "$lib"$system_libs`; if (grep { -f and -x } ".\\testgost.exe") { `.\\testgost.exe`; if ($? != 0) { die "can't find GOST: no GOST support\n"; } } else { die "can't compile GOST test: $compret\n"; } } # OpenSSL EVP interface for AES key wrapping (aka RFC 3394) if ($verbose) { print "checking OpenSSL EVP interface for AES key wrapping\n"; } open F, ">testrfc3394.c" || die $!; print F << 'EOF'; #include int main() { EVP_aes_128_wrap(); return 1; } EOF close F; `cl /nologo /MD /I "$inc" testrfc3394.c "$lib"$system_libs`; if (grep { -f and -x } ".\\testrfc3394.exe") { if ($verbose) { print "RFC 3394 is supported\n"; } $condvals{"RFC3394"} = 1; } else { if ($verbose) { print "can't compile OpenSSL RFC 3394\n"; } } # OpenSSL EVP interface for AES key wrap with pad (aka RFC 5649) if ($verbose) { print "checking OpenSSL EVP interface for AES key wrapping with pad\n"; } open F, ">testrfc5649.c" || die $!; print F << 'EOF'; #include int main() { EVP_aes_128_wrap_pad(); return 1; } EOF close F; `cl /nologo /MD /I "$inc" testrfc5649.c "$lib"$system_libs`; if (grep { -f and -x } ".\\testrfc5649.exe") { if ($verbose) { print "RFC 5649 is supported\n"; } $condvals{"RFC5649"} = 1; } else { if ($verbose) { print "can't compile OpenSSL RFC 5649\n"; } } } # configure CppUnit if ($want_tests eq "yes") { $condvals{"TESTS"} = 1; $cppunit_path = File::Spec->rel2abs($cppunit_path); my $cppunit_inc = File::Spec->catfile($cppunit_path, "include"); if (!-f File::Spec->catfile($cppunit_inc, "cppunit\\Test.h")) { die "can't find CppUnit headers\n"; } $varvals{"CUINCPATH"} = $cppunit_inc; my $cppunit_lib = File::Spec->catfile($cppunit_path, "lib"); if (!-f File::Spec->catfile($cppunit_lib, "cppunit.lib")) { $cppunit_lib = $cppunit_path; } if (!-f File::Spec->catfile($cppunit_lib, "cppunit.lib")) { die "can't find CppUnit library\n"; } if ($enable_debug eq "yes") { if (!-f File::Spec->catfile($cppunit_lib, "cppunitd.lib")) { die "can't find debug CppUnit library\n"; } } $varvals{"CULIBPATH"} = $cppunit_lib; } # misc if ($enable_non_paged eq "yes") { $condvals{"NONPAGE"} = 1; } # escape spaces sub kw { if ($_[0] =~ / /) { return "\"$_[0]\""; } else { return "$_[0]"; } } # setup files with condition stacks and variable expansions sub setupfile { my $line; my @Linesin; my @Linesout; my $filename = $_[0]; my $cond; my @conds; my $pass = 1; my @passes; my $val; open F, $filename . ".in" || die $!; @Linesin = ; close F; foreach $line (@Linesin) { chomp $line; if ($line =~ /^\@IF (.*)$/) { if (defined($cond)) { unshift(@conds, $cond); unshift(@passes, $pass); } $cond = $1; if (defined($condvals{$cond})) { # do nothing } else { $pass = 0; } next; } elsif ($line =~ /^\@ELSE (.*)$/) { if ($cond ne $1) { die "\@ELSE $1 mismatch in $filename\n"; } if (defined($condvals{$cond})) { $pass = 0; } else { if (scalar(@conds) > 0) { $pass = $passes[0]; } else { $pass = 1; } } next; } elsif ($line =~ /^\@END (.*)$/) { if ($cond ne $1) { die "\@END $1 mismatch in $filename\n"; } $cond = shift(@conds); if (scalar(@passes) > 0) { $pass = shift(@passes); } else { $pass = 1; } next; } if ($pass == 0) { next; } while ($line =~ /@([^@ ]*)@/) { if ($1 ~~ @varnames) { if (defined($varvals{$1})) { $val = kw($varvals{$1}); $line = "$`$val$'"; } else { $line = "$`$'"; } } else { die "unknown control $& in $filename\n"; } } push @Linesout, $line; } open F, ">" . $filename || die $!; if ($verbose) { print "Setting up $filename\n"; } foreach $line (@Linesout) { print F $line . "\n"; } close F; } # status if ($verbose) { my $name; print "Configuration Status\n"; print "\tconditions:\n"; foreach $name (@condnames) { if (defined($condvals{$name})) { print "\t\t$name is true\n"; } else { print "\t\t$name is false\n"; } } print "\tsubstitutions:\n"; foreach $name (@varnames) { if (defined($varvals{$name})) { print qq(\t\t$name -> "$varvals{$name}"\n); } } print "\n"; } # run my $file; foreach $file (@filelist) { setupfile($file); } # clean test files if ($enable_keep ne "yes") { cleantest(); } print "Configured.\n"; exit 0; # Notes: Unix configure.ac options # --enable-64bit supported # --enable-ecc supported # --enable-gost supported # --enable-non-paged-memory supported # --enable-visibility (enforced by DLLs) # --with-crypto-backend supported # --with-botan supported (Release and Debug) # --with-openssl supported (Release and Debug) # --with-migrate (useless as SoftHSMv1 is not supported) # --with-objectstore-backend-db (TODO) # --with-sqlite3 (useless until objectstore backend can be chosen) softhsm-2.0.0/win32/convarch/0000775000175000017500000000000012552220146012743 500000000000000softhsm-2.0.0/win32/convarch/convarch.vcxproj.user0000664000175000017500000000021712533040716017062 00000000000000 softhsm-2.0.0/win32/convarch/convarch.vcxproj.in0000664000175000017500000005442412533040716016523 00000000000000 Debug @PLATFORM@ Release @PLATFORM@ @IF BOTAN @END BOTAN @IF OPENSSL @END OPENSSL @IF BOTAN @END BOTAN @IF OPENSSL @END OPENSSL {F64541B6-FFBF-4368-B93A-A5CA8ADAD795} Win32Proj convarch StaticLibrary true Unicode StaticLibrary false true Unicode Level3 Disabled WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\cryptoki_compat;..\..\src\lib\common;..\..\src\lib\object_store;..\..\src\lib\slot_mgr;..\..\src\lib\session_mgr;..\..\src\lib\handle_mgr;..\..\src\lib\crypto;..\..\src\lib\win32;..\..\src\lib\data_mgr;@DEBUGINCPATH@;%(AdditionalIncludeDirectories) Windows true Level3 MaxSpeed true true WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) ..;..\..\src\lib;..\..\src\lib\cryptoki_compat;..\..\src\lib\common;..\..\src\lib\object_store;..\..\src\lib\slot_mgr;..\..\src\lib\session_mgr;..\..\src\lib\handle_mgr;..\..\src\lib\crypto;..\..\src\lib\win32;..\..\src\lib\data_mgr;@INCLUDEPATH@;%(AdditionalIncludeDirectories) Windows true true true softhsm-2.0.0/win32/convarch/convarch.vcxproj.filters.in0000664000175000017500000011406412533040716020167 00000000000000 {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {b657b1af-4cc4-4d97-ba6a-0a7231c5f243} h;hpp;hxx;hm;inl;inc;xsd {aacfc93a-d2e0-4935-aa15-ea0d3690fbcd} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {6337c51f-53e3-440a-9ab9-40f0b9a4f26e} h;hpp;hxx;hm;inl;inc;xsd {8566a5d1-d688-41da-bbc3-3d860f2db764} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {b427db7b-49c3-47b0-982a-7da01cf39c8e} h;hpp;hxx;hm;inl;inc;xsd {04a46825-a433-4b5c-9c3f-8c489978cb8a} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {9e67afe5-3252-4c46-a24f-096e4a35e174} h;hpp;hxx;hm;inl;inc;xsd {b8a7e894-ebbe-43de-ad66-3c45d91aac8e} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {0c47956d-aa5e-4c26-bee4-63ec89c0ab64} h;hpp;hxx;hm;inl;inc;xsd {45c69303-5073-4bde-8b63-2f2e2a688362} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {d1a8b25d-8ebb-4a79-ae8c-70ef3c0bed5f} h;hpp;hxx;hm;inl;inc;xsd {cb379241-3d4b-4f7c-b7d1-c6c83d3a1b62} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {5420eba7-6b85-4daf-a916-c85421362984} h;hpp;hxx;hm;inl;inc;xsd {3c9f55a5-d1a8-4716-a416-ec172a676e63} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {63e3d8a2-0853-4f98-bcaa-de05da380d37} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {59b2221a-36a3-4f2c-9883-6173599baf5a} h;hpp;hxx;hm;inl;inc;xsd Common Header Files Common Header Files Common Header Files Common Header Files Common Header Files Common Header Files Common Header Files Common Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files @IF BOTAN Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files @END BOTAN Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files @IF OPENSSL Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files @END OPENSSL Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Crypto Header Files Data Mgr Header Files Data Mgr Header Files Data Mgr Header Files Data Mgr Header Files Data Mgr Header Files Data Mgr Header Files Handle Mgr Header Files Handle Mgr Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Object Store Header Files Session Mgr Header Files Session Mgr Header Files Slot Mgr Header Files Slot Mgr Header Files Slot Mgr Header Files Win32 Header Files Common Source Files Common Source Files Common Source Files Common Source Files Common Source Files Common Source Files Crypto Source Files Crypto Source Files @IF BOTAN Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files @END BOTAN Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files @IF OPENSSL Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files @END OPENSSL Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Crypto Source Files Data Mgr Source Files Data Mgr Source Files Data Mgr Source Files Data Mgr Source Files Data Mgr Source Files Handle Mgr Source Files Handle Mgr Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Object Store Source Files Session Mgr Source Files Session Mgr Source Files Slot Mgr Source Files Slot Mgr Source Files Slot Mgr Source Files Win32 Source Files softhsm-2.0.0/win32/Configure.py0000664000175000017500000007552212533040716013370 00000000000000#!python # Configure -- python version # # this script builds Visual Studio files import sys import os import os.path import re import subprocess # files to configure filelist = ["config.h", "softhsm2.sln", "convarch\\convarch.vcxproj.filters", "convarch\\convarch.vcxproj", "cryptotest\\cryptotest.vcxproj", "datamgrtest\\datamgrtest.vcxproj", "dump\\dump.vcxproj", "handlemgrtest\\handlemgrtest.vcxproj", "keyconv\\keyconv.vcxproj.filters", "keyconv\\keyconv.vcxproj", "objstoretest\\objstoretest.vcxproj", "p11test\\p11test.vcxproj", "sessionmgrtest\\sessionmgrtest.vcxproj", "slotmgrtest\\slotmgrtest.vcxproj", "softhsm2\\softhsm2.vcxproj", "util\\util.vcxproj.filters", "util\\util.vcxproj"] # test files testlist = ["botan", "ecc", "gnump", "gost", "ossl", "osslv", "rfc3394", "rfc5649"] # variables to expand varvals = {} varnames = ["CUINCPATH", "CULIBPATH", "DEBUGDLLPATH", "DEBUGINCPATH", "DEBUGLIBPATH", "DLLPATH", "EXTRALIBS", "INCLUDEPATH", "LIBNAME", "LIBPATH", "PLATFORM", "PLATFORMDIR"] # conditions to stack condvals = {} condnames = ["BOTAN", "ECC", "GOST", "NONPAGE", "OPENSSL", "RFC3394", "RFC5649", "TESTS"] # enable-xxx/disable-xxx arguments enablelist = ["64bit", "debug", "ecc", "gost", "keep", "non-paged-memory", "verbose"] # with-xxx/without-xxx arguments withlist = ["botan", "cppunit", "crypto-backend", "debug-botan", "debug-openssl", "openssl"] # general commands commandlist = ["help", "clean"] # verbose, keep # usage usage = ["Usage: python Configure.pl help", " python Configure.pl options*", " python Configure.pl clean"] # help myhelp = ["'python Configure.pl' configures SoftHSMv2 build files.\n"] +\ usage + [\ "\nGeneral Commands:", " help print this help", " clean clean up generated files", " print a summary of the configuration", "\nOptional Features:", " enable-verbose print messages [default=no]", " enable-keep keep test files after config [default=no]", " enable-64bit enable 64-bit compiling [default=no]", " enable-debug enable build of Debug config [default=yes]", " enable-ecc enable support for ECC [default=yes]", " enable-gost enable support for GOST [default=yes]", " enable-non-paged-memory enable non-paged memory [default=yes]", "\nOptional Packages:", " with-crypto-backend select the crypto backend [openssl|botan]", " with-botan=PATH speficy prefix of path of Botan (Release)", " with-debug-botan=PATH speficy prefix of path of Botan (Debug)", " with-openssl=PATH speficy prefix of path of OpenSSL (Release)", " with-debug-openssl=PATH speficy prefix of path of OpenSSL (Debug)", " with-cppunit=PATH specify prefix of path of CppUnit"] # variables for parsing verbose = False configargs = None want_help = False want_clean = False want_unknown = False unknown_value = None enable_keep = False enable_debug = True enable_ecc = True enable_gost = True enable_non_paged = True platform = 32 crypto_backend = "openssl" botan_path = "..\\..\\btn" debug_botan_path = None openssl_path = "..\\..\\ssl" debug_openssl_path = None want_tests = True cppunit_path = "..\\..\\cu" def parseargs(args): """parse arguments""" global verbose global enable_keep global want_help global want_clean global want_unknown global unknown_value global debug_botan_path global debug_openssl_path for arg in args: if arg.lower() == "verbose": verbose = True continue if arg.lower() == "keep": enable_keep = True continue if arg.lower() == "help": want_help = True continue di = re.match(r'disable-(.*)', arg, re.I) if di: appargs(arg) myenable(di.group(1), False) continue en = re.match(r'enable-(.*)', arg, re.I) if en: appargs(arg) myenable(en.group(1), True) continue wo = re.match(r'without-(.*)', arg, re.I) if wo: appargs(arg) mywith(wo.group(1), False) continue wv = re.match(r'with-(.*)=(.*)', arg, re.I) if wv: appargs(arg) if wv.group(2).lower() == "no": mywith(wv.group(1), False) continue mywith(wv.group(1), True, wv.group(2)) continue wi = re.match(r'with-(.*)', arg, re.I) if wi: appargs(arg) mywith(wi.group(1), True) continue if arg.lower() == "clean": want_clean = True continue want_unknown = True unknown_value = arg break # debug if enable_debug: if debug_botan_path is None: debug_botan_path = botan_path + "_d" if debug_openssl_path is None: debug_openssl_path = openssl_path + "_d" def appargs(arg): """append seen arguments to configargs""" global configargs # escape backslashes, spaces and double quotes escaped = "" for x in arg: if (x == "\\") or (x == " ") or (x == "\""): escaped += "\\" escaped += x if configargs: configargs += " " + escaped else: configargs = escaped def myenable(key, val): """parse enable/disable""" global platform global enable_debug global enable_ecc global enable_gost global enable_non_paged global enable_keep global verbose global want_unknown global unknown_value if key.lower() == "64bit": if val: platform = 64 return if key.lower() == "debug": if not val: enable_debug = False return if key.lower() == "ecc": if not val: enable_ecc = False return if key.lower() == "gost": if not val: enable_gost = False return if key.lower() == "non-paged-memory": if not val: enable_non_paged = False return if key.lower() == "keep": if val: enable_keep = True return if key.lower() == "verbose": if val: verbose = True return want_unknown = True if not val: unknown_value = "disable-" + key else: unknown_value = "enable-" + key def mywith(key, val, detail=None): """parse with/without""" global crypto_backend global botan_path global debug_botan_path global openssl_path global debug_openssl_path global want_tests global cppunit_path global want_unknown global unknown_value if key.lower() == "crypto-backend": if val and (detail.lower() == "openssl"): crypto_backend = "openssl" return if val and (detail.lower() == "botan"): crypto_backend = "botan" return want_unknown = True unknown_value = "with-crypto-backend=" + detail return if key.lower() == "botan": if not val: want_unknown = True unknown_value = "without-botan doesn't make sense" return if detail.lower() != "yes": botan_path = detail return if key.lower() == "debug-botan": if not val: want_unknown = True unknown_value = "without-debug-botan doesn't make sense" return if detail.lower() != "yes": debug_botan_path = detail return if key.lower() == "openssl": if not val: want_unknown = True unknown_value = "without-openssl doesn't make sense" return if detail.lower() != "yes": openssl_path = detail return if key.lower() == "debug-openssl": if not val: want_unknown = True unknown_value = "without-debug-openssl doesn't make sense" return if detail.lower() != "yes": debug_openssl_path = detail return if key.lower() == "cppunit": if not val: want_tests = False return if detail.lower() != "yes": cppunit_path = detail return want_unknown = True if not val: unknown_value = "without-" + key else: unknown_value = "with-" + key def dohelp(): """help""" for line in myhelp: print line sys.exit(1) def docleantest(): """clean test files""" for basename in testlist: filename = "test" + basename + ".c" if os.path.isfile(filename): os.unlink(filename) filename = "test" + basename + ".cpp" if os.path.isfile(filename): os.unlink(filename) filename = "test" + basename + ".obj" if os.path.isfile(filename): os.unlink(filename) filename = "test" + basename + ".exe" if os.path.isfile(filename): os.unlink(filename) if os.path.isfile("botan.dll"): os.unlink("botan.dll") if os.path.isfile("libeay32.dll"): os.unlink("libeay32.dll") def doclean(): """clean""" docleantest() for filename in filelist: if os.path.isfile(filename): os.unlink(filename) sys.exit(0) def dounknown(): """parsing error""" print >> sys.stderr, "can't parse " + unknown_value + "" sys.exit(1) def doconfig(): """config itself""" global botan_path global debug_botan_path global openssl_path global debug_openssl_path global cppunit_path # configure the platform if platform == 32: varvals["PLATFORM"] = "Win32" else: varvals["PLATFORM"] = "x64" varvals["PLATFORMDIR"] = "x64\\" # configure ECC and GOST if enable_ecc: condvals["ECC"] = True if enable_gost: condvals["GOST"] = True # configure the crypto if crypto_backend == "botan": condvals["BOTAN"] = True varvals["LIBNAME"] = "botan.lib" botan_path = os.path.abspath(botan_path) botan_dll = os.path.join(botan_path, "botan.dll") varvals["DLLPATH"] = botan_dll botan_inc = os.path.join(botan_path, "include") if not os.path.exists(os.path.join(botan_inc, "botan\\init.h")): print >> sys.stderr, "can't find Botan includes" sys.exit(1) varvals["INCLUDEPATH"] = botan_inc if not os.path.exists(os.path.join(botan_path, "botan.lib")): print >> sys.stderr, "can't find Botan library" sys.exit(1) varvals["LIBPATH"] = botan_path if enable_debug: debug_botan_path = os.path.abspath(debug_botan_path) varvals["DEBUGDLLPATH"] = \ os.path.join(debug_botan_path, "botan.dll") debug_botan_inc = os.path.join(debug_botan_path, "include") if not os.path.exists(os.path.join(debug_botan_inc, "botan\\init.h")): print >> sys.stderr, "can't find debug Botan includes" sys.exit(1) varvals["DEBUGINCPATH"] = debug_botan_inc if not os.path.exists(os.path.join(debug_botan_path, "botan.lib")): print >> sys.stderr, "can't find debug Botan library" sys.exit(1) varvals["DEBUGLIBPATH"] = debug_botan_path else: varvals["DEBUGDLLPATH"] = varvals["DLLPATH"] varvals["DEBUGINCPATH"] = varvals["INCLUDEPATH"] varvals["DEBUGLIBPATH"] = varvals["LIBPATH"] # Botan version if verbose: print "checking Botan version" botan_version_minor = 0 system_libs = [] if os.path.exists(botan_dll): subprocess.call(["copy", botan_dll, "."], shell=True) else: system_libs = ["user32.lib", "advapi32.lib"] inc = botan_inc lib = os.path.join(botan_path, "botan.lib") testfile = open("testbotan.cpp", "w") print >>testfile, '\ #include \n\ #include \n\ int main() {\n\ using namespace Botan;\n\ LibraryInitializer::initialize();\n\ #if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(1,10,0)\n\ return 1;\n\ #endif\n\ #if BOTAN_VERSION_CODE > BOTAN_VERSION_CODE_FOR(1,11,0)\n\ return 2;\n\ #endif\n\ return 0;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testbotan.cpp", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testbotan.exe"): print >> sys.stderr, "can't create .\\testbotan.exe" sys.exit(1) ret = subprocess.call(".\\testbotan.exe") if ret == 1: print >> sys.stderr, "Botan version too old" sys.exit(1) if ret == 2: botan_version_minor = 11 print >> sys.stderr, "Botan version 11 not yet supported" sys.exit(1) if ret != 0: print >> sys.stderr, "Botan test failed" sys.exit(1) else: botan_version_minor = 10 # Botan ECC support if enable_ecc: if verbose: print "checking Botan ECC support" testfile = open("testecc.cpp", "w") print >>testfile, '\ #include \n\ #include \n\ #include \n\ int main() {\n\ Botan::LibraryInitializer::initialize();\n\ const std::string name("secp256r1");\n\ const Botan::OID oid(Botan::OIDS::lookup(name));\n\ const Botan::EC_Group ecg(oid);\n\ try {\n\ const Botan::SecureVector der =\n\ ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID);\n\ } catch(...) {\n\ return 1;\n\ }\n\ return 0;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testecc.cpp", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testecc.exe"): print >> sys.stderr, "can't create .\\testecc.exe" sys.exit(1) if subprocess.call(".\\testecc.exe") != 0: print >> sys.stderr, \ "can't find P256: upgrade to Botan >= 1.10.6" sys.exit(1) # Botan GOST support if enable_gost: if verbose: print "checking Botan GOST support" testfile = open("testgost.cpp", "w") print >>testfile, '\ #include \n\ #include \n\ #include \n\ int main() {\n\ Botan::LibraryInitializer::initialize();\n\ const std::string name("gost_256A");\n\ const Botan::OID oid(Botan::OIDS::lookup(name));\n\ const Botan::EC_Group ecg(oid);\n\ try {\n\ const Botan::SecureVector der =\n\ ecg.DER_encode(Botan::EC_DOMPAR_ENC_OID);\n\ } catch(...) {\n\ return 1;\n\ }\n\ return 0;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testgost.cpp", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testgost.exe"): print >> sys.stderr, "can't create .\\testgost.exe" sys.exit(1) if subprocess.call(".\\testgost.exe") != 0: print >> sys.stderr, \ "can't find GOST: upgrade to Botan >= 1.10.6" sys.exit(1) # no check for Botan RFC3394 support condvals["RFC3394"] = True # Botan RFC5649 support if verbose: print "checking Botan RFC5649 support" testfile = open("testrfc5649.cpp", "w") print >>testfile, '\ #include \n\ #include \n\ int main() {\n\ using namespace Botan;\n\ SecureVector key(10);\n\ SymmetricKey kek("AABB");\n\ Algorithm_Factory& af = global_state().algorithm_factory();\n\ SecureVector x = rfc5649_keywrap(key, kek, af);\n\ return 1;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testrfc5649.cpp", lib] command.extend(system_libs) subprocess.call(command) if not os.path.exists(".\\testrfc5649.exe"): if verbose: print "Found AES key wrap with pad" condvals["RFC5649"] = True else: if verbose: print "can't compile Botan AES key wrap with pad" # Botan GNU MP support if botan_version_minor == 10: if verbose: print "checking Botan GNU MP support" testfile = open("testgnump.cpp", "w") print >>testfile, '\ #include \n\ int main() {\n\ #ifndef BOTAN_HAS_ENGINE_GNU_MP\n\ #error "No GNU MP support";\n\ #endif\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testgnump.cpp", lib] command.extend(system_libs) subprocess.call(command) if not os.path.exists(".\\testgnump.exe"): if verbose: print "Botan GNU MP is supported" else: if verbose: print "Botan GNU MP is not supported" else: condvals["OPENSSL"] = True varvals["LIBNAME"] = "libeay32.lib" varvals["EXTRALIBS"] = "crypt32.lib;" openssl_path = os.path.abspath(openssl_path) openssl_dll = os.path.join(openssl_path, "bin\\libeay32.dll") varvals["DLLPATH"] = openssl_dll openssl_inc = os.path.join(openssl_path, "include") if not os.path.exists(os.path.join(openssl_inc, "openssl\\ssl.h")): print >> sys.stderr, "can't find OpenSSL headers" sys.exit(1) varvals["INCLUDEPATH"] = openssl_inc openssl_lib = os.path.join(openssl_path, "lib") if not os.path.exists(os.path.join(openssl_lib, "libeay32.lib")): print >> sys.stderr, "can't find OpenSSL library" sys.exit(1) varvals["LIBPATH"] = openssl_lib if enable_debug: debug_openssl_path = os.path.abspath(debug_openssl_path) varvals["DEBUGDLLPATH"] = \ os.path.join(debug_openssl_path, "bin\\libeay32.dll") debug_openssl_inc = os.path.join(debug_openssl_path, "include") if not os.path.exists(os.path.join(debug_openssl_inc, "openssl\\ssl.h")): print >> sys.stderr, "can't find debug OpenSSL headers" sys.exit(1) varvals["DEBUGINCPATH"] = debug_openssl_inc debug_openssl_lib = os.path.join(debug_openssl_path, "lib") if not os.path.exists(os.path.join(debug_openssl_lib, "libeay32.lib")): print >> sys.stderr, "can't find debug OpenSSL library" sys.exit(1) varvals["DEBUGLIBPATH"] = debug_openssl_lib else: varvals["DEBUGDLLPATH"] = varvals["DLLPATH"] varvals["DEBUGINCPATH"] = varvals["INCLUDEPATH"] varvals["DEBUGLIBPATH"] = varvals["LIBPATH"] # OpenSSL support if verbose: print "checking OpenSSL" system_libs = [] if os.path.exists(openssl_dll): subprocess.call(["copy", openssl_dll, "."], shell=True) else: system_libs = ["user32.lib", "advapi32.lib", "gdi32.lib", "crypt32.lib"] inc = openssl_inc lib = os.path.join(openssl_lib, "libeay32.lib") testfile = open("testossl.c", "w") print >>testfile, '\ #include \n\ int main() {\n\ ERR_clear_error();\n\ return 0;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testossl.c", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testossl.exe"): print >> sys.stderr, "can't create .\\testossl.exe" sys.exit(1) if subprocess.call(".\\testossl.exe") != 0: print >> sys.stderr, "OpenSSL test failed" sys.exit(1) # OpenSSL version if verbose: print "checking OpenSSL version" testfile = open("testosslv.c", "w") print >>testfile, '\ #include \n\ #include \n\ int main() {\n\ #ifndef OPENSSL_VERSION_NUMBER\n\ return -1;\n\ #endif\n\ #if OPENSSL_VERSION_NUMBER >= 0x010000000L\n\ return 0;\n\ #else\n\ return 1;\n\ #endif\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testosslv.c", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testosslv.exe"): print >> sys.stderr, "can't create .\\testosslv.exe" sys.exit(1) if subprocess.call(".\\testosslv.exe") != 0: print >> sys.stderr, \ "OpenSLL version too old (1.0.0 or later required)" sys.exit(1) # OpenSSL ECC support if enable_ecc: if verbose: print "checking OpenSSL ECC support" testfile = open("testecc.c", "w") print >>testfile, '\ #include \n\ #include \n\ int main() {\n\ EC_KEY *ec256, *ec384;\n\ ec256 = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);\n\ ec384 = EC_KEY_new_by_curve_name(NID_secp384r1);\n\ if (ec256 == NULL || ec384 == NULL)\n\ return 1;\n\ return 0;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testecc.c", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testecc.exe"): print >> sys.stderr, "can't create .\\testecc.exe" sys.exit(1) if subprocess.call(".\\testecc.exe") != 0: print >> sys.stderr, "can't find P256 or P384: no ECC support" sys.exit(1) # OpenSSL GOST support if enable_gost: if verbose: print "checking OpenSSL GOST support" testfile = open("testgost.c", "w") print >>testfile, '\ #include \n\ #include \n\ int main() {\n\ ENGINE *e;\n\ EC_KEY *ek;\n\ ek = NULL;\n\ OPENSSL_config(NULL);\n\ e = ENGINE_by_id("gost");\n\ if (e == NULL)\n\ return 1;\n\ if (ENGINE_init(e) <= 0)\n\ return 1;\n\ return 0;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testgost.c", lib] command.extend(system_libs) subprocess.check_output(command, stderr=subprocess.STDOUT) if not os.path.exists(".\\testgost.exe"): print >> sys.stderr, "can't create .\\testgost.exe" sys.exit(1) if subprocess.call(".\\testgost.exe") != 0: print >> sys.stderr, "can't find GOST: no GOST support" sys.exit(1) # OpenSSL EVP interface for AES key wrapping (aka RFC 3394) if verbose: print "checking OpenSSL EVP interface for AES key wrapping" testfile = open("testrfc3394.c", "w") print >>testfile, '\ #include \n\ int main() {\n\ EVP_aes_128_wrap();\n\ return 1;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testrfc3394.c", lib] command.extend(system_libs) subprocess.call(command) if os.path.exists(".\\testrfc3394.exe"): if verbose: print "RFC 3394 is supported" condvals["RFC3394"] = True else: if verbose: print "can't compile OpenSSL RFC 3394" # OpenSSL EVP interface for AES key wrap with pad (aka RFC 5649) if verbose: print "checking OpenSSL EVP interface for AES key wrapping with pad" testfile = open("testrfc5649.c", "w") print >>testfile, '\ #include \n\ int main() {\n\ EVP_aes_128_wrap_pad();\n\ return 1;\n\ }' testfile.close() command = ["cl", "/nologo", "/MD", "/I", inc, "testrfc5649.c", lib] command.extend(system_libs) subprocess.call(command) if os.path.exists(".\\testrfc5649.exe"): if verbose: print "RFC 5649 is supported" condvals["RFC5649"] = True else: if verbose: print "can't compile OpenSSL RFC 5649" # configure CppUnit if want_tests: condvals["TESTS"] = True cppunit_path = os.path.abspath(cppunit_path) cppunit_inc = os.path.join(cppunit_path, "include") if not os.path.exists(os.path.join(cppunit_inc, "cppunit\\Test.h")): print >> sys.stderr, "can't find CppUnit headers" sys.exit(1) varvals["CUINCPATH"] = cppunit_inc cppunit_lib = os.path.join(cppunit_path, "lib") if not os.path.exists(os.path.join(cppunit_lib, "cppunit.lib")): cppunit_lib = cppunit_path if not os.path.exists(os.path.join(cppunit_lib, "cppunit.lib")): print >> sys.stderr, "can't find CppUnit library" sys.exit(1) if enable_debug: if not os.path.exists(os.path.join(cppunit_lib, "cppunitd.lib")): print >> sys.stderr, "can't find debug CppUnit library" sys.exit(1) varvals["CULIBPATH"] = cppunit_lib # misc if enable_non_paged: condvals["NONPAGE"] = True def kw(path): """escape spaces""" if re.search(r' ', path): return '"' + path + '"' else: return path def setupfile(filename): """setup files with condition stacks and variable expansions""" cond = "@@@" conds = [] passing = True passes = [] filein = open(filename + ".in", "r") fileout = open(filename, "w") for line in filein: line = line.rstrip("\r\n") cif = re.match(r'@IF (.*)', line) if cif: conds.append(cond) passes.append(passing) cond = cif.group(1) if condvals.get(cond): # do nothing pass else: passing = False continue celse = re.match(r'@ELSE (.*)', line) if celse: if cond != celse.group(1): raise SyntaxError("@ELSE " + celse.group(1) + " mismatch in " + filename) if condvals.get(cond): passing = False else: if len(passes) > 0: passing = passes[-1] else: passing = True continue cend = re.match(r'@END (.*)', line) if cend: if cond != cend.group(1): raise SyntaxError("@END " + cend.group(1) + " mismatch in " + filename) cond = conds.pop() if len(passes) > 0: passing = passes.pop() else: passing = True continue if not passing: continue while True: vm = re.match(r'([^@]*)@([^@ ]*)@(.*)', line) if vm: if vm.group(2) in varnames: if varvals.get(vm.group(2)): val = kw(varvals[vm.group(2)]) else: val = "" line = vm.group(1) + val + vm.group(3) continue else: raise SyntaxError("unknown control @" + vm.group(2) + "@ in " + filename) break print >>fileout, line if verbose: print "Setting up " + filename filein.close() fileout.close() def main(args): """run it""" # no arguments -> usage if len(args) <= 1: for line in usage: print line sys.exit(1) parseargs(args[1:]) if want_help: dohelp() if want_clean: doclean() if want_unknown: dounknown() # status before config if verbose: if enable_keep: print "keep: enabled" else: print "keep: disabled" if platform == 64: print "64bit: enabled" else: print "64bit: disabled" if enable_debug: print "debug: enabled" else: print "debug: disabled" if enable_ecc: print "ecc: enabled" else: print "ecc: disabled" if enable_gost: print "gost: enabled" else: print "gost: disabled" if enable_non_paged: print "non-paged-memory: enabled" else: print "non-paged-memory: disabled" print "crypto-backend: " + crypto_backend if crypto_backend == "botan": print "botan-path: " + botan_path if enable_debug: print "debug-botan-path: " + debug_botan_path else: print "openssl-path: " + openssl_path if enable_debug: print "debug-openssl-path: " + debug_openssl_path if want_tests: print "cppunit-path: " + cppunit_path doconfig() # status after config if verbose: print "Configuration Status" print "\tconditions:" for name in condnames: if condvals.get(name): print "\t\t" + name + " is true" else: print "\t\t" + name + " is false" print "\tsubstitutions:" for name in varnames: if varvals.get(name): print "\t\t" + name + '-> "' + varvals[name] + '"' print for filename in filelist: setupfile(filename) # clean test file if not enable_keep: cleantest() print "Configured." sys.exit(0) main(sys.argv) # Notes: Unix configure.ac options # --enable-64bit supported # --enable-ecc supported # --enable-gost supported # --enable-non-paged-memory supported # --enable-visibility (enforced by DLLs) # --with-crypto-backend supported # --with-botan supported (Release and Debug) # --with-openssl supported (Release and Debug) # --with-migrate (useless as SoftHSMv1 is not supported) # --with-objectstore-backend-db (TODO) # --with-sqlite3 (useless until objectstore backend can be chosen) softhsm-2.0.0/aclocal.m40000664000175000017500000012347412552216617012001 00000000000000# generated automatically by aclocal 1.14.1 -*- Autoconf -*- # Copyright (C) 1996-2013 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.69],, [m4_warning([this file was generated for autoconf 2.69. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically 'autoreconf'.])]) # Copyright (C) 2002-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_AUTOMAKE_VERSION(VERSION) # ---------------------------- # Automake X.Y traces this macro to ensure aclocal.m4 has been # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version='1.14' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. m4_if([$1], [1.14.1], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) # _AM_AUTOCONF_VERSION(VERSION) # ----------------------------- # aclocal traces this macro to find the Autoconf version. # This is a private macro too. Using m4_define simplifies # the logic in aclocal, which can simply ignore this definition. m4_define([_AM_AUTOCONF_VERSION], []) # AM_SET_CURRENT_AUTOMAKE_VERSION # ------------------------------- # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], [AM_AUTOMAKE_VERSION([1.14.1])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # AM_AUX_DIR_EXPAND -*- Autoconf -*- # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets # $ac_aux_dir to '$srcdir/foo'. In other projects, it is set to # '$srcdir', '$srcdir/..', or '$srcdir/../..'. # # Of course, Automake must honor this variable whenever it calls a # tool from the auxiliary directory. The problem is that $srcdir (and # therefore $ac_aux_dir as well) can be either absolute or relative, # depending on how configure is run. This is pretty annoying, since # it makes $ac_aux_dir quite unusable in subdirectories: in the top # source directory, any form will work fine, but in subdirectories a # relative path needs to be adjusted first. # # $ac_aux_dir/missing # fails when called from a subdirectory if $ac_aux_dir is relative # $top_srcdir/$ac_aux_dir/missing # fails if $ac_aux_dir is absolute, # fails when called from a subdirectory in a VPATH build with # a relative $ac_aux_dir # # The reason of the latter failure is that $top_srcdir and $ac_aux_dir # are both prefixed by $srcdir. In an in-source build this is usually # harmless because $srcdir is '.', but things will broke when you # start a VPATH build or use an absolute $srcdir. # # So we could use something similar to $top_srcdir/$ac_aux_dir/missing, # iff we strip the leading $srcdir from $ac_aux_dir. That would be: # am_aux_dir='\$(top_srcdir)/'`expr "$ac_aux_dir" : "$srcdir//*\(.*\)"` # and then we would define $MISSING as # MISSING="\${SHELL} $am_aux_dir/missing" # This will work as long as MISSING is not called from configure, because # unfortunately $(top_srcdir) has no meaning in configure. # However there are other variables, like CC, which are often used in # configure, and could therefore not use this "fixed" $ac_aux_dir. # # Another solution, used here, is to always expand $ac_aux_dir to an # absolute PATH. The drawback is that using absolute paths prevent a # configured tree to be moved without reconfiguration. AC_DEFUN([AM_AUX_DIR_EXPAND], [dnl Rely on autoconf to set up CDPATH properly. AC_PREREQ([2.50])dnl # expand $ac_aux_dir to an absolute path am_aux_dir=`cd $ac_aux_dir && pwd` ]) # AM_CONDITIONAL -*- Autoconf -*- # Copyright (C) 1997-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_CONDITIONAL(NAME, SHELL-CONDITION) # ------------------------------------- # Define a conditional. AC_DEFUN([AM_CONDITIONAL], [AC_PREREQ([2.52])dnl m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl AC_SUBST([$1_TRUE])dnl AC_SUBST([$1_FALSE])dnl _AM_SUBST_NOTMAKE([$1_TRUE])dnl _AM_SUBST_NOTMAKE([$1_FALSE])dnl m4_define([_AM_COND_VALUE_$1], [$2])dnl if $2; then $1_TRUE= $1_FALSE='#' else $1_TRUE='#' $1_FALSE= fi AC_CONFIG_COMMANDS_PRE( [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then AC_MSG_ERROR([[conditional "$1" was never defined. Usually this means the macro was only invoked conditionally.]]) fi])]) # Copyright (C) 1999-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # There are a few dirty hacks below to avoid letting 'AC_PROG_CC' be # written in clear, in which case automake, when reading aclocal.m4, # will think it sees a *use*, and therefore will trigger all it's # C support machinery. Also note that it means that autoscan, seeing # CC etc. in the Makefile, will ask for an AC_PROG_CC use... # _AM_DEPENDENCIES(NAME) # ---------------------- # See how the compiler implements dependency checking. # NAME is "CC", "CXX", "OBJC", "OBJCXX", "UPC", or "GJC". # We try a few techniques and use that to set a single cache variable. # # We don't AC_REQUIRE the corresponding AC_PROG_CC since the latter was # modified to invoke _AM_DEPENDENCIES(CC); we would have a circular # dependency, and given that the user is not expected to run this macro, # just rely on AC_PROG_CC. AC_DEFUN([_AM_DEPENDENCIES], [AC_REQUIRE([AM_SET_DEPDIR])dnl AC_REQUIRE([AM_OUTPUT_DEPENDENCY_COMMANDS])dnl AC_REQUIRE([AM_MAKE_INCLUDE])dnl AC_REQUIRE([AM_DEP_TRACK])dnl m4_if([$1], [CC], [depcc="$CC" am_compiler_list=], [$1], [CXX], [depcc="$CXX" am_compiler_list=], [$1], [OBJC], [depcc="$OBJC" am_compiler_list='gcc3 gcc'], [$1], [OBJCXX], [depcc="$OBJCXX" am_compiler_list='gcc3 gcc'], [$1], [UPC], [depcc="$UPC" am_compiler_list=], [$1], [GCJ], [depcc="$GCJ" am_compiler_list='gcc3 gcc'], [depcc="$$1" am_compiler_list=]) AC_CACHE_CHECK([dependency style of $depcc], [am_cv_$1_dependencies_compiler_type], [if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up # making a dummy file named 'D' -- because '-MD' means "put the output # in D". rm -rf conftest.dir mkdir conftest.dir # Copy depcomp to subdir because otherwise we won't find it if we're # using a relative directory. cp "$am_depcomp" conftest.dir cd conftest.dir # We will build objects and dependencies in a subdirectory because # it helps to detect inapplicable dependency modes. For instance # both Tru64's cc and ICC support -MD to output dependencies as a # side effect of compilation, but ICC will put the dependencies in # the current directory while Tru64 will put them in the object # directory. mkdir sub am_cv_$1_dependencies_compiler_type=none if test "$am_compiler_list" = ""; then am_compiler_list=`sed -n ['s/^#*\([a-zA-Z0-9]*\))$/\1/p'] < ./depcomp` fi am__universal=false m4_case([$1], [CC], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac], [CXX], [case " $depcc " in #( *\ -arch\ *\ -arch\ *) am__universal=true ;; esac]) for depmode in $am_compiler_list; do # Setup a source with many dependencies, because some compilers # like to wrap large dependency lists on column 80 (with \), and # we should not choose a depcomp mode which is confused by this. # # We need to recreate these files for each test, as the compiler may # overwrite some of them when testing with obscure command lines. # This happens at least with the AIX C compiler. : > sub/conftest.c for i in 1 2 3 4 5 6; do echo '#include "conftst'$i'.h"' >> sub/conftest.c # Using ": > sub/conftst$i.h" creates only sub/conftst1.h with # Solaris 10 /bin/sh. echo '/* dummy */' > sub/conftst$i.h done echo "${am__include} ${am__quote}sub/conftest.Po${am__quote}" > confmf # We check with '-c' and '-o' for the sake of the "dashmstdout" # mode. It turns out that the SunPro C++ compiler does not properly # handle '-M -o', and we need to detect this. Also, some Intel # versions had trouble with output in subdirs. am__obj=sub/conftest.${OBJEXT-o} am__minus_obj="-o $am__obj" case $depmode in gcc) # This depmode causes a compiler race in universal mode. test "$am__universal" = false || continue ;; nosideeffect) # After this tag, mechanisms are not by side-effect, so they'll # only be used when explicitly requested. if test "x$enable_dependency_tracking" = xyes; then continue else break fi ;; msvc7 | msvc7msys | msvisualcpp | msvcmsys) # This compiler won't grok '-c -o', but also, the minuso test has # not run yet. These depmodes are late enough in the game, and # so weak that their functioning should not be impacted. am__obj=conftest.${OBJEXT-o} am__minus_obj= ;; none) break ;; esac if depmode=$depmode \ source=sub/conftest.c object=$am__obj \ depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \ $SHELL ./depcomp $depcc -c $am__minus_obj sub/conftest.c \ >/dev/null 2>conftest.err && grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 && grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 && grep $am__obj sub/conftest.Po > /dev/null 2>&1 && ${MAKE-make} -s -f confmf > /dev/null 2>&1; then # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. # When given -MP, icc 7.0 and 7.1 complain thusly: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported if (grep 'ignoring option' conftest.err || grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else am_cv_$1_dependencies_compiler_type=$depmode break fi fi done cd .. rm -rf conftest.dir else am_cv_$1_dependencies_compiler_type=none fi ]) AC_SUBST([$1DEPMODE], [depmode=$am_cv_$1_dependencies_compiler_type]) AM_CONDITIONAL([am__fastdep$1], [ test "x$enable_dependency_tracking" != xno \ && test "$am_cv_$1_dependencies_compiler_type" = gcc3]) ]) # AM_SET_DEPDIR # ------------- # Choose a directory name for dependency files. # This macro is AC_REQUIREd in _AM_DEPENDENCIES. AC_DEFUN([AM_SET_DEPDIR], [AC_REQUIRE([AM_SET_LEADING_DOT])dnl AC_SUBST([DEPDIR], ["${am__leading_dot}deps"])dnl ]) # AM_DEP_TRACK # ------------ AC_DEFUN([AM_DEP_TRACK], [AC_ARG_ENABLE([dependency-tracking], [dnl AS_HELP_STRING( [--enable-dependency-tracking], [do not reject slow dependency extractors]) AS_HELP_STRING( [--disable-dependency-tracking], [speeds up one-time build])]) if test "x$enable_dependency_tracking" != xno; then am_depcomp="$ac_aux_dir/depcomp" AMDEPBACKSLASH='\' am__nodep='_no' fi AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno]) AC_SUBST([AMDEPBACKSLASH])dnl _AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl AC_SUBST([am__nodep])dnl _AM_SUBST_NOTMAKE([am__nodep])dnl ]) # Generate code to set up dependency tracking. -*- Autoconf -*- # Copyright (C) 1999-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_OUTPUT_DEPENDENCY_COMMANDS # ------------------------------ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS], [{ # Older Autoconf quotes --file arguments for eval, but not when files # are listed without --file. Let's play safe and only enable the eval # if we detect the quoting. case $CONFIG_FILES in *\'*) eval set x "$CONFIG_FILES" ;; *) set x $CONFIG_FILES ;; esac shift for mf do # Strip MF so we end up with the name of the file. mf=`echo "$mf" | sed -e 's/:.*$//'` # Check whether this is an Automake generated Makefile or not. # We used to match only the files named 'Makefile.in', but # some people rename them; so instead we look at the file content. # Grep'ing the first line is not enough: some people post-process # each Makefile.in and add a new line on top of each file to say so. # Grep'ing the whole file is not good either: AIX grep has a line # limit of 2048, but all sed's we know have understand at least 4000. if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then dirpart=`AS_DIRNAME("$mf")` else continue fi # Extract the definition of DEPDIR, am__include, and am__quote # from the Makefile without running 'make'. DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"` test -z "$DEPDIR" && continue am__include=`sed -n 's/^am__include = //p' < "$mf"` test -z "$am__include" && continue am__quote=`sed -n 's/^am__quote = //p' < "$mf"` # Find all dependency output files, they are included files with # $(DEPDIR) in their names. We invoke sed twice because it is the # simplest approach to changing $(DEPDIR) to its actual value in the # expansion. for file in `sed -n " s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \ sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g'`; do # Make sure the directory exists. test -f "$dirpart/$file" && continue fdir=`AS_DIRNAME(["$file"])` AS_MKDIR_P([$dirpart/$fdir]) # echo "creating $dirpart/$file" echo '# dummy' > "$dirpart/$file" done done } ])# _AM_OUTPUT_DEPENDENCY_COMMANDS # AM_OUTPUT_DEPENDENCY_COMMANDS # ----------------------------- # This macro should only be invoked once -- use via AC_REQUIRE. # # This code is only required when automatic dependency tracking # is enabled. FIXME. This creates each '.P' file that we will # need in order to bootstrap the dependency handling code. AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], [AC_CONFIG_COMMANDS([depfiles], [test x"$AMDEP_TRUE" != x"" || _AM_OUTPUT_DEPENDENCY_COMMANDS], [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"]) ]) # Do all the work for Automake. -*- Autoconf -*- # Copyright (C) 1996-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This macro actually does too much. Some checks are only needed if # your package does certain things. But this isn't really a big deal. dnl Redefine AC_PROG_CC to automatically invoke _AM_PROG_CC_C_O. m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC]) [_AM_PROG_CC_C_O ]) # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE]) # AM_INIT_AUTOMAKE([OPTIONS]) # ----------------------------------------------- # The call with PACKAGE and VERSION arguments is the old style # call (pre autoconf-2.50), which is being phased out. PACKAGE # and VERSION should now be passed to AC_INIT and removed from # the call to AM_INIT_AUTOMAKE. # We support both call styles for the transition. After # the next Automake release, Autoconf can make the AC_INIT # arguments mandatory, and then we can depend on a new Autoconf # release and drop the old call support. AC_DEFUN([AM_INIT_AUTOMAKE], [AC_PREREQ([2.65])dnl dnl Autoconf wants to disallow AM_ names. We explicitly allow dnl the ones we care about. m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl AC_REQUIRE([AC_PROG_INSTALL])dnl if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl # test to see if srcdir already configured if test -f $srcdir/config.status; then AC_MSG_ERROR([source directory already configured; run "make distclean" there first]) fi fi # test whether we have cygpath if test -z "$CYGPATH_W"; then if (cygpath --version) >/dev/null 2>/dev/null; then CYGPATH_W='cygpath -w' else CYGPATH_W=echo fi fi AC_SUBST([CYGPATH_W]) # Define the identity of the package. dnl Distinguish between old-style and new-style calls. m4_ifval([$2], [AC_DIAGNOSE([obsolete], [$0: two- and three-arguments forms are deprecated.]) m4_ifval([$3], [_AM_SET_OPTION([no-define])])dnl AC_SUBST([PACKAGE], [$1])dnl AC_SUBST([VERSION], [$2])], [_AM_SET_OPTIONS([$1])dnl dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT. m4_if( m4_ifdef([AC_PACKAGE_NAME], [ok]):m4_ifdef([AC_PACKAGE_VERSION], [ok]), [ok:ok],, [m4_fatal([AC_INIT should be called with package and version arguments])])dnl AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl _AM_IF_OPTION([no-define],, [AC_DEFINE_UNQUOTED([PACKAGE], ["$PACKAGE"], [Name of package]) AC_DEFINE_UNQUOTED([VERSION], ["$VERSION"], [Version number of package])])dnl # Some tools Automake needs. AC_REQUIRE([AM_SANITY_CHECK])dnl AC_REQUIRE([AC_ARG_PROGRAM])dnl AM_MISSING_PROG([ACLOCAL], [aclocal-${am__api_version}]) AM_MISSING_PROG([AUTOCONF], [autoconf]) AM_MISSING_PROG([AUTOMAKE], [automake-${am__api_version}]) AM_MISSING_PROG([AUTOHEADER], [autoheader]) AM_MISSING_PROG([MAKEINFO], [makeinfo]) AC_REQUIRE([AM_PROG_INSTALL_SH])dnl AC_REQUIRE([AM_PROG_INSTALL_STRIP])dnl AC_REQUIRE([AC_PROG_MKDIR_P])dnl # For better backward compatibility. To be removed once Automake 1.9.x # dies out for good. For more background, see: # # AC_SUBST([mkdir_p], ['$(MKDIR_P)']) # We need awk for the "check" target. The system "awk" is bad on # some platforms. AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], [_AM_PROG_TAR([v7])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], [m4_define([AC_PROG_CC], m4_defn([AC_PROG_CC])[_AM_DEPENDENCIES([CC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_CXX], [_AM_DEPENDENCIES([CXX])], [m4_define([AC_PROG_CXX], m4_defn([AC_PROG_CXX])[_AM_DEPENDENCIES([CXX])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJC], [_AM_DEPENDENCIES([OBJC])], [m4_define([AC_PROG_OBJC], m4_defn([AC_PROG_OBJC])[_AM_DEPENDENCIES([OBJC])])])dnl AC_PROVIDE_IFELSE([AC_PROG_OBJCXX], [_AM_DEPENDENCIES([OBJCXX])], [m4_define([AC_PROG_OBJCXX], m4_defn([AC_PROG_OBJCXX])[_AM_DEPENDENCIES([OBJCXX])])])dnl ]) AC_REQUIRE([AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl # POSIX will say in a future version that running "rm -f" with no argument # is OK; and we want to be able to make that assumption in our Makefile # recipes. So use an aggressive probe to check that the usage we want is # actually supported "in the wild" to an acceptable degree. # See automake bug#10828. # To make any issue more visible, cause the running configure to be aborted # by default if the 'rm' program in use doesn't match our expectations; the # user can still override this though. if rm -f && rm -fr && rm -rf; then : OK; else cat >&2 <<'END' Oops! Your 'rm' program seems unable to run without file operands specified on the command line, even when the '-f' option is present. This is contrary to the behaviour of most rm programs out there, and not conforming with the upcoming POSIX standard: Please tell bug-automake@gnu.org about your system, including the value of your $PATH and any error possibly output before this message. This can help us improve future automake versions. END if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then echo 'Configuration will proceed anyway, since you have set the' >&2 echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 echo >&2 else cat >&2 <<'END' Aborting the configuration process, to ensure you take notice of the issue. You can download and install GNU coreutils to get an 'rm' implementation that behaves properly: . If you want to complete the configuration process using your problematic 'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM to "yes", and re-run configure. END AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) fi fi]) dnl Hook into '_AC_COMPILER_EXEEXT' early to learn its expansion. Do not dnl add the conditional right here, as _AC_COMPILER_EXEEXT may be further dnl mangled by Autoconf and run in a shell conditional statement. m4_define([_AC_COMPILER_EXEEXT], m4_defn([_AC_COMPILER_EXEEXT])[m4_provide([_AM_COMPILER_EXEEXT])]) # When config.status generates a header, we must update the stamp-h file. # This file resides in the same directory as the config header # that is generated. The stamp files are numbered to have different names. # Autoconf calls _AC_AM_CONFIG_HEADER_HOOK (when defined) in the # loop where config.status creates the headers, so we can generate # our stamp files there. AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK], [# Compute $1's index in $config_headers. _am_arg=$1 _am_stamp_count=1 for _am_header in $config_headers :; do case $_am_header in $_am_arg | $_am_arg:* ) break ;; * ) _am_stamp_count=`expr $_am_stamp_count + 1` ;; esac done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_SH # ------------------ # Define $install_sh. AC_DEFUN([AM_PROG_INSTALL_SH], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl if test x"${install_sh}" != xset; then case $am_aux_dir in *\ * | *\ *) install_sh="\${SHELL} '$am_aux_dir/install-sh'" ;; *) install_sh="\${SHELL} $am_aux_dir/install-sh" esac fi AC_SUBST([install_sh])]) # Copyright (C) 2003-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # Check whether the underlying file-system supports filenames # with a leading dot. For instance MS-DOS doesn't. AC_DEFUN([AM_SET_LEADING_DOT], [rm -rf .tst 2>/dev/null mkdir .tst 2>/dev/null if test -d .tst; then am__leading_dot=. else am__leading_dot=_ fi rmdir .tst 2>/dev/null AC_SUBST([am__leading_dot])]) # Check to see how 'make' treats includes. -*- Autoconf -*- # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MAKE_INCLUDE() # ----------------- # Check to see how make treats includes. AC_DEFUN([AM_MAKE_INCLUDE], [am_make=${MAKE-make} cat > confinc << 'END' am__doit: @echo this is the am__doit target .PHONY: am__doit END # If we don't find an include directive, just comment out the code. AC_MSG_CHECKING([for style of include used by $am_make]) am__include="#" am__quote= _am_result=none # First try GNU make style include. echo "include confinc" > confmf # Ignore all kinds of additional output from 'make'. case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=include am__quote= _am_result=GNU ;; esac # Now try BSD make style include. if test "$am__include" = "#"; then echo '.include "confinc"' > confmf case `$am_make -s -f confmf 2> /dev/null` in #( *the\ am__doit\ target*) am__include=.include am__quote="\"" _am_result=BSD ;; esac fi AC_SUBST([am__include]) AC_SUBST([am__quote]) AC_MSG_RESULT([$_am_result]) rm -f confinc confmf ]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- # Copyright (C) 1997-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_MISSING_PROG(NAME, PROGRAM) # ------------------------------ AC_DEFUN([AM_MISSING_PROG], [AC_REQUIRE([AM_MISSING_HAS_RUN]) $1=${$1-"${am_missing_run}$2"} AC_SUBST($1)]) # AM_MISSING_HAS_RUN # ------------------ # Define MISSING if not defined so far and test if it is modern enough. # If it is, set am_missing_run to use it, otherwise, to nothing. AC_DEFUN([AM_MISSING_HAS_RUN], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([missing])dnl if test x"${MISSING+set}" != xset; then case $am_aux_dir in *\ * | *\ *) MISSING="\${SHELL} \"$am_aux_dir/missing\"" ;; *) MISSING="\${SHELL} $am_aux_dir/missing" ;; esac fi # Use eval to expand $SHELL if eval "$MISSING --is-lightweight"; then am_missing_run="$MISSING " else am_missing_run= AC_MSG_WARN(['missing' script is too old or missing]) fi ]) # Helper functions for option handling. -*- Autoconf -*- # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_MANGLE_OPTION(NAME) # ----------------------- AC_DEFUN([_AM_MANGLE_OPTION], [[_AM_OPTION_]m4_bpatsubst($1, [[^a-zA-Z0-9_]], [_])]) # _AM_SET_OPTION(NAME) # -------------------- # Set option NAME. Presently that only means defining a flag for this option. AC_DEFUN([_AM_SET_OPTION], [m4_define(_AM_MANGLE_OPTION([$1]), [1])]) # _AM_SET_OPTIONS(OPTIONS) # ------------------------ # OPTIONS is a space-separated list of Automake options. AC_DEFUN([_AM_SET_OPTIONS], [m4_foreach_w([_AM_Option], [$1], [_AM_SET_OPTION(_AM_Option)])]) # _AM_IF_OPTION(OPTION, IF-SET, [IF-NOT-SET]) # ------------------------------------------- # Execute IF-SET if OPTION is set, IF-NOT-SET otherwise. AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) # Copyright (C) 1999-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_CC_C_O # --------------- # Like AC_PROG_CC_C_O, but changed for automake. We rewrite AC_PROG_CC # to automatically call this. AC_DEFUN([_AM_PROG_CC_C_O], [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl AC_REQUIRE_AUX_FILE([compile])dnl AC_LANG_PUSH([C])dnl AC_CACHE_CHECK( [whether $CC understands -c and -o together], [am_cv_prog_cc_c_o], [AC_LANG_CONFTEST([AC_LANG_PROGRAM([])]) # Make sure it works both with $CC and with simple cc. # Following AC_PROG_CC_C_O, we do the test twice because some # compilers refuse to overwrite an existing .o file with -o, # though they will create one. am_cv_prog_cc_c_o=yes for am_i in 1 2; do if AM_RUN_LOG([$CC -c conftest.$ac_ext -o conftest2.$ac_objext]) \ && test -f conftest2.$ac_objext; then : OK else am_cv_prog_cc_c_o=no break fi done rm -f core conftest* unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. # FIXME: It is wrong to rewrite CC. # But if we don't then we get into trouble of one sort or another. # A longer-term fix would be to have automake use am__CC in this case, # and then we could set am__CC="\$(top_srcdir)/compile \$(CC)" CC="$am_aux_dir/compile $CC" fi AC_LANG_POP([C])]) # For backward compatibility. AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_RUN_LOG(COMMAND) # ------------------- # Run COMMAND, save the exit status in ac_status, and log it. # (This has been adapted from Autoconf's _AC_RUN_LOG macro.) AC_DEFUN([AM_RUN_LOG], [{ echo "$as_me:$LINENO: $1" >&AS_MESSAGE_LOG_FD ($1) >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ac_status=$? echo "$as_me:$LINENO: \$? = $ac_status" >&AS_MESSAGE_LOG_FD (exit $ac_status); }]) # Check to make sure that the build environment is sane. -*- Autoconf -*- # Copyright (C) 1996-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], [AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac # Do 'set' in a subshell so we don't clobber the current shell's # arguments. Must try -L first in case configure is actually a # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). if ( am_has_slept=no for am_try in 1 2; do echo "timestamp, slept: $am_has_slept" > conftest.file set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` if test "$[*]" = "X"; then # -L didn't work. set X `ls -t "$srcdir/configure" conftest.file` fi if test "$[*]" != "X $srcdir/configure conftest.file" \ && test "$[*]" != "X conftest.file $srcdir/configure"; then # If neither matched, then we have a broken ls. This can happen # if, for instance, CONFIG_SHELL is bash and it inherits a # broken ls alias from the environment. This has actually # happened. Such a system could not be considered "sane". AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken alias in your environment]) fi if test "$[2]" = conftest.file || test $am_try -eq 2; then break fi # Just in case. sleep 1 am_has_slept=yes done test "$[2]" = conftest.file ) then # Ok. : else AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi AC_MSG_RESULT([yes]) # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= if grep 'slept: no' conftest.file >/dev/null 2>&1; then ( sleep 1 ) & am_sleep_pid=$! fi AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then # Hide warnings about reused PIDs. wait $am_sleep_pid 2>/dev/null fi AC_MSG_RESULT([done])]) rm -f conftest.file ]) # Copyright (C) 2009-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_SILENT_RULES([DEFAULT]) # -------------------------- # Enable less verbose build rules; with the default set to DEFAULT # ("yes" being less verbose, "no" or empty being verbose). AC_DEFUN([AM_SILENT_RULES], [AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) case $enable_silent_rules in @%:@ ((( yes) AM_DEFAULT_VERBOSITY=0;; no) AM_DEFAULT_VERBOSITY=1;; *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. dnl See automake bug#9928 and bug#10237. am_make=${MAKE-make} AC_CACHE_CHECK([whether $am_make supports nested variables], [am_cv_make_support_nested_variables], [if AS_ECHO([['TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 am__doit: @$(TRUE) .PHONY: am__doit']]) | $am_make -f - >/dev/null 2>&1; then am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no fi]) if test $am_cv_make_support_nested_variables = yes; then dnl Using '$V' instead of '$(V)' breaks IRIX make. AM_V='$(V)' AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' else AM_V=$AM_DEFAULT_VERBOSITY AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl AM_SUBST_NOTMAKE([AM_DEFAULT_V])dnl AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl ]) # Copyright (C) 2001-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # AM_PROG_INSTALL_STRIP # --------------------- # One issue with vendor 'install' (even GNU) is that you can't # specify the program used to strip binaries. This is especially # annoying in cross-compiling environments, where the build's strip # is unlikely to handle the host's binaries. # Fortunately install-sh will honor a STRIPPROG variable, so we # always use install-sh in "make install-strip", and initialize # STRIPPROG with the value of the STRIP variable (set by the user). AC_DEFUN([AM_PROG_INSTALL_STRIP], [AC_REQUIRE([AM_PROG_INSTALL_SH])dnl # Installed binaries are usually stripped using 'strip' when the user # run "make install-strip". However 'strip' might not be the right # tool to use in cross-compilation environments, therefore Automake # will honor the 'STRIP' environment variable to overrule this program. dnl Don't test for $cross_compiling = yes, because it might be 'maybe'. if test "$cross_compiling" != no; then AC_CHECK_TOOL([STRIP], [strip], :) fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) # Copyright (C) 2006-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_SUBST_NOTMAKE(VARIABLE) # --------------------------- # Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. # This macro is traced by Automake. AC_DEFUN([_AM_SUBST_NOTMAKE]) # AM_SUBST_NOTMAKE(VARIABLE) # -------------------------- # Public sister of _AM_SUBST_NOTMAKE. AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- # Copyright (C) 2004-2013 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # _AM_PROG_TAR(FORMAT) # -------------------- # Check how to create a tarball in format FORMAT. # FORMAT should be one of 'v7', 'ustar', or 'pax'. # # Substitute a variable $(am__tar) that is a command # writing to stdout a FORMAT-tarball containing the directory # $tardir. # tardir=directory && $(am__tar) > result.tar # # Substitute a variable $(am__untar) that extract such # a tarball read from stdin. # $(am__untar) < result.tar # AC_DEFUN([_AM_PROG_TAR], [# Always define AMTAR for backward compatibility. Yes, it's still used # in the wild :-( We should find a proper way to deprecate it ... AC_SUBST([AMTAR], ['$${TAR-tar}']) # We'll loop over all known methods to create a tar archive until one works. _am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none' m4_if([$1], [v7], [am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -'], [m4_case([$1], [ustar], [# The POSIX 1988 'ustar' format is defined with fixed-size fields. # There is notably a 21 bits limit for the UID and the GID. In fact, # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 # and bug#13588). am_max_uid=2097151 # 2^21 - 1 am_max_gid=$am_max_uid # The $UID and $GID variables are not portable, so we need to resort # to the POSIX-mandated id(1) utility. Errors in the 'id' calls # below are definitely unexpected, so allow the users to see them # (that is, avoid stderr redirection). am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) if test $am_uid -le $am_max_uid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) if test $am_gid -le $am_max_gid; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none fi], [pax], [], [m4_fatal([Unknown tar format])]) AC_MSG_CHECKING([how to create a $1 tar archive]) # Go ahead even if we have the value already cached. We do so because we # need to set the values for the 'am__tar' and 'am__untar' variables. _am_tools=${am_cv_prog_tar_$1-$_am_tools} for _am_tool in $_am_tools; do case $_am_tool in gnutar) for _am_tar in tar gnutar gtar; do AM_RUN_LOG([$_am_tar --version]) && break done am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"' am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"' am__untar="$_am_tar -xf -" ;; plaintar) # Must skip GNU tar: if it does not support --format= it doesn't create # ustar tarball either. (tar --version) >/dev/null 2>&1 && continue am__tar='tar chf - "$$tardir"' am__tar_='tar chf - "$tardir"' am__untar='tar xf -' ;; pax) am__tar='pax -L -x $1 -w "$$tardir"' am__tar_='pax -L -x $1 -w "$tardir"' am__untar='pax -r' ;; cpio) am__tar='find "$$tardir" -print | cpio -o -H $1 -L' am__tar_='find "$tardir" -print | cpio -o -H $1 -L' am__untar='cpio -i -H $1 -d' ;; none) am__tar=false am__tar_=false am__untar=false ;; esac # If the value was cached, stop now. We just wanted to have am__tar # and am__untar set. test -n "${am_cv_prog_tar_$1}" && break # tar/untar a dummy directory, and stop if the command works. rm -rf conftest.dir mkdir conftest.dir echo GrepMe > conftest.dir/file AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar]) rm -rf conftest.dir if test -s conftest.tar; then AM_RUN_LOG([$am__untar /dev/null 2>&1 && break fi done rm -rf conftest.dir AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool]) AC_MSG_RESULT([$am_cv_prog_tar_$1])]) AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR m4_include([m4/acx_64bit.m4]) m4_include([m4/acx_botan.m4]) m4_include([m4/acx_botan_ecc.m4]) m4_include([m4/acx_botan_gnump.m4]) m4_include([m4/acx_botan_gost.m4]) m4_include([m4/acx_botan_rfc5649.m4]) m4_include([m4/acx_crypto_backend.m4]) m4_include([m4/acx_dlopen.m4]) m4_include([m4/acx_non_paged_memory.m4]) m4_include([m4/acx_openssl.m4]) m4_include([m4/acx_openssl_ecc.m4]) m4_include([m4/acx_openssl_fips.m4]) m4_include([m4/acx_openssl_gost.m4]) m4_include([m4/acx_openssl_rfc5649.m4]) m4_include([m4/acx_pedantic.m4]) m4_include([m4/acx_prefixhack.m4]) m4_include([m4/acx_sqlite3.m4]) m4_include([m4/acx_strict.m4]) m4_include([m4/acx_visibility.m4]) m4_include([m4/acx_yield.m4]) m4_include([m4/ax_cxx_compile_stdcxx_11.m4]) m4_include([m4/libtool.m4]) m4_include([m4/ltoptions.m4]) m4_include([m4/ltsugar.m4]) m4_include([m4/ltversion.m4]) m4_include([m4/lt~obsolete.m4])