From eca49bb06a71980ef61d078904573f25890fc7f2 Mon Sep 17 00:00:00 2001 From: zautrix Date: Tue, 19 Oct 2004 20:16:14 +0000 Subject: Initial revision --- (limited to 'pwmanager/libcrypt/crypt') diff --git a/pwmanager/libcrypt/crypt/Manifest b/pwmanager/libcrypt/crypt/Manifest new file mode 100644 index 0000000..2d003d8 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/Manifest @@ -0,0 +1,58 @@ +# Manifest - checksums of the src directory +# Copyright 2004 Free Software Foundation, Inc. +# +# This file is part of Libgcrypt. +# +# Libgcrypt is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser general Public License as +# published by the Free Software Foundation; either version 2.1 of +# the License, or (at your option) any later version. +# +# Libgcrypt is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + +# Checksums for all source files in this directory. Format is +# filename, blanks, base-64 part of an OpenPGP detached signature +# without the header lines. Blank lines and lines beginning with a +# hash mark are ignored. A tool to process this file is available by +# cvs -d :pserver:anoncvs@cvs.gnupg.org:/cvs/wk co misc-scripts/manifest-tool +# +# The special entry "$names$" holds a signature over all sorted +# filenames excluding itself. + +gcrypt.h iQCVAwUAQH5RsTEAnp832S/7AQK7xgP+Kc3NY9lipZkaAMrnHDkQVLdHYwTbZWuGOYdTLp8Xy7Auh9wtWV9hrWVUqs+kxDzT/2iF6XkO3WT3rf/PmQ/Q0TIGfOyjE3c/qvB/jVippaxoGda3tnGpODytdI3XPhfPS0Ss8nDzfCStPBGAEq0OVU7imnExrFzhRXt+Gljr0o0==Yagz +gcrypt-module.h iQCVAwUAQH5UXzEAnp832S/7AQJMQgQAzumz9aaZelhw+FxTCeVadphBxt1bbNQvMrnddYYblyJv+AcxZ9ZxGz2oPeusN58Qg54DQcaW3lYhTgnWfXultsi+Ruxlz7400OUrzSXOl3At7KssdODAoscFzZIgh94G9lzQxEBr9lTXI9R3LsPFJP6muNG4frcNBAA42yckK7w==BBp5 + +ath.c iQCVAwUAQH5E+DEAnp832S/7AQKFpgP+KSZHtVcnh9FFggIyHKbALUljW2FXauasZvFyN8Sk/mIMgKxyXFOG1THBAUzWLaKWIEWU+WkYU7uThqBtpnEImM5AenWzbQuJjftPC3gVHO8yjjmBWD4zmJj28htoKDoa/xDsoqumrHxae3FYcaCWtYGVjM/Pbl+OMRMOFAhp0ho==lQZ3 +ath.h iQCVAwUAQH5FODEAnp832S/7AQKiuQQAg4K+KOAn1LWBZN32MAhms4FeZKoce0fAuZW7BpyY4cCxIVgxqrtUC90CDykw8XegFfOyyYrgd0NmaMVdY7HZDncNOvIPxpgFQPCZrycsMOoAtoVwjK704RDeNo3zmeyxTKeDH+3M1J7JmLiafaEdSbOC8flX/W0icaV0Ol4dmBc==Ll6w + +cipher.h iQCVAwUAQH5FUzEAnp832S/7AQJKLgP9GSSk9f7EINIRqSQH1XKX+dYzt3phDHdqFTUGIfYNh7YzGdy0drvgFhG4k15nqDouKRuFVM/hKY3ZVY7JccmKXKGAH6+ZYShoG6LMFfIGgDX8zne0dNxc72PLfns3fVxNn/RlHmHBkrQ+ppjR9HnSthFmOqzbQaW1BKmc3Z2x5GU==lIeW +g10lib.h iQCVAwUAQH5FejEAnp832S/7AQJ75wP/ZjOybwRix5eoXdfVeXPjoPygejzpYJJdMUGN3Y5UtkfBu9mPREsKfvZ6tH+Evjx+3xfeAb4bU/k2mRMp0tiWnk2koToS08vI9uxnioKQr9oulZH6r28S+NLSgMQuEGN1JNUky6RQ9TTNRndeTjKKSrEjZ7V6bv+rb8A1bYCKChs==P5mk +mpi.h iQCVAwUAQH5FwzEAnp832S/7AQJJ4wP9E3jVkcO9M0YtSBHIbjG3hDWKWXzi86AlUh51qiE8/2XP0FfjA4TosyvmicZs7j48HitAByr9tHOSxnbeo7NBf17ICwAo6Eqty+wKDg+eyLeEGUy7VpVK3RJRQAA4H+kl3S2l3YMTKf3WJlbc7qkWSXZspdy5c9sAxeodCKrAubU==oALf + +global.c iQCVAwUAQH5HFzEAnp832S/7AQJc+QQAvi53ZkMCzLnVULHvhI6W+EX537zi9n8cplYguvIJqUhAZrP68yGAIyqyCONbZVDyB7wqeXdUMLzMk7W8fg+xuk5JSDpppAQf2m/bdQyze6XVqJso682eYBM8+b9z/IVEvLaFwhZcOKO1bcXudBlBCcJgVDpupfTtAWgPnewil9Q==Xwy1 +misc.c iQCVAwUAQH5IIjEAnp832S/7AQKNJAQAkEpyY3fCG7tvADJFAW9xA7DEQwLCa8YmiUhHvrEsWOI4YgvS7LUbWWc7VqK+ryORvXLKRAVieznbnHAuy0TKtqdnmA/kUmiurS0ah5SWqR/iuAeJtt0RGsmZaZ6oa2m4PZ2Y2GCHSTZqcclvwsetS9eq5AipxHxYFUltu5wGZNI==twM2 +missing-string.c iQCVAwUAQH5JfjEAnp832S/7AQI3ZQQAg55eEJbGQQHyBEJGxvt/FXpQiXcoDit3ZHzvdaQn/NUgdLjCHiWVzhyCXACGivLWMNModDaSaZk073NXxVkWfPcX9vkF//Wugwzidd5P3Bfu5k35o+Xxz82fsk5KuFGGq1mBUZ07xUYQ8KkKkhADUkr0QiQAuypp079Yq0uUC7Q==zvKn +module.c iQCVAwUAQH5JvjEAnp832S/7AQKlMgQAjZYTXMpWb5kHxCMXzRi069Ku/4/xnWsD+S0dje1LiKzCnRpwTTxARzc/y10Y8OcygkMuR4unEaWedO+9syjjty3fBCcue/j7YlLitq5EC9UE4o23poWvWCuX9Tadm2DK5qf4p7smMJ22O22cLTYTVCyAoYTQ2xC8ajzBsBRkX80==yRRD +secmem.c iQCVAwUAQH5LLDEAnp832S/7AQKtFwQAwY2wBr6WJC1cwqp/1DQoKzHx9C3plONxbZMazwR7VMI83NUbBAbv1mcxpeZWXmb2dRrnsR1VBbNPDSbJLN5T6czLQ2nIb6mnq9u8Ip4SAa+GCWfDV4AUtAJ4hN/yvWo8iEKu+KD5iJ6xJh31NdXjt5yk6vnk46SA6R4FkHdIEXc==UKVr +secmem.h iQCVAwUAQH5LTDEAnp832S/7AQIsJwQAkZUu4hvmh9NXCLNm98+tGZFzWYvZO/NffC2wdPE8Q/OTa/m3g+oBbEhaV1ze3oY4t1F/p7ZHFx5CsIp4zVjyPkxlni8AAVMUOQr/LopyxouHn2OjKO+dVqecWQf01+nPWjklbL2FZ3mQ99k2qeWZlVSkz0nm8u39F3v7z3OTCss==AJqE +sexp.c iQCVAwUAQH5LojEAnp832S/7AQKCTQQArlrj1KGwR2x93fcyN3M0iXuGkBq5R9KNu+1Bq04G4SLlpZ1RRY0OjV3L9To1BHTd01lXlO8MNz7NpRxWlG1Sw5FohbBlhWZQRcW8GdAawJPcfIY2Y8Ek6Yx8quZKbk9uD3bcBmStmg0P+TIA0nr20bmtfB3uX2KQVHQqWZQT5qU==P8FE +stdmem.c iQCVAwUAQH5LzjEAnp832S/7AQLOUAP9FU16itXBBrkfRDGmhUjAOeEEKdd+brQ3XdT8xoLvP/IH/6U1Kq3ampP2/xcL4kwVdz2rw6NRzP7jlL/yM3tW722lSS/JPJkH+2+qUkcb0fYNoql/WYPMYp1/Mzu6ttXnjag1cQGlKIyYAD+G6h3FtpLwQy0hEJopnF9+Ovd8U7A==CkiZ +stdmem.h iQCVAwUAQH5L8jEAnp832S/7AQIH0wP+Lyqh0tj++s2L79Tmf/gqgCK+HLMxTddcewF3XbsYf9T5FmLez1gz6Ggti4Ss9VjozOA3ti3trCiA/YNRmV9AYw4zLUPm+MsjJuveL/AgB9HdoD2v+RfJm0WwgSKiysp+8iyjg3Plopmhba4cGuOP5MJ3CWTqYwPmJVscUKC6g38==02MN + +types.h iQCVAwUAQH5MKTEAnp832S/7AQLqTAP6A3mUMD5MMkBkebq4bRY6Bq0KsgdKfZ8TLhc2o87gFay8YD0Uom3YJNG2LF/rAIct2ih4jYJaIb5dRfJ0KJoPi2ETd462J8OFCL4fjq9TaSjB2pXcB+kWoxzPasGNg2Ukk0dQ6lvF1tSYrtt32PVI7q/UaPsjTylgRmzLfX/VxrU==OMu3 + + +# Configuration +Makefile.am iQCVAwUAQH5WVjEAnp832S/7AQLmsQP/bbI8/UWAC5yITVhGcCOCbN/FaMqXVKjxESzo6GTs02jxK1y3RuuaoNU1ssQZGAxpFiMJW8u933V3yTHFMxWpwHemDnEyv/a8YACxJBQ0tQgpgHS716BjMbHOfcuOis2WlCOOm0ErjhAYNa4NQ1q3jwkOvTDLFpdnqaWI2wWn08U==Yjun +libgcrypt.m4 iQCVAwUAQH5MbTEAnp832S/7AQJ1uAQA1C6xI7qXiKVtUeXawhPytAldosrzcXmqz34xi7JklQqw83d68WtWHFMBEUa7MKfi4WCbuQb7FjGUvMRw5z/T9ez7CoDekHc63+cIIZLQ23weUK8GaA1uQLoD0scmT41J5RkBlJbH7ck1zRd3d04o75rWNEUNit6KBvrQ4Pd8oQ8==uMgB +libgcrypt-config.in iQCVAwUAQH5UbzEAnp832S/7AQJISgP+Nbd2AQnDM/k8sQLbvz8YZjwX3LigZM+AkF1VAwyAm6YOU3nrXnz5t+cXkQD2dkz4L2F0AAsIkFiJsrgmZgCp2h1L6LeFnH+hoId9RhbYw4NkDaHb+MC9JcalpcfFvvxq6vM/W37bSFimM78P+5RLKypXCytVQNAAaIRgZjVfXY8==IGDS +libgcrypt.vers iQCVAwUAQH5MjTEAnp832S/7AQKCdQQAotG6Z3zdcePI0V33YY2sh91uYkLBNhQw+PzyE3BRRAVhMGLOBD1nSWJHJvE3eyCVOqFY0ZmvpVex51Fa0D/TwsJOO4RVxf1L9bbAncu9OuEXaGXKytLZp54TliDTAWGDq0lvtx1TvDDgtM8TbbaXvMbjfQ4wXBxdLvaenFCTlR4==kgHq + +$names$ iQCVAwUAQH5UhDEAnp832S/7AQK/jwP9H7A3mI99M1NGuhD+16C+2gJIITB8GJeYeUd3vm8kWQ5n76WyMCdeA62qn0JUddIBjAbagtfvTL5aesnD9MlhEGaNlHauU7SINTIJ8njKf87EAAfDZrhS/tGDziC2nakMPweRxXQCLDWHkBPjYfrspSLLohjdegqBvTNyVM76+KE==3p9Z diff --git a/pwmanager/libcrypt/crypt/ath.c b/pwmanager/libcrypt/crypt/ath.c new file mode 100644 index 0000000..6788bba --- a/dev/null +++ b/pwmanager/libcrypt/crypt/ath.c @@ -0,0 +1,287 @@ +/* ath.c - Thread-safeness library. + Copyright (C) 2002, 2003, 2004 g10 Code GmbH + + This file is part of Libgcrypt. + + Libgcrypt is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation; either version 2.1 of + the License, or (at your option) any later version. + + Libgcrypt 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 Lesser General Public + License along with Libgcrypt; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + 02111-1307, USA. */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#ifdef HAVE_SYS_SELECT_H +# include +#else +# include +#endif +#include +#include +#include + +#include "ath.h" + + +/* The interface table. */ +static struct ath_ops ops; + +/* True if we should use the external callbacks. */ +static int ops_set; + + +/* For the dummy interface. */ +#define MUTEX_UNLOCKED ((ath_mutex_t) 0) +#define MUTEX_LOCKED ((ath_mutex_t) 1) +#define MUTEX_DESTROYED ((ath_mutex_t) 2) + + + +/* The lock we take while checking for lazy lock initialization. */ +static ath_mutex_t check_init_lock = ATH_MUTEX_INITIALIZER; + +int +ath_init (void) +{ + int err = 0; + + if (ops_set) + { + if (ops.init) + err = (*ops.init) (); + if (err) + return err; + err = (*ops.mutex_init) (&check_init_lock); + } + return err; +} + + +/* Initialize the locking library. Returns 0 if the operation was + successful, EINVAL if the operation table was invalid and EBUSY if + we already were initialized. */ +gpg_err_code_t +ath_install (struct ath_ops *ath_ops, int check_only) +{ + if (check_only) + { + enum ath_thread_option option = ATH_THREAD_OPTION_DEFAULT; + + /* Check if the requested thread option is compatible to the + thread option we are already committed to. */ + if (ath_ops) + option = ath_ops->option; + + if (!ops_set && option) + return GPG_ERR_NOT_SUPPORTED; + + if (ops.option == ATH_THREAD_OPTION_USER + || option == ATH_THREAD_OPTION_USER + || ops.option != option) + return GPG_ERR_NOT_SUPPORTED; + + return 0; + } + + if (ath_ops) + { + /* It is convenient to not require DESTROY. */ + if (!ath_ops->mutex_init || !ath_ops->mutex_lock + || !ath_ops->mutex_unlock) + return GPG_ERR_INV_ARG; + + ops = *ath_ops; + ops_set = 1; + } + else + ops_set = 0; + + return 0; +} + + +static int +mutex_init (ath_mutex_t *lock, int just_check) +{ + int err = 0; + + if (just_check) + (*ops.mutex_lock) (&check_init_lock); + if (*lock == ATH_MUTEX_INITIALIZER || !just_check) + err = (*ops.mutex_init) (lock); + if (just_check) + (*ops.mutex_unlock) (&check_init_lock); + return err; +} + + +int +ath_mutex_init (ath_mutex_t *lock) +{ + if (ops_set) + return mutex_init (lock, 0); + +#ifndef NDEBUG + *lock = MUTEX_UNLOCKED; +#endif + return 0; +} + + +int +ath_mutex_destroy (ath_mutex_t *lock) +{ + if (ops_set) + { + int err = mutex_init (lock, 1); + + if (err) + return err; + + if (ops.mutex_destroy) + return (*ops.mutex_destroy) (lock); + else + return 0; + } + +#ifndef NDEBUG + assert (*lock == MUTEX_UNLOCKED); + + *lock = MUTEX_DESTROYED; +#endif + return 0; +} + + +int +ath_mutex_lock (ath_mutex_t *lock) +{ + if (ops_set) + { + int ret = mutex_init (lock, 1); + if (ret) + return ret; + return (*ops.mutex_lock) (lock); + } + +#ifndef NDEBUG + assert (*lock == MUTEX_UNLOCKED); + + *lock = MUTEX_LOCKED; +#endif + return 0; +} + + +int +ath_mutex_unlock (ath_mutex_t *lock) +{ + if (ops_set) + { + int ret = mutex_init (lock, 1); + if (ret) + return ret; + return (*ops.mutex_unlock) (lock); + } + +#ifndef NDEBUG + assert (*lock == MUTEX_LOCKED); + + *lock = MUTEX_UNLOCKED; +#endif + return 0; +} + + +ssize_t +ath_read (int fd, void *buf, size_t nbytes) +{ + if (ops_set && ops.read) + return (*ops.read) (fd, buf, nbytes); + else + return read (fd, buf, nbytes); +} + + +ssize_t +ath_write (int fd, const void *buf, size_t nbytes) +{ + if (ops_set && ops.write) + return (*ops.write) (fd, buf, nbytes); + else + return write (fd, buf, nbytes); +} + + +ssize_t +ath_select (int nfd, fd_set *rset, fd_set *wset, fd_set *eset, + struct timeval *timeout) +{ + if (ops_set && ops.select) + return (*ops.select) (nfd, rset, wset, eset, timeout); + else + return select (nfd, rset, wset, eset, timeout); +} + + +ssize_t +ath_waitpid (pid_t pid, int *status, int options) +{ + if (ops_set && ops.waitpid) + return (*ops.waitpid) (pid, status, options); + else + return waitpid (pid, status, options); +} + + +int +ath_accept (int s, struct sockaddr *addr, socklen_t *length_ptr) +{ + if (ops_set && ops.accept) + return (*ops.accept) (s, addr, length_ptr); + else + return accept (s, addr, length_ptr); +} + + +int +ath_connect (int s, struct sockaddr *addr, socklen_t length) +{ + if (ops_set && ops.connect) + return (*ops.connect) (s, addr, length); + else + return connect (s, addr, length); +} + + +int +ath_sendmsg (int s, const struct msghdr *msg, int flags) +{ + if (ops_set && ops.sendmsg) + return (*ops.sendmsg) (s, msg, flags); + else + return sendmsg (s, msg, flags); +} + + +int +ath_recvmsg (int s, struct msghdr *msg, int flags) +{ + if (ops_set && ops.recvmsg) + return (*ops.recvmsg) (s, msg, flags); + else + return recvmsg (s, msg, flags); +} diff --git a/pwmanager/libcrypt/crypt/ath.h b/pwmanager/libcrypt/crypt/ath.h new file mode 100644 index 0000000..d492c2a --- a/dev/null +++ b/pwmanager/libcrypt/crypt/ath.h @@ -0,0 +1,116 @@ +/* ath.h - Thread-safeness library. + Copyright (C) 2002, 2003, 2004 g10 Code GmbH + + This file is part of Libgcrypt. + + Libgcrypt is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation; either version 2.1 of + the License, or (at your option) any later version. + + Libgcrypt 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 Lesser General Public + License along with Libgcrypt; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA + 02111-1307, USA. */ + +#ifndef ATH_H +#define ATH_H + +#ifdef _WIN32 +#warning We need to replace these hacks by cleaner code. +typedef int ssize_t; +typedef int pid_t; +#include +#else +#include +#include +#endif +#include + +#include + + +/* Define _ATH_EXT_SYM_PREFIX if you want to give all external symbols + a prefix. */ +#define _ATH_EXT_SYM_PREFIX _gcry_ + +#ifdef _ATH_EXT_SYM_PREFIX +#define _ATH_PREFIX1(x,y) x ## y +#define _ATH_PREFIX2(x,y) _ATH_PREFIX1(x,y) +#define _ATH_PREFIX(x) _ATH_PREFIX2(_ATH_EXT_SYM_PREFIX,x) +#define ath_install _ATH_PREFIX(ath_install) +#define ath_init _ATH_PREFIX(ath_init) +#define ath_mutex_init _ATH_PREFIX(ath_mutex_init) +#define ath_mutex_destroy _ATH_PREFIX(ath_mutex_destroy) +#define ath_mutex_lock _ATH_PREFIX(ath_mutex_lock) +#define ath_mutex_unlock _ATH_PREFIX(ath_mutex_unlock) +#define ath_read _ATH_PREFIX(ath_read) +#define ath_write _ATH_PREFIX(ath_write) +#define ath_select _ATH_PREFIX(ath_select) +#define ath_waitpid _ATH_PREFIX(ath_waitpid) +#define ath_connect _ATH_PREFIX(ath_connect) +#define ath_accept _ATH_PREFIX(ath_accept) +#define ath_sendmsg _ATH_PREFIX(ath_sendmsg) +#define ath_recvmsg _ATH_PREFIX(ath_recvmsg) +#endif + + +enum ath_thread_option + { + ATH_THREAD_OPTION_DEFAULT = 0, + ATH_THREAD_OPTION_USER = 1, + ATH_THREAD_OPTION_PTH = 2, + ATH_THREAD_OPTION_PTHREAD = 3 + }; + +struct ath_ops +{ + enum ath_thread_option option; + int (*init) (void); + int (*mutex_init) (void **priv); + int (*mutex_destroy) (void *priv); + int (*mutex_lock) (void *priv); + int (*mutex_unlock) (void *priv); + ssize_t (*read) (int fd, void *buf, size_t nbytes); + ssize_t (*write) (int fd, const void *buf, size_t nbytes); + ssize_t (*select) (int nfd, fd_set *rset, fd_set *wset, fd_set *eset, + struct timeval *timeout); + ssize_t (*waitpid) (pid_t pid, int *status, int options); + int (*accept) (int s, struct sockaddr *addr, socklen_t *length_ptr); + int (*connect) (int s, struct sockaddr *addr, socklen_t length); + int (*sendmsg) (int s, const struct msghdr *msg, int flags); + int (*recvmsg) (int s, struct msghdr *msg, int flags); +}; + +gpg_err_code_t ath_install (struct ath_ops *ath_ops, int check_only); +int ath_init (void); + + +/* Functions for mutual exclusion. */ +typedef void *ath_mutex_t; +#define ATH_MUTEX_INITIALIZER 0 + +int ath_mutex_init (ath_mutex_t *mutex); +int ath_mutex_destroy (ath_mutex_t *mutex); +int ath_mutex_lock (ath_mutex_t *mutex); +int ath_mutex_unlock (ath_mutex_t *mutex); + + +/* Replacement for the POSIX functions, which can be used to allow + other (user-level) threads to run. */ +ssize_t ath_read (int fd, void *buf, size_t nbytes); +ssize_t ath_write (int fd, const void *buf, size_t nbytes); +ssize_t ath_select (int nfd, fd_set *rset, fd_set *wset, fd_set *eset, + struct timeval *timeout); +ssize_t ath_waitpid (pid_t pid, int *status, int options); +int ath_accept (int s, struct sockaddr *addr, socklen_t *length_ptr); +int ath_connect (int s, struct sockaddr *addr, socklen_t length); +int ath_sendmsg (int s, const struct msghdr *msg, int flags); +int ath_recvmsg (int s, struct msghdr *msg, int flags); + +#endif /* ATH_H */ diff --git a/pwmanager/libcrypt/crypt/cipher.h b/pwmanager/libcrypt/crypt/cipher.h new file mode 100644 index 0000000..a5f194e --- a/dev/null +++ b/pwmanager/libcrypt/crypt/cipher.h @@ -0,0 +1,80 @@ +/* cipher.h + * Copyright (C) 1998, 2002, 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ +#ifndef G10_CIPHER_H +#define G10_CIPHER_H + +#include + +#define DBG_CIPHER _gcry_get_debug_flag( 1 ) + +#include "../cipher/random.h" + +#define PUBKEY_FLAG_NO_BLINDING (1 << 0) + +/*-- rmd160.c --*/ +void _gcry_rmd160_hash_buffer (char *outbuf, const char *buffer, size_t length); +/*-- sha1.c --*/ +void _gcry_sha1_hash_buffer (char *outbuf, const char *buffer, size_t length); + +/*-- dsa.c --*/ +void _gcry_register_pk_dsa_progress (gcry_handler_progress_t cbc, void *cb_data); +/*-- elgamal.c --*/ +void _gcry_register_pk_elg_progress (gcry_handler_progress_t cb, void *cb_data); +/*-- primegen.c --*/ +void _gcry_register_primegen_progress (gcry_handler_progress_t cb, void *cb_data); + +/*-- pubkey.c --*/ +const char * _gcry_pk_aliased_algo_name (int algorithm); + +/* Declarations for the cipher specifications. */ +extern gcry_cipher_spec_t _gcry_cipher_spec_blowfish; +extern gcry_cipher_spec_t _gcry_cipher_spec_des; +extern gcry_cipher_spec_t _gcry_cipher_spec_tripledes; +extern gcry_cipher_spec_t _gcry_cipher_spec_arcfour; +extern gcry_cipher_spec_t _gcry_cipher_spec_cast5; +extern gcry_cipher_spec_t _gcry_cipher_spec_aes; +extern gcry_cipher_spec_t _gcry_cipher_spec_aes192; +extern gcry_cipher_spec_t _gcry_cipher_spec_aes256; +extern gcry_cipher_spec_t _gcry_cipher_spec_twofish; +extern gcry_cipher_spec_t _gcry_cipher_spec_twofish128; +extern gcry_cipher_spec_t _gcry_cipher_spec_serpent128; +extern gcry_cipher_spec_t _gcry_cipher_spec_serpent192; +extern gcry_cipher_spec_t _gcry_cipher_spec_serpent256; +extern gcry_cipher_spec_t _gcry_cipher_spec_rfc2268_40; + +/* Declarations for the digest specifications. */ +extern gcry_md_spec_t _gcry_digest_spec_crc32; +extern gcry_md_spec_t _gcry_digest_spec_crc32_rfc1510; +extern gcry_md_spec_t _gcry_digest_spec_crc24_rfc2440; +extern gcry_md_spec_t _gcry_digest_spec_md4; +extern gcry_md_spec_t _gcry_digest_spec_md5; +extern gcry_md_spec_t _gcry_digest_spec_rmd160; +extern gcry_md_spec_t _gcry_digest_spec_sha1; +extern gcry_md_spec_t _gcry_digest_spec_sha256; +extern gcry_md_spec_t _gcry_digest_spec_sha512; +extern gcry_md_spec_t _gcry_digest_spec_sha384; +extern gcry_md_spec_t _gcry_digest_spec_tiger; + +/* Declarations for the pubkey cipher specifications. */ +extern gcry_pk_spec_t _gcry_pubkey_spec_rsa; +extern gcry_pk_spec_t _gcry_pubkey_spec_elg; +extern gcry_pk_spec_t _gcry_pubkey_spec_dsa; + +#endif /*G10_CIPHER_H*/ diff --git a/pwmanager/libcrypt/crypt/g10lib.h b/pwmanager/libcrypt/crypt/g10lib.h new file mode 100644 index 0000000..0aef376 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/g10lib.h @@ -0,0 +1,250 @@ +/* g10lib.h - internal defintions for libgcrypt + * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc. + * + * This header is to be used inside of libgcrypt in place of gcrypt.h. + * This way we can better distinguish between internal and external + * usage of gcrypt.h + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef G10LIB_H +#define G10LIB_H 1 + +#ifdef _GCRYPT_H +#error gcrypt.h already included +#endif + +#ifndef _GCRYPT_IN_LIBGCRYPT +#error something is wrong with config.h +#endif + +#include +#include "types.h" + +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) +#define JNLIB_GCC_M_FUNCTION 1 +#define JNLIB_GCC_A_NR __attribute__ ((noreturn)) +#define JNLIB_GCC_A_PRINTF( f, a ) __attribute__ ((format (printf,f,a))) +#define JNLIB_GCC_A_NR_PRINTF( f, a ) \ + __attribute__ ((noreturn, format (printf,f,a))) +#define GCC_ATTR_NORETURN __attribute__ ((__noreturn__)) +#else +#define JNLIB_GCC_A_NR +#define JNLIB_GCC_A_PRINTF( f, a ) +#define JNLIB_GCC_A_NR_PRINTF( f, a ) +#define GCC_ATTR_NORETURN +#endif + +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96 ) +#define GCC_ATTR_PURE __attribute__ ((__pure__)) +#else +#define GCC_ATTR_PURE +#endif + +/* (The malloc attribute might be defined prior to 3.2 - I am just not sure) */ +#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2 ) +#define GCC_ATTR_MALLOC __attribute__ ((__malloc__)) +#else +#define GCC_ATTR_MALLOC +#endif + +#ifdef G10_I18N_H +#error i18n should not be included here +#endif + +#define _(a) _gcry_gettext(a) +#define N_(a) (a) + +void _gcry_check_heap( const void *a ); + +int _gcry_get_debug_flag( unsigned int mask ); + + +/*-- gcrypt/misc.c --*/ + +#ifdef JNLIB_GCC_M_FUNCTION +void _gcry_bug (const char *file, int line, + const char *func) GCC_ATTR_NORETURN; +#else +void _gcry_bug (const char *file, int line); +#endif + +const char *_gcry_gettext (const char *key); +void _gcry_fatal_error(int rc, const char *text ) JNLIB_GCC_A_NR; +void _gcry_log( int level, const char *fmt, ... ) JNLIB_GCC_A_PRINTF(2,3); +void _gcry_log_bug( const char *fmt, ... ) JNLIB_GCC_A_NR_PRINTF(1,2); +void _gcry_log_fatal( const char *fmt, ... ) JNLIB_GCC_A_NR_PRINTF(1,2); +void _gcry_log_error( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); +void _gcry_log_info( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); +void _gcry_log_debug( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); +void _gcry_log_printf ( const char *fmt, ... ) JNLIB_GCC_A_PRINTF(1,2); + +void _gcry_set_log_verbosity( int level ); +int _gcry_log_verbosity( int level ); + +#ifdef JNLIB_GCC_M_FUNCTION +#define BUG() _gcry_bug( __FILE__ , __LINE__, __FUNCTION__ ) +#else +#define BUG() _gcry_bug( __FILE__ , __LINE__ ) +#endif + +#define log_hexdump _gcry_log_hexdump +#define log_bug _gcry_log_bug +#define log_fatal _gcry_log_fatal +#define log_error _gcry_log_error +#define log_info _gcry_log_info +#define log_debug _gcry_log_debug +#define log_printf _gcry_log_printf + + + + +/*-- cipher/pubkey.c --*/ + +#ifndef mpi_powm +#define mpi_powm(w,b,e,m) gcry_mpi_powm( (w), (b), (e), (m) ) +#endif + +/*-- primegen.c --*/ +gcry_mpi_t _gcry_generate_secret_prime (unsigned int nbits, + int (*extra_check)(void*, gcry_mpi_t), + void *extra_check_arg); +gcry_mpi_t _gcry_generate_public_prime (unsigned int nbits, + int (*extra_check)(void*, gcry_mpi_t), + void *extra_check_arg); +gcry_mpi_t _gcry_generate_elg_prime( int mode, unsigned pbits, unsigned qbits, + gcry_mpi_t g, gcry_mpi_t **factors ); + + +/* replacements of missing functions (missing-string.c)*/ +#ifndef HAVE_STPCPY +char *stpcpy (char *a, const char *b); +#endif +#ifndef HAVE_STRCASECMP +int strcasecmp (const char *a, const char *b) GCC_ATTR_PURE; +#endif + +/* macros used to rename missing functions */ +#ifndef HAVE_STRTOUL +#define strtoul(a,b,c) ((unsigned long)strtol((a),(b),(c))) +#endif +#ifndef HAVE_MEMMOVE +#define memmove(d, s, n) bcopy((s), (d), (n)) +#endif +#ifndef HAVE_STRICMP +#define stricmp(a,b) strcasecmp( (a), (b) ) +#endif +#ifndef HAVE_ATEXIT +#define atexit(a) (on_exit((a),0)) +#endif +#ifndef HAVE_RAISE +#define raise(a) kill(getpid(), (a)) +#endif + + +/* some handy macros */ +#ifndef STR +#define STR(v) #v +#endif +#define STR2(v) STR(v) +#define DIM(v) (sizeof(v)/sizeof((v)[0])) +#define DIMof(type,member) DIM(((type *)0)->member) + +/* Stack burning. */ + +void _gcry_burn_stack (int bytes); + + +/* To avoid that a compiler optimizes certain memset calls away, these + macros may be used instead. */ +#define wipememory2(_ptr,_set,_len) do { \ + volatile char *_vptr=(volatile char *)(_ptr); \ + size_t _vlen=(_len); \ + while(_vlen) { *_vptr=(_set); _vptr++; _vlen--; } \ + } while(0) +#define wipememory(_ptr,_len) wipememory2(_ptr,0,_len) + + + +/* Digit predicates. */ + +#define digitp(p) (*(p) >= '0' && *(p) <= '9') +#define octdigitp(p) (*(p) >= '0' && *(p) <= '7') +#define alphap(a) ( (*(a) >= 'A' && *(a) <= 'Z') \ + || (*(a) >= 'a' && *(a) <= 'z')) +#define hexdigitp(a) (digitp (a) \ + || (*(a) >= 'A' && *(a) <= 'F') \ + || (*(a) >= 'a' && *(a) <= 'f')) + +/* Management for ciphers/digests/pubkey-ciphers. */ + +/* Structure for each registered `module'. */ +struct gcry_module +{ + struct gcry_module *next; /* List pointers. */ + struct gcry_module **prevp; + void *spec; /* The acctual specs. */ + int flags; /* Associated flags. */ + int counter; /* Use counter. */ + unsigned int mod_id; /* ID of this module. */ +}; + +/* Flags for the `flags' member of gcry_module_t. */ +#define FLAG_MODULE_DISABLED 1 << 0 + +gcry_err_code_t _gcry_module_add (gcry_module_t *entries, + unsigned int id, + void *spec, + gcry_module_t *module); + +typedef int (*gcry_module_lookup_t) (void *spec, void *data); + +/* Lookup a module specification by it's ID. After a successfull + lookup, the module has it's resource counter incremented. */ +gcry_module_t _gcry_module_lookup_id (gcry_module_t entries, + unsigned int id); + +/* Internal function. Lookup a module specification. */ +gcry_module_t _gcry_module_lookup (gcry_module_t entries, void *data, + gcry_module_lookup_t func); + +/* Release a module. In case the use-counter reaches zero, destroy + the module. */ +void _gcry_module_release (gcry_module_t entry); + +/* Add a reference to a module. */ +void _gcry_module_use (gcry_module_t module); + +/* Return a list of module IDs. */ +gcry_err_code_t _gcry_module_list (gcry_module_t modules, + int *list, int *list_length); + +gcry_err_code_t _gcry_cipher_init (void); +gcry_err_code_t _gcry_md_init (void); +gcry_err_code_t _gcry_pk_init (void); + +gcry_err_code_t _gcry_pk_module_lookup (int id, gcry_module_t *module); +void _gcry_pk_module_release (gcry_module_t module); + +/* Memory management. */ + +gcry_err_code_t _gcry_malloc (size_t n, unsigned int flags, void **mem); + +#define GCRY_ALLOC_FLAG_SECURE (1 << 0) + +#endif /* G10LIB_H */ diff --git a/pwmanager/libcrypt/crypt/gcrypt-module.h b/pwmanager/libcrypt/crypt/gcrypt-module.h new file mode 100644 index 0000000..1099c92 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/gcrypt-module.h @@ -0,0 +1,225 @@ +/* gcrypt-module.h - GNU cryptographic library interface + * Copyright (C) 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +/* This file contains the necessary declarations/definitions for + working with Libgcrypt modules. */ + +#ifndef _GCRYPT_MODULE_H +#define _GCRYPT_MODULE_H + +#ifdef __cplusplus +extern "C" { +#if 0 /* keep Emacsens's auto-indent happy */ +} +#endif +#endif + +/* This type represents a `module'. */ +typedef struct gcry_module *gcry_module_t; + +/* Check that the library fulfills the version requirement. */ + +/* Type for the cipher_setkey function. */ +typedef gcry_err_code_t (*gcry_cipher_setkey_t) (void *c, + const unsigned char *key, + unsigned keylen); + +/* Type for the cipher_encrypt function. */ +typedef void (*gcry_cipher_encrypt_t) (void *c, + unsigned char *outbuf, + const unsigned char *inbuf); + +/* Type for the cipher_decrypt function. */ +typedef void (*gcry_cipher_decrypt_t) (void *c, + unsigned char *outbuf, + const unsigned char *inbuf); + +/* Type for the cipher_stencrypt function. */ +typedef void (*gcry_cipher_stencrypt_t) (void *c, + unsigned char *outbuf, + const unsigned char *inbuf, + unsigned int n); + +/* Type for the cipher_stdecrypt function. */ +typedef void (*gcry_cipher_stdecrypt_t) (void *c, + unsigned char *outbuf, + const unsigned char *inbuf, + unsigned int n); + +typedef struct gcry_cipher_oid_spec +{ + const char *oid; + int mode; +} gcry_cipher_oid_spec_t; + +/* Module specification structure for ciphers. */ +typedef struct gcry_cipher_spec +{ + const char *name; + const char **aliases; + gcry_cipher_oid_spec_t *oids; + size_t blocksize; + size_t keylen; + size_t contextsize; + gcry_cipher_setkey_t setkey; + gcry_cipher_encrypt_t encrypt; + gcry_cipher_decrypt_t decrypt; + gcry_cipher_stencrypt_t stencrypt; + gcry_cipher_stdecrypt_t stdecrypt; +} gcry_cipher_spec_t; + +/* Register a new cipher module whose specification can be found in + CIPHER. On success, a new algorithm ID is stored in ALGORITHM_ID + and a pointer representhing this module is stored in MODULE. */ +gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *cipher, + unsigned int *algorithm_id, + gcry_module_t *module); + +/* Unregister the cipher identified by MODULE, which must have been + registered with gcry_cipher_register. */ +void gcry_cipher_unregister (gcry_module_t module); + +/* ********************** */ + +/* Type for the pk_generate function. */ +typedef gcry_err_code_t (*gcry_pk_generate_t) (int algo, + unsigned int nbits, + unsigned long use_e, + gcry_mpi_t *skey, + gcry_mpi_t **retfactors); + +/* Type for the pk_check_secret_key function. */ +typedef gcry_err_code_t (*gcry_pk_check_secret_key_t) (int algo, + gcry_mpi_t *skey); + +/* Type for the pk_encrypt function. */ +typedef gcry_err_code_t (*gcry_pk_encrypt_t) (int algo, + gcry_mpi_t *resarr, + gcry_mpi_t data, + gcry_mpi_t *pkey, + int flags); + +/* Type for the pk_decrypt function. */ +typedef gcry_err_code_t (*gcry_pk_decrypt_t) (int algo, + gcry_mpi_t *result, + gcry_mpi_t *data, + gcry_mpi_t *skey, + int flags); + +/* Type for the pk_sign function. */ +typedef gcry_err_code_t (*gcry_pk_sign_t) (int algo, + gcry_mpi_t *resarr, + gcry_mpi_t data, + gcry_mpi_t *skey); + +/* Type for the pk_verify function. */ +typedef gcry_err_code_t (*gcry_pk_verify_t) (int algo, + gcry_mpi_t hash, + gcry_mpi_t *data, + gcry_mpi_t *pkey, + int (*cmp) (void *, gcry_mpi_t), + void *opaquev); + +/* Type for the pk_get_nbits function. */ +typedef unsigned (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey); + +/* Module specification structure for message digests. */ +typedef struct gcry_pk_spec +{ + const char *name; + char **aliases; + const char *elements_pkey; + const char *elements_skey; + const char *elements_enc; + const char *elements_sig; + const char *elements_grip; + int use; + gcry_pk_generate_t generate; + gcry_pk_check_secret_key_t check_secret_key; + gcry_pk_encrypt_t encrypt; + gcry_pk_decrypt_t decrypt; + gcry_pk_sign_t sign; + gcry_pk_verify_t verify; + gcry_pk_get_nbits_t get_nbits; +} gcry_pk_spec_t; + +/* Register a new pubkey module whose specification can be found in + PUBKEY. On success, a new algorithm ID is stored in ALGORITHM_ID + and a pointer representhing this module is stored in MODULE. */ +gcry_error_t gcry_pk_register (gcry_pk_spec_t *pubkey, + unsigned int *algorithm_id, + gcry_module_t *module); + +/* Unregister the pubkey identified by ID, which must have been + registered with gcry_pk_register. */ +void gcry_pk_unregister (gcry_module_t module); + +/* ********************** */ + +/* Type for the md_init function. */ +typedef void (*gcry_md_init_t) (void *c); + +/* Type for the md_write function. */ +typedef void (*gcry_md_write_t) (void *c, unsigned char *buf, size_t nbytes); + +/* Type for the md_final function. */ +typedef void (*gcry_md_final_t) (void *c); + +/* Type for the md_read function. */ +typedef unsigned char *(*gcry_md_read_t) (void *c); + +typedef struct gcry_md_oid_spec +{ + const char *oidstring; +} gcry_md_oid_spec_t; + +/* Module specification structure for message digests. */ +typedef struct gcry_md_spec +{ + const char *name; + unsigned char *asnoid; + int asnlen; + gcry_md_oid_spec_t *oids; + int mdlen; + gcry_md_init_t init; + gcry_md_write_t write; + gcry_md_final_t final; + gcry_md_read_t read; + size_t contextsize; /* allocate this amount of context */ +} gcry_md_spec_t; + +/* Register a new digest module whose specification can be found in + DIGEST. On success, a new algorithm ID is stored in ALGORITHM_ID + and a pointer representhing this module is stored in MODULE. */ +gcry_error_t gcry_md_register (gcry_md_spec_t *digest, + unsigned int *algorithm_id, + gcry_module_t *module); + +/* Unregister the digest identified by ID, which must have been + registered with gcry_digest_register. */ +void gcry_md_unregister (gcry_module_t module); + +#if 0 /* keep Emacsens's auto-indent happy */ +{ +#endif +#ifdef __cplusplus +} +#endif +#endif diff --git a/pwmanager/libcrypt/crypt/gcrypt.h b/pwmanager/libcrypt/crypt/gcrypt.h new file mode 100644 index 0000000..49ac53f --- a/dev/null +++ b/pwmanager/libcrypt/crypt/gcrypt.h @@ -0,0 +1,1497 @@ +/* gcrypt.h - GNU cryptographic library interface + * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004 + * 2004 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef _GCRYPT_H +#define _GCRYPT_H + +#include +#include + +#include + +#include +#include + +/* This is required for error code compatibility. */ +#define _GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_GCRYPT + +#ifdef __cplusplus +extern "C" { +#if 0 /* keep Emacsens' auto-indent happy */ +} +#endif +#endif + +/* The version of this header should match the one of the library. It + should not be used by a program because gcry_check_version() should + return the same version. The purpose of this macro is to let + autoconf (using the AM_PATH_GCRYPT macro) check that this header + matches the installed library. Note: Do not edit the next line as + configure may fix the string here. */ +#define GCRYPT_VERSION "1.2.0" + +/* Internal: We can't use the convenience macros for the multi + precision integer functions when building this library. */ +#ifdef _GCRYPT_IN_LIBGCRYPT +#ifndef GCRYPT_NO_MPI_MACROS +#define GCRYPT_NO_MPI_MACROS 1 +#endif +#endif + +/* We want to use gcc attributes when possible. Warning: Don't use + these macros in your programs: As indicated by the leading + underscore they are subject to change without notice. */ +#ifdef __GNUC__ + +#define _GCRY_GCC_VERSION (__GNUC__ * 10000 \ + + __GNUC_MINOR__ * 100 \ + + __GNUC_PATCHLEVEL__) + +#if _GCRY_GCC_VERSION >= 30100 +#define _GCRY_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__)) +#endif + +#if _GCRY_GCC_VERSION >= 29600 +#define _GCRY_GCC_ATTR_PURE __attribute__ ((__pure__)) +#endif + +#if _GCRY_GCC_VERSION >= 300200 +#define _GCRY_GCC_ATTR_MALLOC __attribute__ ((__malloc__)) +#endif + +#endif /*__GNUC__*/ + +#ifndef _GCRY_GCC_ATTR_DEPRECATED +#define _GCRY_GCC_ATTR_DEPRECATED +#endif +#ifndef _GCRY_GCC_ATTR_PURE +#define _GCRY_GCC_ATTR_PURE +#endif +#ifndef _GCRY_GCC_ATTR_MALLOC +#define _GCRY_GCC_ATTR_MALLOC +#endif + +/* Wrappers for the libgpg-error library. */ + +typedef gpg_error_t gcry_error_t; +typedef gpg_err_code_t gcry_err_code_t; +typedef gpg_err_source_t gcry_err_source_t; + +static GPG_ERR_INLINE gcry_error_t +gcry_err_make (gcry_err_source_t source, gcry_err_code_t code) +{ + return gpg_err_make (source, code); +} + +/* The user can define GPG_ERR_SOURCE_DEFAULT before including this + file to specify a default source for gpg_error. */ +#ifndef GCRY_ERR_SOURCE_DEFAULT +#define GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_USER_1 +#endif + +static GPG_ERR_INLINE gcry_error_t +gcry_error (gcry_err_code_t code) +{ + return gcry_err_make (GCRY_ERR_SOURCE_DEFAULT, code); +} + +static GPG_ERR_INLINE gcry_err_code_t +gcry_err_code (gcry_error_t err) +{ + return gpg_err_code (err); +} + + +static GPG_ERR_INLINE gcry_err_source_t +gcry_err_source (gcry_error_t err) +{ + return gpg_err_source (err); +} + +/* Return a pointer to a string containing a description of the error + code in the error value ERR. */ +const char *gcry_strerror (gcry_error_t err); + +/* Return a pointer to a string containing a description of the error + source in the error value ERR. */ +const char *gcry_strsource (gcry_error_t err); + +/* Retrieve the error code for the system error ERR. This returns + GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report + this). */ +gcry_err_code_t gcry_err_code_from_errno (int err); + +/* Retrieve the system error for the error code CODE. This returns 0 + if CODE is not a system error code. */ +int gcry_err_code_to_errno (gcry_err_code_t code); + +/* Return an error value with the error source SOURCE and the system + error ERR. */ +gcry_error_t gcry_err_make_from_errno (gcry_err_source_t source, int err); + +/* Return an error value with the system error ERR. */ +gcry_err_code_t gcry_error_from_errno (int err); + + +enum gcry_thread_option + { + GCRY_THREAD_OPTION_DEFAULT = 0, + GCRY_THREAD_OPTION_USER = 1, + GCRY_THREAD_OPTION_PTH = 2, + GCRY_THREAD_OPTION_PTHREAD = 3 + }; + +/* Wrapper for struct ath_ops. */ +struct gcry_thread_cbs +{ + enum gcry_thread_option option; + int (*init) (void); + int (*mutex_init) (void **priv); + int (*mutex_destroy) (void **priv); + int (*mutex_lock) (void **priv); + int (*mutex_unlock) (void **priv); + ssize_t (*read) (int fd, void *buf, size_t nbytes); + ssize_t (*write) (int fd, const void *buf, size_t nbytes); + ssize_t (*select) (int nfd, fd_set *rset, fd_set *wset, fd_set *eset, + struct timeval *timeout); + ssize_t (*waitpid) (pid_t pid, int *status, int options); + int (*accept) (int s, struct sockaddr *addr, socklen_t *length_ptr); + int (*connect) (int s, struct sockaddr *addr, socklen_t length); + int (*sendmsg) (int s, const struct msghdr *msg, int flags); + int (*recvmsg) (int s, struct msghdr *msg, int flags); +}; + +#define GCRY_THREAD_OPTION_PTH_IMPL \ +static int gcry_pth_init (void) \ +{ return (pth_init () == FALSE) ? errno : 0; } \ +static int gcry_pth_mutex_init (void **priv) \ +{ \ + int err = 0; \ + pth_mutex_t *lock = malloc (sizeof (pth_mutex_t)); \ + \ + if (!lock) \ + err = ENOMEM; \ + if (!err) \ + { \ + err = pth_mutex_init (lock); \ + if (err == FALSE) \ + err = errno; \ + else \ + err = 0; \ + if (err) \ + free (lock); \ + else \ + *priv = lock; \ + } \ + return err; \ +} \ +static int gcry_pth_mutex_destroy (void **lock) \ + { /* GNU Pth has no destructor function. */ free (*lock); return 0; } \ +static int gcry_pth_mutex_lock (void **lock) \ + { return ((pth_mutex_acquire (*lock, 0, NULL)) == FALSE) \ + ? errno : 0; } \ +static int gcry_pth_mutex_unlock (void **lock) \ + { return ((pth_mutex_release (*lock)) == FALSE) \ + ? errno : 0; } \ +static ssize_t gcry_pth_read (int fd, void *buf, size_t nbytes) \ + { return pth_read (fd, buf, nbytes); } \ +static ssize_t gcry_pth_write (int fd, const void *buf, size_t nbytes) \ + { return pth_write (fd, buf, nbytes); } \ +static ssize_t gcry_pth_select (int nfd, fd_set *rset, fd_set *wset, \ + fd_set *eset, struct timeval *timeout) \ + { return pth_select (nfd, rset, wset, eset, timeout); } \ +static ssize_t gcry_pth_waitpid (pid_t pid, int *status, int options) \ + { return pth_waitpid (pid, status, options); } \ +static int gcry_pth_accept (int s, struct sockaddr *addr, \ + socklen_t *length_ptr) \ + { return pth_accept (s, addr, length_ptr); } \ +static int gcry_pth_connect (int s, struct sockaddr *addr, socklen_t length) \ + { return pth_connect (s, addr, length); } \ + \ +/* FIXME: GNU Pth is missing pth_sendmsg and pth_recvmsg. */ \ +static struct gcry_thread_cbs gcry_threads_pth = { GCRY_THREAD_OPTION_PTH, \ + gcry_pth_init, gcry_pth_mutex_init, gcry_pth_mutex_destroy, \ + gcry_pth_mutex_lock, gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, \ + gcry_pth_select, gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect } + +#define GCRY_THREAD_OPTION_PTHREAD_IMPL \ +static int gcry_pthread_mutex_init (void **priv) \ +{ \ + int err = 0; \ + pthread_mutex_t *lock = malloc (sizeof (pthread_mutex_t)); \ + \ + if (!lock) \ + err = ENOMEM; \ + if (!err) \ + { \ + err = pthread_mutex_init (lock, NULL); \ + if (err) \ + free (lock); \ + else \ + *priv = lock; \ + } \ + return err; \ +} \ +static int gcry_pthread_mutex_destroy (void **lock) \ + { int err = pthread_mutex_destroy (*lock); free (*lock); return err; } \ +static int gcry_pthread_mutex_lock (void **lock) \ + { return pthread_mutex_lock (*lock); } \ +static int gcry_pthread_mutex_unlock (void **lock) \ + { return pthread_mutex_unlock (*lock); } \ + \ +static struct gcry_thread_cbs gcry_threads_pthread = \ +{ GCRY_THREAD_OPTION_PTHREAD, NULL, \ + gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, \ + gcry_pthread_mutex_lock, gcry_pthread_mutex_unlock } + + +/* The data object used to hold a multi precision integer. */ +struct gcry_mpi; +typedef struct gcry_mpi *gcry_mpi_t; + +typedef struct gcry_mpi *GCRY_MPI _GCRY_GCC_ATTR_DEPRECATED; +typedef struct gcry_mpi *GcryMPI _GCRY_GCC_ATTR_DEPRECATED; + + + +/* Check that the library fulfills the version requirement. */ +const char *gcry_check_version (const char *req_version); + +/* Codes for function dispatchers. */ + +/* Codes used with the gcry_control function. */ +enum gcry_ctl_cmds + { + GCRYCTL_SET_KEY = 1, + GCRYCTL_SET_IV = 2, + GCRYCTL_CFB_SYNC = 3, + GCRYCTL_RESET = 4, /* e.g. for MDs */ + GCRYCTL_FINALIZE = 5, + GCRYCTL_GET_KEYLEN = 6, + GCRYCTL_GET_BLKLEN = 7, + GCRYCTL_TEST_ALGO = 8, + GCRYCTL_IS_SECURE = 9, + GCRYCTL_GET_ASNOID = 10, + GCRYCTL_ENABLE_ALGO = 11, + GCRYCTL_DISABLE_ALGO = 12, + GCRYCTL_DUMP_RANDOM_STATS = 13, + GCRYCTL_DUMP_SECMEM_STATS = 14, + GCRYCTL_GET_ALGO_NPKEY = 15, + GCRYCTL_GET_ALGO_NSKEY = 16, + GCRYCTL_GET_ALGO_NSIGN = 17, + GCRYCTL_GET_ALGO_NENCR = 18, + GCRYCTL_SET_VERBOSITY = 19, + GCRYCTL_SET_DEBUG_FLAGS = 20, + GCRYCTL_CLEAR_DEBUG_FLAGS = 21, + GCRYCTL_USE_SECURE_RNDPOOL= 22, + GCRYCTL_DUMP_MEMORY_STATS = 23, + GCRYCTL_INIT_SECMEM = 24, + GCRYCTL_TERM_SECMEM = 25, + GCRYCTL_DISABLE_SECMEM_WARN = 27, + GCRYCTL_SUSPEND_SECMEM_WARN = 28, + GCRYCTL_RESUME_SECMEM_WARN = 29, + GCRYCTL_DROP_PRIVS = 30, + GCRYCTL_ENABLE_M_GUARD = 31, + GCRYCTL_START_DUMP = 32, + GCRYCTL_STOP_DUMP = 33, + GCRYCTL_GET_ALGO_USAGE = 34, + GCRYCTL_IS_ALGO_ENABLED = 35, + GCRYCTL_DISABLE_INTERNAL_LOCKING = 36, + GCRYCTL_DISABLE_SECMEM = 37, + GCRYCTL_INITIALIZATION_FINISHED = 38, + GCRYCTL_INITIALIZATION_FINISHED_P = 39, + GCRYCTL_ANY_INITIALIZATION_P = 40, + GCRYCTL_SET_CBC_CTS = 41, + GCRYCTL_SET_CBC_MAC = 42, + GCRYCTL_SET_CTR = 43, + GCRYCTL_ENABLE_QUICK_RANDOM = 44, + GCRYCTL_SET_RANDOM_SEED_FILE = 45, + GCRYCTL_UPDATE_RANDOM_SEED_FILE = 46, + GCRYCTL_SET_THREAD_CBS = 47 + }; + +/* Perform various operations defined by CMD. */ +gcry_error_t gcry_control (enum gcry_ctl_cmds CMD, ...); + + +/* S-expression management. */ + +/* The object to represent an S-expression as used with the public key + functions. */ +struct gcry_sexp; +typedef struct gcry_sexp *gcry_sexp_t; + +typedef struct gcry_sexp *GCRY_SEXP _GCRY_GCC_ATTR_DEPRECATED; +typedef struct gcry_sexp *GcrySexp _GCRY_GCC_ATTR_DEPRECATED; + +/* The possible values for the S-expression format. */ +enum gcry_sexp_format + { + GCRYSEXP_FMT_DEFAULT = 0, + GCRYSEXP_FMT_CANON = 1, + GCRYSEXP_FMT_BASE64 = 2, + GCRYSEXP_FMT_ADVANCED = 3 + }; + +/* Create an new S-expression object from BUFFER of size LENGTH and + return it in RETSEXP. With AUTODETECT set to 0 the data in BUFFER + is expected to be in canonized format. */ +gcry_error_t gcry_sexp_new (gcry_sexp_t *retsexp, + const void *buffer, size_t length, + int autodetect); + + /* Same as gcry_sexp_new but allows to pass a FREEFNC which has the + effect to transfer ownership of BUFFER to the created object. */ +gcry_error_t gcry_sexp_create (gcry_sexp_t *retsexp, + void *buffer, size_t length, + int autodetect, void (*freefnc) (void *)); + +/* Scan BUFFER and return a new S-expression object in RETSEXP. This + function expects a printf like string in BUFFER. */ +gcry_error_t gcry_sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff, + const char *buffer, size_t length); + +/* Same as gcry_sexp_sscan but expects a string in FORMAT and can thus + only be used for certain encodings. */ +gcry_error_t gcry_sexp_build (gcry_sexp_t *retsexp, size_t *erroff, + const char *format, ...); + +/* Like gcry_sexp_build, but uses an array instead of variable + function arguments. */ +gcry_error_t gcry_sexp_build_array (gcry_sexp_t *retsexp, size_t *erroff, + const char *format, void **arg_list); + +/* Release the S-expression object SEXP */ +void gcry_sexp_release (gcry_sexp_t sexp); + +/* Calculate the length of an canonized S-expresion in BUFFER and + check for a valid encoding. */ +size_t gcry_sexp_canon_len (const unsigned char *buffer, size_t length, + size_t *erroff, gcry_error_t *errcode); + +/* Copies the S-expression object SEXP into BUFFER using the format + specified in MODE. */ +size_t gcry_sexp_sprint (gcry_sexp_t sexp, int mode, char *buffer, + size_t maxlength); + +/* Dumps the S-expression object A in a aformat suitable for debugging + to Libgcrypt's logging stream. */ +void gcry_sexp_dump (const gcry_sexp_t a); + +gcry_sexp_t gcry_sexp_cons (const gcry_sexp_t a, const gcry_sexp_t b); +gcry_sexp_t gcry_sexp_alist (const gcry_sexp_t *array); +gcry_sexp_t gcry_sexp_vlist (const gcry_sexp_t a, ...); +gcry_sexp_t gcry_sexp_append (const gcry_sexp_t a, const gcry_sexp_t n); +gcry_sexp_t gcry_sexp_prepend (const gcry_sexp_t a, const gcry_sexp_t n); + +/* Scan the S-expression for a sublist with a type (the car of the + list) matching the string TOKEN. If TOKLEN is not 0, the token is + assumed to be raw memory of this length. The function returns a + newly allocated S-expression consisting of the found sublist or + `NULL' when not found. */ +gcry_sexp_t gcry_sexp_find_token (gcry_sexp_t list, + const char *tok, size_t toklen); +/* Return the length of the LIST. For a valid S-expression this + should be at least 1. */ +int gcry_sexp_length (const gcry_sexp_t list); + +/* Create and return a new S-expression from the element with index + NUMBER in LIST. Note that the first element has the index 0. If + there is no such element, `NULL' is returned. */ +gcry_sexp_t gcry_sexp_nth (const gcry_sexp_t list, int number); + +/* Create and return a new S-expression from the first element in + LIST; this called the "type" and should always exist and be a + string. `NULL' is returned in case of a problem. */ +gcry_sexp_t gcry_sexp_car (const gcry_sexp_t list); + +/* Create and return a new list form all elements except for the first + one. Note, that this function may return an invalid S-expression + because it is not guaranteed, that the type exists and is a string. + However, for parsing a complex S-expression it might be useful for + intermediate lists. Returns `NULL' on error. */ +gcry_sexp_t gcry_sexp_cdr (const gcry_sexp_t list); + +gcry_sexp_t gcry_sexp_cadr (const gcry_sexp_t list); + + +/* This function is used to get data from a LIST. A pointer to the + actual data with index NUMBER is returned and the length of this + data will be stored to DATALEN. If there is no data at the given + index or the index represents another list, `NULL' is returned. + *Note:* The returned pointer is valid as long as LIST is not + modified or released. */ +const char *gcry_sexp_nth_data (const gcry_sexp_t list, int number, + size_t *datalen); + +/* This function is used to get and convert data from a LIST. This + data is assumed to be an MPI stored in the format described by + MPIFMT and returned as a standard Libgcrypt MPI. The caller must + release this returned value using `gcry_mpi_release'. If there is + no data at the given index, the index represents a list or the + value can't be converted to an MPI, `NULL' is returned. */ +gcry_mpi_t gcry_sexp_nth_mpi (gcry_sexp_t list, int number, int mpifmt); + + + +/******************************************* + * * + * multi precision integer functions * + * * + *******************************************/ + +/* Different formats of external big integer representation. */ +enum gcry_mpi_format + { + GCRYMPI_FMT_NONE= 0, + GCRYMPI_FMT_STD = 1, /* twos complement stored without length */ + GCRYMPI_FMT_PGP = 2, /* As used by OpenPGP (only defined as unsigned)*/ + GCRYMPI_FMT_SSH = 3, /* As used by SSH (same as 1 but with length)*/ + GCRYMPI_FMT_HEX = 4, /* hex format */ + GCRYMPI_FMT_USG = 5 /* like STD but this is an unsigned one */ + }; + +/* Flags used for creating big integers. */ +enum gcry_mpi_flag + { + GCRYMPI_FLAG_SECURE = 1, /* Allocate the number in "secure" memory. */ + GCRYMPI_FLAG_OPAQUE = 2 /* The number is not a real one but just a + way to store some bytes. This is + useful for encrypted big integers. */ + }; + + +/* Allocate a new big integer object, initialize it with 0 and + initially allocate memory for a number of at least NBITS. */ +gcry_mpi_t gcry_mpi_new (unsigned int nbits); + +/* Same as gcry_mpi_new() but allocate in "secure" memory. */ +gcry_mpi_t gcry_mpi_snew (unsigned int nbits); + +/* Release the number A and free all associated resources. */ +void gcry_mpi_release (gcry_mpi_t a); + +/* Create a new number with the same value as A. */ +gcry_mpi_t gcry_mpi_copy (const gcry_mpi_t a); + +/* Store the big integer value U in W. */ +gcry_mpi_t gcry_mpi_set (gcry_mpi_t w, const gcry_mpi_t u); + +/* Store the unsigned integer value U in W. */ +gcry_mpi_t gcry_mpi_set_ui (gcry_mpi_t w, unsigned long u); + +/* Swap the values of A and B. */ +void gcry_mpi_swap (gcry_mpi_t a, gcry_mpi_t b); + +/* Compare the big integer number U and V returning 0 for equality, a + positive value for U > V and a negative for U < V. */ +int gcry_mpi_cmp (const gcry_mpi_t u, const gcry_mpi_t v); + +/* Compare the big integer number U with the unsigned integer V + returning 0 for equality, a positive value for U > V and a negative + for U < V. */ +int gcry_mpi_cmp_ui (const gcry_mpi_t u, unsigned long v); + +/* Convert the external representation of an integer stored in BUFFER + with a length of BUFLEN into a newly create MPI returned in + RET_MPI. If NSCANNED is not NULL, it will receive the number of + bytes actually scanned after a successful operation. */ +gcry_error_t gcry_mpi_scan (gcry_mpi_t *ret_mpi, enum gcry_mpi_format format, + const unsigned char *buffer, size_t buflen, + size_t *nscanned); + +/* Convert the big integer A into the external representation + described by FORMAT and store it in the provided BUFFER which has + been allocated by the user with a size of BUFLEN bytes. NWRITTEN + receives the actual length of the external representation unless it + has been passed as NULL. */ +gcry_error_t gcry_mpi_print (enum gcry_mpi_format format, + unsigned char *buffer, size_t buflen, + size_t *nwritten, + const gcry_mpi_t a); + +/* Convert the big integer A int the external representation described + by FORMAT and store it in a newly allocated buffer which address + will be put into BUFFER. NWRITTEN receives the actual lengths of the + external representation. */ +gcry_error_t gcry_mpi_aprint (enum gcry_mpi_format format, + unsigned char **buffer, size_t *nwritten, + const gcry_mpi_t a); + +/* Dump the value of A in a format suitable for debugging to + Libgcrypt's logging stream. Note that one leading space but no + trailing space or linefeed will be printed. It is okay to pass + NULL for A. */ +void gcry_mpi_dump (const gcry_mpi_t a); + + +/* W = U + V. */ +void gcry_mpi_add (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); + +/* W = U + V. V is an unsigned integer. */ +void gcry_mpi_add_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v); + +/* W = U + V mod M. */ +void gcry_mpi_addm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); + +/* W = U - V. */ +void gcry_mpi_sub (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); + +/* W = U - V. V is an unsigned integer. */ +void gcry_mpi_sub_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v ); + +/* W = U - V mod M */ +void gcry_mpi_subm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); + +/* W = U * V. */ +void gcry_mpi_mul (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v); + +/* W = U * V. V is an unsigned integer. */ +void gcry_mpi_mul_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v ); + +/* W = U * V mod M. */ +void gcry_mpi_mulm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m); + +/* W = U * (2 ^ CNT). */ +void gcry_mpi_mul_2exp (gcry_mpi_t w, gcry_mpi_t u, unsigned long cnt); + +/* Q = DIVIDEND / DIVISOR, R = DIVIDEND % DIVISOR, + Q or R may be passed as NULL. ROUND should be negative or 0. */ +void gcry_mpi_div (gcry_mpi_t q, gcry_mpi_t r, + gcry_mpi_t dividend, gcry_mpi_t divisor, int round); + +/* R = DIVIDEND % DIVISOR */ +void gcry_mpi_mod (gcry_mpi_t r, gcry_mpi_t dividend, gcry_mpi_t divisor); + +/* W = B ^ E mod M. */ +void gcry_mpi_powm (gcry_mpi_t w, + const gcry_mpi_t b, const gcry_mpi_t e, + const gcry_mpi_t m); + +/* Set G to the greatest common divisor of A and B. + Return true if the G is 1. */ +int gcry_mpi_gcd (gcry_mpi_t g, gcry_mpi_t a, gcry_mpi_t b); + +/* Set X to the multiplicative inverse of A mod M. + Return true if the value exists. */ +int gcry_mpi_invm (gcry_mpi_t x, gcry_mpi_t a, gcry_mpi_t m); + + +/* Return the number of bits required to represent A. */ +unsigned int gcry_mpi_get_nbits (gcry_mpi_t a); + +/* Return true when bit number N (counting from 0) is set in A. */ +int gcry_mpi_test_bit (gcry_mpi_t a, unsigned int n); + +/* Set bit number N in A. */ +void gcry_mpi_set_bit (gcry_mpi_t a, unsigned int n); + +/* Clear bit number N in A. */ +void gcry_mpi_clear_bit (gcry_mpi_t a, unsigned int n); + +/* Set bit number N in A and clear all bits greater than N. */ +void gcry_mpi_set_highbit (gcry_mpi_t a, unsigned int n); + +/* Clear bit number N in A and all bits greater than N. */ +void gcry_mpi_clear_highbit (gcry_mpi_t a, unsigned int n); + +/* Shift the value of A by N bits to the right and store the result in X. */ +void gcry_mpi_rshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n); + +/* Store NBITS of the value P points to in A and mark A as an opaque + value. WARNING: Never use an opaque MPI for anything thing else then + gcry_mpi_release, gcry_mpi_get_opaque. */ +gcry_mpi_t gcry_mpi_set_opaque (gcry_mpi_t a, void *p, unsigned int nbits); + +/* Return a pointer to an opaque value stored in A and return its size + in NBITS. Note that the returned pointer is still owned by A and + that the function should never be used for an non-opaque MPI. */ +void *gcry_mpi_get_opaque (gcry_mpi_t a, unsigned int *nbits); + +/* Set the FLAG for the big integer A. Currently only the flag + GCRYMPI_FLAG_SECURE is allowed to convert A into an big intger + stored in "secure" memory. */ +void gcry_mpi_set_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); + +/* Clear FLAG for the big integer A. Note that this function is + currently useless as no flags are allowed. */ +void gcry_mpi_clear_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); + +/* Return true when the FLAG is set for A. */ +int gcry_mpi_get_flag (gcry_mpi_t a, enum gcry_mpi_flag flag); + +/* Unless the GCRYPT_NO_MPI_MACROS is used, provide a couple of + convenience macors for the big integer functions. */ +#ifndef GCRYPT_NO_MPI_MACROS +#define mpi_new(n) gcry_mpi_new( (n) ) +#define mpi_secure_new( n ) gcry_mpi_snew( (n) ) +#define mpi_release(a) \ + do \ + { \ + gcry_mpi_release ((a)); \ + (a) = NULL; \ + } \ + while (0) + +#define mpi_copy( a ) gcry_mpi_copy( (a) ) +#define mpi_set( w, u) gcry_mpi_set( (w), (u) ) +#define mpi_set_ui( w, u) gcry_mpi_set_ui( (w), (u) ) +#define mpi_cmp( u, v ) gcry_mpi_cmp( (u), (v) ) +#define mpi_cmp_ui( u, v ) gcry_mpi_cmp_ui( (u), (v) ) + +#define mpi_add_ui(w,u,v) gcry_mpi_add_ui((w),(u),(v)) +#define mpi_add(w,u,v) gcry_mpi_add ((w),(u),(v)) +#define mpi_addm(w,u,v,m) gcry_mpi_addm ((w),(u),(v),(m)) +#define mpi_sub_ui(w,u,v) gcry_mpi_sub_ui ((w),(u),(v)) +#define mpi_sub(w,u,v) gcry_mpi_sub ((w),(u),(v)) +#define mpi_subm(w,u,v,m) gcry_mpi_subm ((w),(u),(v),(m)) +#define mpi_mul_ui(w,u,v) gcry_mpi_mul_ui ((w),(u),(v)) +#define mpi_mul_2exp(w,u,v) gcry_mpi_mul_2exp ((w),(u),(v)) +#define mpi_mul(w,u,v) gcry_mpi_mul ((w),(u),(v)) +#define mpi_mulm(w,u,v,m) gcry_mpi_mulm ((w),(u),(v),(m)) +#define mpi_powm(w,b,e,m) gcry_mpi_powm ( (w), (b), (e), (m) ) +#define mpi_tdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), 0) +#define mpi_fdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), -1) +#define mpi_mod(r,a,m) gcry_mpi_mod ((r), (a), (m)) +#define mpi_gcd(g,a,b) gcry_mpi_gcd ( (g), (a), (b) ) +#define mpi_invm(g,a,b) gcry_mpi_invm ( (g), (a), (b) ) + +#define mpi_get_nbits(a) gcry_mpi_get_nbits ((a)) +#define mpi_test_bit(a,b) gcry_mpi_test_bit ((a),(b)) +#define mpi_set_bit(a,b) gcry_mpi_set_bit ((a),(b)) +#define mpi_set_highbit(a,b) gcry_mpi_set_highbit ((a),(b)) +#define mpi_clear_bit(a,b) gcry_mpi_clear_bit ((a),(b)) +#define mpi_clear_highbit(a,b) gcry_mpi_clear_highbit ((a),(b)) +#define mpi_rshift(a,b,c) gcry_mpi_rshift ((a),(b),(c)) + +#define mpi_set_opaque(a,b,c) gcry_mpi_set_opaque( (a), (b), (c) ) +#define mpi_get_opaque(a,b) gcry_mpi_get_opaque( (a), (b) ) +#endif /* GCRYPT_NO_MPI_MACROS */ + + + +/************************************ + * * + * symmetric cipher functions * + * * + ************************************/ + +/* The data object used to hold a handle to an encryption object. */ +struct gcry_cipher_handle; +typedef struct gcry_cipher_handle *gcry_cipher_hd_t; + +typedef struct gcry_cipher_handle *GCRY_CIPHER_HD _GCRY_GCC_ATTR_DEPRECATED; +typedef struct gcry_cipher_handle *GcryCipherHd _GCRY_GCC_ATTR_DEPRECATED; + +/* All symmetric encryption algorithms are identified by their IDs. + More IDs may be registered at runtime. */ +enum gcry_cipher_algos + { + GCRY_CIPHER_NONE = 0, + GCRY_CIPHER_IDEA = 1, + GCRY_CIPHER_3DES = 2, + GCRY_CIPHER_CAST5 = 3, + GCRY_CIPHER_BLOWFISH = 4, + GCRY_CIPHER_SAFER_SK128 = 5, + GCRY_CIPHER_DES_SK = 6, + GCRY_CIPHER_AES = 7, + GCRY_CIPHER_AES192 = 8, + GCRY_CIPHER_AES256 = 9, + GCRY_CIPHER_TWOFISH = 10, + + /* Other cipher numbers are above 300 for OpenPGP reasons. */ + GCRY_CIPHER_ARCFOUR = 301, /* Fully compatible with RSA's RC4 (tm). */ + GCRY_CIPHER_DES = 302, /* Yes, this is single key 56 bit DES. */ + GCRY_CIPHER_TWOFISH128 = 303, + GCRY_CIPHER_SERPENT128 = 304, + GCRY_CIPHER_SERPENT192 = 305, + GCRY_CIPHER_SERPENT256 = 306, + GCRY_CIPHER_RFC2268_40 = 307, /* Ron's Cipher 2 (40 bit). */ + GCRY_CIPHER_RFC2268_128 = 308, /* Ron's Cipher 2 (128 bit). */ + }; + +/* The Rijndael algorithm is basically AES, so provide some macros. */ +#define GCRY_CIPHER_AES128 GCRY_CIPHER_AES +#define GCRY_CIPHER_RIJNDAEL GCRY_CIPHER_AES +#define GCRY_CIPHER_RIJNDAEL128 GCRY_CIPHER_AES128 +#define GCRY_CIPHER_RIJNDAEL192 GCRY_CIPHER_AES192 +#define GCRY_CIPHER_RIJNDAEL256 GCRY_CIPHER_AES256 + +/* The supported encryption modes. Note that not all of them are + supported for each algorithm. */ +enum gcry_cipher_modes + { + GCRY_CIPHER_MODE_NONE = 0, /* Not yet specified. */ + GCRY_CIPHER_MODE_ECB = 1, /* Electronic codebook. */ + GCRY_CIPHER_MODE_CFB = 2, /* Cipher feedback. */ + GCRY_CIPHER_MODE_CBC = 3, /* Cipher block chaining. */ + GCRY_CIPHER_MODE_STREAM = 4, /* Used with stream ciphers. */ + GCRY_CIPHER_MODE_OFB = 5, /* Outer feedback. */ + GCRY_CIPHER_MODE_CTR = 6 /* Counter. */ + }; + +/* Flags used with the open function. */ +enum gcry_cipher_flags + { + GCRY_CIPHER_SECURE = 1, /* Allocate in secure memory. */ + GCRY_CIPHER_ENABLE_SYNC = 2, /* Enable CFB sync mode. */ + GCRY_CIPHER_CBC_CTS = 4, /* Enable CBC cipher text stealing (CTS). */ + GCRY_CIPHER_CBC_MAC = 8 /* Enable CBC message auth. code (MAC). */ + }; + + +/* Create a handle for algorithm ALGO to be used in MODE. FLAGS may + be given as an bitwise OR of the gcry_cipher_flags values. */ +gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *handle, + int algo, int mode, unsigned int flags); + +/* Close the cioher handle H and release all resource. */ +void gcry_cipher_close (gcry_cipher_hd_t h); + +/* Perform various operations on the cipher object H. */ +gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer, + size_t buflen); + +/* Retrieve various information about the cipher object H. */ +gcry_error_t gcry_cipher_info (gcry_cipher_hd_t h, int what, void *buffer, + size_t *nbytes); + +/* Retrieve various information about the cipher algorithm ALGO. */ +gcry_error_t gcry_cipher_algo_info (int algo, int what, void *buffer, + size_t *nbytes); + +/* Map the cipher algorithm id ALGO to a string representation of that + algorithm name. For unknown algorithms this functions returns an + empty string. */ +const char *gcry_cipher_algo_name (int algo) _GCRY_GCC_ATTR_PURE; + +/* Map the algorithm name NAME to an cipher algorithm ID. Return 0 if + the algorithm name is not known. */ +int gcry_cipher_map_name (const char *name) _GCRY_GCC_ATTR_PURE; + +/* Given an ASN.1 object identifier in standard IETF dotted decimal + format in STRING, return the encryption mode associated with that + OID or 0 if not known or applicable. */ +int gcry_cipher_mode_from_oid (const char *string) _GCRY_GCC_ATTR_PURE; + +/* Encrypt the plaintext of size INLEN in IN using the cipher handle H + into the buffer OUT which has an allocated length of OUTSIZE. For + most algorithms it is possible to pass NULL for in and 0 for INLEN + and do a in-place decryption of the data provided in OUT. */ +gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t h, + unsigned char *out, size_t outsize, + const unsigned char *in, size_t inlen); + +/* The counterpart to gcry_cipher_encrypt. */ +gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t h, + unsigned char *out, size_t outsize, + const unsigned char *in, size_t inlen); + +/* Set key K of length L for the cipher handle H. (We have to cast + away a const char* here - this catch-all ctl function was probably + not the best choice) */ +#define gcry_cipher_setkey(h,k,l) gcry_cipher_ctl( (h), GCRYCTL_SET_KEY, \ + (char*)(k), (l) ) + +/* Set initialization vector K of length L for the cipher handle H. */ +#define gcry_cipher_setiv(h,k,l) gcry_cipher_ctl( (h), GCRYCTL_SET_IV, \ + (char*)(k), (l) ) + +/* Reset the handle to the state after open. */ +#define gcry_cipher_reset(h) gcry_cipher_ctl ((h), GCRYCTL_RESET, NULL, 0) + +/* Perform the the OpenPGP sync operation if this is enabled for the + cipher handle H. */ +#define gcry_cipher_sync(h) gcry_cipher_ctl( (h), GCRYCTL_CFB_SYNC, \ + NULL, 0 ) + +/* Enable or disable CTS in future calls to gcry_encrypt(). CBC mode only. */ +#define gcry_cipher_cts(h,on) gcry_cipher_ctl( (h), GCRYCTL_SET_CBC_CTS, \ + NULL, on ) + +/* Set counter for CTR mode. (K,L) must denote a buffer of block size + length, or (NULL,0) to set the CTR to the all-zero block. */ +#define gcry_cipher_setctr(h,k,l) gcry_cipher_ctl( (h), GCRYCTL_SET_CTR, \ + (char*)(k), (l) ) + +/* Retrieved the key length used with algorithm A. */ +size_t gcry_cipher_get_algo_keylen (int algo); + +/* Retrieve the block length used with algorithm A. */ +size_t gcry_cipher_get_algo_blklen (int algo); + +/* Return 0 if the algorithm A is available for use. */ +#define gcry_cipher_test_algo(a) \ + gcry_cipher_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) + +/* Get a list consisting of the IDs of the loaded cipher modules. If + LIST is zero, write the number of loaded cipher modules to + LIST_LENGTH and return. If LIST is non-zero, the first + *LIST_LENGTH algorithm IDs are stored in LIST, which must be of + according size. In case there are less cipher modules than + *LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */ +gcry_error_t gcry_cipher_list (int *list, int *list_length); + + +/************************************ + * * + * asymmetric cipher functions * + * * + ************************************/ + +/* The algorithms and their IDs we support. */ +enum gcry_pk_algos + { + GCRY_PK_RSA = 1, + GCRY_PK_RSA_E = 2, /* deprecated */ + GCRY_PK_RSA_S = 3, /* deprecated */ + GCRY_PK_ELG_E = 16, /* use only for OpenPGP */ + GCRY_PK_DSA = 17, + GCRY_PK_ELG = 20 + }; + +/* Flags describing usage capabilities of a PK algorithm. */ +#define GCRY_PK_USAGE_SIGN 1 +#define GCRY_PK_USAGE_ENCR 2 + +/* Encrypt the DATA using the public key PKEY and store the result as + a newly created S-expression at RESULT. */ +gcry_error_t gcry_pk_encrypt (gcry_sexp_t *result, + gcry_sexp_t data, gcry_sexp_t pkey); + +/* Decrypt the DATA using the private key SKEY and store the result as + a newly created S-expression at RESULT. */ +gcry_error_t gcry_pk_decrypt (gcry_sexp_t *result, + gcry_sexp_t data, gcry_sexp_t skey); + +/* Sign the DATA using the private key SKEY and store the result as + a newly created S-expression at RESULT. */ +gcry_error_t gcry_pk_sign (gcry_sexp_t *result, + gcry_sexp_t data, gcry_sexp_t skey); + +/* Check the signature SIGVAL on DATA using the public key PKEY. */ +gcry_error_t gcry_pk_verify (gcry_sexp_t sigval, + gcry_sexp_t data, gcry_sexp_t pkey); + +/* Check that private KEY is sane. */ +gcry_error_t gcry_pk_testkey (gcry_sexp_t key); + +/* Generate a new key pair according to the parameters given in + S_PARMS. The new key pair is returned in as an S-expression in + R_KEY. */ +gcry_error_t gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms); + +/* Catch all function for miscellaneous operations. */ +gcry_error_t gcry_pk_ctl (int cmd, void *buffer, size_t buflen); + +/* Retrieve information about the public key algorithm ALGO. */ +gcry_error_t gcry_pk_algo_info (int algo, int what, + void *buffer, size_t *nbytes); + +/* Map the public key algorithm id ALGO to a string representation of the + algorithm name. For unknown algorithms this functions returns an + empty string. */ +const char *gcry_pk_algo_name (int algo) _GCRY_GCC_ATTR_PURE; + +/* Map the algorithm NAME to a public key algorithm Id. Return 0 if + the algorithm name is not known. */ +int gcry_pk_map_name (const char* name) _GCRY_GCC_ATTR_PURE; + +/* Return what is commonly referred as the key length for the given + public or private KEY. */ +unsigned int gcry_pk_get_nbits (gcry_sexp_t key) _GCRY_GCC_ATTR_PURE; + +/* Please note that keygrip is still experimental and should not be + used without contacting the author. */ +unsigned char *gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array); + +/* Return 0 if the public key algorithm A is available for use. */ +#define gcry_pk_test_algo(a) \ + gcry_pk_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) + +/* Get a list consisting of the IDs of the loaded pubkey modules. If + LIST is zero, write the number of loaded pubkey modules to + LIST_LENGTH and return. If LIST is non-zero, the first + *LIST_LENGTH algorithm IDs are stored in LIST, which must be of + according size. In case there are less pubkey modules than + *LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */ +gcry_error_t gcry_pk_list (int *list, int *list_length); + +/* Alternative interface for asymetric cryptography. */ + +/* The algorithm IDs. */ +typedef enum gcry_ac_id + { + GCRY_AC_RSA = 1, + GCRY_AC_DSA = 17, + GCRY_AC_ELG = 20, + GCRY_AC_ELG_E = 16, + } +gcry_ac_id_t; + +/* Key types. */ +typedef enum gcry_ac_key_type + { + GCRY_AC_KEY_SECRET, + GCRY_AC_KEY_PUBLIC, + } +gcry_ac_key_type_t; + +/* AC data. */ +#define GCRY_AC_FLAG_DEALLOC (1 << 0) +#define GCRY_AC_FLAG_COPY (1 << 1) +#define GCRY_AC_FLAG_NO_BLINDING (1 << 2) + +/* This type represents a `data set'. */ +typedef struct gcry_ac_data *gcry_ac_data_t; + +/* This type represents a single `key', either a secret one or a + public one. */ +typedef struct gcry_ac_key *gcry_ac_key_t; + +/* This type represents a `key pair' containing a secret and a public + key. */ +typedef struct gcry_ac_key_pair *gcry_ac_key_pair_t; + +/* This type represents a `handle' that is needed by functions + performing cryptographic operations. */ +typedef struct gcry_ac_handle *gcry_ac_handle_t; + +/* The caller of gcry_ac_key_pair_generate can provide one of these + structures in order to influence the key generation process in an + algorithm-specific way. */ +typedef struct gcry_ac_key_spec_rsa +{ + gcry_mpi_t e; /* E to use. */ +} gcry_ac_key_spec_rsa_t; + +/* Returns a new, empty data set in DATA. */ +gcry_error_t gcry_ac_data_new (gcry_ac_data_t *data); + +/* Destroy the data set DATA. */ +void gcry_ac_data_destroy (gcry_ac_data_t data); + +/* Create a copy of the data set DATA and store it in DATA_CP. */ +gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *data_cp, + gcry_ac_data_t data); + +/* Return the number of named MPI values inside of the data set + DATA. */ +unsigned int gcry_ac_data_length (gcry_ac_data_t data); + +/* Destroy any values contained in the data set DATA. */ +void gcry_ac_data_clear (gcry_ac_data_t data); + +/* Add the value MPI to DATA with the label NAME. If FLAGS contains + GCRY_AC_FLAG_DATA_COPY, the data set will contain copies of NAME + and MPI. If FLAGS contains GCRY_AC_FLAG_DATA_DEALLOC or + GCRY_AC_FLAG_DATA_COPY, the values contained in the data set will + be deallocated when they are to be removed from the data set. */ +gcry_error_t gcry_ac_data_set (gcry_ac_data_t data, unsigned int flags, + const char *name, gcry_mpi_t mpi); + +/* Store the value labelled with NAME found in DATA in MPI. If FLAGS + contains GCRY_AC_FLAG_COPY, store a copy of the MPI value contained + in the data set. MPI may be NULL. */ +gcry_error_t gcry_ac_data_get_name (gcry_ac_data_t data, unsigned int flags, + const char *name, gcry_mpi_t *mpi); + +/* Stores in NAME and MPI the named MPI value contained in the data + set DATA with the index IDX. If FLAGS contains GCRY_AC_FLAG_COPY, + store copies of the values contained in the data set. NAME or MPI + may be NULL. */ +gcry_error_t gcry_ac_data_get_index (gcry_ac_data_t data, unsigned int flags, + unsigned int idx, + const char **name, gcry_mpi_t *mpi); + +/* Create a new ac handle. */ +gcry_error_t gcry_ac_open (gcry_ac_handle_t *handle, + gcry_ac_id_t algorithm, unsigned int flags); + +/* Destroy an ac handle. */ +void gcry_ac_close (gcry_ac_handle_t handle); + +/* Initialize a key from a given data set. */ +gcry_error_t gcry_ac_key_init (gcry_ac_key_t *key, gcry_ac_handle_t handle, + gcry_ac_key_type_t type, gcry_ac_data_t data); + +/* Generates a new key pair via the handle HANDLE of NBITS bits and + stores it in KEY_PAIR. In case non-standard settings are wanted, a + pointer to a structure of type gcry_ac_key_spec__t, + matching the selected algorithm, can be given as KEY_SPEC. + MISC_DATA is not used yet. */ +gcry_error_t gcry_ac_key_pair_generate (gcry_ac_handle_t handle, + unsigned int nbits, void *spec, + gcry_ac_key_pair_t *key_pair, + gcry_mpi_t **misc_data); + +/* Returns the key of type WHICH out of the key pair KEY_PAIR. */ +gcry_ac_key_t gcry_ac_key_pair_extract (gcry_ac_key_pair_t key_pair, + gcry_ac_key_type_t which); + +/* Returns the data set contained in the key KEY. */ +gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t key); + +/* Verifies that the key KEY is sane via HANDLE. */ +gcry_error_t gcry_ac_key_test (gcry_ac_handle_t handle, gcry_ac_key_t key); + +/* Stores the number of bits of the key KEY in NBITS via HANDLE. */ +gcry_error_t gcry_ac_key_get_nbits (gcry_ac_handle_t handle, + gcry_ac_key_t key, unsigned int *nbits); + +/* Writes the 20 byte long key grip of the key KEY to KEY_GRIP via + HANDLE. */ +gcry_error_t gcry_ac_key_get_grip (gcry_ac_handle_t handle, gcry_ac_key_t key, + unsigned char *key_grip); + +/* Destroy a key. */ +void gcry_ac_key_destroy (gcry_ac_key_t key); + +/* Destroy a key pair. */ +void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t key_pair); + +/* Encrypt the plain text MPI value DATA_PLAIN with the key KEY under + the control of the flags FLAGS and store the resulting data set + into DATA_ENCRYPTED. */ +gcry_error_t gcry_ac_data_encrypt (gcry_ac_handle_t handle, + unsigned int flags, + gcry_ac_key_t key, + gcry_mpi_t data_plain, + gcry_ac_data_t *data_encrypted); + +/* Decrypt the decrypted data contained in the data set DATA_ENCRYPTED + with the key KEY under the control of the flags FLAGS and store the + resulting plain text MPI value in DATA_PLAIN. */ +gcry_error_t gcry_ac_data_decrypt (gcry_ac_handle_t handle, + unsigned int flags, + gcry_ac_key_t key, + gcry_mpi_t *data_plain, + gcry_ac_data_t data_encrypted); + +/* Sign the data contained in DATA with the key KEY and store the + resulting signature in the data set DATA_SIGNATURE. */ +gcry_error_t gcry_ac_data_sign (gcry_ac_handle_t handle, + gcry_ac_key_t key, + gcry_mpi_t data, + gcry_ac_data_t *data_signature); + +/* Verify that the signature contained in the data set DATA_SIGNATURE + is indeed the result of signing the data contained in DATA with the + secret key belonging to the public key KEY. */ +gcry_error_t gcry_ac_data_verify (gcry_ac_handle_t handle, + gcry_ac_key_t key, + gcry_mpi_t data, + gcry_ac_data_t data_signature); + +/* Store the textual representation of the algorithm whose id is given + in ALGORITHM in NAME. */ +gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t algorithm, + const char **name); + +/* Store the numeric ID of the algorithm whose textual representation + is contained in NAME in ALGORITHM. */ +gcry_error_t gcry_ac_name_to_id (const char *name, + gcry_ac_id_t *algorithm); + + + +/************************************ + * * + * cryptograhic hash functions * + * * + ************************************/ + +/* Algorithm IDs for the hash functions we know about. Not all of them + are implemnted. */ +enum gcry_md_algos + { + GCRY_MD_NONE = 0, + GCRY_MD_MD5 = 1, + GCRY_MD_SHA1 = 2, + GCRY_MD_RMD160 = 3, + GCRY_MD_MD2 = 5, + GCRY_MD_TIGER = 6, /* TIGER/192. */ + GCRY_MD_HAVAL = 7, /* HAVAL, 5 pass, 160 bit. */ + GCRY_MD_SHA256 = 8, + GCRY_MD_SHA384 = 9, + GCRY_MD_SHA512 = 10, + GCRY_MD_MD4 = 301, + GCRY_MD_CRC32 = 302, + GCRY_MD_CRC32_RFC1510 = 303, + GCRY_MD_CRC24_RFC2440 = 304 + }; + +/* Flags used with the open function. */ +enum gcry_md_flags + { + GCRY_MD_FLAG_SECURE = 1, /* Allocate all buffers in "secure" + memory. */ + GCRY_MD_FLAG_HMAC = 2 /* Make an HMAC out of this + algorithm. */ + }; + +/* Forward declaration. */ +struct gcry_md_context; + +/* This object is used to hold a handle to a message digest object. + This structure is private - only to be used by the public gcry_md_* + macros. */ +typedef struct gcry_md_handle +{ + /* Actual context. */ + struct gcry_md_context *ctx; + + /* Buffer management. */ + int bufpos; + int bufsize; + unsigned char buf[1]; +} *gcry_md_hd_t; + +/* Compatibility types, do not use them. */ +typedef struct gcry_md_handle *GCRY_MD_HD _GCRY_GCC_ATTR_DEPRECATED; +typedef struct gcry_md_handle *GcryMDHd _GCRY_GCC_ATTR_DEPRECATED; + +/* Create a message digest object for algorithm ALGO. FLAGS may be + given as an bitwise OR of the gcry_md_flags values. ALGO may be + given as 0 if the algorithms to be used are later set using + gcry_md_enable. */ +gcry_error_t gcry_md_open (gcry_md_hd_t *h, int algo, unsigned int flags); + +/* Release the message digest object HD. */ +void gcry_md_close (gcry_md_hd_t hd); + +/* Add the message digest algorithm ALGO to the digest object HD. */ +gcry_error_t gcry_md_enable (gcry_md_hd_t hd, int algo); + +/* Create a new digest object as an exact copy of the object HD. */ +gcry_error_t gcry_md_copy (gcry_md_hd_t *bhd, gcry_md_hd_t ahd); + +/* Reset the digest object HD to its initial state. */ +void gcry_md_reset (gcry_md_hd_t hd); + +/* Perform various operations on the digets object HD. */ +gcry_error_t gcry_md_ctl (gcry_md_hd_t hd, int cmd, unsigned char *buffer, + size_t buflen); + +/* Pass LENGTH bytes of data in BUFFER to the digest object HD so that + it can update the digest values. This is the actual hash + function. */ +void gcry_md_write (gcry_md_hd_t hd, const void *buffer, size_t length); + +/* Read out the final digest from HD return the digest value for + algorithm ALGO. */ +unsigned char *gcry_md_read (gcry_md_hd_t hd, int algo); + +/* Convenience function to calculate the hash from the data in BUFFER + of size LENGTH using the algorithm ALGO avoiding the creating of a + hash object. The hash is returned in the caller provided buffer + DIGEST which must be large enough to hold the digest of the given + algorithm. */ +void gcry_md_hash_buffer (int algo, void *digest, + const void *buffer, size_t length); + +/* Retrieve the algorithm used with HD. This does not work reliable + if more than one algorithm is enabled in HD. */ +int gcry_md_get_algo (gcry_md_hd_t hd); + +/* Retrieve the length in bytes of the digest yielded by algorithm + ALGO. */ +unsigned int gcry_md_get_algo_dlen (int algo); + +/* Return true if the the algorithm ALGO is enabled in the digest + object A. */ +int gcry_md_is_enabled (gcry_md_hd_t a, int algo); + +/* Return true if the digest object A is allocated in "secure" memory. */ +int gcry_md_is_secure (gcry_md_hd_t a); + +/* Retrieve various information about the object H. */ +gcry_error_t gcry_md_info (gcry_md_hd_t h, int what, void *buffer, + size_t *nbytes); + +/* Retrieve various information about the algorithm ALGO. */ +gcry_error_t gcry_md_algo_info (int algo, int what, void *buffer, + size_t *nbytes); + +/* Map the digest algorithm id ALGO to a string representation of the + algorithm name. For unknown algorithms this functions returns an + empty string. */ +const char *gcry_md_algo_name (int algo) _GCRY_GCC_ATTR_PURE; + +/* Map the algorithm NAME to a digest algorithm Id. Return 0 if + the algorithm name is not known. */ +int gcry_md_map_name (const char* name) _GCRY_GCC_ATTR_PURE; + +/* For use with the HMAC feature, the set MAC key to the KEY of + KEYLEN. */ +gcry_error_t gcry_md_setkey (gcry_md_hd_t hd, const void *key, size_t keylen); + +/* Update the hash(s) of H with the character C. This is a buffered + version of the gcry_md_write function. */ +#define gcry_md_putc(h,c) \ + do { \ + gcry_md_hd_t h__ = (h); \ + if( (h__)->bufpos == (h__)->bufsize ) \ + gcry_md_write( (h__), NULL, 0 ); \ + (h__)->buf[(h__)->bufpos++] = (c) & 0xff; \ + } while(0) + +/* Finalize the digest calculation. This is not really needed because + gcry_md_read() does this implicitly. */ +#define gcry_md_final(a) \ + gcry_md_ctl ((a), GCRYCTL_FINALIZE, NULL, 0) + +/* Return 0 if the algorithm A is available for use. */ +#define gcry_md_test_algo(a) \ + gcry_md_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL ) + +/* Return an DER encoded ASN.1 OID for the algorithm A in buffer B. N + must point to size_t variable with the available size of buffer B. + After return it will receive the actual size of the returned + OID. */ +#define gcry_md_get_asnoid(a,b,n) \ + gcry_md_algo_info((a), GCRYCTL_GET_ASNOID, (b), (n)) + +/* Enable debugging for digets object A; i.e. create files named + dbgmd-. while hashing. B is a string used as the suffix + for the filename. */ +#define gcry_md_start_debug(a,b) \ + gcry_md_ctl( (a), GCRYCTL_START_DUMP, (b), 0 ) + +/* Disable the debugging of A. */ +#define gcry_md_stop_debug(a,b) \ + gcry_md_ctl( (a), GCRYCTL_STOP_DUMP, (b), 0 ) + +/* Get a list consisting of the IDs of the loaded message digest + modules. If LIST is zero, write the number of loaded message + digest modules to LIST_LENGTH and return. If LIST is non-zero, the + first *LIST_LENGTH algorithm IDs are stored in LIST, which must be + of according size. In case there are less message digest modules + than *LIST_LENGTH, *LIST_LENGTH is updated to the correct + number. */ +gcry_error_t gcry_md_list (int *list, int *list_length); + + +/************************************ + * * + * random generating functions * + * * + ************************************/ + +/* The possible values for the random quality. The rule of thumb is + to use STRONG for session keys and VERY_STRONG for key material. + WEAK is currently an alias for STRONG and should not be used + anymore - use gcry_create_nonce instead. */ +typedef enum gcry_random_level + { + GCRY_WEAK_RANDOM = 0, + GCRY_STRONG_RANDOM = 1, + GCRY_VERY_STRONG_RANDOM = 2 + } +gcry_random_level_t; + +/* Fill BUFFER with LENGTH bytes of random, using random numbers of + quality LEVEL. */ +void gcry_randomize (unsigned char *buffer, size_t length, + enum gcry_random_level level); + +/* Add the external random from BUFFER with LENGTH bytes into the + pool. QUALITY should either be -1 for unknown or in the range of 0 + to 100 */ +gcry_error_t gcry_random_add_bytes (const void *buffer, size_t length, + int quality); + +/* Return NBYTES of allocated random using a random numbers of quality + LEVEL. */ +void *gcry_random_bytes (size_t nbytes, enum gcry_random_level level) + _GCRY_GCC_ATTR_MALLOC; + +/* Return NBYTES of allocated random using a random numbers of quality + LEVEL. The random numbers are created returned in "secure" + memory. */ +void *gcry_random_bytes_secure (size_t nbytes, enum gcry_random_level level) + _GCRY_GCC_ATTR_MALLOC; + + +/* Set the big integer W to a random value of NBITS using a random + generator with quality LEVEL. */ +void gcry_mpi_randomize (gcry_mpi_t w, + unsigned int nbits, enum gcry_random_level level); + + +/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */ +void gcry_create_nonce (unsigned char *buffer, size_t length); + + + +/* Prime interface. */ + +/* Mode values passed to a gcry_prime_check_func_t. */ +#define GCRY_PRIME_CHECK_AT_FINISH 0 +#define GCRY_PRIME_CHECK_AT_GOT_PRIME 1 +#define GCRY_PRIME_CHECK_AT_MAYBE_PRIME 2 + +/* The function should return 1 if the operation shall continue, 0 to + reject the prime candidate. */ +typedef int (*gcry_prime_check_func_t) (void *arg, int mode, + gcry_mpi_t candidate); + +/* Flags for gcry_prime_generate(): */ + +/* Allocate prime numbers and factors in secure memory. */ +#define GCRY_PRIME_FLAG_SECRET (1 << 0) + +/* Make sure that at least one prime factor is of size + `FACTOR_BITS'. */ +#define GCRY_PRIME_FLAG_SPECIAL_FACTOR (1 << 1) + +/* Generate a new prime number of PRIME_BITS bits and store it in + PRIME. If FACTOR_BITS is non-zero, one of the prime factors of + (prime - 1) / 2 must be FACTOR_BITS bits long. If FACTORS is + non-zero, allocate a new, NULL-terminated array holding the prime + factors and store it in FACTORS. FLAGS might be used to influence + the prime number generation process. */ +gcry_error_t gcry_prime_generate (gcry_mpi_t *prime, + unsigned int prime_bits, + unsigned int factor_bits, + gcry_mpi_t **factors, + gcry_prime_check_func_t cb_func, + void *cb_arg, + gcry_random_level_t random_level, + unsigned int flags); + +/* Find a generator for PRIME where the factorization of (prime-1) is + in the NULL terminated array FACTORS. Return the generator as a + newly allocated MPI in R_G. If START_G is not NULL, use this as + teh start for the search. */ +gcry_error_t gcry_prime_group_generator (gcry_mpi_t *r_g, + gcry_mpi_t prime, gcry_mpi_t *factors, + gcry_mpi_t start_g); + + +/* Convenience function to release the FACTORS array. */ +void gcry_prime_release_factors (gcry_mpi_t *factors); + + +/* Check wether the number X is prime. */ +gcry_error_t gcry_prime_check (gcry_mpi_t x, unsigned int flags); + + + +/************************************ + * * + * miscellaneous stuff * + * * + ************************************/ + +/* Log levels used by the internal logging facility. */ +enum gcry_log_levels + { + GCRY_LOG_CONT = 0, /* continue the last log line */ + GCRY_LOG_INFO = 10, + GCRY_LOG_WARN = 20, + GCRY_LOG_ERROR = 30, + GCRY_LOG_FATAL = 40, + GCRY_LOG_BUG = 50, + GCRY_LOG_DEBUG = 100 + }; + +/* Type for progress handlers. */ +typedef void (*gcry_handler_progress_t) (void *, const char *, int, int, int); + +/* Type for memory allocation handlers. */ +typedef void *(*gcry_handler_alloc_t) (size_t n); + +/* Type for secure memory check handlers. */ +typedef int (*gcry_handler_secure_check_t) (const void *); + +/* Type for memory reallocation handlers. */ +typedef void *(*gcry_handler_realloc_t) (void *p, size_t n); + +/* Type for memory free handlers. */ +typedef void (*gcry_handler_free_t) (void *); + +/* Type for out-of-memory handlers. */ +typedef int (*gcry_handler_no_mem_t) (void *, size_t, unsigned int); + +/* Type for fatal error handlers. */ +typedef void (*gcry_handler_error_t) (void *, int, const char *); + +/* Type for logging handlers. */ +typedef void (*gcry_handler_log_t) (void *, int, const char *, va_list); + +/* Certain operations can provide progress information. This function + is used to register a handler for retrieving these information. */ +void gcry_set_progress_handler (gcry_handler_progress_t cb, void *cb_data); + + +/* Register a custom memory allocation functions. */ +void gcry_set_allocation_handler ( + gcry_handler_alloc_t func_alloc, + gcry_handler_alloc_t func_alloc_secure, + gcry_handler_secure_check_t func_secure_check, + gcry_handler_realloc_t func_realloc, + gcry_handler_free_t func_free); + +/* Register a function used instead of the internal out of memory + handler. */ +void gcry_set_outofcore_handler (gcry_handler_no_mem_t h, void *opaque); + +/* Register a function used instead of the internal fatal error + handler. */ +void gcry_set_fatalerror_handler (gcry_handler_error_t fnc, void *opaque); + +/* Register a function used instead of the internal logging + facility. */ +void gcry_set_log_handler (gcry_handler_log_t f, void *opaque); + +/* Reserved for future use. */ +void gcry_set_gettext_handler (const char *(*f)(const char*)); + +/* Libgcrypt uses its own memory allocation. It is important to use + gcry_free () to release memory allocated by libgcrypt. */ +void *gcry_malloc (size_t n) _GCRY_GCC_ATTR_MALLOC; +void *gcry_calloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; +void *gcry_malloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; +void *gcry_calloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; +void *gcry_realloc (void *a, size_t n); +char *gcry_strdup (const char *string) _GCRY_GCC_ATTR_MALLOC; +void *gcry_xmalloc (size_t n) _GCRY_GCC_ATTR_MALLOC; +void *gcry_xcalloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; +void *gcry_xmalloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC; +void *gcry_xcalloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; +void *gcry_xrealloc (void *a, size_t n); +char *gcry_xstrdup (const char * a) _GCRY_GCC_ATTR_MALLOC; +void gcry_free (void *a); + +/* Return true if A is allocated in "secure" memory. */ +int gcry_is_secure (const void *a) _GCRY_GCC_ATTR_PURE; + +/* Include support for Libgcrypt modules. */ +#include + +#if 0 /* keep Emacsens' auto-indent happy */ +{ +#endif +#ifdef __cplusplus +} +#endif +#endif /* _GCRYPT_H */ diff --git a/pwmanager/libcrypt/crypt/global.c b/pwmanager/libcrypt/crypt/global.c new file mode 100644 index 0000000..9e7165b --- a/dev/null +++ b/pwmanager/libcrypt/crypt/global.c @@ -0,0 +1,672 @@ +/* global.c - global control functions + * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 + * 2004 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "g10lib.h" +#include "cipher.h" +#include "stdmem.h" /* our own memory allocator */ +#include "secmem.h" /* our own secmem allocator */ +#include "ath.h" + +/**************** + * flag bits: 0 : general cipher debug + * 1 : general MPI debug + */ +static unsigned int debug_flags; + +static gcry_handler_alloc_t alloc_func; +static gcry_handler_alloc_t alloc_secure_func; +static gcry_handler_secure_check_t is_secure_func; +static gcry_handler_realloc_t realloc_func; +static gcry_handler_free_t free_func; +static gcry_handler_no_mem_t outofcore_handler; + +static void *outofcore_handler_value = NULL; +static int no_secure_memory = 0; +static int any_init_done; + +/* This is our handmade constructor. It gets called by any function + likely to be called at startup. The suggested way for an + application to make sure that this has been called is by using + gcry_check_version. */ +static void +global_init (void) +{ + gcry_err_code_t err = GPG_ERR_NO_ERROR; + + if (any_init_done) + return; + any_init_done = 1; + + err = ath_init (); + if (! err) + _gcry_cipher_init (); + if (! err) + _gcry_md_init (); + if (! err) + _gcry_pk_init (); + + if (err) + /* FIXME? */ + BUG (); +} + + +static const char* +parse_version_number( const char *s, int *number ) +{ + int val = 0; + + if( *s == '0' && isdigit(s[1]) ) + return NULL; /* leading zeros are not allowed */ + for ( ; isdigit(*s); s++ ) { + val *= 10; + val += *s - '0'; + } + *number = val; + return val < 0? NULL : s; +} + + +static const char * +parse_version_string( const char *s, int *major, int *minor, int *micro ) +{ + s = parse_version_number( s, major ); + if( !s || *s != '.' ) + return NULL; + s++; + s = parse_version_number( s, minor ); + if( !s || *s != '.' ) + return NULL; + s++; + s = parse_version_number( s, micro ); + if( !s ) + return NULL; + return s; /* patchlevel */ +} + +/**************** + * Check that the the version of the library is at minimum the requested one + * and return the version string; return NULL if the condition is not + * satisfied. If a NULL is passed to this function, no check is done, + * but the version string is simply returned. + */ +const char * +gcry_check_version( const char *req_version ) +{ + const char *ver = VERSION; + int my_major, my_minor, my_micro; + int rq_major, rq_minor, rq_micro; + const char *my_plvl, *rq_plvl; + + global_init (); + if ( !req_version ) + return ver; + + my_plvl = parse_version_string( ver, &my_major, &my_minor, &my_micro ); + if ( !my_plvl ) + return NULL; /* very strange our own version is bogus */ + rq_plvl = parse_version_string( req_version, &rq_major, &rq_minor, + &rq_micro ); + if ( !rq_plvl ) + return NULL; /* req version string is invalid */ + + if ( my_major > rq_major + || (my_major == rq_major && my_minor > rq_minor) + || (my_major == rq_major && my_minor == rq_minor + && my_micro > rq_micro) + || (my_major == rq_major && my_minor == rq_minor + && my_micro == rq_micro + && strcmp( my_plvl, rq_plvl ) >= 0) ) { + return ver; + } + return NULL; +} + +gcry_error_t +gcry_control (enum gcry_ctl_cmds cmd, ...) +{ + gcry_err_code_t err = GPG_ERR_NO_ERROR; + static int init_finished = 0; + va_list arg_ptr; + + va_start (arg_ptr, cmd); + switch (cmd) + { + case GCRYCTL_ENABLE_M_GUARD: + _gcry_private_enable_m_guard (); + break; + + case GCRYCTL_ENABLE_QUICK_RANDOM: + _gcry_quick_random_gen (1); + break; + + case GCRYCTL_DUMP_RANDOM_STATS: + _gcry_random_dump_stats (); + break; + + case GCRYCTL_DUMP_MEMORY_STATS: + /*m_print_stats("[fixme: prefix]");*/ + break; + + case GCRYCTL_DUMP_SECMEM_STATS: + _gcry_secmem_dump_stats (); + break; + + case GCRYCTL_DROP_PRIVS: + global_init (); + _gcry_secmem_init (0); + break; + + case GCRYCTL_DISABLE_SECMEM: + global_init (); + no_secure_memory = 1; + break; + + case GCRYCTL_INIT_SECMEM: + global_init (); + _gcry_secmem_init (va_arg (arg_ptr, unsigned int)); + break; + + case GCRYCTL_TERM_SECMEM: + global_init (); + _gcry_secmem_term (); + break; + + case GCRYCTL_DISABLE_SECMEM_WARN: + _gcry_secmem_set_flags ((_gcry_secmem_get_flags () + | GCRY_SECMEM_FLAG_NO_WARNING)); + break; + + case GCRYCTL_SUSPEND_SECMEM_WARN: + _gcry_secmem_set_flags ((_gcry_secmem_get_flags () + | GCRY_SECMEM_FLAG_SUSPEND_WARNING)); + break; + + case GCRYCTL_RESUME_SECMEM_WARN: + _gcry_secmem_set_flags ((_gcry_secmem_get_flags () + & ~GCRY_SECMEM_FLAG_SUSPEND_WARNING)); + break; + + case GCRYCTL_USE_SECURE_RNDPOOL: + global_init (); + _gcry_secure_random_alloc (); /* put random number into secure memory */ + break; + + case GCRYCTL_SET_RANDOM_SEED_FILE: + _gcry_set_random_seed_file (va_arg (arg_ptr, const char *)); + break; + + case GCRYCTL_UPDATE_RANDOM_SEED_FILE: + _gcry_update_random_seed_file (); + break; + + case GCRYCTL_SET_VERBOSITY: + _gcry_set_log_verbosity (va_arg (arg_ptr, int)); + break; + + case GCRYCTL_SET_DEBUG_FLAGS: + debug_flags |= va_arg (arg_ptr, unsigned int); + break; + + case GCRYCTL_CLEAR_DEBUG_FLAGS: + debug_flags &= ~va_arg (arg_ptr, unsigned int); + break; + + case GCRYCTL_DISABLE_INTERNAL_LOCKING: + global_init (); + break; + + case GCRYCTL_ANY_INITIALIZATION_P: + if (any_init_done) + err = GPG_ERR_GENERAL; + break; + + case GCRYCTL_INITIALIZATION_FINISHED_P: + if (init_finished) + err = GPG_ERR_GENERAL; + break; + + case GCRYCTL_INITIALIZATION_FINISHED: + /* This is a hook which should be used by an application after + all initialization has been done and right before any threads + are started. It is not really needed but the only way to be + really sure that all initialization for thread-safety has + been done. */ + if (! init_finished) + { + global_init (); + _gcry_random_initialize (); + init_finished = 1; + } + break; + + case GCRYCTL_SET_THREAD_CBS: + err = ath_install (va_arg (arg_ptr, void *), any_init_done); + break; + + default: + err = GPG_ERR_INV_OP; + } + + va_end(arg_ptr); + return gcry_error (err); +} + +/* Return a pointer to a string containing a description of the error + code in the error value ERR. */ +const char * +gcry_strerror (gcry_error_t err) +{ + return gpg_strerror (err); +} + +/* Return a pointer to a string containing a description of the error + source in the error value ERR. */ +const char * +gcry_strsource (gcry_error_t err) +{ + return gpg_strsource (err); +} + +/* Retrieve the error code for the system error ERR. This returns + GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report + this). */ +gcry_err_code_t +gcry_err_code_from_errno (int err) +{ + return gpg_err_code_from_errno (err); +} + + +/* Retrieve the system error for the error code CODE. This returns 0 + if CODE is not a system error code. */ +int +gcry_err_code_to_errno (gcry_err_code_t code) +{ + return gpg_err_code_from_errno (code); +} + + +/* Return an error value with the error source SOURCE and the system + error ERR. */ +gcry_error_t +gcry_err_make_from_errno (gpg_err_source_t source, int err) +{ + return gpg_err_make_from_errno (source, err); +} + + +/* Return an error value with the system error ERR. */ +gcry_err_code_t +gcry_error_from_errno (int err) +{ + return gcry_error (gpg_err_code_from_errno (err)); +} + +/**************** + * NOTE: All 5 functions should be set. */ +void +gcry_set_allocation_handler (gcry_handler_alloc_t new_alloc_func, + gcry_handler_alloc_t new_alloc_secure_func, + gcry_handler_secure_check_t new_is_secure_func, + gcry_handler_realloc_t new_realloc_func, + gcry_handler_free_t new_free_func) +{ + global_init (); + + alloc_func = new_alloc_func; + alloc_secure_func = new_alloc_secure_func; + is_secure_func = new_is_secure_func; + realloc_func = new_realloc_func; + free_func = new_free_func; +} + + + +/**************** + * Set an optional handler which is called in case the xmalloc functions + * ran out of memory. This handler may do one of these things: + * o free some memory and return true, so that the xmalloc function + * tries again. + * o Do whatever it like and return false, so that the xmalloc functions + * use the default fatal error handler. + * o Terminate the program and don't return. + * + * The handler function is called with 3 arguments: The opaque value set with + * this function, the requested memory size, and a flag with these bits + * currently defined: + * bit 0 set = secure memory has been requested. + */ +void +gcry_set_outofcore_handler( int (*f)( void*, size_t, unsigned int ), + void *value ) +{ + global_init (); + + outofcore_handler = f; + outofcore_handler_value = value; +} + +gcry_err_code_t +_gcry_malloc (size_t n, unsigned int flags, void **mem) +{ + gcry_err_code_t err = GPG_ERR_NO_ERROR; + void *m = NULL; + + if ((flags & GCRY_ALLOC_FLAG_SECURE) && !no_secure_memory) + { + if (alloc_secure_func) + m = (*alloc_secure_func) (n); + else + m = _gcry_private_malloc_secure (n); + } + else + { + if (alloc_func) + m = (*alloc_func) (n); + else + m = _gcry_private_malloc (n); + } + + if (! m) + err = gpg_err_code_from_errno (ENOMEM); + else + *mem = m; + + return err; +} + +void * +gcry_malloc (size_t n) +{ + void *mem = NULL; + + _gcry_malloc (n, 0, &mem); + + return mem; +} + +void * +gcry_malloc_secure (size_t n) +{ + void *mem = NULL; + + _gcry_malloc (n, GCRY_ALLOC_FLAG_SECURE, &mem); + + return mem; +} + +int +gcry_is_secure (const void *a) +{ + if (no_secure_memory) + return 0; + if (is_secure_func) + return is_secure_func (a) ; + return _gcry_private_is_secure (a); +} + +void +_gcry_check_heap( const void *a ) +{ + /* FIXME: implement this*/ +#if 0 + if( some_handler ) + some_handler(a) + else + _gcry_private_check_heap(a) +#endif +} + +void * +gcry_realloc (void *a, size_t n) +{ + if (realloc_func) + return realloc_func (a, n); + return _gcry_private_realloc (a, n); +} + +void +gcry_free( void *p ) +{ + if( !p ) + return; + + if (free_func) + free_func (p); + else + _gcry_private_free (p); +} + +void * +gcry_calloc (size_t n, size_t m) +{ + size_t bytes; + void *p; + + bytes = n * m; /* size_t is unsigned so the behavior on overflow is + defined. */ + if (m && bytes / m != n) + { + errno = ENOMEM; + return NULL; + } + + p = gcry_malloc (bytes); + if (p) + memset (p, 0, bytes); + return p; +} + +void * +gcry_calloc_secure (size_t n, size_t m) +{ + size_t bytes; + void *p; + + bytes = n * m; /* size_t is unsigned so the behavior on overflow is + defined. */ + if (m && bytes / m != n) + { + errno = ENOMEM; + return NULL; + } + + p = gcry_malloc_secure (bytes); + if (p) + memset (p, 0, bytes); + return p; +} + + +/* Create and return a copy of the null-terminated string STRING. If + it is contained in secure memory, the copy will be contained in + secure memory as well. In an out-of-memory condition, NULL is + returned. */ +char * +gcry_strdup (const char *string) +{ + char *string_cp = NULL; + size_t string_n = 0; + + string_n = strlen (string); + + if (gcry_is_secure (string)) + string_cp = gcry_malloc_secure (string_n + 1); + else + string_cp = gcry_malloc (string_n + 1); + + if (string_cp) + strcpy (string_cp, string); + + return string_cp; +} + + +void * +gcry_xmalloc( size_t n ) +{ + void *p; + + while ( !(p = gcry_malloc( n )) ) { + if( !outofcore_handler + || !outofcore_handler( outofcore_handler_value, n, 0 ) ) { + _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL ); + } + } + return p; +} + +void * +gcry_xrealloc( void *a, size_t n ) +{ + void *p; + + while ( !(p = gcry_realloc( a, n )) ) { + if( !outofcore_handler + || !outofcore_handler( outofcore_handler_value, n, 2 ) ) { + _gcry_fatal_error(gpg_err_code_from_errno (errno), NULL ); + } + } + return p; +} + +void * +gcry_xmalloc_secure( size_t n ) +{ + void *p; + + while ( !(p = gcry_malloc_secure( n )) ) { + if( !outofcore_handler + || !outofcore_handler( outofcore_handler_value, n, 1 ) ) { + _gcry_fatal_error(gpg_err_code_from_errno (errno), + _("out of core in secure memory")); + } + } + return p; +} + +void * +gcry_xcalloc( size_t n, size_t m ) +{ + void *p = gcry_xmalloc( n*m ); + memset( p, 0, n*m ); + return p; +} + +void * +gcry_xcalloc_secure( size_t n, size_t m ) +{ + void *p = gcry_xmalloc_secure( n* m ); + memset( p, 0, n*m ); + return p; +} + +char * +gcry_xstrdup (const char *string) +{ + char *p; + + while ( !(p = gcry_strdup (string)) ) + { + size_t n = strlen (string); + int is_sec = !!gcry_is_secure (string); + + if (!outofcore_handler + || !outofcore_handler (outofcore_handler_value, n, is_sec) ) + { + _gcry_fatal_error (gpg_err_code_from_errno (errno), + is_sec? _("out of core in secure memory"):NULL); + } + } + + strcpy( p, string ); + return p; +} + + +int +_gcry_get_debug_flag( unsigned int mask ) +{ + return debug_flags & mask; +} + + + +/* It is often useful to get some feedback of long running operations. + This function may be used to register a handler for this. + The callback function CB is used as: + + void cb (void *opaque, const char *what, int printchar, + int current, int total); + + Where WHAT is a string identifying the the type of the progress + output, PRINTCHAR the character usually printed, CURRENT the amount + of progress currently done and TOTAL the expected amount of + progress. A value of 0 for TOTAL indicates that there is no + estimation available. + + Defined values for WHAT: + + "need_entropy" X 0 number-of-bytes-required + When running low on entropy + "primegen" '\n' 0 0 + Prime generated + '!' + Need to refresh the prime pool + '<','>' + Number of bits adjusted + '^' + Looking for a generator + '.' + Fermat tests on 10 candidates failed + ':' + Restart with a new random value + '+' + Rabin Miller test passed + "pk_elg" '+','-','.','\n' 0 0 + Only used in debugging mode. + "pk_dsa" + Only used in debugging mode. +*/ +void +gcry_set_progress_handler (void (*cb)(void *,const char*,int, int, int), + void *cb_data) +{ +#if USE_DSA + _gcry_register_pk_dsa_progress (cb, cb_data); +#endif +#if USE_ELGAMAL + _gcry_register_pk_elg_progress (cb, cb_data); +#endif + _gcry_register_primegen_progress (cb, cb_data); + _gcry_register_random_progress (cb, cb_data); +} diff --git a/pwmanager/libcrypt/crypt/misc.c b/pwmanager/libcrypt/crypt/misc.c new file mode 100644 index 0000000..6b630e6 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/misc.c @@ -0,0 +1,241 @@ +/* misc.c + * Copyright (C) 1999, 2001, 2002, 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "g10lib.h" + +static int verbosity_level = 0; + +static void (*fatal_error_handler)(void*,int, const char*) = NULL; +static void *fatal_error_handler_value = 0; +static void (*log_handler)(void*,int, const char*, va_list) = NULL; +static void *log_handler_value = 0; + +static const char *(*user_gettext_handler)( const char * ) = NULL; + +void +gcry_set_gettext_handler( const char *(*f)(const char*) ) +{ + user_gettext_handler = f; +} + + +const char * +_gcry_gettext( const char *key ) +{ + if( user_gettext_handler ) + return user_gettext_handler( key ); + /* FIXME: switch the domain to gnupg and restore later */ + return key; +} + +void +gcry_set_fatalerror_handler( void (*fnc)(void*,int, const char*), void *value) +{ + fatal_error_handler_value = value; + fatal_error_handler = fnc; +} + +static void +write2stderr( const char *s ) +{ + write( 2, s, strlen(s) ); +} + +/* + * This function is called for fatal errors. A caller might want to + * set his own handler because this function simply calls abort(). + */ +void +_gcry_fatal_error (int rc, const char *text) +{ + if ( !text ) /* get a default text */ + text = gpg_strerror (rc); + + if (fatal_error_handler) + fatal_error_handler (fatal_error_handler_value, rc, text); + + write2stderr("\nFatal error: "); + write2stderr(text); + write2stderr("\n"); + abort (); +} + +void +gcry_set_log_handler( void (*f)(void*,int, const char*, va_list ), + void *opaque ) +{ + log_handler = f; + log_handler_value = opaque; +} + +void +_gcry_set_log_verbosity( int level ) +{ + verbosity_level = level; +} + +int +_gcry_log_verbosity( int level ) +{ + return verbosity_level >= level; +} + +/**************** + * This is our log function which prints all log messages to stderr or + * using the function defined with gcry_set_log_handler(). + */ +static void +_gcry_logv( int level, const char *fmt, va_list arg_ptr ) +{ + if( log_handler ) + log_handler( log_handler_value, level, fmt, arg_ptr ); + else { + switch ( level ) { + case GCRY_LOG_CONT: break; + case GCRY_LOG_INFO: break; + case GCRY_LOG_WARN: break; + case GCRY_LOG_ERROR: break; + case GCRY_LOG_FATAL: fputs("Fatal: ",stderr ); break; + case GCRY_LOG_BUG: fputs("Ohhhh jeeee: ", stderr); break; + case GCRY_LOG_DEBUG: fputs("DBG: ", stderr ); break; + default: fprintf(stderr,"[Unknown log level %d]: ", level ); break; + } + vfprintf(stderr,fmt,arg_ptr) ; + } + + if( level == GCRY_LOG_FATAL ) + exit(2); + else if( level == GCRY_LOG_BUG ) + abort(); +} + +void +_gcry_log( int level, const char *fmt, ... ) +{ + va_list arg_ptr ; + + va_start( arg_ptr, fmt ) ; + _gcry_logv( level, fmt, arg_ptr ); + va_end(arg_ptr); +} + + +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5 ) +void +_gcry_bug( const char *file, int line, const char *func ) +{ + _gcry_log( GCRY_LOG_BUG, + ("... this is a bug (%s:%d:%s)\n"), file, line, func ); + abort(); /* never called, but it makes the compiler happy */ +} +#else +void +_gcry_bug( const char *file, int line ) +{ + _gcry_log( GCRY_LOG_BUG, + _("you found a bug ... (%s:%d)\n"), file, line); + abort(); /* never called, but it makes the compiler happy */ +} +#endif + +void +_gcry_log_info( const char *fmt, ... ) +{ + va_list arg_ptr ; + + va_start( arg_ptr, fmt ) ; + _gcry_logv( GCRY_LOG_INFO, fmt, arg_ptr ); + va_end(arg_ptr); +} + +void +_gcry_log_error( const char *fmt, ... ) +{ + va_list arg_ptr ; + + va_start( arg_ptr, fmt ) ; + _gcry_logv( GCRY_LOG_ERROR, fmt, arg_ptr ); + va_end(arg_ptr); +} + + +void +_gcry_log_fatal( const char *fmt, ... ) +{ + va_list arg_ptr ; + + va_start( arg_ptr, fmt ) ; + _gcry_logv( GCRY_LOG_FATAL, fmt, arg_ptr ); + va_end(arg_ptr); + abort(); /* never called, but it makes the compiler happy */ +} + +void +_gcry_log_bug( const char *fmt, ... ) +{ + va_list arg_ptr ; + + va_start( arg_ptr, fmt ) ; + _gcry_logv( GCRY_LOG_BUG, fmt, arg_ptr ); + va_end(arg_ptr); + abort(); /* never called, but it makes the compiler happy */ +} + +void +_gcry_log_debug( const char *fmt, ... ) +{ + va_list arg_ptr ; + + va_start( arg_ptr, fmt ) ; + _gcry_logv( GCRY_LOG_DEBUG, fmt, arg_ptr ); + va_end(arg_ptr); +} + +void +_gcry_log_printf (const char *fmt, ...) +{ + va_list arg_ptr; + + if (fmt) + { + va_start( arg_ptr, fmt ) ; + _gcry_logv (GCRY_LOG_CONT, fmt, arg_ptr); + va_end(arg_ptr); + } +} + +void +_gcry_burn_stack (int bytes) +{ + char buf[64]; + + wipememory (buf, sizeof buf); + bytes -= sizeof buf; + if (bytes > 0) + _gcry_burn_stack (bytes); +} diff --git a/pwmanager/libcrypt/crypt/missing-string.c b/pwmanager/libcrypt/crypt/missing-string.c new file mode 100644 index 0000000..80ff052 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/missing-string.c @@ -0,0 +1,151 @@ +/* missing-string.c - missing string utilities + * Copyright (C) 1994, 1998, 1999, 2000, 2001, + * 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include + +#include "g10lib.h" + + +#ifndef HAVE_STPCPY +char * +stpcpy(char *a,const char *b) +{ + while( *b ) + *a++ = *b++; + *a = 0; + + return (char*)a; +} +#endif + + +#ifndef HAVE_STRCASECMP +int +strcasecmp( const char *a, const char *b ) +{ + for( ; *a && *b; a++, b++ ) { + if( *a != *b && toupper(*a) != toupper(*b) ) + break; + } + return *(const byte*)a - *(const byte*)b; +} +#endif + + +#ifdef __MINGW32__ +/* + * Like vsprintf but provides a pointer to malloc'd storage, which + * must be freed by the caller (gcry_free). Taken from libiberty as + * found in gcc-2.95.2 and a little bit modernized. + * FIXME: Write a new CRT for W32. + */ +int +vasprintf ( char **result, const char *format, va_list args) +{ + const char *p = format; + /* Add one to make sure that it is never zero, which might cause malloc + to return NULL. */ + int total_width = strlen (format) + 1; + va_list ap; + + /* this is not really portable but works under Windows */ + memcpy ( &ap, &args, sizeof (va_list)); + + while (*p != '\0') + { + if (*p++ == '%') + { + while (strchr ("-+ #0", *p)) + ++p; + if (*p == '*') + { + ++p; + total_width += abs (va_arg (ap, int)); + } + else + { + char *endp; + total_width += strtoul (p, &endp, 10); + p = endp; + } + if (*p == '.') + { + ++p; + if (*p == '*') + { + ++p; + total_width += abs (va_arg (ap, int)); + } + else + { + char *endp; + total_width += strtoul (p, &endp, 10); + p = endp; + } + } + while (strchr ("hlL", *p)) + ++p; + /* Should be big enough for any format specifier except %s + and floats. */ + total_width += 30; + switch (*p) + { + case 'd': + case 'i': + case 'o': + case 'u': + case 'x': + case 'X': + case 'c': + (void) va_arg (ap, int); + break; + case 'f': + case 'e': + case 'E': + case 'g': + case 'G': + (void) va_arg (ap, double); + /* Since an ieee double can have an exponent of 307, we'll + make the buffer wide enough to cover the gross case. */ + total_width += 307; + + case 's': + total_width += strlen (va_arg (ap, char *)); + break; + case 'p': + case 'n': + (void) va_arg (ap, char *); + break; + } + } + } + *result = gcry_malloc (total_width); + if (*result != NULL) + return vsprintf (*result, format, args); + else + return 0; +} + +#endif /*__MINGW32__*/ + diff --git a/pwmanager/libcrypt/crypt/module.c b/pwmanager/libcrypt/crypt/module.c new file mode 100644 index 0000000..e98c36e --- a/dev/null +++ b/pwmanager/libcrypt/crypt/module.c @@ -0,0 +1,200 @@ +/* module.c - Module management for libgcrypt. + * Copyright (C) 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include "g10lib.h" + +#define MODULE_ID_MIN 600 + +/* Internal function. Generate a new, unique module ID for a module + that should be inserted into the module chain starting at + MODULES. */ +static gcry_err_code_t +_gcry_module_id_new (gcry_module_t modules, unsigned int *id_new) +{ + /* FIXME, what should be the ID of the first module registered by + the user? */ + unsigned int id_min = MODULE_ID_MIN, id_max = (unsigned int) -1, mod_id; + gcry_err_code_t err = GPG_ERR_NO_ERROR; + gcry_module_t module; + + /* Search for unused ID. */ + for (mod_id = id_min; mod_id < id_max; mod_id++) + { + /* Search for a module with the current ID. */ + for (module = modules; module; module = module->next) + if (mod_id == module->mod_id) + break; + + if (! module) + /* None found -> the ID is available for use. */ + break; + } + + if (mod_id < id_max) + /* Done. */ + *id_new = mod_id; + else + /* No free ID found. */ + err = GPG_ERR_INTERNAL; + + return err; +} + +/* Add a module specification to the list ENTRIES. The new module has + it's use-counter set to one. */ +gcry_err_code_t +_gcry_module_add (gcry_module_t *entries, unsigned int mod_id, + void *spec, gcry_module_t *module) +{ + gcry_err_code_t err = 0; + gcry_module_t entry; + + if (! mod_id) + err = _gcry_module_id_new (*entries, &mod_id); + + if (! err) + { + entry = gcry_malloc (sizeof (struct gcry_module)); + if (! entry) + err = gpg_err_code_from_errno (errno); + } + + if (! err) + { + /* Fill new module entry. */ + entry->flags = 0; + entry->counter = 1; + entry->spec = spec; + entry->mod_id = mod_id; + + /* Link it into the list. */ + entry->next = *entries; + entry->prevp = entries; + if (*entries) + (*entries)->prevp = &entry->next; + *entries = entry; + + /* And give it to the caller. */ + if (module) + *module = entry; + } + return err; +} + +/* Internal function. Unlink CIPHER_ENTRY from the list of registered + ciphers and destroy it. */ +static void +_gcry_module_drop (gcry_module_t entry) +{ + *entry->prevp = entry->next; + if (entry->next) + entry->next->prevp = entry->prevp; + + gcry_free (entry); +} + +/* Lookup a module specification by it's ID. After a successfull + lookup, the module has it's resource counter incremented. */ +gcry_module_t +_gcry_module_lookup_id (gcry_module_t entries, unsigned int mod_id) +{ + gcry_module_t entry; + + for (entry = entries; entry; entry = entry->next) + if (entry->mod_id == mod_id) + { + entry->counter++; + break; + } + + return entry; +} + +/* Lookup a module specification. After a successfull lookup, the + module has it's resource counter incremented. FUNC is a function + provided by the caller, which is responsible for identifying the + wanted module. */ +gcry_module_t +_gcry_module_lookup (gcry_module_t entries, void *data, + gcry_module_lookup_t func) +{ + gcry_module_t entry; + + for (entry = entries; entry; entry = entry->next) + if ((*func) (entry->spec, data)) + { + entry->counter++; + break; + } + + return entry; +} + +/* Release a module. In case the use-counter reaches zero, destroy + the module. Passing MODULE as NULL is a dummy operation (similar + to free()). */ +void +_gcry_module_release (gcry_module_t module) +{ + if (module && ! --module->counter) + _gcry_module_drop (module); +} + +/* Add a reference to a module. */ +void +_gcry_module_use (gcry_module_t module) +{ + ++module->counter; +} + +/* If LIST is zero, write the number of modules identified by MODULES + to LIST_LENGTH and return. If LIST is non-zero, the first + *LIST_LENGTH algorithm IDs are stored in LIST, which must be of + according size. In case there are less cipher modules than + *LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */ +gcry_err_code_t +_gcry_module_list (gcry_module_t modules, + int *list, int *list_length) +{ + gcry_err_code_t err = GPG_ERR_NO_ERROR; + gcry_module_t module; + int length, i; + + for (module = modules, length = 0; module; module = module->next, length++); + + if (list) + { + if (length > *list_length) + length = *list_length; + + for (module = modules, i = 0; i < length; module = module->next, i++) + list[i] = module->mod_id; + + if (length < *list_length) + *list_length = length; + } + else + *list_length = length; + + return err; +} diff --git a/pwmanager/libcrypt/crypt/mpi.h b/pwmanager/libcrypt/crypt/mpi.h new file mode 100644 index 0000000..9e0037e --- a/dev/null +++ b/pwmanager/libcrypt/crypt/mpi.h @@ -0,0 +1,199 @@ +/* mpi.h - Multi Precision Integers + * Copyright (C) 1994, 1996, 1998, 2001, 2002, 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * Note: This code is heavily based on the GNU MP Library. + * Actually it's the same code with only minor changes in the + * way the data is stored; this is to support the abstraction + * of an optional secure memory allocation which may be used + * to avoid revealing of sensitive data due to paging etc. + */ + +#ifndef G10_MPI_H +#define G10_MPI_H + +#include +#include +#include "types.h" +#include "memory.h" +#include "../mpi/mpi-asm-defs.h" + +#include "g10lib.h" + +#ifndef _GCRYPT_IN_LIBGCRYPT +#error this file should only be used inside libgcrypt +#endif + +#ifndef BITS_PER_MPI_LIMB +#if BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_INT + typedef unsigned int mpi_limb_t; + typedef signed int mpi_limb_signed_t; +#elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG + typedef unsigned long int mpi_limb_t; + typedef signed long int mpi_limb_signed_t; +#elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_LONG_LONG + typedef unsigned long long int mpi_limb_t; + typedef signed long long int mpi_limb_signed_t; +#elif BYTES_PER_MPI_LIMB == SIZEOF_UNSIGNED_SHORT + typedef unsigned short int mpi_limb_t; + typedef signed short int mpi_limb_signed_t; +#else +#error BYTES_PER_MPI_LIMB does not match any C type +#endif +#define BITS_PER_MPI_LIMB (8*BYTES_PER_MPI_LIMB) +#endif /*BITS_PER_MPI_LIMB*/ + +#define DBG_MPI _gcry_get_debug_flag( 2 ); + +struct gcry_mpi { + int alloced; /* array size (# of allocated limbs) */ + int nlimbs; /* number of valid limbs */ + int sign; /* indicates a negative number and is used for opaque + * MPIs to store the length */ + unsigned flags; /* bit 0: array must be allocated in secure memory space */ + /* bit 2: the limb is a pointer to some m_alloced data */ + mpi_limb_t *d; /* array with the limbs */ +}; + +#define MPI_NULL NULL + +#define mpi_get_nlimbs(a) ((a)->nlimbs) +#define mpi_is_neg(a) ((a)->sign) + +/*-- mpiutil.c --*/ + +#ifdef M_DEBUG +#define mpi_alloc(n) _gcry_mpi_debug_alloc((n), M_DBGINFO( __LINE__ ) ) +#define mpi_alloc_secure(n) _gcry_mpi_debug_alloc_secure((n), M_DBGINFO( __LINE__ ) ) +#define mpi_free(a) _gcry_mpi_debug_free((a), M_DBGINFO(__LINE__) ) +#define mpi_resize(a,b) _gcry_mpi_debug_resize((a),(b), M_DBGINFO(__LINE__) ) +#define mpi_copy(a) _gcry_mpi_debug_copy((a), M_DBGINFO(__LINE__) ) + gcry_mpi_t _gcry_mpi_debug_alloc( unsigned nlimbs, const char *info ); + gcry_mpi_t _gcry_mpi_debug_alloc_secure( unsigned nlimbs, const char *info ); + void _gcry_mpi_debug_free( gcry_mpi_t a, const char *info ); + void _gcry_mpi_debug_resize( gcry_mpi_t a, unsigned nlimbs, const char *info ); + gcry_mpi_t _gcry_mpi_debug_copy( gcry_mpi_t a, const char *info ); +#else +#define mpi_alloc(n) _gcry_mpi_alloc((n) ) +#define mpi_alloc_secure(n) _gcry_mpi_alloc_secure((n) ) +#define mpi_free(a) _gcry_mpi_free((a) ) +#define mpi_resize(a,b) _gcry_mpi_resize((a),(b)) +#define mpi_copy(a) _gcry_mpi_copy((a)) + gcry_mpi_t _gcry_mpi_alloc( unsigned nlimbs ); + gcry_mpi_t _gcry_mpi_alloc_secure( unsigned nlimbs ); + void _gcry_mpi_free( gcry_mpi_t a ); + void _gcry_mpi_resize( gcry_mpi_t a, unsigned nlimbs ); + gcry_mpi_t _gcry_mpi_copy( gcry_mpi_t a ); +#endif +#define mpi_is_opaque(a) ((a) && ((a)->flags&4)) +#define mpi_is_secure(a) ((a) && ((a)->flags&1)) +#define mpi_clear(a) _gcry_mpi_clear ((a)) +#define mpi_alloc_like(a) _gcry_mpi_alloc_like((a)) +#define mpi_set(a,b) _gcry_mpi_set ((a),(b)) +#define mpi_set_ui(a,b) _gcry_mpi_set_ui ((a),(b)) +#define mpi_alloc_set_ui(a) _gcry_mpi_alloc_set_ui ((a)) +#define mpi_m_check(a) _gcry_mpi_m_check ((a)) +#define mpi_swap(a,b) _gcry_mpi_swap ((a),(b)) + +void _gcry_mpi_clear( gcry_mpi_t a ); +gcry_mpi_t _gcry_mpi_alloc_like( gcry_mpi_t a ); +void _gcry_mpi_set( gcry_mpi_t w, gcry_mpi_t u); +void _gcry_mpi_set_ui( gcry_mpi_t w, ulong u); +gcry_mpi_t _gcry_mpi_alloc_set_ui( unsigned long u); +void _gcry_mpi_m_check( gcry_mpi_t a ); +void _gcry_mpi_swap( gcry_mpi_t a, gcry_mpi_t b); + +/*-- mpicoder.c --*/ +void _gcry_log_mpidump( const char *text, gcry_mpi_t a ); +u32 _gcry_mpi_get_keyid( gcry_mpi_t a, u32 *keyid ); +byte *_gcry_mpi_get_buffer( gcry_mpi_t a, unsigned *nbytes, int *sign ); +byte *_gcry_mpi_get_secure_buffer( gcry_mpi_t a, unsigned *nbytes, int *sign ); +void _gcry_mpi_set_buffer( gcry_mpi_t a, const byte *buffer, unsigned nbytes, int sign ); + +#define log_mpidump _gcry_log_mpidump + +/*-- mpi-add.c --*/ +#define mpi_add_ui(w,u,v) gcry_mpi_add_ui((w),(u),(v)) +#define mpi_add(w,u,v) gcry_mpi_add ((w),(u),(v)) +#define mpi_addm(w,u,v,m) gcry_mpi_addm ((w),(u),(v),(m)) +#define mpi_sub_ui(w,u,v) gcry_mpi_sub_ui ((w),(u),(v)) +#define mpi_sub(w,u,v) gcry_mpi_sub ((w),(u),(v)) +#define mpi_subm(w,u,v,m) gcry_mpi_subm ((w),(u),(v),(m)) + + +/*-- mpi-mul.c --*/ +#define mpi_mul_ui(w,u,v) gcry_mpi_mul_ui ((w),(u),(v)) +#define mpi_mul_2exp(w,u,v) gcry_mpi_mul_2exp ((w),(u),(v)) +#define mpi_mul(w,u,v) gcry_mpi_mul ((w),(u),(v)) +#define mpi_mulm(w,u,v,m) gcry_mpi_mulm ((w),(u),(v),(m)) + + +/*-- mpi-div.c --*/ +#define mpi_fdiv_r_ui(a,b,c) _gcry_mpi_fdiv_r_ui((a),(b),(c)) +#define mpi_fdiv_r(a,b,c) _gcry_mpi_fdiv_r((a),(b),(c)) +#define mpi_fdiv_q(a,b,c) _gcry_mpi_fdiv_q((a),(b),(c)) +#define mpi_fdiv_qr(a,b,c,d) _gcry_mpi_fdiv_qr((a),(b),(c),(d)) +#define mpi_tdiv_r(a,b,c) _gcry_mpi_tdiv_r((a),(b),(c)) +#define mpi_tdiv_qr(a,b,c,d) _gcry_mpi_tdiv_qr((a),(b),(c),(d)) +#define mpi_tdiv_q_2exp(a,b,c) _gcry_mpi_tdiv_q_2exp((a),(b),(c)) +#define mpi_divisible_ui(a,b) _gcry_mpi_divisible_ui((a),(b)) +ulong _gcry_mpi_fdiv_r_ui( gcry_mpi_t rem, gcry_mpi_t dividend, ulong divisor ); +void _gcry_mpi_fdiv_r( gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor ); +void _gcry_mpi_fdiv_q( gcry_mpi_t quot, gcry_mpi_t dividend, gcry_mpi_t divisor ); +void _gcry_mpi_fdiv_qr( gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t dividend, gcry_mpi_t divisor ); +void _gcry_mpi_tdiv_r( gcry_mpi_t rem, gcry_mpi_t num, gcry_mpi_t den); +void _gcry_mpi_tdiv_qr( gcry_mpi_t quot, gcry_mpi_t rem, gcry_mpi_t num, gcry_mpi_t den); +void _gcry_mpi_tdiv_q_2exp( gcry_mpi_t w, gcry_mpi_t u, unsigned count ); +int _gcry_mpi_divisible_ui(gcry_mpi_t dividend, ulong divisor ); + +/*-- mpi-gcd.c --*/ + +/*-- mpi-mpow.c --*/ +#define mpi_mulpowm(a,b,c,d) _gcry_mpi_mulpowm ((a),(b),(c),(d)) +void _gcry_mpi_mulpowm( gcry_mpi_t res, gcry_mpi_t *basearray, gcry_mpi_t *exparray, gcry_mpi_t mod); + +/*-- mpi-cmp.c --*/ +#define mpi_cmp_ui(a,b) gcry_mpi_cmp_ui ((a),(b)) +#define mpi_cmp(a,b) gcry_mpi_cmp ((a),(b)) +int gcry_mpi_cmp_ui( gcry_mpi_t u, ulong v ); +int gcry_mpi_cmp( gcry_mpi_t u, gcry_mpi_t v ); + +/*-- mpi-scan.c --*/ +#define mpi_trailing_zeros(a) _gcry_mpi_trailing_zeros ((a)) +int _gcry_mpi_getbyte( gcry_mpi_t a, unsigned idx ); +void _gcry_mpi_putbyte( gcry_mpi_t a, unsigned idx, int value ); +unsigned _gcry_mpi_trailing_zeros( gcry_mpi_t a ); + +/*-- mpi-bit.c --*/ +#define mpi_normalize(a) _gcry_mpi_normalize ((a)) +#define mpi_get_nbits(a) gcry_mpi_get_nbits ((a)) +#define mpi_test_bit(a,b) gcry_mpi_test_bit ((a),(b)) +#define mpi_set_bit(a,b) gcry_mpi_set_bit ((a),(b)) +#define mpi_set_highbit(a,b) gcry_mpi_set_highbit ((a),(b)) +#define mpi_clear_bit(a,b) gcry_mpi_clear_bit ((a),(b)) +#define mpi_clear_highbit(a,b) gcry_mpi_clear_highbit ((a),(b)) +#define mpi_rshift(a,b,c) gcry_mpi_rshift ((a),(b),(c)) + +void _gcry_mpi_normalize( gcry_mpi_t a ); + +/*-- mpi-inv.c --*/ +#define mpi_invm(a,b,c) _gcry_mpi_invm ((a),(b),(c)) +void _gcry_mpi_invm( gcry_mpi_t x, gcry_mpi_t u, gcry_mpi_t v ); + + +#endif /*G10_MPI_H*/ diff --git a/pwmanager/libcrypt/crypt/secmem.c b/pwmanager/libcrypt/crypt/secmem.c new file mode 100644 index 0000000..163bf20 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/secmem.c @@ -0,0 +1,653 @@ +/* secmem.c - memory allocation from a secure heap + * Copyright (C) 1998, 1999, 2000, 2001, 2002, + * 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(HAVE_MLOCK) || defined(HAVE_MMAP) +#include +#include +#include +#ifdef USE_CAPABILITIES +#include +#endif +#endif + +#include "ath.h" +#include "g10lib.h" +#include "secmem.h" + +#if defined (MAP_ANON) && ! defined (MAP_ANONYMOUS) +#define MAP_ANONYMOUS MAP_ANON +#endif + +#define DEFAULT_POOL_SIZE 16384 +#define DEFAULT_PAGE_SIZE 4096 + +typedef struct memblock +{ + unsigned size; /* Size of the memory available to the + user. */ + int flags; /* See below. */ + PROPERLY_ALIGNED_TYPE aligned; +} memblock_t; + +/* This flag specifies that the memory block is in use. */ +#define MB_FLAG_ACTIVE 1 << 0 + +/* The pool of secure memory. */ +static void *pool; + +/* Size of POOL in bytes. */ +static size_t pool_size; + +/* True, if the memory pool is ready for use. May be checked in an + atexit function. */ +static volatile int pool_okay; + +/* True, if the memory pool is mmapped. */ +static volatile int pool_is_mmapped; + +/* FIXME? */ +static int disable_secmem; +static int show_warning; +static int no_warning; +static int suspend_warning; + +/* Stats. */ +static unsigned int cur_alloced, cur_blocks; + +/* Lock protecting accesses to the memory pool. */ +static ath_mutex_t secmem_lock; + +/* Convenient macros. */ +#define SECMEM_LOCK ath_mutex_lock (&secmem_lock) +#define SECMEM_UNLOCK ath_mutex_unlock (&secmem_lock) + +/* The size of the memblock structure; this does not include the + memory that is available to the user. */ +#define BLOCK_HEAD_SIZE \ + offsetof (memblock_t, aligned) + +/* Convert an address into the according memory block structure. */ +#define ADDR_TO_BLOCK(addr) \ + (memblock_t *) ((char *) addr - BLOCK_HEAD_SIZE) + +/* Check wether MB is a valid block. */ +#define BLOCK_VALID(mb) \ + (((char *) mb - (char *) pool) < pool_size) + +/* Update the stats. */ +static void +stats_update (size_t add, size_t sub) +{ + if (add) + { + cur_alloced += add; + cur_blocks++; + } + if (sub) + { + cur_alloced -= sub; + cur_blocks--; + } +} + +/* Return the block following MB or NULL, if MB is the last block. */ +static memblock_t * +mb_get_next (memblock_t *mb) +{ + memblock_t *mb_next; + + mb_next = (memblock_t *) ((char *) mb + BLOCK_HEAD_SIZE + mb->size); + + if (! BLOCK_VALID (mb_next)) + mb_next = NULL; + + return mb_next; +} + +/* Return the block preceeding MB or NULL, if MB is the first + block. */ +static memblock_t * +mb_get_prev (memblock_t *mb) +{ + memblock_t *mb_prev, *mb_next; + + if (mb == pool) + mb_prev = NULL; + else + { + mb_prev = (memblock_t *) pool; + while (1) + { + mb_next = mb_get_next (mb_prev); + if (mb_next == mb) + break; + else + mb_prev = mb_next; + } + } + + return mb_prev; +} + +/* If the preceeding block of MB and/or the following block of MB + exist and are not active, merge them to form a bigger block. */ +static void +mb_merge (memblock_t *mb) +{ + memblock_t *mb_prev, *mb_next; + + mb_prev = mb_get_prev (mb); + mb_next = mb_get_next (mb); + + if (mb_prev && (! (mb_prev->flags & MB_FLAG_ACTIVE))) + { + mb_prev->size += BLOCK_HEAD_SIZE + mb->size; + mb = mb_prev; + } + if (mb_next && (! (mb_next->flags & MB_FLAG_ACTIVE))) + mb->size += BLOCK_HEAD_SIZE + mb_next->size; +} + +/* Return a new block, which can hold SIZE bytes. */ +static memblock_t * +mb_get_new (memblock_t *block, size_t size) +{ + memblock_t *mb, *mb_split; + + for (mb = block; BLOCK_VALID (mb); mb = mb_get_next (mb)) + if (! (mb->flags & MB_FLAG_ACTIVE) && mb->size >= size) + { + /* Found a free block. */ + mb->flags |= MB_FLAG_ACTIVE; + + if (mb->size - size > BLOCK_HEAD_SIZE) + { + /* Split block. */ + + mb_split = (memblock_t *) (((char *) mb) + BLOCK_HEAD_SIZE + size); + mb_split->size = mb->size - size - BLOCK_HEAD_SIZE; + mb_split->flags = 0; + + mb->size = size; + + mb_merge (mb_split); + + } + + break; + } + + if (! BLOCK_VALID (mb)) + mb = NULL; + + return mb; +} + +/* Print a warning message. */ +static void +print_warn (void) +{ + if (!no_warning) + log_info (_("Warning: using insecure memory!\n")); +} + +/* Lock the memory pages into core and drop privileges. */ +static void +lock_pool (void *p, size_t n) +{ +#if defined(USE_CAPABILITIES) && defined(HAVE_MLOCK) + int err; + + cap_set_proc (cap_from_text ("cap_ipc_lock+ep")); + err = mlock (p, n); + if (err && errno) + err = errno; + cap_set_proc (cap_from_text ("cap_ipc_lock+p")); + + if (err) + { + if (errno != EPERM +#ifdef EAGAIN /* OpenBSD returns this */ + && errno != EAGAIN +#endif +#ifdef ENOSYS /* Some SCOs return this (function not implemented) */ + && errno != ENOSYS +#endif +#ifdef ENOMEM /* Linux might return this. */ + && errno != ENOMEM +#endif + ) + log_error ("can't lock memory: %s\n", strerror (err)); + show_warning = 1; + } + +#elif defined(HAVE_MLOCK) + uid_t uid; + int err; + + uid = getuid (); + +#ifdef HAVE_BROKEN_MLOCK + /* Under HP/UX mlock segfaults if called by non-root. Note, we have + noch checked whether mlock does really work under AIX where we + also detected a broken nlock. Note further, that using plock () + is not a good idea under AIX. */ + if (uid) + { + errno = EPERM; + err = errno; + } + else + { + err = mlock (p, n); + if (err && errno) + err = errno; + } +#else /* !HAVE_BROKEN_MLOCK */ + err = mlock (p, n); + if (err && errno) + err = errno; +#endif /* !HAVE_BROKEN_MLOCK */ + + if (uid && ! geteuid ()) + { + /* check that we really dropped the privs. + * Note: setuid(0) should always fail */ + if (setuid (uid) || getuid () != geteuid () || !setuid (0)) + log_fatal ("failed to reset uid: %s\n", strerror (errno)); + } + + if (err) + { + if (errno != EPERM +#ifdef EAGAIN /* OpenBSD returns this. */ + && errno != EAGAIN +#endif +#ifdef ENOSYS /* Some SCOs return this (function not implemented). */ + && errno != ENOSYS +#endif +#ifdef ENOMEM /* Linux might return this. */ + && errno != ENOMEM +#endif + ) + log_error ("can't lock memory: %s\n", strerror (err)); + show_warning = 1; + } + +#elif defined ( __QNX__ ) + /* QNX does not page at all, so the whole secure memory stuff does + * not make much sense. However it is still of use because it + * wipes out the memory on a free(). + * Therefore it is sufficient to suppress the warning + */ +#elif defined (HAVE_DOSISH_SYSTEM) || defined (__CYGWIN__) + /* It does not make sense to print such a warning, given the fact that + * this whole Windows !@#$% and their user base are inherently insecure + */ +#elif defined (__riscos__) + /* no virtual memory on RISC OS, so no pages are swapped to disc, + * besides we don't have mmap, so we don't use it! ;-) + * But don't complain, as explained above. + */ +#else + log_info ("Please note that you don't have secure memory on this system\n"); +#endif +} + +/* Initialize POOL. */ +static void +init_pool (size_t n) +{ + size_t pgsize; + memblock_t *mb; + + pool_size = n; + + if (disable_secmem) + log_bug ("secure memory is disabled"); + +#ifdef HAVE_GETPAGESIZE + pgsize = getpagesize (); +#else + pgsize = DEFAULT_PAGE_SIZE; +#endif + +#if HAVE_MMAP + pool_size = (pool_size + pgsize - 1) & ~(pgsize - 1); +#ifdef MAP_ANONYMOUS + pool = mmap (0, pool_size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); +#else /* map /dev/zero instead */ + { + int fd; + + fd = open ("/dev/zero", O_RDWR); + if (fd == -1) + { + log_error ("can't open /dev/zero: %s\n", strerror (errno)); + pool = (void *) -1; + } + else + { + pool = mmap (0, pool_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); + } + } +#endif + if (pool == (void *) -1) + log_info ("can't mmap pool of %u bytes: %s - using malloc\n", + (unsigned) pool_size, strerror (errno)); + else + { + pool_is_mmapped = 1; + pool_okay = 1; + } + +#endif + if (!pool_okay) + { + pool = malloc (pool_size); + if (!pool) + log_fatal ("can't allocate memory pool of %u bytes\n", + (unsigned) pool_size); + else + pool_okay = 1; + } + + /* Initialize first memory block. */ + mb = (memblock_t *) pool; + mb->size = pool_size; + mb->flags = 0; +} + +void +_gcry_secmem_set_flags (unsigned flags) +{ + int was_susp; + + SECMEM_LOCK; + + was_susp = suspend_warning; + no_warning = flags & GCRY_SECMEM_FLAG_NO_WARNING; + suspend_warning = flags & GCRY_SECMEM_FLAG_SUSPEND_WARNING; + + /* and now issue the warning if it is not longer suspended */ + if (was_susp && !suspend_warning && show_warning) + { + show_warning = 0; + print_warn (); + } + + SECMEM_UNLOCK; +} + +unsigned +_gcry_secmem_get_flags (void) +{ + unsigned flags; + + SECMEM_LOCK; + + flags = no_warning ? GCRY_SECMEM_FLAG_NO_WARNING : 0; + flags |= suspend_warning ? GCRY_SECMEM_FLAG_SUSPEND_WARNING : 0; + + SECMEM_UNLOCK; + + return flags; +} + +/* Initialize the secure memory system. If running with the necessary + privileges, the secure memory pool will be locked into the core in + order to prevent page-outs of the data. Furthermore allocated + secure memory will be wiped out when released. */ +void +_gcry_secmem_init (size_t n) +{ + SECMEM_LOCK; + + if (!n) + { +#ifdef USE_CAPABILITIES + /* drop all capabilities */ + cap_set_proc (cap_from_text ("all-eip")); + +#elif !defined(HAVE_DOSISH_SYSTEM) + uid_t uid; + + disable_secmem = 1; + uid = getuid (); + if (uid != geteuid ()) + { + if (setuid (uid) || getuid () != geteuid () || !setuid (0)) + log_fatal ("failed to drop setuid\n"); + } +#endif + } + else + { + if (n < DEFAULT_POOL_SIZE) + n = DEFAULT_POOL_SIZE; + if (! pool_okay) + { + init_pool (n); + if (! geteuid ()) + lock_pool (pool, n); + else if (!no_warning) + log_info ("Secure memory is not locked into core\n"); + } + else + log_error ("Oops, secure memory pool already initialized\n"); + } + + SECMEM_UNLOCK; +} + + +static void * +_gcry_secmem_malloc_internal (size_t size) +{ + memblock_t *mb; + + if (!pool_okay) + { + log_info (_ + ("operation is not possible without initialized secure memory\n")); + exit (2); + } + if (show_warning && !suspend_warning) + { + show_warning = 0; + print_warn (); + } + + /* Blocks are always a multiple of 32. */ + size = ((size + 31) / 32) * 32; + + mb = mb_get_new ((memblock_t *) pool, size); + if (mb) + stats_update (size, 0); + + return mb ? &mb->aligned.c : NULL; +} + +void * +_gcry_secmem_malloc (size_t size) +{ + void *p; + + SECMEM_LOCK; + p = _gcry_secmem_malloc_internal (size); + SECMEM_UNLOCK; + + return p; +} + +static void +_gcry_secmem_free_internal (void *a) +{ + memblock_t *mb; + int size; + + if (!a) + return; + + mb = ADDR_TO_BLOCK (a); + size = mb->size; + + /* This does not make much sense: probably this memory is held in the + * cache. We do it anyway: */ +#define MB_WIPE_OUT(byte) \ + memset ((memblock_t *) ((char *) mb + BLOCK_HEAD_SIZE), (byte), size); + + MB_WIPE_OUT (0xff); + MB_WIPE_OUT (0xaa); + MB_WIPE_OUT (0x55); + MB_WIPE_OUT (0x00); + + stats_update (0, size); + + mb->flags &= ~MB_FLAG_ACTIVE; + + /* Update stats. */ + + mb_merge (mb); +} + +/* Wipe out and release memory. */ +void +_gcry_secmem_free (void *a) +{ + SECMEM_LOCK; + _gcry_secmem_free_internal (a); + SECMEM_UNLOCK; +} + +/* Realloc memory. */ +void * +_gcry_secmem_realloc (void *p, size_t newsize) +{ + memblock_t *mb; + size_t size; + void *a; + + SECMEM_LOCK; + + mb = (memblock_t *) ((char *) p - ((size_t) &((memblock_t *) 0)->aligned.c)); + size = mb->size; + if (newsize < size) + { + /* It is easier to not shrink the memory. */ + a = p; + } + else + { + a = _gcry_secmem_malloc_internal (newsize); + if (a) + { + memcpy (a, p, size); + memset ((char *) a + size, 0, newsize - size); + _gcry_secmem_free_internal (p); + } + } + + SECMEM_UNLOCK; + + return a; +} + +int +_gcry_private_is_secure (const void *p) +{ + int ret = 0; + + SECMEM_LOCK; + + if (pool_okay && BLOCK_VALID (ADDR_TO_BLOCK (p))) + ret = 1; + + SECMEM_UNLOCK; + + return ret; +} + + +/**************** + * Warning: This code might be called by an interrupt handler + * and frankly, there should really be such a handler, + * to make sure that the memory is wiped out. + * We hope that the OS wipes out mlocked memory after + * receiving a SIGKILL - it really should do so, otherwise + * there is no chance to get the secure memory cleaned. + */ +void +_gcry_secmem_term () +{ + if (!pool_okay) + return; + + wipememory2 (pool, 0xff, pool_size); + wipememory2 (pool, 0xaa, pool_size); + wipememory2 (pool, 0x55, pool_size); + wipememory2 (pool, 0x00, pool_size); +#if HAVE_MMAP + if (pool_is_mmapped) + munmap (pool, pool_size); +#endif + pool = NULL; + pool_okay = 0; + pool_size = 0; +} + + +void +_gcry_secmem_dump_stats () +{ +#if 1 + SECMEM_LOCK; + + if (pool_okay) + log_info ("secmem usage: %u/%lu bytes in %u blocks\n", + cur_alloced, (unsigned long)pool_size, cur_blocks); + SECMEM_UNLOCK; +#else + memblock_t *mb; + int i; + + SECMEM_LOCK; + + for (i = 0, mb = (memblock_t *) pool; + BLOCK_VALID (mb); + mb = mb_get_next (mb), i++) + log_info ("SECMEM: [%s] block: %i; size: %i\n", + (mb->flags & MB_FLAG_ACTIVE) ? "used" : "free", + i, + mb->size); + SECMEM_UNLOCK; +#endif +} diff --git a/pwmanager/libcrypt/crypt/secmem.h b/pwmanager/libcrypt/crypt/secmem.h new file mode 100644 index 0000000..54e16ba --- a/dev/null +++ b/pwmanager/libcrypt/crypt/secmem.h @@ -0,0 +1,38 @@ +/* secmem.h - internal definitions for secmem + * Copyright (C) 2000, 2001, 2002, 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef G10_SECMEM_H +#define G10_SECMEM_H 1 + +void _gcry_secmem_init (size_t npool); +void _gcry_secmem_term (void); +void *_gcry_secmem_malloc (size_t size) GCC_ATTR_MALLOC; +void *_gcry_secmem_realloc (void *a, size_t newsize); +void _gcry_secmem_free (void *a); +void _gcry_secmem_dump_stats (void); +void _gcry_secmem_set_flags (unsigned flags); +unsigned _gcry_secmem_get_flags(void) GCC_ATTR_PURE; +int _gcry_private_is_secure (const void *p) GCC_ATTR_PURE; + +/* Flags for _gcry_secmem_{set,get}_flags. */ +#define GCRY_SECMEM_FLAG_NO_WARNING 1 << 0 +#define GCRY_SECMEM_FLAG_SUSPEND_WARNING 1 << 1 + +#endif /* G10_SECMEM_H */ diff --git a/pwmanager/libcrypt/crypt/sexp.c b/pwmanager/libcrypt/crypt/sexp.c new file mode 100644 index 0000000..c19dc33 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/sexp.c @@ -0,0 +1,1804 @@ +/* sexp.c - S-Expression handling + * Copyright (C) 1999, 2000, 2001, 2002, 2003, + * 2004 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + + +#include +#include +#include +#include +#include +#include +#include + +#define GCRYPT_NO_MPI_MACROS 1 +#include "g10lib.h" +#include "memory.h" + +typedef struct gcry_sexp *NODE; +typedef unsigned short DATALEN; + +struct gcry_sexp +{ + byte d[1]; +}; + +#define ST_STOP 0 +#define ST_DATA 1 /* datalen follows */ +#define ST_HINT 2 /* datalen follows */ +#define ST_OPEN 3 +#define ST_CLOSE 4 + +/* the atoi macros assume that the buffer has only valid digits */ +#define atoi_1(p) (*(p) - '0' ) +#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \ + *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10)) +#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1)) + +#define TOKEN_SPECIALS "-./_:*+=" + +static gcry_error_t +sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff, + const char *buffer, size_t length, int argflag, + va_list arg_ptr, void **arg_list); + +#if 0 +static void +dump_mpi( gcry_mpi_t a ) +{ + char buffer[1000]; + size_t n = 1000; + + if( !a ) + fputs("[no MPI]", stderr ); + else if( gcry_mpi_print( GCRYMPI_FMT_HEX, buffer, &n, a ) ) + fputs("[MPI too large to print]", stderr ); + else + fputs( buffer, stderr ); +} +#endif + +static void +dump_string (const byte *p, size_t n, int delim ) +{ + for (; n; n--, p++ ) + { + if ((*p & 0x80) || iscntrl( *p ) || *p == delim ) + { + if( *p == '\n' ) + log_printf ("\\n"); + else if( *p == '\r' ) + log_printf ("\\r"); + else if( *p == '\f' ) + log_printf ("\\f"); + else if( *p == '\v' ) + log_printf ("\\v"); + else if( *p == '\b' ) + log_printf ("\\b"); + else if( !*p ) + log_printf ("\\0"); + else + log_printf ("\\x%02x", *p ); + } + else + log_printf ("%c", *p); + } +} + + +void +gcry_sexp_dump (const gcry_sexp_t a) +{ + const byte *p; + int indent = 0; + int type; + + if (!a) + { + log_printf ( "[nil]\n"); + return; + } + + p = a->d; + while ( (type = *p) != ST_STOP ) + { + p++; + switch ( type ) + { + case ST_OPEN: + log_printf ("%*s[open]\n", 2*indent, ""); + indent++; + break; + case ST_CLOSE: + if( indent ) + indent--; + log_printf ("%*s[close]\n", 2*indent, ""); + break; + case ST_DATA: { + DATALEN n; + memcpy ( &n, p, sizeof n ); + p += sizeof n; + log_printf ("%*s[data=\"", 2*indent, "" ); + dump_string (p, n, '\"' ); + log_printf ("\"]\n"); + p += n; + } + break; + default: + log_printf ("%*s[unknown tag %d]\n", 2*indent, "", type); + break; + } + } +} + +/**************** + * Pass list through except when it is an empty list - in that case + * return NULL and release the passed list. + */ +static gcry_sexp_t +normalize ( gcry_sexp_t list ) +{ + char *p; + if ( !list ) + return NULL; + p = list->d; + if ( *p == ST_STOP ) { + /* this is "" */ + gcry_sexp_release ( list ); + return NULL; + } + if( *p == ST_OPEN && p[1] == ST_CLOSE ) { + /* this is "()" */ + gcry_sexp_release ( list ); + return NULL; + } + + return list; +} + +/* Create a new S-expression object by reading LENGTH bytes from + BUFFER, assuming it is canonilized encoded or autodetected encoding + when AUTODETECT is set to 1. With FREEFNC not NULL, ownership of + the buffer is transferred to tyhe newle created object. FREEFNC + should be the freefnc used to release BUFFER; there is no guarantee + at which point this function is called; most likey you want to use + free() or gcry_free(). + + Passing LENGTH and AUTODETECT as 0 is allowed to indicate that + BUFFER points to a valid canonical encoded S-expression. A LENGTH + of 0 and AUTODETECT 1 indicates that buffer points to a + null-terminated string. + + This function returns 0 and and the pointer to the new object in + RETSEXP or an error code in which case RETSEXP is set to NULL. */ +gcry_error_t +gcry_sexp_create (gcry_sexp_t *retsexp, void *buffer, size_t length, + int autodetect, void (*freefnc)(void*) ) +{ + gcry_error_t errcode; + gcry_sexp_t se; + volatile va_list dummy_arg_ptr; + + if (!retsexp) + return gcry_error (GPG_ERR_INV_ARG); + *retsexp = NULL; + if (autodetect < 0 || autodetect > 1 || !buffer) + return gcry_error (GPG_ERR_INV_ARG); + + if (!length && !autodetect) + { /* What a brave caller to assume that there is really a canonical + encoded S-expression in buffer */ + length = gcry_sexp_canon_len (buffer, 0, NULL, &errcode); + if (!length) + return errcode; + } + else if (!length && autodetect) + { /* buffer is a string */ + length = strlen ((char *)buffer); + } + + errcode = sexp_sscan (&se, NULL, buffer, length, 0, dummy_arg_ptr, NULL); + if (errcode) + return errcode; + + *retsexp = se; + if (freefnc) + { + /* For now we release the buffer immediately. As soon as we + have changed the internal represenation of S-expression to + the canoncial format - which has the advantage of faster + parsing - we will use this function as a closure in our + GCRYSEXP object and use the BUFFER directly */ + freefnc (buffer); + } + return gcry_error (GPG_ERR_NO_ERROR); +} + +/* Same as gcry_sexp_create but don't transfer ownership */ +gcry_error_t +gcry_sexp_new (gcry_sexp_t *retsexp, const void *buffer, size_t length, + int autodetect) +{ + return gcry_sexp_create (retsexp, (void *)buffer, length, autodetect, NULL); +} + + +/**************** + * Release resource of the given SEXP object. + */ +void +gcry_sexp_release( gcry_sexp_t sexp ) +{ + if (sexp) + { + if (gcry_is_secure (sexp)) + { + /* Extra paranoid wiping. */ + const byte *p = sexp->d; + int type; + + while ( (type = *p) != ST_STOP ) + { + p++; + switch ( type ) + { + case ST_OPEN: + break; + case ST_CLOSE: + break; + case ST_DATA: + { + DATALEN n; + memcpy ( &n, p, sizeof n ); + p += sizeof n; + p += n; + } + break; + default: + break; + } + } + wipememory (sexp->d, p - sexp->d); + } + gcry_free ( sexp ); + } +} + + +/**************** + * Make a pair from lists a and b, don't use a or b later on. + * Special behaviour: If one is a single element list we put the + * element straight into the new pair. + */ +gcry_sexp_t +gcry_sexp_cons( const gcry_sexp_t a, const gcry_sexp_t b ) +{ + /* NYI: Implementation should be quite easy with our new data + representation */ + BUG (); + return NULL; +} + + +/**************** + * Make a list from all items in the array the end of the array is marked + * with a NULL. + */ +gcry_sexp_t +gcry_sexp_alist( const gcry_sexp_t *array ) +{ + /* NYI: Implementation should be quite easy with our new data + representation. */ + BUG (); + return NULL; +} + +/**************** + * Make a list from all items, the end of list is indicated by a NULL + */ +gcry_sexp_t +gcry_sexp_vlist( const gcry_sexp_t a, ... ) +{ + /* NYI: Implementation should be quite easy with our new data + representation. */ + BUG (); + return NULL; +} + + +/**************** + * Append n to the list a + * Returns: a new ist (which maybe a) + */ +gcry_sexp_t +gcry_sexp_append( const gcry_sexp_t a, const gcry_sexp_t n ) +{ + /* NYI: Implementation should be quite easy with our new data + representation. */ + BUG (); + return NULL; +} + +gcry_sexp_t +gcry_sexp_prepend( const gcry_sexp_t a, const gcry_sexp_t n ) +{ + /* NYI: Implementation should be quite easy with our new data + representation. */ + BUG (); + return NULL; +} + + + +/**************** + * Locate token in a list. The token must be the car of a sublist. + * Returns: A new list with this sublist or NULL if not found. + */ +gcry_sexp_t +gcry_sexp_find_token( const gcry_sexp_t list, const char *tok, size_t toklen ) +{ + const byte *p; + DATALEN n; + + if ( !list ) + return NULL; + + if( !toklen ) + toklen = strlen(tok); + p = list->d; + while ( *p != ST_STOP ) { + if ( *p == ST_OPEN && p[1] == ST_DATA ) { + const byte *head = p; + + p += 2; + memcpy ( &n, p, sizeof n ); p += sizeof n; + if ( n == toklen && !memcmp( p, tok, toklen ) ) { /* found it */ + gcry_sexp_t newlist; + byte *d; + int level = 1; + + /* look for the end of the list */ + for ( p += n; level; p++ ) { + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; /* compensate for later increment */ + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + } + else if ( *p == ST_STOP ) { + BUG (); + } + } while ( level ); + n = p - head; + + newlist = gcry_xmalloc ( sizeof *newlist + n ); + d = newlist->d; + memcpy ( d, head, n ); d += n; + *d++ = ST_STOP; + return normalize ( newlist ); + } + p += n; + } + else if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); p += sizeof n; + p += n; + } + else + p++; + } + return NULL; +} + +/**************** + * Return the length of the given list + */ +int +gcry_sexp_length( const gcry_sexp_t list ) +{ + const byte *p; + DATALEN n; + int type; + int length = 0; + int level = 0; + + if ( !list ) + return 0; + + p = list->d; + while ( (type=*p) != ST_STOP ) { + p++; + if ( type == ST_DATA ) { + memcpy ( &n, p, sizeof n ); + p += sizeof n + n; + if ( level == 1 ) + length++; + } + else if ( type == ST_OPEN ) { + if ( level == 1 ) + length++; + level++; + } + else if ( type == ST_CLOSE ) { + level--; + } + } + return length; +} + + + +/**************** + * Extract the CAR of the given list + */ +gcry_sexp_t +gcry_sexp_nth( const gcry_sexp_t list, int number ) +{ + const byte *p; + DATALEN n; + gcry_sexp_t newlist; + byte *d; + int level = 0; + + if ( !list || list->d[0] != ST_OPEN ) + return NULL; + p = list->d; + + while ( number > 0 ) { + p++; + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; + if ( !level ) + number--; + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + if ( !level ) + number--; + } + else if ( *p == ST_STOP ) { + return NULL; + } + } + p++; + + if ( *p == ST_DATA ) { + memcpy ( &n, p, sizeof n ); p += sizeof n; + newlist = gcry_xmalloc ( sizeof *newlist + n + 1 ); + d = newlist->d; + memcpy ( d, p, n ); d += n; + *d++ = ST_STOP; + } + else if ( *p == ST_OPEN ) { + const byte *head = p; + + level = 1; + do { + p++; + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + } + else if ( *p == ST_STOP ) { + BUG (); + } + } while ( level ); + n = p + 1 - head; + + newlist = gcry_xmalloc ( sizeof *newlist + n ); + d = newlist->d; + memcpy ( d, head, n ); d += n; + *d++ = ST_STOP; + } + else + newlist = NULL; + + return normalize (newlist); +} + +gcry_sexp_t +gcry_sexp_car( const gcry_sexp_t list ) +{ + return gcry_sexp_nth ( list, 0 ); +} + +/**************** + * Get data from the car. The returned value is valid as long as the list + * is not modified. + */ +const char * +gcry_sexp_nth_data( const gcry_sexp_t list, int number, size_t *datalen ) +{ + const byte *p; + DATALEN n; + int level = 0; + + *datalen = 0; + if ( !list ) { + return NULL; + } + p = list->d; + if ( *p == ST_OPEN ) + p++; /* yep, a list */ + else if (number ) + return NULL; /* not a list but an n > 0 element requested */ + + /* skip n elements */ + while ( number > 0 ) { + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; + if ( !level ) + number--; + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + if ( !level ) + number--; + } + else if ( *p == ST_STOP ) { + return NULL; + } + p++; + } + + + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + *datalen = n; + return p + sizeof n; + } + + return NULL; +} + +/**************** + * Get a MPI from the car + */ +gcry_mpi_t +gcry_sexp_nth_mpi( gcry_sexp_t list, int number, int mpifmt ) +{ + const byte *p; + DATALEN n; + int level = 0; + + if ( !list ) + return NULL; + if ( !mpifmt ) + mpifmt = GCRYMPI_FMT_STD; + + p = list->d; + if ( *p == ST_OPEN ) + p++; /* yep, a list */ + else if (number ) + return NULL; /* not a list but an n > 0 element requested */ + + /* skip n elements */ + while ( number > 0 ) { + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; + if ( !level ) + number--; + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + if ( !level ) + number--; + } + else if ( *p == ST_STOP ) { + return NULL; + } + p++; + } + + if ( *p == ST_DATA ) { + gcry_mpi_t a; + size_t nbytes; + + memcpy ( &n, ++p, sizeof n ); + p += sizeof n; + nbytes = n; + if( !gcry_mpi_scan( &a, mpifmt, p, n, &nbytes ) ) + return a; + } + + return NULL; +} + + +/**************** + * Get the CDR + */ +gcry_sexp_t +gcry_sexp_cdr( const gcry_sexp_t list ) +{ + const byte *p; + const byte *head; + DATALEN n; + gcry_sexp_t newlist; + byte *d; + int level = 0; + int skip = 1; + + if ( !list || list->d[0] != ST_OPEN ) + return NULL; + p = list->d; + + while ( skip > 0 ) { + p++; + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; + if ( !level ) + skip--; + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + if ( !level ) + skip--; + } + else if ( *p == ST_STOP ) { + return NULL; + } + } + p++; + + head = p; + level = 0; + do { + if ( *p == ST_DATA ) { + memcpy ( &n, ++p, sizeof n ); + p += sizeof n + n; + p--; + } + else if ( *p == ST_OPEN ) { + level++; + } + else if ( *p == ST_CLOSE ) { + level--; + } + else if ( *p == ST_STOP ) { + return NULL; + } + p++; + } while ( level ); + n = p - head; + + newlist = gcry_xmalloc ( sizeof *newlist + n + 2 ); + d = newlist->d; + *d++ = ST_OPEN; + memcpy ( d, head, n ); d += n; + *d++ = ST_CLOSE; + *d++ = ST_STOP; + + return normalize (newlist); +} + +gcry_sexp_t +gcry_sexp_cadr ( const gcry_sexp_t list ) +{ + gcry_sexp_t a, b; + + a = gcry_sexp_cdr ( list ); + b = gcry_sexp_car ( a ); + gcry_sexp_release ( a ); + return b; +} + + + +static int +hextobyte( const byte *s ) +{ + int c=0; + + if( *s >= '0' && *s <= '9' ) + c = 16 * (*s - '0'); + else if( *s >= 'A' && *s <= 'F' ) + c = 16 * (10 + *s - 'A'); + else if( *s >= 'a' && *s <= 'f' ) { + c = 16 * (10 + *s - 'a'); + } + s++; + if( *s >= '0' && *s <= '9' ) + c += *s - '0'; + else if( *s >= 'A' && *s <= 'F' ) + c += 10 + *s - 'A'; + else if( *s >= 'a' && *s <= 'f' ) { + c += 10 + *s - 'a'; + } + return c; +} + +struct make_space_ctx { + gcry_sexp_t sexp; + size_t allocated; + byte *pos; +}; + +static void +make_space ( struct make_space_ctx *c, size_t n ) +{ + size_t used = c->pos - c->sexp->d; + + if ( used + n + sizeof(DATALEN) + 1 >= c->allocated ) { + gcry_sexp_t newsexp; + byte *newhead; + + c->allocated += 2*(n+sizeof(DATALEN)+1); + newsexp = gcry_xrealloc ( c->sexp, sizeof *newsexp + c->allocated - 1 ); + newhead = newsexp->d; + c->pos = newhead + used; + c->sexp = newsexp; + } +} + + +/* Unquote STRING of LENGTH and store it into BUF. The surrounding + quotes are must already be removed from STRING. We assume that the + quoted string is syntacillay correct. */ +static size_t +unquote_string (const unsigned char *string, size_t length, unsigned char *buf) +{ + int esc = 0; + const unsigned char *s = string; + unsigned char *d = buf; + size_t n = length; + + for (; n; n--, s++) + { + if (esc) + { + switch (*s) + { + case 'b': *d++ = '\b'; break; + case 't': *d++ = '\t'; break; + case 'v': *d++ = '\v'; break; + case 'n': *d++ = '\n'; break; + case 'f': *d++ = '\f'; break; + case 'r': *d++ = '\r'; break; + case '"': *d++ = '\"'; break; + case '\'': *d++ = '\''; break; + case '\\': *d++ = '\\'; break; + + case '\r': /* ignore CR[,LF] */ + if (n>1 && s[1] == '\n') + { + s++; n--; + } + esc = 0; + break; + + case '\n': /* ignore LF[,CR] */ + if (n>1 && s[1] == '\r') + { + s++; n--; + } + break; + + case 'x': /* hex value */ + if (n>2 && hexdigitp (s+1) && hexdigitp (s+2)) + { + s++; n--; + *d++ = xtoi_2 (s); + s++; n--; + } + break; + + default: + if (n>2 && octdigitp (s) && octdigitp (s+1) && octdigitp (s+2)) + { + *d++ = (atoi_1 (s)*64) + (atoi_1 (s+1)*8) + atoi_1 (s+2); + s += 2; + n -= 2; + } + break; + } + esc = 0; + } + else if( *s == '\\' ) + esc = 1; + else + *d++ = *s; + } + + return d - buf; +} + +/**************** + * Scan the provided buffer and return the S expression in our internal + * format. Returns a newly allocated expression. If erroff is not NULL and + * a parsing error has occured, the offset into buffer will be returned. + * If ARGFLAG is true, the function supports some printf like + * expressions. + * These are: + * %m - MPI + * %s - string (no autoswitch to secure allocation) + * %d - integer stored as string (no autoswitch to secure allocation) + * %b - memory buffer; this takes _two_ arguments: an integer with the + * length of the buffer and a pointer to the buffer. + * all other format elements are currently not defined and return an error. + * this includes the "%%" sequence becauce the percent sign is not an + * allowed character. + * FIXME: We should find a way to store the secure-MPIs not in the string + * but as reference to somewhere - this can help us to save huge amounts + * of secure memory. The problem is, that if only one element is secure, all + * other elements are automagicaly copied to secure memory too, so the most + * common operation gcry_sexp_cdr_mpi() will always return a secure MPI + * regardless whether it is needed or not. + */ +static gcry_error_t +sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff, + const char *buffer, size_t length, int argflag, + va_list arg_ptr, void **arg_list) +{ + gcry_err_code_t err = GPG_ERR_NO_ERROR; + static const char tokenchars[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789-./_:*+="; + const char *p; + size_t n; + const char *digptr = NULL; + const char *quoted = NULL; + const char *tokenp = NULL; + const char *hexfmt = NULL; + const char *base64 = NULL; + const char *disphint = NULL; + const char *percent = NULL; + int hexcount = 0; + int quoted_esc = 0; + int datalen = 0; + size_t dummy_erroff; + struct make_space_ctx c; + int arg_counter = 0; + int level = 0; + + /* FIXME: invent better error codes (?). */ + + if (! erroff) + erroff = &dummy_erroff; + + /* Depending on wether ARG_LIST is non-zero or not, this macro gives + us the next argument, either from the variable argument list as + specified by ARG_PTR or from the argument array ARG_LIST. */ +#define ARG_NEXT(storage, type) \ + do \ + { \ + if (! arg_list) \ + storage = va_arg (arg_ptr, type); \ + else \ + storage = *((type *) (arg_list[arg_counter++])); \ + } \ + while (0) + +#define MAKE_SPACE(n) do { make_space ( &c, (n) ); } while (0) +#define STORE_LEN(p,n) do { \ + DATALEN ashort = (n); \ + memcpy ( (p), &ashort, sizeof(ashort) ); \ + (p) += sizeof (ashort); \ + } while (0) + + /* We assume that the internal representation takes less memory + * than the provided one. However, we add space for one extra datalen + * so that the code which does the ST_CLOSE can use MAKE_SPACE */ + c.allocated = length + sizeof(DATALEN); + if (buffer && length && gcry_is_secure (buffer)) + c.sexp = gcry_xmalloc_secure (sizeof *c.sexp + c.allocated - 1); + else + c.sexp = gcry_xmalloc (sizeof *c.sexp + c.allocated - 1); + c.pos = c.sexp->d; + + for (p = buffer, n = length; n; p++, n--) + { + if (tokenp && (! hexfmt)) + { + if (strchr (tokenchars, *p)) + continue; + else + { + datalen = p - tokenp; + MAKE_SPACE (datalen); + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, datalen); + memcpy (c.pos, tokenp, datalen); + c.pos += datalen; + tokenp = NULL; + } + } + + if (quoted) + { + if (quoted_esc) + { + switch (*p) + { + case 'b': case 't': case 'v': case 'n': case 'f': + case 'r': case '"': case '\'': case '\\': + quoted_esc = 0; + break; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': + if (! ((n > 2) + && (p[1] >= '0') && (p[1] <= '7') + && (p[2] >= '0') && (p[2] <= '7'))) + { + *erroff = p - buffer; + /* Invalid octal value. */ + err = GPG_ERR_SEXP_BAD_QUOTATION; + //return gcry_error (GPG_ERR_SEXP_BAD_QUOTATION); + } + p += 2; + n -= 2; + quoted_esc = 0; + break; + + case 'x': + if (! ((n > 2) && isxdigit(p[1]) && isxdigit(p[2]))) + { + *erroff = p - buffer; + /* Invalid hex value. */ + err = GPG_ERR_SEXP_BAD_QUOTATION; + //return gcry_error (GPG_ERR_SEXP_BAD_QUOTATION); + } + p += 2; + n -= 2; + quoted_esc = 0; + break; + + case '\r': + /* ignore CR[,LF] */ + if (n && (p[1] == '\n')) + { + p++; + n--; + } + quoted_esc = 0; + break; + + case '\n': + /* ignore LF[,CR] */ + if (n && (p[1] == '\r')) + { + p++; + n--; + } + quoted_esc = 0; + break; + + default: + *erroff = p - buffer; + /* Invalid quoted string escape. */ + err = GPG_ERR_SEXP_BAD_QUOTATION; + } + } + else if (*p == '\\') + quoted_esc = 1; + else if (*p == '\"') + { + /* Keep it easy - we know that the unquoted string will + never be larger. */ + char *save; + size_t len; + + quoted++; /* Skip leading quote. */ + MAKE_SPACE (p - quoted); + *c.pos++ = ST_DATA; + save = c.pos; + STORE_LEN (c.pos, 0); /* Will be fixed up later. */ + len = unquote_string (quoted, p - quoted, c.pos); + c.pos += len; + STORE_LEN (save, len); + quoted = NULL; + } + } + else if (hexfmt) + { + if (isxdigit (*p)) + hexcount++; + else if (*p == '#') + { + if ((hexcount & 1)) + { + *erroff = p - buffer; + err = GPG_ERR_SEXP_ODD_HEX_NUMBERS; + } + + datalen = hexcount / 2; + MAKE_SPACE (datalen); + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, datalen); + for (hexfmt++; hexfmt < p; hexfmt++) + { + if (isspace (*hexfmt)) + continue; + *c.pos++ = hextobyte (hexfmt); + hexfmt++; + } + hexfmt = NULL; + } + else if (! isspace (*p)) + { + *erroff = p - buffer; + err = GPG_ERR_SEXP_BAD_HEX_CHAR; + } + } + else if (base64) + { + if (*p == '|') + base64 = NULL; + } + else if (digptr) + { + if (isdigit (*p)) + ; + else if (*p == ':') + { + datalen = atoi (digptr); /* FIXME: check for overflow. */ + digptr = NULL; + if (datalen > n - 1) + { + *erroff = p - buffer; + /* Buffer too short. */ + err = GPG_ERR_SEXP_STRING_TOO_LONG; + } + /* Make a new list entry. */ + MAKE_SPACE (datalen); + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, datalen); + memcpy (c.pos, p + 1, datalen); + c.pos += datalen; + n -= datalen; + p += datalen; + } + else if (*p == '\"') + { + digptr = NULL; /* We ignore the optional length. */ + quoted = p; + quoted_esc = 0; + } + else if (*p == '#') + { + digptr = NULL; /* We ignore the optional length. */ + hexfmt = p; + hexcount = 0; + } + else if (*p == '|') + { + digptr = NULL; /* We ignore the optional length. */ + base64 = p; + } + else + { + *erroff = p - buffer; + err = GPG_ERR_SEXP_INV_LEN_SPEC; + } + } + else if (percent) + { + if (*p == 'm') + { + /* Insert an MPI. */ + gcry_mpi_t m; + size_t nm = 0; + + ARG_NEXT (m, gcry_mpi_t); + + if (gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &nm, m)) + BUG (); + + MAKE_SPACE (nm); + if ((! gcry_is_secure (c.sexp->d)) + && gcry_mpi_get_flag ( m, GCRYMPI_FLAG_SECURE)) + { + /* We have to switch to secure allocation. */ + gcry_sexp_t newsexp; + byte *newhead; + + newsexp = gcry_xmalloc_secure (sizeof *newsexp + + c.allocated - 1); + newhead = newsexp->d; + memcpy (newhead, c.sexp->d, (c.pos - c.sexp->d)); + c.pos = newhead + (c.pos - c.sexp->d); + gcry_free (c.sexp); + c.sexp = newsexp; + } + + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, nm); + if (gcry_mpi_print (GCRYMPI_FMT_STD, c.pos, nm, &nm, m)) + BUG (); + c.pos += nm; + } + else if (*p == 's') + { + /* Insert an string. */ + const char *astr; + size_t alen; + + ARG_NEXT (astr, const char *); + alen = strlen (astr); + + MAKE_SPACE (alen); + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, alen); + memcpy (c.pos, astr, alen); + c.pos += alen; + } + else if (*p == 'b') + { + /* Insert a memory buffer. */ + const char *astr; + int alen; + + ARG_NEXT (alen, int); + ARG_NEXT (astr, const char *); + + MAKE_SPACE (alen); + if (alen + && !gcry_is_secure (c.sexp->d) + && gcry_is_secure (astr)) + { + /* We have to switch to secure allocation. */ + gcry_sexp_t newsexp; + byte *newhead; + + newsexp = gcry_xmalloc_secure (sizeof *newsexp + + c.allocated - 1); + newhead = newsexp->d; + memcpy (newhead, c.sexp->d, (c.pos - c.sexp->d)); + c.pos = newhead + (c.pos - c.sexp->d); + gcry_free (c.sexp); + c.sexp = newsexp; + } + + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, alen); + memcpy (c.pos, astr, alen); + c.pos += alen; + } + else if (*p == 'd') + { + /* Insert an integer as string. */ + int aint; + size_t alen; + char buf[20]; + + ARG_NEXT (aint, int); + sprintf (buf, "%d", aint); + alen = strlen (buf); + MAKE_SPACE (alen); + *c.pos++ = ST_DATA; + STORE_LEN (c.pos, alen); + memcpy (c.pos, buf, alen); + c.pos += alen; + } + else + { + *erroff = p - buffer; + /* Invalid format specifier. */ + err = GPG_ERR_SEXP_INV_LEN_SPEC; + } + percent = NULL; + } + else if (*p == '(') + { + if (disphint) + { + *erroff = p - buffer; + /* Open display hint. */ + err = GPG_ERR_SEXP_UNMATCHED_DH; + } + MAKE_SPACE (0); + *c.pos++ = ST_OPEN; + level++; + } + else if (*p == ')') + { + /* Walk up. */ + if (disphint) + { + *erroff = p - buffer; + /* Open display hint. */ + err = GPG_ERR_SEXP_UNMATCHED_DH; + } + MAKE_SPACE (0); + *c.pos++ = ST_CLOSE; + level--; + } + else if (*p == '\"') + { + quoted = p; + quoted_esc = 0; + } + else if (*p == '#') + { + hexfmt = p; + hexcount = 0; + } + else if (*p == '|') + base64 = p; + else if (*p == '[') + { + if (disphint) + { + *erroff = p - buffer; + /* Open display hint. */ + err = GPG_ERR_SEXP_NESTED_DH; + } + disphint = p; + } + else if (*p == ']') + { + if (! disphint) + { + *erroff = p - buffer; + /* Open display hint. */ + err = GPG_ERR_SEXP_UNMATCHED_DH; + } + disphint = NULL; + } + else if (isdigit (*p)) + { + if (*p == '0') + { + /* A length may not begin with zero. */ + *erroff = p - buffer; + err = GPG_ERR_SEXP_ZERO_PREFIX; + } + digptr = p; + } + else if (strchr (tokenchars, *p)) + tokenp = p; + else if (isspace (*p)) + ; + else if (*p == '{') + { + /* fixme: handle rescanning: we can do this by saving our + current state and start over at p+1 -- Hmmm. At this + point here we are in a well defined state, so we don't + need to save it. Great. */ + *erroff = p - buffer; + err = GPG_ERR_SEXP_UNEXPECTED_PUNC; + } + else if (strchr ("&\\", *p)) + { + /* Reserved punctuation. */ + *erroff = p - buffer; + err = GPG_ERR_SEXP_UNEXPECTED_PUNC; + } + else if (argflag && (*p == '%')) + percent = p; + else + { + /* Bad or unavailable. */ + *erroff = p - buffer; + err = GPG_ERR_SEXP_BAD_CHARACTER; + } + } + MAKE_SPACE (0); + *c.pos++ = ST_STOP; + + if (level) + err = GPG_ERR_SEXP_UNMATCHED_PAREN; + + if (err) + { + /* Error -> deallocate. */ + if (c.sexp) + { + /* Extra paranoid wipe on error. */ + if (gcry_is_secure (c.sexp)) + wipememory (c.sexp, sizeof (struct gcry_sexp) + c.allocated - 1); + gcry_free (c.sexp); + } + /* This might be expected by existing code... */ + *retsexp = NULL; + } + else + *retsexp = normalize (c.sexp); + + return gcry_error (err); +#undef MAKE_SPACE +#undef STORE_LEN +} + +gcry_error_t +gcry_sexp_build (gcry_sexp_t *retsexp, size_t *erroff, const char *format, ...) +{ + gcry_error_t rc; + va_list arg_ptr; + + va_start (arg_ptr, format); + rc = sexp_sscan (retsexp, erroff, format, strlen(format), 1, + arg_ptr, NULL); + va_end (arg_ptr); + + return rc; +} + +/* Like gcry_sexp_build, but uses an array instead of variable + function arguments. */ +gcry_error_t +gcry_sexp_build_array (gcry_sexp_t *retsexp, size_t *erroff, + const char *format, void **arg_list) +{ + /* We don't need the va_list because it is controlled by the + following flag, however we have to pass it but can't initialize + it as there is no portable way to do so. volatile is needed to + suppress the compiler warning */ + volatile va_list dummy_arg_ptr; + + gcry_error_t rc; + + rc = sexp_sscan (retsexp, erroff, format, strlen(format), 1, + dummy_arg_ptr, arg_list); + + return rc; +} + +gcry_error_t +gcry_sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff, + const char *buffer, size_t length) +{ + /* We don't need the va_list because it is controlled by the + following flag, however we have to pass it but can't initialize + it as there is no portable way to do so. volatile is needed to + suppress the compiler warning */ + volatile va_list dummy_arg_ptr; + + return sexp_sscan (retsexp, erroff, buffer, length, 0, + dummy_arg_ptr, NULL); +} + + +/* Figure out a suitable encoding for BUFFER of LENGTH. + Returns: 0 = Binary + 1 = String possible + 2 = Token possible +*/ +static int +suitable_encoding (const unsigned char *buffer, size_t length) +{ + const unsigned char *s; + int maybe_token = 1; + + if (!length) + return 1; + + for (s=buffer; length; s++, length--) + { + if ( (*s < 0x20 || (*s >= 0x7f && *s <= 0xa0)) + && !strchr ("\b\t\v\n\f\r\"\'\\", *s)) + return 0; /*binary*/ + if ( maybe_token + && !alphap (s) && !digitp (s) && !strchr (TOKEN_SPECIALS, *s)) + maybe_token = 0; + } + s = buffer; + if ( maybe_token && !digitp (s) ) + return 2; + return 1; +} + + +static int +convert_to_hex (const unsigned char *src, size_t len, unsigned char *dest) +{ + int i; + + if (dest) + { + *dest++ = '#'; + for (i=0; i < len; i++, dest += 2 ) + sprintf (dest, "%02X", src[i]); + *dest++ = '#'; + } + return len*2+2; +} + +static int +convert_to_string (const unsigned char *s, size_t len, unsigned char *dest) +{ + if (dest) + { + unsigned char *p = dest; + *p++ = '\"'; + for (; len; len--, s++ ) + { + switch (*s) + { + case '\b': *p++ = '\\'; *p++ = 'b'; break; + case '\t': *p++ = '\\'; *p++ = 't'; break; + case '\v': *p++ = '\\'; *p++ = 'v'; break; + case '\n': *p++ = '\\'; *p++ = 'n'; break; + case '\f': *p++ = '\\'; *p++ = 'f'; break; + case '\r': *p++ = '\\'; *p++ = 'r'; break; + case '\"': *p++ = '\\'; *p++ = '\"'; break; + case '\'': *p++ = '\\'; *p++ = '\''; break; + case '\\': *p++ = '\\'; *p++ = '\\'; break; + default: + if ( (*s < 0x20 || (*s >= 0x7f && *s <= 0xa0))) + { + sprintf (p, "\\x%02x", *s); + p += 4; + } + else + *p++ = *s; + } + } + *p++ = '\"'; + return p - dest; + } + else + { + int count = 2; + for (; len; len--, s++ ) + { + switch (*s) + { + case '\b': + case '\t': + case '\v': + case '\n': + case '\f': + case '\r': + case '\"': + case '\'': + case '\\': count += 2; break; + default: + if ( (*s < 0x20 || (*s >= 0x7f && *s <= 0xa0))) + count += 4; + else + count++; + } + } + return count; + } +} + + + +static int +convert_to_token (const unsigned char *src, size_t len, unsigned char *dest) +{ + if (dest) + memcpy (dest, src, len); + return len; +} + + +/**************** + * Print SEXP to buffer using the MODE. Returns the length of the + * SEXP in buffer or 0 if the buffer is too short (We have at least an + * empty list consisting of 2 bytes). If a buffer of NULL is provided, + * the required length is returned. + */ +size_t +gcry_sexp_sprint( const gcry_sexp_t list, int mode, + char *buffer, size_t maxlength ) +{ + static byte empty[3] = { ST_OPEN, ST_CLOSE, ST_STOP }; + const byte *s; + char *d; + DATALEN n; + char numbuf[20]; + size_t len = 0; + int i, indent = 0; + + s = list? list->d : empty; + d = buffer; + while ( *s != ST_STOP ) + { + switch ( *s ) + { + case ST_OPEN: + s++; + if ( mode != GCRYSEXP_FMT_CANON ) + { + if (indent) + len++; + len += indent; + } + len++; + if ( buffer ) + { + if ( len >= maxlength ) + return 0; + if ( mode != GCRYSEXP_FMT_CANON ) + { + if (indent) + *d++ = '\n'; + for (i=0; i < indent; i++) + *d++ = ' '; + } + *d++ = '('; + } + indent++; + break; + case ST_CLOSE: + s++; + len++; + if ( buffer ) + { + if ( len >= maxlength ) + return 0; + *d++ = ')'; + } + indent--; + if (*s != ST_OPEN && *s != ST_STOP && mode != GCRYSEXP_FMT_CANON) + { + len++; + len += indent; + if (buffer) + { + if (len >= maxlength) + return 0; + *d++ = '\n'; + for (i=0; i < indent; i++) + *d++ = ' '; + } + } + break; + case ST_DATA: + s++; + memcpy ( &n, s, sizeof n ); s += sizeof n; + if (mode == GCRYSEXP_FMT_ADVANCED) + { + int type; + size_t nn; + + switch ( (type=suitable_encoding (s, n))) + { + case 1: nn = convert_to_string (s, n, NULL); break; + case 2: nn = convert_to_token (s, n, NULL); break; + default: nn = convert_to_hex (s, n, NULL); break; + } + len += nn; + if (buffer) + { + if (len >= maxlength) + return 0; + switch (type) + { + case 1: convert_to_string (s, n, d); break; + case 2: convert_to_token (s, n, d); break; + default: convert_to_hex (s, n, d); break; + } + d += nn; + } + if (s[n] != ST_CLOSE) + { + len++; + if (buffer) + { + if (len >= maxlength) + return 0; + *d++ = ' '; + } + } + } + else + { + sprintf (numbuf, "%u:", (unsigned int)n ); + len += strlen (numbuf) + n; + if ( buffer ) + { + if ( len >= maxlength ) + return 0; + d = stpcpy ( d, numbuf ); + memcpy ( d, s, n ); d += n; + } + } + s += n; + break; + default: + BUG (); + } + } + if ( mode != GCRYSEXP_FMT_CANON ) + { + len++; + if (buffer) + { + if ( len >= maxlength ) + return 0; + *d++ = '\n'; + } + } + if (buffer) + { + if ( len >= maxlength ) + return 0; + *d++ = 0; /* for convenience we make a C string */ + } + else + len++; /* we need one byte more for this */ + + return len; +} + + +/* Scan a cannocial encoded buffer with implicit length values and + return the actual length this S-expression uses. For a valid S-Exp + it should never return 0. If LENGTH is not zero, the maximum + length to scan is given - this can be used for syntax checks of + data passed from outside. errorcode and erroff may both be passed as + NULL. */ +size_t +gcry_sexp_canon_len (const unsigned char *buffer, size_t length, + size_t *erroff, gcry_error_t *errcode) +{ + const unsigned char *p; + const char *disphint=NULL; + unsigned int datalen = 0; + size_t dummy_erroff; + gcry_error_t dummy_errcode; + size_t count = 0; + int level = 0; + + if (!erroff) + erroff = &dummy_erroff; + if (!errcode) + errcode = &dummy_errcode; + + *errcode = gcry_error (GPG_ERR_NO_ERROR); + *erroff = 0; + if (!buffer) + return 0; + if (*buffer != '(') + { + *errcode = gcry_error (GPG_ERR_SEXP_NOT_CANONICAL); + return 0; + } + + for (p=buffer; ; p++, count++ ) + { + if (length && count >= length) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_STRING_TOO_LONG); + return 0; + } + + if (datalen) + { + if (*p == ':') + { + if (length && (count+datalen) >= length) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_STRING_TOO_LONG); + return 0; + } + count += datalen; + p += datalen; + datalen = 0; + } + else if (digitp(p)) + datalen = datalen*10 + atoi_1(p); + else + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_INV_LEN_SPEC); + return 0; + } + } + else if (*p == '(') + { + if (disphint) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_UNMATCHED_DH); + return 0; + } + level++; + } + else if (*p == ')') + { /* walk up */ + if (!level) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_UNMATCHED_PAREN); + return 0; + } + if (disphint) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_UNMATCHED_DH); + return 0; + } + if (!--level) + return ++count; /* ready */ + } + else if (*p == '[') + { + if (disphint) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_NESTED_DH); + return 0; + } + disphint = p; + } + else if (*p == ']') + { + if( !disphint ) + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_UNMATCHED_DH); + return 0; + } + disphint = NULL; + } + else if (digitp (p) ) + { + if (*p == '0') + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_ZERO_PREFIX); + return 0; + } + datalen = atoi_1 (p); + } + else if (*p == '&' || *p == '\\') + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_UNEXPECTED_PUNC); + return 0; + } + else + { + *erroff = count; + *errcode = gcry_error (GPG_ERR_SEXP_BAD_CHARACTER); + return 0; + } + } +} diff --git a/pwmanager/libcrypt/crypt/stdmem.c b/pwmanager/libcrypt/crypt/stdmem.c new file mode 100644 index 0000000..659bc4e --- a/dev/null +++ b/pwmanager/libcrypt/crypt/stdmem.c @@ -0,0 +1,195 @@ +/* stdmem.c - private memory allocator + * Copyright (C) 1998, 2000, 2002 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#include +#include +#include +#include +#include + +#include "g10lib.h" +#include "stdmem.h" +#include "secmem.h" + + +#define MAGIC_NOR_BYTE 0x55 +#define MAGIC_SEC_BYTE 0xcc +#define MAGIC_END_BYTE 0xaa + +#if SIZEOF_UNSIGNED_LONG == 8 +#define EXTRA_ALIGN 4 +#else +#define EXTRA_ALIGN 0 +#endif + + +static int use_m_guard = 0; + +/**************** + * Warning: Never use this function after any of the functions + * here have been used. + */ +void +_gcry_private_enable_m_guard(void) +{ + use_m_guard = 1; +} + +/**************** + * Allocate memory of size n. + * Return NULL if we are out of memory. + */ +void * +_gcry_private_malloc( size_t n) +{ + if(!n) + return NULL; /* allocating 0 bytes is undefined - better return + an error */ + if( use_m_guard ) { + char *p; + + if( !(p = malloc( n + EXTRA_ALIGN+5 )) ) + return NULL; + ((byte*)p)[EXTRA_ALIGN+0] = n; + ((byte*)p)[EXTRA_ALIGN+1] = n >> 8 ; + ((byte*)p)[EXTRA_ALIGN+2] = n >> 16 ; + ((byte*)p)[EXTRA_ALIGN+3] = MAGIC_NOR_BYTE; + p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE; + return p+EXTRA_ALIGN+4; + } + else { + return malloc( n ); + } +} + +/**************** + * Allocate memory of size n from the secure memory pool. + * Return NULL if we are out of memory. + */ +void * +_gcry_private_malloc_secure( size_t n) +{ + if(!n) + return NULL; /* allocating 0 bytes is undefined - better return + an error */ + if( use_m_guard ) { + char *p; + + if( !(p = _gcry_secmem_malloc( n +EXTRA_ALIGN+ 5 )) ) + return NULL; + ((byte*)p)[EXTRA_ALIGN+0] = n; + ((byte*)p)[EXTRA_ALIGN+1] = n >> 8 ; + ((byte*)p)[EXTRA_ALIGN+2] = n >> 16 ; + ((byte*)p)[EXTRA_ALIGN+3] = MAGIC_SEC_BYTE; + p[4+EXTRA_ALIGN+n] = MAGIC_END_BYTE; + return p+EXTRA_ALIGN+4; + } + else { + return _gcry_secmem_malloc( n ); + } +} + + +/**************** + * realloc and clear the old space + * Return NULL if there is not enoug memory. + */ +void * +_gcry_private_realloc( void *a, size_t n ) +{ + if( use_m_guard ) { + unsigned char *p = a; + char *b; + size_t len; + + if (!a) + return _gcry_private_malloc(n); + + _gcry_private_check_heap(p); + len = p[-4]; + len |= p[-3] << 8; + len |= p[-2] << 16; + if( len >= n ) /* we don't shrink for now */ + return a; + if( p[-1] == MAGIC_SEC_BYTE ) + b = _gcry_private_malloc_secure(n); + else + b = _gcry_private_malloc(n); + if( !b ) + return NULL; + memcpy(b, a, len ); + memset(b+len, 0, n-len ); + _gcry_private_free( p ); + return b; + } + else if( _gcry_private_is_secure(a) ) { + return _gcry_secmem_realloc( a, n ); + } + else { + return realloc( a, n ); + } +} + + +void +_gcry_private_check_heap( const void *a ) +{ + if( use_m_guard ) { + const byte *p = a; + size_t len; + + if( !p ) + return; + + if( !(p[-1] == MAGIC_NOR_BYTE || p[-1] == MAGIC_SEC_BYTE) ) + _gcry_log_fatal("memory at %p corrupted (underflow=%02x)\n", p, p[-1] ); + len = p[-4]; + len |= p[-3] << 8; + len |= p[-2] << 16; + if( p[len] != MAGIC_END_BYTE ) + _gcry_log_fatal("memory at %p corrupted (overflow=%02x)\n", p, p[-1] ); + } +} + +/**************** + * Free a memory block allocated by this opr the secmem module + */ +void +_gcry_private_free( void *a ) +{ + byte *p = a; + + if( !p ) + return; + if( use_m_guard ) { + _gcry_private_check_heap(p); + if( _gcry_private_is_secure(a) ) + _gcry_secmem_free(p-EXTRA_ALIGN-4); + else { + free(p-EXTRA_ALIGN-4); + } + } + else if( _gcry_private_is_secure(a) ) + _gcry_secmem_free(p); + else + free(p); +} + + diff --git a/pwmanager/libcrypt/crypt/stdmem.h b/pwmanager/libcrypt/crypt/stdmem.h new file mode 100644 index 0000000..cf83f68 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/stdmem.h @@ -0,0 +1,32 @@ +/* stdmem.h - internal definitions for stdmem + * Copyright (C) 2000, 2002 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef G10_STDMEM_H +#define G10_STDMEM_H 1 + +void _gcry_private_enable_m_guard(void); + +void *_gcry_private_malloc (size_t n) GCC_ATTR_MALLOC; +void *_gcry_private_malloc_secure (size_t n) GCC_ATTR_MALLOC; +void *_gcry_private_realloc (void *a, size_t n); +void _gcry_private_check_heap (const void *a); +void _gcry_private_free (void *a); + +#endif /* G10_STDMEM_H */ diff --git a/pwmanager/libcrypt/crypt/types.h b/pwmanager/libcrypt/crypt/types.h new file mode 100644 index 0000000..c3a9d93 --- a/dev/null +++ b/pwmanager/libcrypt/crypt/types.h @@ -0,0 +1,124 @@ +/* types.h - some common typedefs + * Copyright (C) 1998, 2000, 2002, 2003 Free Software Foundation, Inc. + * + * This file is part of Libgcrypt. + * + * Libgcrypt is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser general Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * Libgcrypt is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#ifndef GCRYPT_TYPES_H +#define GCRYPT_TYPES_H + + +/* The AC_CHECK_SIZEOF() in configure fails for some machines. + * we provide some fallback values here */ +#if !SIZEOF_UNSIGNED_SHORT +#undef SIZEOF_UNSIGNED_SHORT +#define SIZEOF_UNSIGNED_SHORT 2 +#endif +#if !SIZEOF_UNSIGNED_INT +#undef SIZEOF_UNSIGNED_INT +#define SIZEOF_UNSIGNED_INT 4 +#endif +#if !SIZEOF_UNSIGNED_LONG +#undef SIZEOF_UNSIGNED_LONG +#define SIZEOF_UNSIGNED_LONG 4 +#endif + + +#include + + +#ifndef HAVE_BYTE_TYPEDEF +#undef byte /* maybe there is a macro with this name */ + typedef unsigned char byte; +#define HAVE_BYTE_TYPEDEF +#endif + +#ifndef HAVE_USHORT_TYPEDEF +#undef ushort /* maybe there is a macro with this name */ + typedef unsigned short ushort; +#define HAVE_USHORT_TYPEDEF +#endif + +#ifndef HAVE_ULONG_TYPEDEF +#undef ulong /* maybe there is a macro with this name */ + typedef unsigned long ulong; +#define HAVE_ULONG_TYPEDEF +#endif + +#ifndef HAVE_U16_TYPEDEF +#undef u16 /* maybe there is a macro with this name */ +#if SIZEOF_UNSIGNED_INT == 2 + typedef unsigned int u16; +#elif SIZEOF_UNSIGNED_SHORT == 2 + typedef unsigned short u16; +#else +#error no typedef for u16 +#endif +#define HAVE_U16_TYPEDEF +#endif + +#ifndef HAVE_U32_TYPEDEF +#undef u32 /* maybe there is a macro with this name */ +#if SIZEOF_UNSIGNED_INT == 4 + typedef unsigned int u32; +#elif SIZEOF_UNSIGNED_LONG == 4 + typedef unsigned long u32; +#else +#error no typedef for u32 +#endif +#define HAVE_U32_TYPEDEF +#endif + +/**************** + * Warning: Some systems segfault when this u64 typedef and + * the dummy code in cipher/md.c is not available. Examples are + * Solaris and IRIX. + */ +#ifndef HAVE_U64_TYPEDEF +#undef u64 /* maybe there is a macro with this name */ +#if SIZEOF_UNSIGNED_INT == 8 + typedef unsigned int u64; +#define U64_C(c) (c ## U) +#define HAVE_U64_TYPEDEF +#elif SIZEOF_UNSIGNED_LONG == 8 + typedef unsigned long u64; +#define U64_C(c) (c ## UL) +#define HAVE_U64_TYPEDEF +#elif SIZEOF_UNSIGNED_LONG_LONG == 8 + typedef unsigned long long u64; +#define U64_C(c) (c ## ULL) +#define HAVE_U64_TYPEDEF +#elif SIZEOF_UINT64_T == 8 + typedef uint64_t u64; +#define U64_C(c) (UINT64_C(c)) +#define HAVE_U64_TYPEDEF +#endif +#endif + +typedef union { + int a; + short b; + char c[1]; + long d; +#ifdef HAVE_U64_TYPEDEF + u64 e; +#endif + float f; + double g; +} PROPERLY_ALIGNED_TYPE; + +#endif /*GCRYPT_TYPES_H*/ -- cgit v0.9.0.2