From cvs at cvs.gnupg.org Thu Jun 1 15:56:56 2017 From: cvs at cvs.gnupg.org (by Jo Van Bulck) Date: Thu, 01 Jun 2017 15:56:56 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-90-g5a22de9 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 5a22de904a0a366ae79f03ff1e13a1232a89e26b (commit) from 45c39340c9926c2c5801dbab7609687c41e9ff1f (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 5a22de904a0a366ae79f03ff1e13a1232a89e26b Author: Jo Van Bulck Date: Thu Jan 19 17:00:15 2017 +0100 ecc: Store EdDSA session key in secure memory. * cipher/ecc-eddsa.c (_gcry_ecc_eddsa_sign): use mpi_snew to allocate session key. -- An attacker who learns the EdDSA session key from side-channel observation during the signing process, can easily revover the long- term secret key. Storing the session key in secure memory ensures that constant time point operations are used in the MPI library. Signed-off-by: Jo Van Bulck diff --git a/cipher/ecc-eddsa.c b/cipher/ecc-eddsa.c index f91f848..813e030 100644 --- a/cipher/ecc-eddsa.c +++ b/cipher/ecc-eddsa.c @@ -603,7 +603,7 @@ _gcry_ecc_eddsa_sign (gcry_mpi_t input, ECC_secret_key *skey, a = mpi_snew (0); x = mpi_new (0); y = mpi_new (0); - r = mpi_new (0); + r = mpi_snew (0); ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0, skey->E.p, skey->E.a, skey->E.b); b = (ctx->nbits+7)/8; ----------------------------------------------------------------------- Summary of changes: cipher/ecc-eddsa.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Fri Jun 2 03:38:20 2017 From: cvs at cvs.gnupg.org (by NIIBE Yutaka) Date: Fri, 02 Jun 2017 03:38:20 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-91-ge0958de Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via e0958debe1a7db1bec1283115cdc6a14bf3b43e5 (commit) from 5a22de904a0a366ae79f03ff1e13a1232a89e26b (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit e0958debe1a7db1bec1283115cdc6a14bf3b43e5 Author: NIIBE Yutaka Date: Fri Jun 2 10:34:42 2017 +0900 secmem: Fix SEGV and stat calculation. * src/secmem (init_pool): Care about the header size. (_gcry_secmem_malloc_internal): Likewise. (_gcry_secmem_malloc_internal): Use mb->size for stats. -- GnuPG-bug-id: 3027 Signed-off-by: NIIBE Yutaka diff --git a/src/secmem.c b/src/secmem.c index 8eb6630..86de72d 100644 --- a/src/secmem.c +++ b/src/secmem.c @@ -454,7 +454,7 @@ init_pool (pooldesc_t *pool, size_t n) /* Initialize first memory block. */ mb = (memblock_t *) pool->mem; - mb->size = pool->size; + mb->size = pool->size - BLOCK_HEAD_SIZE; mb->flags = 0; } @@ -610,7 +610,7 @@ _gcry_secmem_malloc_internal (size_t size, int xhint) mb = mb_get_new (pool, (memblock_t *) pool->mem, size); if (mb) { - stats_update (pool, size, 0); + stats_update (pool, mb->size, 0); return &mb->aligned.c; } @@ -624,7 +624,7 @@ _gcry_secmem_malloc_internal (size_t size, int xhint) mb = mb_get_new (pool, (memblock_t *) pool->mem, size); if (mb) { - stats_update (pool, size, 0); + stats_update (pool, mb->size, 0); return &mb->aligned.c; } } @@ -641,7 +641,7 @@ _gcry_secmem_malloc_internal (size_t size, int xhint) return NULL; /* Not enough memory available for a new pool. */ /* Initialize first memory block. */ mb = (memblock_t *) pool->mem; - mb->size = pool->size; + mb->size = pool->size - BLOCK_HEAD_SIZE; mb->flags = 0; pool->okay = 1; @@ -660,7 +660,7 @@ _gcry_secmem_malloc_internal (size_t size, int xhint) mb = mb_get_new (pool, (memblock_t *) pool->mem, size); if (mb) { - stats_update (pool, size, 0); + stats_update (pool, mb->size, 0); return &mb->aligned.c; } } ----------------------------------------------------------------------- Summary of changes: src/secmem.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Fri Jun 2 09:22:55 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Fri, 02 Jun 2017 09:22:55 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-92-g9964d3a Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 9964d3a3fe0c79da79f9132998fe35923e31d92a (commit) from e0958debe1a7db1bec1283115cdc6a14bf3b43e5 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 9964d3a3fe0c79da79f9132998fe35923e31d92a Author: Werner Koch Date: Fri Jun 2 09:19:05 2017 +0200 Add release info from 1.7.7 to NEWS -- diff --git a/NEWS b/NEWS index 48ddeb3..d7e9bd9 100644 --- a/NEWS +++ b/NEWS @@ -58,6 +58,11 @@ Noteworthy changes in version 1.8.0 (unreleased) [C21/A1/R_] - Fix error code handling of mlock calls. [also in 1.7.4] + - Fix possible timing attack on EdDSA session key. [also in 1.7.7] + + - Fix long standing bug in secure memory implementation which could + lead to a segv on free. [bug#3027] [also in 1.7.7] + * Interface changes relative to the 1.7.0 release: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -67,6 +72,7 @@ Noteworthy changes in version 1.8.0 (unreleased) [C21/A1/R_] * Release dates of 1.7.x versions: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Version 1.7.7 (2017-06-02) [C21/A1/R7] Version 1.7.6 (2017-01-18) [C21/A1/R6] Version 1.7.5 (2016-12-15) [C21/A1/R5] Version 1.7.4 (2016-12-09) [C21/A1/R4] ----------------------------------------------------------------------- Summary of changes: NEWS | 6 ++++++ 1 file changed, 6 insertions(+) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From wk at gnupg.org Fri Jun 2 11:08:52 2017 From: wk at gnupg.org (Werner Koch) Date: Fri, 02 Jun 2017 11:08:52 +0200 Subject: [PATCH] ecc: store EdDSA session key in secure memory In-Reply-To: <7288bb2b-f88a-997f-a126-fb7846f91631@cs.kuleuven.be> (Jo Van Bulck's message of "Thu, 19 Jan 2017 17:22:52 +0100") References: <7288bb2b-f88a-997f-a126-fb7846f91631@cs.kuleuven.be> Message-ID: <87efv27o4b.fsf@wheatstone.g10code.de> On Thu, 19 Jan 2017 17:22, jo.vanbulck at cs.kuleuven.be said: > Regarding the function _gcry_ecc_eddsa_sign (cipher/ecc-eddsa.c), I am > wondering why the long-term secret key 'a' is stored in secure memory, > whereas the derived session key 'r' is not. This seems particularly > important in the case of EdDSA as the function _gcry_mpi_ec_mul_point > (mpi/ec.c) attempts to provide side-channel protection by using > constant time operations for scalars residing in secure memory. I applied your patch and released Libgcrypt 1.7.7 a few minutes ago. Thanks. Shalom-Salam, Werner -- Die Gedanken sind frei. Ausnahmen regelt ein Bundesgesetz. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 227 bytes Desc: not available URL: From ametzler at bebt.de Sun Jun 4 13:39:12 2017 From: ametzler at bebt.de (Andreas Metzler) Date: Sun, 4 Jun 2017 13:39:12 +0200 Subject: Libgcrypt 1.7.7 - empty changelog Message-ID: <20170604113912.4mqeipfqlstpr546@argenau.bebt.de> Hello, ChangeLog in the 1.7.7 relase tarball is empty, it only contains the disclaimer about being generated by make dist. cu Andreas -- `What a good friend you are to him, Dr. Maturin. His other friends are so grateful to you.' `I sew his ears on from time to time, sure' From marek.belisko at gmail.com Tue Jun 6 09:17:42 2017 From: marek.belisko at gmail.com (Belisko Marek) Date: Tue, 6 Jun 2017 09:17:42 +0200 Subject: AES-CFB-128 test failed (using wpa_supplicant) Message-ID: Hi, I'm using wpa_supplicant v2.4 on custom x86 platform (VIA board). When I'm trying connect to AP with WPA2 and AES encryption I cannot connect due to the errors like (with TKIP it works fine): selftest for CFB failed - see syslog for details and when inspecting syslog I found : Libgcrypt warning: AES-CFB-128 test failed (plaintext mismatch, parallel path) I'm using libgcryp 1.6.3 and whole system is build using yocto. Compared to my laptop with same version of wpa_suplicant (v2.4) but libgcrypt was 1.6.5 it works fine here . Could it be some missing configuration or any pointer where to look? I have enabled in kernel config CONFIG_CRYPTO_AES_NI_INTEL=y and also CONFIG_CRYPTO_DEV_PADLOCK_AES=y. Thanks a lot. BR, marek -- as simple and primitive as possible ------------------------------------------------- Marek Belisko - OPEN-NANDRA Freelance Developer Ruska Nova Ves 219 | Presov, 08005 Slovak Republic Tel: +421 915 052 184 skype: marekwhite twitter: #opennandra web: http://open-nandra.com From jussi.kivilinna at iki.fi Tue Jun 6 18:55:45 2017 From: jussi.kivilinna at iki.fi (Jussi Kivilinna) Date: Tue, 6 Jun 2017 19:55:45 +0300 Subject: AES-CFB-128 test failed (using wpa_supplicant) In-Reply-To: References: Message-ID: <3b470a12-a253-1897-66eb-1af53a9d5084@iki.fi> Hello, On 06.06.2017 10:17, Belisko Marek wrote: > Hi, > > I'm using wpa_supplicant v2.4 on custom x86 platform (VIA board). When > I'm trying > connect to AP with WPA2 and AES encryption I cannot connect due to the > errors like (with TKIP it works fine): > > selftest for CFB failed - see syslog for details Looks like there is wrong use of assembly operand constraints in Padlock accelerated AES code. Can you test if the attached patch helps? Patch is for libgcrypt-1.6.x. -Jussi > > and when inspecting syslog I found : > Libgcrypt warning: AES-CFB-128 test failed (plaintext mismatch, parallel path) > > I'm using libgcryp 1.6.3 and whole system is build using yocto. > Compared to my laptop with same version of wpa_suplicant (v2.4) but > libgcrypt was 1.6.5 it works fine here . Could it be some missing > configuration or any pointer where to look? I have enabled in kernel > config CONFIG_CRYPTO_AES_NI_INTEL=y and also > CONFIG_CRYPTO_DEV_PADLOCK_AES=y. Thanks a lot. > > BR, > > marek > -------------- next part -------------- A non-text attachment was scrubbed... Name: fix-padlock-1.patch Type: text/x-patch Size: 1389 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 671 bytes Desc: OpenPGP digital signature URL: From marek.belisko at gmail.com Tue Jun 6 23:13:02 2017 From: marek.belisko at gmail.com (Belisko Marek) Date: Tue, 6 Jun 2017 23:13:02 +0200 Subject: AES-CFB-128 test failed (using wpa_supplicant) In-Reply-To: <3b470a12-a253-1897-66eb-1af53a9d5084@iki.fi> References: <3b470a12-a253-1897-66eb-1af53a9d5084@iki.fi> Message-ID: Hi Jussi, On Tue, Jun 6, 2017 at 6:55 PM, Jussi Kivilinna wrote: > Hello, > > On 06.06.2017 10:17, Belisko Marek wrote: >> Hi, >> >> I'm using wpa_supplicant v2.4 on custom x86 platform (VIA board). When >> I'm trying >> connect to AP with WPA2 and AES encryption I cannot connect due to the >> errors like (with TKIP it works fine): >> >> selftest for CFB failed - see syslog for details > > Looks like there is wrong use of assembly operand constraints in Padlock > accelerated AES code. Can you test if the attached patch helps? Patch is > for libgcrypt-1.6.x. After applying patch there are no more erro messages in syslog and I can connect to wifi successfully. Thanks a lot. Is this patch present in newer version of libgcrypt? Thanks. > > -Jussi > >> >> and when inspecting syslog I found : >> Libgcrypt warning: AES-CFB-128 test failed (plaintext mismatch, parallel path) >> >> I'm using libgcryp 1.6.3 and whole system is build using yocto. >> Compared to my laptop with same version of wpa_suplicant (v2.4) but >> libgcrypt was 1.6.5 it works fine here . Could it be some missing >> configuration or any pointer where to look? I have enabled in kernel >> config CONFIG_CRYPTO_AES_NI_INTEL=y and also >> CONFIG_CRYPTO_DEV_PADLOCK_AES=y. Thanks a lot. >> >> BR, >> >> marek >> > > > _______________________________________________ > Gcrypt-devel mailing list > Gcrypt-devel at gnupg.org > http://lists.gnupg.org/mailman/listinfo/gcrypt-devel > BR, marek -- as simple and primitive as possible ------------------------------------------------- Marek Belisko - OPEN-NANDRA Freelance Developer Ruska Nova Ves 219 | Presov, 08005 Slovak Republic Tel: +421 915 052 184 skype: marekwhite twitter: #opennandra web: http://open-nandra.com From cvs at cvs.gnupg.org Thu Jun 8 10:14:44 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Thu, 08 Jun 2017 10:14:44 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-93-gcdfd7ea Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via cdfd7ea72a44657f037dd0dbba6e5ea0c2b344aa (commit) from 9964d3a3fe0c79da79f9132998fe35923e31d92a (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit cdfd7ea72a44657f037dd0dbba6e5ea0c2b344aa Author: Werner Koch Date: Thu Jun 8 10:10:47 2017 +0200 build: Fix ChangeLog building for builds from other worktrees. * Makefile.am (gen-ChangeLog): Test for existance of ".git" regardless on whether it is a file or directory. -- git worktree create a plain file ".git" and not a ".git" directory. Thus we can't check for the existance of a directory. Signed-off-by: Werner Koch diff --git a/Makefile.am b/Makefile.am index f946df2..f97af7f 100644 --- a/Makefile.am +++ b/Makefile.am @@ -78,7 +78,7 @@ distcheck-hook: gen_start_date = 2011-12-01T14:00:00 .PHONY: gen-ChangeLog gen-ChangeLog: - if test -d $(top_srcdir)/.git; then \ + if test -e $(top_srcdir)/.git; then \ (cd $(top_srcdir) && \ $(GITLOG_TO_CHANGELOG) --append-dot --tear-off \ --amend=build-aux/git-log-fix \ ----------------------------------------------------------------------- Summary of changes: Makefile.am | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From wk at gnupg.org Thu Jun 8 10:12:26 2017 From: wk at gnupg.org (Werner Koch) Date: Thu, 08 Jun 2017 10:12:26 +0200 Subject: Libgcrypt 1.7.7 - empty changelog In-Reply-To: <20170604113912.4mqeipfqlstpr546@argenau.bebt.de> (Andreas Metzler's message of "Sun, 4 Jun 2017 13:39:12 +0200") References: <20170604113912.4mqeipfqlstpr546@argenau.bebt.de> Message-ID: <87r2yuq4np.fsf@wheatstone.g10code.de> On Sun, 4 Jun 2017 13:39, ametzler at bebt.de said: > ChangeLog in the 1.7.7 relase tarball is empty, it only contains the > disclaimer about being generated by make dist. I am built from another git worktree which caused the problem. Will be fixed for the next release. Salam-Shalom, Werner ==== build: Fix ChangeLog building for builds from other worktrees. * Makefile.am (gen-ChangeLog): Test for existance of ".git" regardless on whether it is a file or directory. -- git worktree create a plain file ".git" and not a ".git" directory. Thus we can't check for the existance of a directory. Signed-off-by: Werner Koch Modified Makefile.am diff --git a/Makefile.am b/Makefile.am index f946df2..f97af7f 100644 --- a/Makefile.am +++ b/Makefile.am @@ -78,7 +78,7 @@ distcheck-hook: gen_start_date = 2011-12-01T14:00:00 .PHONY: gen-ChangeLog gen-ChangeLog: - if test -d $(top_srcdir)/.git; then \ + if test -e $(top_srcdir)/.git; then \ (cd $(top_srcdir) && \ $(GITLOG_TO_CHANGELOG) --append-dot --tear-off \ --amend=build-aux/git-log-fix \ -- Die Gedanken sind frei. Ausnahmen regelt ein Bundesgesetz. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 227 bytes Desc: not available URL: From jussi.kivilinna at iki.fi Wed Jun 7 09:34:58 2017 From: jussi.kivilinna at iki.fi (Jussi Kivilinna) Date: Wed, 7 Jun 2017 10:34:58 +0300 Subject: AES-CFB-128 test failed (using wpa_supplicant) In-Reply-To: References: <3b470a12-a253-1897-66eb-1af53a9d5084@iki.fi> Message-ID: Hello, On 07.06.2017 00:13, Belisko Marek wrote: > Hi Jussi, > > On Tue, Jun 6, 2017 at 6:55 PM, Jussi Kivilinna wrote: >> Hello, >> >> On 06.06.2017 10:17, Belisko Marek wrote: >> >> Looks like there is wrong use of assembly operand constraints in Padlock >> accelerated AES code. Can you test if the attached patch helps? Patch is >> for libgcrypt-1.6.x. > After applying patch there are no more erro messages in syslog and I > can connect to wifi successfully. > Thanks a lot. Is this patch present in newer version of libgcrypt? Thanks. Not yet, I'll prepare patch for development branch later this week. The problem is less likely to manifest in 1.7 and later since the Padlock assembly function is no longer inlined to bulk AES functions (in this case CFB). This is because as Padlock function has moved to separate sourcefile and behind indirect function call, so compiler is much less likely to generate code that break. -Jussi From stefbon at gmail.com Sat Jun 10 07:32:00 2017 From: stefbon at gmail.com (Stef Bon) Date: Sat, 10 Jun 2017 07:32:00 +0200 Subject: Howto read a mpi point from buffer? Message-ID: Hi, I'm implementing the ed25519 pubkey method in my application using libgcrypt. Earlier I'v added rsa and dss. I cannot find a function to read a mpi point. Is there one? Stef From stefbon at gmail.com Sat Jun 10 19:55:35 2017 From: stefbon at gmail.com (Stef Bon) Date: Sat, 10 Jun 2017 19:55:35 +0200 Subject: Howto read a mpi point from buffer? In-Reply-To: References: Message-ID: 2017-06-10 7:32 GMT+02:00 Stef Bon : > Hi, > > I'm implementing the ed25519 pubkey method in my application using libgcrypt. > Earlier I'v added rsa and dss. > > I cannot find a function to read a mpi point. Is there one? > The file I want to read is the public key stored by openssh, where the "q" (elliptic curve point octet string) of the key: string "ed25519" string "q" (and also the private key, but this is using the same technique). Stef From wk at gnupg.org Sun Jun 11 14:28:10 2017 From: wk at gnupg.org (Werner Koch) Date: Sun, 11 Jun 2017 14:28:10 +0200 Subject: Howto read a mpi point from buffer? In-Reply-To: (Stef Bon's message of "Sat, 10 Jun 2017 19:55:35 +0200") References: Message-ID: <87poeak8th.fsf@wheatstone.g10code.de> On Sat, 10 Jun 2017 19:55, stefbon at gmail.com said: > The file I want to read is the public key stored by openssh, where the "q" > (elliptic curve point octet string) of the key: > > string "ed25519" > string "q" I suggest to read gnupg/agent/command-ssh.c. In particular the functions ssh_receive_key and stream_read_blob. The trick here is that you don't read a proper MPI but merely use the MPI object to store an opaque value - the ECC crypto function can handle them. Salam-Shalom, Werner -- Die Gedanken sind frei. Ausnahmen regelt ein Bundesgesetz. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 227 bytes Desc: not available URL: From jussi.kivilinna at iki.fi Sun Jun 11 14:35:49 2017 From: jussi.kivilinna at iki.fi (Jussi Kivilinna) Date: Sun, 11 Jun 2017 15:35:49 +0300 Subject: [PATCH] rijndael-padlock: change asm operands from read-only to read/write Message-ID: <149718454906.26299.4167610989758596561.stgit@localhost.localdomain> * cipher/rijndael-padlock.c (do_padlock): Change ESI/EDI/ECX to use read/write operands as XCRYPT instruction modifies these registers. -- Signed-off-by: Jussi Kivilinna --- 0 files changed diff --git a/cipher/rijndael-padlock.c b/cipher/rijndael-padlock.c index 476772af..234751b9 100644 --- a/cipher/rijndael-padlock.c +++ b/cipher/rijndael-padlock.c @@ -43,6 +43,8 @@ do_padlock (const RIJNDAEL_context *ctx, unsigned char *bx, unsigned char a[16] __attribute__ ((aligned (16))); unsigned char b[16] __attribute__ ((aligned (16))); unsigned int cword[4] __attribute__ ((aligned (16))); + unsigned char *pa = a; + unsigned char *pb = b; int blocks; /* The control word fields are: @@ -63,19 +65,19 @@ do_padlock (const RIJNDAEL_context *ctx, unsigned char *bx, ("pushfq\n\t" /* Force key reload. */ "popfq\n\t" ".byte 0xf3, 0x0f, 0xa7, 0xc8\n\t" /* REP XCRYPT ECB. */ - : /* No output */ - : "S" (a), "D" (b), "d" (cword), "b" (ctx->padlockkey), "c" (blocks) + : "+S" (pa), "+D" (pb), "+c" (blocks) + : "d" (cword), "b" (ctx->padlockkey) : "cc", "memory" ); #else asm volatile ("pushfl\n\t" /* Force key reload. */ "popfl\n\t" - "xchg %3, %%ebx\n\t" /* Load key. */ + "xchg %4, %%ebx\n\t" /* Load key. */ ".byte 0xf3, 0x0f, 0xa7, 0xc8\n\t" /* REP XCRYPT ECB. */ - "xchg %3, %%ebx\n" /* Restore GOT register. */ - : /* No output */ - : "S" (a), "D" (b), "d" (cword), "r" (ctx->padlockkey), "c" (blocks) + "xchg %4, %%ebx\n" /* Restore GOT register. */ + : "+S" (pa), "+D" (pb), "+c" (blocks) + : "d" (cword), "r" (ctx->padlockkey) : "cc", "memory" ); #endif From stefbon at gmail.com Sun Jun 11 15:48:06 2017 From: stefbon at gmail.com (Stef Bon) Date: Sun, 11 Jun 2017 15:48:06 +0200 Subject: Howto read a mpi point from buffer? In-Reply-To: <87poeak8th.fsf@wheatstone.g10code.de> References: <87poeak8th.fsf@wheatstone.g10code.de> Message-ID: 2017-06-11 14:28 GMT+02:00 Werner Koch : > > I suggest to read gnupg/agent/command-ssh.c. In particular the > functions ssh_receive_key and stream_read_blob. The trick here is that > you don't read a proper MPI but merely use the MPI object to store an > opaque value - the ECC crypto function can handle them. > A thanks! I will read that code. I've found something in the test/t-mpi-point.c code. The "q" of a sample ed25519 is read using a hex2mpi function, which on his turn uses the gcry_mpi_scan function using the GCRYMPI_FMT_HEX format. Stef From cvs at cvs.gnupg.org Wed Jun 14 14:11:42 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Wed, 14 Jun 2017 14:11:42 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-98-gf5e7763 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via f5e7763ddca59dcd9ac9f2f4d50cb41b14a34a9e (commit) via 6c882fb1fdb6c7cba2215fa7391110d63e24b9dc (commit) via 06f303a633ea2b992259688bef2b023c3f388f73 (commit) via a44c45675f8b631e11048a540bb1fbb7a022ebb4 (commit) via f0ae18ecf48fbe2da0b9fb3f354d0dd3173d91d3 (commit) from cdfd7ea72a44657f037dd0dbba6e5ea0c2b344aa (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit f5e7763ddca59dcd9ac9f2f4d50cb41b14a34a9e Author: Werner Koch Date: Wed Jun 14 14:03:05 2017 +0200 random: Add jitter RND based entropy collector. * random/rndjent.c: New. * random/rndlinux.c (_gcry_rndlinux_gather_random): Use rndjent. * random/rndw32.c (_gcry_rndw32_gather_random): Use rndjent. (slow_gatherer): Fix compiler warning. * random/Makefile.am (librandom_la_SOURCES): Add rndjent.c (EXTRA_librandom_la_SOURCES): Add jitterentropy-base.c and jitterentropy.h. (rndjent.o, rndjent.lo): New rules. * configure.ac: New option --disbale-jent-support (ENABLE_JENT_SUPPORT): New ac-define. Signed-off-by: Werner Koch diff --git a/AUTHORS b/AUTHORS index b80d43e..c1e813d 100644 --- a/AUTHORS +++ b/AUTHORS @@ -30,13 +30,14 @@ List of Copyright holders Copyright (C) 1996-2006 Peter Gutmann, Matt Thomlinson and Blake Coverett Copyright (C) 2003 Nikos Mavroyanopoulos Copyright (C) 2006-2007 NTT (Nippon Telegraph and Telephone Corporation) - Copyright (C) 2012-2016 g10 Code GmbH + Copyright (C) 2012-2017 g10 Code GmbH Copyright (C) 2012 Simon Josefsson, Niels M?ller Copyright (c) 2012 Intel Corporation Copyright (C) 2013 Christian Grothoff Copyright (C) 2013-2016 Jussi Kivilinna Copyright (C) 2013-2014 Dmitry Eremin-Solenikov Copyright (C) 2014 Stephan Mueller + Copyright (C) 2017 Bundesamt f?r Sicherheit in der Informationstechnik Authors with a FSF copyright assignment diff --git a/configure.ac b/configure.ac index 7ea0b6a..d36673f 100644 --- a/configure.ac +++ b/configure.ac @@ -577,6 +577,14 @@ if test "$use_hmac_binary_check" = yes ; then fi +# Implementation of the --disable-jent-support switch. +AC_MSG_CHECKING([whether jitter entropy support is requested]) +AC_ARG_ENABLE(jent-support, + AC_HELP_STRING([--disable-jent-support], + [Disable support for the Jitter entropy collector]), + jentsupport=$enableval,jentsupport=yes) +AC_MSG_RESULT($jentsupport) + # Implementation of the --disable-padlock-support switch. AC_MSG_CHECKING([whether padlock support is requested]) AC_ARG_ENABLE(padlock-support, @@ -1185,6 +1193,7 @@ if test "$mpi_cpu_arch" != "x86" ; then avxsupport="n/a" avx2support="n/a" padlocksupport="n/a" + jentsupport="n/a" drngsupport="n/a" fi @@ -1980,6 +1989,10 @@ if test x"$armcryptosupport" = xyes ; then AC_DEFINE(ENABLE_ARM_CRYPTO_SUPPORT,1, [Enable support for ARMv8 Crypto Extension instructions.]) fi +if test x"$jentsupport" = xyes ; then + AC_DEFINE(ENABLE_JENT_SUPPORT, 1, + [Enable support for the jitter entropy collector.]) +fi if test x"$padlocksupport" = xyes ; then AC_DEFINE(ENABLE_PADLOCK_SUPPORT, 1, [Enable support for the PadLock engine.]) @@ -2619,6 +2632,7 @@ GCRY_MSG_WRAP([Enabled digest algorithms:],[$enabled_digests]) GCRY_MSG_WRAP([Enabled kdf algorithms: ],[$enabled_kdfs]) GCRY_MSG_WRAP([Enabled pubkey algorithms:],[$enabled_pubkey_ciphers]) GCRY_MSG_SHOW([Random number generator: ],[$random]) +GCRY_MSG_SHOW([Try using jitter entropy: ],[$jentsupport]) GCRY_MSG_SHOW([Using linux capabilities: ],[$use_capabilities]) GCRY_MSG_SHOW([Try using Padlock crypto: ],[$padlocksupport]) GCRY_MSG_SHOW([Try using AES-NI crypto: ],[$aesnisupport]) diff --git a/random/Makefile.am b/random/Makefile.am index 92aba20..aaf205e 100644 --- a/random/Makefile.am +++ b/random/Makefile.am @@ -36,6 +36,7 @@ rand-internal.h \ random-csprng.c \ random-drbg.c \ random-system.c \ +rndjent.c \ rndhw.c if USE_RANDOM_DAEMON @@ -48,4 +49,21 @@ rndlinux.c \ rndegd.c \ rndunix.c \ rndw32.c \ -rndw32ce.c +rndw32ce.c \ +jitterentropy-base.c jitterentropy.h + + +# The rndjent module needs to be compiled without optimization. */ +if ENABLE_O_FLAG_MUNGING +o_flag_munging = sed -e 's/-O\([1-9s][1-9s]*\)/-O0/' -e 's/-Ofast/-O0/g' +else +o_flag_munging = cat +endif + +rndjent.o: $(srcdir)/rndjent.c \ + $(srcdir)/jitterentropy-base.c $(srcdir)/jitterentropy.h + `echo $(COMPILE) -c $(srcdir)/rndjent.c | $(o_flag_munging) ` + +rndjent.lo: $(srcdir)/rndjent.c \ + $(srcdir)/jitterentropy-base.c $(srcdir)/jitterentropy.h + `echo $(LTCOMPILE) -c $(srcdir)/rndjent.c | $(o_flag_munging) ` diff --git a/random/rand-internal.h b/random/rand-internal.h index 8c8623e..7a798e9 100644 --- a/random/rand-internal.h +++ b/random/rand-internal.h @@ -98,7 +98,7 @@ int _gcry_rndunix_gather_random (void (*add) (const void *, size_t, enum random_origins origin, size_t length, int level); -/*-- rndelg.c --*/ +/*-- rndegd.c --*/ int _gcry_rndegd_gather_random (void (*add) (const void *, size_t, enum random_origins), enum random_origins origin, @@ -123,6 +123,12 @@ void _gcry_rndw32ce_gather_random_fast (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin ); +/*-- rndjent.c --*/ +size_t _gcry_rndjent_poll (void (*add)(const void*, + size_t, enum random_origins), + enum random_origins origin, + size_t length); + /*-- rndhw.c --*/ int _gcry_rndhw_failed_p (void); void _gcry_rndhw_poll_fast (void (*add)(const void*, size_t, diff --git a/random/rndjent.c b/random/rndjent.c new file mode 100644 index 0000000..fa3bb99 --- /dev/null +++ b/random/rndjent.c @@ -0,0 +1,208 @@ +/* rndjent.c - Driver for the jitterentropy module. + * Copyright (C) 2017 g10 Code GmbH + * Copyright (C) 2017 Bundesamt f?r Sicherheit in der Informationstechnik + * + * 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, see . + */ + +#include +#include +#include +#ifdef HAVE_STDINT_H +# include +#endif + +#include "types.h" +#include "g10lib.h" +#include "../cipher/bithelp.h" +#include "rand-internal.h" + +/* + * Decide whether we can support jent at compile time. + */ +#undef USE_JENT +#ifdef ENABLE_JENT_SUPPORT +# if defined (__i386__) || defined(__x86_64__) +# define USE_JENT 1 +# endif +#endif /*ENABLE_JENT_SUPPORT*/ + + +#ifdef USE_JENT + +/* When using the libgcrypt secure memory mechanism, all precautions + * are taken to protect our state. If the user disables secmem during + * runtime, it is his decision and we thus try not to overrule his + * decision for less memory protection. */ +#define JENT_CPU_JITTERENTROPY_SECURE_MEMORY 1 +#define jent_zalloc(n) _gcry_calloc_secure (1, (n)) + + + +/* + * Libgcrypt specific platform dependent functions. + */ + + +static void +jent_get_nstime(u64 *out) +{ + u32 t_eax, t_edx; + + asm volatile (".byte 0x0f,0x31\n\t" + : "=a" (t_eax), "=d" (t_edx) + ); + *out = (((u64)t_edx << 32) | t_eax); +} + + +static GPGRT_INLINE void +jent_zfree (void *ptr, unsigned int len) +{ + if (ptr) + { + wipememory (ptr, len); + _gcry_free (ptr); + } +} + +static GPGRT_INLINE int +jent_fips_enabled(void) +{ + return fips_mode(); +} + + +/* + * We source include the actual jitter entropy code. Note that the + * included code has been slightly changed from the Linux kernel + * version for namespace reasons. We define MODULE so that the + * EXPORT_SYMBOL macro will not be used. + */ +#undef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT +/* Uncomment the next line to build with statistics. */ +/* #define CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT 1 */ + +#undef MODULE +#define MODULE 1 + +#ifndef HAVE_STDINT_H +# error This module needs stdint.h - try ./configure --disable-jent-support +#endif +#include "jitterentropy-base.c" + + +/* This is the lock we use to serialize access to this RNG. The extra + * integer variable is only used to check the locking state; that is, + * it is not meant to be thread-safe but merely as a failsafe feature + * to assert proper locking. */ +GPGRT_LOCK_DEFINE (jent_rng_lock); +static int jent_rng_is_locked; + +/* This flag tracks whether the RNG has been initialized - either + * with error or with success. Protected by JENT_RNG_LOCK. */ +static int jent_rng_is_initialized; + +/* Our collector. The RNG is in a working state if its value is not + * NULL. Protected by JENT_RNG_LOCK. */ +struct rand_data *jent_rng_collector; + + +/* Acquire the jent_rng_lock. */ +static void +lock_rng (void) +{ + gpg_err_code_t rc; + + rc = gpgrt_lock_lock (&jent_rng_lock); + if (rc) + log_fatal ("failed to acquire the Jent RNG lock: %s\n", + gpg_strerror (rc)); + jent_rng_is_locked = 1; +} + + +/* Release the jent_rng_lock. */ +static void +unlock_rng (void) +{ + gpg_err_code_t rc; + + jent_rng_is_locked = 0; + rc = gpgrt_lock_unlock (&jent_rng_lock); + if (rc) + log_fatal ("failed to release the Jent RNG lock: %s\n", + gpg_strerror (rc)); +} + +#endif /* USE_JENT */ + + +/* + * The API used by the high level code. + */ + +/* Read up to LENGTH bytes from a jitter RNG and return the number of + * bytes actually read. */ +size_t +_gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), + enum random_origins origin, size_t length) +{ + size_t nbytes = 0; + + (void)add; + (void)origin; + +#ifdef USE_JENT + if ((_gcry_get_hw_features () & HWF_INTEL_RDTSC)) + { + lock_rng (); + + if (!jent_rng_is_initialized) + { + /* Auto-initialize. */ + jent_rng_is_initialized = 1; + jent_entropy_collector_free (jent_rng_collector); + jent_rng_collector = NULL; + if (!jent_entropy_init ()) + jent_rng_collector = jent_entropy_collector_alloc (1, 0); + } + + if (jent_rng_collector) + { + /* We have a working JENT. */ + char buffer[256]; + + while (length) + { + int rc; + size_t n = length < sizeof(buffer)? length : sizeof (buffer); + + rc = jent_read_entropy (jent_rng_collector, buffer, n); + if (rc < 0) + break; + (*add) (buffer, rc, origin); + length -= rc; + nbytes += rc; + } + } + + unlock_rng (); + } +#endif + + return nbytes; +} diff --git a/random/rndlinux.c b/random/rndlinux.c index d3a144a..f1548fb 100644 --- a/random/rndlinux.c +++ b/random/rndlinux.c @@ -158,6 +158,19 @@ _gcry_rndlinux_gather_random (void (*add)(const void*, size_t, if (length > 1) length -= n_hw; + /* When using a blocking random generator try to get some entropy + * from the jitter based RNG. In this case we take up to 50% of the + * remaining requested bytes. */ + if (level >= GCRY_VERY_STRONG_RANDOM) + { + n_hw = _gcry_rndjent_poll (add, origin, length/2); + if (n_hw > length/2) + n_hw = length/2; + if (length > 1) + length -= n_hw; + } + + /* Open the requested device. The first time a device is to be opened we fail with a fatal error if the device does not exists. In case the device has ever been closed, further open requests @@ -165,7 +178,7 @@ _gcry_rndlinux_gather_random (void (*add)(const void*, size_t, that we always require the device to be existent but want a more graceful behaviour if the rarely needed close operation has been used and the device needs to be re-opened later. */ - if (level >= 2) + if (level >= GCRY_VERY_STRONG_RANDOM) { if (fd_random == -1) { diff --git a/random/rndw32.c b/random/rndw32.c index 1dec5a7..7e9ac50 100644 --- a/random/rndw32.c +++ b/random/rndw32.c @@ -584,8 +584,8 @@ slow_gatherer ( void (*add)(const void*, size_t, enum random_origins), if (hNetAPI32 && !pNetStatisticsGet (NULL, - is_workstation ? L"LanmanWorkstation" : - L"LanmanServer", 0, 0, &lpBuffer)) + (LPWSTR)(is_workstation ? L"LanmanWorkstation" : + L"LanmanServer"), 0, 0, &lpBuffer)) { if ( debug_me ) log_debug ("rndw32#slow_gatherer: get netstats\n" ); @@ -776,6 +776,7 @@ _gcry_rndw32_gather_random (void (*add)(const void*, size_t, size_t length, int level ) { static int is_initialized; + size_t n; if (!level) return 0; @@ -808,6 +809,13 @@ _gcry_rndw32_gather_random (void (*add)(const void*, size_t, slow_gatherer (add, origin); + /* Round requested LENGTH up to full 32 bytes. */ + n = _gcry_rndjent_poll (add, origin, ((length + 31) / 32) * 32); + + if (debug_me) + log_debug ("rndw32#gather_random: jent contributed extra %u bytes\n", + (unsigned int)n); + return 0; } commit 6c882fb1fdb6c7cba2215fa7391110d63e24b9dc Author: Werner Koch Date: Wed Jun 14 13:58:18 2017 +0200 cipher: New helper function rol64. * cipher/bithelp.h (rol64): New inline functions. Signed-off-by: Werner Koch diff --git a/cipher/bithelp.h b/cipher/bithelp.h index 4575380..26ef7c3 100644 --- a/cipher/bithelp.h +++ b/cipher/bithelp.h @@ -35,6 +35,11 @@ static inline u32 ror(u32 x, int n) return ( (x >> (n&(32-1))) | (x << ((32-n)&(32-1))) ); } +static inline u64 rol64(u64 x, int n) +{ + return ( (x << (n&(64-1))) | (x >> ((64-n)&(64-1))) ); +} + /* Byte swap for 32-bit and 64-bit integers. If available, use compiler provided helpers. */ #ifdef HAVE_BUILTIN_BSWAP32 commit 06f303a633ea2b992259688bef2b023c3f388f73 Author: Werner Koch Date: Wed Jun 14 13:57:45 2017 +0200 New hardware feature flag HWF_INTEL_RDTSC. * src/g10lib.h (HWF_INTEL_RDTSC): New. * src/hwfeatures.c (hwflist): Add "intel-rdtsc". * src/hwf-x86.c (detect_x86_gnuc): Get EDX features and test for TSC. Signed-off-by: Werner Koch diff --git a/doc/gcrypt.texi b/doc/gcrypt.texi index 464c673..ae66dfc 100644 --- a/doc/gcrypt.texi +++ b/doc/gcrypt.texi @@ -570,6 +570,7 @@ are @item intel-rdrand @item intel-avx @item intel-avx2 + at item intel-rdtsc @item arm-neon @end table diff --git a/src/g10lib.h b/src/g10lib.h index 0309a83..82562c7 100644 --- a/src/g10lib.h +++ b/src/g10lib.h @@ -227,6 +227,9 @@ char **_gcry_strtokenize (const char *string, const char *delim); #define HWF_ARM_SHA2 (1 << 18) #define HWF_ARM_PMULL (1 << 19) +#define HWF_INTEL_RDTSC (1 << 20) + + gpg_err_code_t _gcry_disable_hw_feature (const char *name); void _gcry_detect_hw_features (void); diff --git a/src/hwf-x86.c b/src/hwf-x86.c index 53e00d9..0d3a1f4 100644 --- a/src/hwf-x86.c +++ b/src/hwf-x86.c @@ -175,7 +175,7 @@ detect_x86_gnuc (void) char c[12+1]; unsigned int ui[3]; } vendor_id; - unsigned int features; + unsigned int features, features2; unsigned int os_supports_avx_avx2_registers = 0; unsigned int max_cpuid_level; unsigned int fms, family, model; @@ -240,8 +240,8 @@ detect_x86_gnuc (void) /* Detect Intel features, that might also be supported by other vendors. */ - /* Get CPU family/model/stepping (EAX) and Intel feature flags (ECX). */ - get_cpuid(1, &fms, NULL, &features, NULL); + /* Get CPU family/model/stepping (EAX) and Intel feature flags (ECX, EDX). */ + get_cpuid(1, &fms, NULL, &features, &features2); family = ((fms & 0xf00) >> 8) + ((fms & 0xff00000) >> 20); model = ((fms & 0xf0) >> 4) + ((fms & 0xf0000) >> 12); @@ -331,6 +331,10 @@ detect_x86_gnuc (void) result |= HWF_INTEL_RDRAND; #endif /*ENABLE_DRNG_SUPPORT*/ + /* Test bit 4 of EDX for TSC. */ + if (features2 & 0x00000010) + result |= HWF_INTEL_RDTSC; + /* Check additional Intel feature flags. Early Intel P5 processors report * too high max_cpuid_level, so don't check level 7 if processor does not * support SSE3 (as cpuid:7 contains only features for newer processors). diff --git a/src/hwfeatures.c b/src/hwfeatures.c index b2ae7c3..45d7680 100644 --- a/src/hwfeatures.c +++ b/src/hwfeatures.c @@ -57,6 +57,7 @@ static struct { HWF_INTEL_AVX, "intel-avx" }, { HWF_INTEL_AVX2, "intel-avx2" }, { HWF_INTEL_FAST_VPGATHER, "intel-fast-vpgather" }, + { HWF_INTEL_RDTSC, "intel-rdtsc" }, { HWF_ARM_NEON, "arm-neon" }, { HWF_ARM_AES, "arm-aes" }, { HWF_ARM_SHA1, "arm-sha1" }, commit a44c45675f8b631e11048a540bb1fbb7a022ebb4 Author: Werner Koch Date: Wed Jun 14 13:51:51 2017 +0200 random: Changes to original Jitter RNG implementation * random/jitterentropy-base.c: Change double underscore symbols and make all functions static. * random/jitterentropy.h: Likewise. Signed-off-by: Werner Koch diff --git a/random/jitterentropy-base.c b/random/jitterentropy-base.c index 23ac695..e80ca6e 100644 --- a/random/jitterentropy-base.c +++ b/random/jitterentropy-base.c @@ -81,6 +81,7 @@ * * Return: Version number of kcapi library */ +#if 0 unsigned int jent_version(void) { unsigned int version = 0; @@ -91,6 +92,7 @@ unsigned int jent_version(void) return version; } +#endif /** * Update of the loop count used for the next round of @@ -104,11 +106,11 @@ unsigned int jent_version(void) * * @return Newly calculated loop counter */ -static __u64 jent_loop_shuffle(struct rand_data *ec, +static u64 jent_loop_shuffle(struct rand_data *ec, unsigned int bits, unsigned int min) { - __u64 time = 0; - __u64 shuffle = 0; + u64 time = 0; + u64 shuffle = 0; unsigned int i = 0; unsigned int mask = (1<data; for (i = 1; (DATA_SIZE_BITS) >= i; i++) { - __u64 tmp = time << (DATA_SIZE_BITS - i); + u64 tmp = time << (DATA_SIZE_BITS - i); tmp = tmp >> (DATA_SIZE_BITS - 1); @@ -240,13 +242,13 @@ static __u64 jent_lfsr_time(struct rand_data *ec, __u64 time, * * @return Number of memory access operations */ -static unsigned int jent_memaccess(struct rand_data *ec, __u64 loop_cnt) +static unsigned int jent_memaccess(struct rand_data *ec, u64 loop_cnt) { unsigned int wrap = 0; - __u64 i = 0; + u64 i = 0; #define MAX_ACC_LOOP_BIT 7 #define MIN_ACC_LOOP_BIT 0 - __u64 acc_loop_cnt = + u64 acc_loop_cnt = jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT); if (NULL == ec || NULL == ec->mem) @@ -299,10 +301,10 @@ static unsigned int jent_memaccess(struct rand_data *ec, __u64 loop_cnt) * 0 jitter measurement not stuck (good bit) * 1 jitter measurement stuck (reject bit) */ -static int jent_stuck(struct rand_data *ec, __u64 current_delta) +static int jent_stuck(struct rand_data *ec, u64 current_delta) { - __s64 delta2 = ec->last_delta - current_delta; - __s64 delta3 = delta2 - ec->last_delta2; + int64_t delta2 = ec->last_delta - current_delta; + int64_t delta3 = delta2 - ec->last_delta2; ec->last_delta = current_delta; ec->last_delta2 = delta2; @@ -329,8 +331,8 @@ static int jent_stuck(struct rand_data *ec, __u64 current_delta) */ static int jent_measure_jitter(struct rand_data *ec) { - __u64 time = 0; - __u64 current_delta = 0; + u64 time = 0; + u64 current_delta = 0; int stuck; /* Invoke one noise source before time measurement to add variations */ @@ -389,8 +391,8 @@ static void jent_stir_pool(struct rand_data *entropy_collector) * with two 32 bit variables */ union c { - __u64 u64; - __u32 u32[2]; + u64 u64; + u32 u32[2]; }; /* * This constant is derived from the first two 32 bit initialization @@ -449,7 +451,7 @@ static void jent_gen_entropy(struct rand_data *ec) jent_measure_jitter(ec); while (1) { - __u64 prev_data = ec->data; + u64 prev_data = ec->data; /* If a stuck measurement is received, repeat measurement */ if (jent_measure_jitter(ec)) @@ -491,7 +493,7 @@ static void jent_gen_entropy(struct rand_data *ec) * The following error codes can occur: * -1 entropy_collector is NULL */ -ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len) +static int jent_read_entropy(struct rand_data *ec, char *data, size_t len) { char *p = data; size_t orig_len = len; @@ -540,8 +542,8 @@ EXPORT_SYMBOL(jent_read_entropy); * Initialization logic ***************************************************************************/ -struct rand_data *jent_entropy_collector_alloc(unsigned int osr, - unsigned int flags) +static struct rand_data *jent_entropy_collector_alloc(unsigned int osr, + unsigned int flags) { struct rand_data *entropy_collector; @@ -584,7 +586,7 @@ struct rand_data *jent_entropy_collector_alloc(unsigned int osr, EXPORT_SYMBOL(jent_entropy_collector_alloc); #endif -void jent_entropy_collector_free(struct rand_data *entropy_collector) +static void jent_entropy_collector_free(struct rand_data *entropy_collector) { if (NULL != entropy_collector) { if (NULL != entropy_collector->mem) { @@ -598,11 +600,11 @@ void jent_entropy_collector_free(struct rand_data *entropy_collector) EXPORT_SYMBOL(jent_entropy_collector_free); #endif -int jent_entropy_init(void) +static int jent_entropy_init(void) { int i; - __u64 delta_sum = 0; - __u64 old_delta = 0; + u64 delta_sum = 0; + u64 old_delta = 0; int time_backwards = 0; int count_var = 0; int count_mod = 0; @@ -633,9 +635,9 @@ int jent_entropy_init(void) #define TESTLOOPCOUNT 300 #define CLEARCACHE 100 for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) { - __u64 time = 0; - __u64 time2 = 0; - __u64 delta = 0; + u64 time = 0; + u64 time2 = 0; + u64 delta = 0; unsigned int lowdelta = 0; jent_get_nstime(&time); @@ -751,10 +753,10 @@ void jent_gen_entropy_stat(struct rand_data *entropy_collector, * Statistical test: obtain the distribution of the LFSR state value from * jent_lfsr_time */ -void jent_lfsr_time_stat(struct rand_data *ec, __u64 *fold, __u64 *loop_cnt) +void jent_lfsr_time_stat(struct rand_data *ec, u64 *fold, u64 *loop_cnt) { - __u64 time = 0; - __u64 time2 = 0; + u64 time = 0; + u64 time2 = 0; jent_get_nstime(&time); jent_memaccess(ec, 0); /* implement the priming logic */ @@ -770,10 +772,10 @@ void jent_lfsr_time_stat(struct rand_data *ec, __u64 *fold, __u64 *loop_cnt) * is set, perform the given number of foldings. Otherwise, allow the * loop count shuffling to define the number of foldings. */ -__u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min) +u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min) { - __u64 time = 0; - __u64 time2 = 0; + u64 time = 0; + u64 time2 = 0; jent_get_nstime(&time); jent_memaccess(ec, min); diff --git a/random/jitterentropy.h b/random/jitterentropy.h index 8012419..2c33256 100644 --- a/random/jitterentropy.h +++ b/random/jitterentropy.h @@ -39,14 +39,14 @@ * DAMAGE. */ -#ifndef _JITTERENTROPY_H -#define _JITTERENTROPY_H +#ifndef GCRYPT_JITTERENTROPY_H +#define GCRYPT_JITTERENTROPY_H -#ifdef __KERNEL__ -#include "jitterentropy-base-kernel.h" -#else -#include "jitterentropy-base-user.h" -#endif /* __KERNEL__ */ +/* #ifdef __KERNEL__ */ +/* #include "jitterentropy-base-kernel.h" */ +/* #else */ +/* #include "jitterentropy-base-user.h" */ +/* #endif /\* __KERNEL__ *\/ */ /* Statistical data from the entropy source */ struct entropy_stat { @@ -66,10 +66,10 @@ struct entropy_stat { other hand, the bit statistics test is not interested in exact timing */ - __u64 collection_begin; /* timer for beginning of one + u64 collection_begin; /* timer for beginning of one entropy collection round */ - __u64 collection_end; /* timer for end of one round */ - __u64 old_delta; /* Time delta of previous round to + u64 collection_end; /* timer for end of one round */ + u64 old_delta; /* Time delta of previous round to calculate delta of deltas */ unsigned int setbits; /* see _jent_calc_statistic */ unsigned int varbits; /* see _jent_calc_statistic */ @@ -84,11 +84,11 @@ struct rand_data * of the RNG are marked as SENSITIVE. A user must not * access that information while the RNG executes its loops to * calculate the next random value. */ - __u64 data; /* SENSITIVE Actual random number */ - __u64 prev_time; /* SENSITIVE Previous time stamp */ -#define DATA_SIZE_BITS ((sizeof(__u64)) * 8) - __u64 last_delta; /* SENSITIVE stuck test */ - __s64 last_delta2; /* SENSITIVE stuck test */ + u64 data; /* SENSITIVE Actual random number */ + u64 prev_time; /* SENSITIVE Previous time stamp */ +#define DATA_SIZE_BITS ((sizeof(u64)) * 8) + u64 last_delta; /* SENSITIVE stuck test */ + int64_t last_delta2; /* SENSITIVE stuck test */ unsigned int osr; /* Oversample rate */ unsigned int stir:1; /* Post-processing stirring */ unsigned int disable_unbias:1; /* Deactivate Von-Neuman unbias */ @@ -121,22 +121,26 @@ struct rand_data /* Number of low bits of the time value that we want to consider */ /* get raw entropy */ -ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len); +static int jent_read_entropy (struct rand_data *ec, + char *data, size_t len); + /* initialize an instance of the entropy collector */ -struct rand_data *jent_entropy_collector_alloc(unsigned int osr, - unsigned int flags); +static struct rand_data *jent_entropy_collector_alloc (unsigned int osr, + unsigned int flags); + /* clearing of entropy collector */ -void jent_entropy_collector_free(struct rand_data *entropy_collector); +static void jent_entropy_collector_free (struct rand_data *ent_coll); /* initialization of entropy collector */ -int jent_entropy_init(void); +static int jent_entropy_init (void); /* return version number of core library */ -unsigned int jent_version(void); +/* unsigned int jent_version(void); */ /* -- END of Main interface functions -- */ /* -- BEGIN error codes for init function -- */ +/* FIXME!!! */ #define ENOTIME 1 /* Timer service not available */ #define ECOARSETIME 2 /* Timer too coarse for RNG */ #define ENOMONOTONIC 3 /* Timer is not monotonic increasing */ @@ -148,25 +152,26 @@ unsigned int jent_version(void); /* -- BEGIN statistical test functions only complied with CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT -- */ -void _jent_init_statistic(struct rand_data *entropy_collector); -void _jent_calc_statistic(struct rand_data *entropy_collector, +#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT + +static void jent_init_statistic(struct rand_data *entropy_collector); +static void jent_calc_statistic(struct rand_data *entropy_collector, struct entropy_stat *stat, unsigned int loop_cnt); -void _jent_bit_count(struct rand_data *entropy_collector, __u64 prev_data); +static void jent_bit_count (struct rand_data *entropy_collector, u64 prev_data); + +static void jent_gen_entropy_stat (struct rand_data *entropy_collector, + struct entropy_stat *stat); +static void jent_lfsr_time_stat(struct rand_data *ec, u64 *fold, u64 *loop_cnt); +static u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min); -#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT -#define jent_init_statistic(x) do { _jent_init_statistic(x); } while (0) -#define jent_calc_statistic(x, y, z) do { _jent_calc_statistic(x, y, z); } while (0) -#define jent_bit_count(x,y) do { _jent_bit_count(x, y); } while (0) -void jent_gen_entropy_stat(struct rand_data *entropy_collector, - struct entropy_stat *stat); -void jent_lfsr_time_stat(struct rand_data *ec, __u64 *fold, __u64 *loop_cnt); -__u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min); #else /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ -#define jent_init_statistic(x) do { if(0) _jent_init_statistic(x); } while (0) -#define jent_calc_statistic(x, y, z) do { if(0) _jent_calc_statistic(x, y, z); } while (0) -#define jent_bit_count(x,y) do { if(0) _jent_bit_count(x,y); } while (0) + +# define jent_init_statistic(x) do { } while (0) +# define jent_calc_statistic(x, y, z) do { } while (0) +# define jent_bit_count(x,y) do { (void)(y); } while (0) + #endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ /* -- END of statistical test function -- */ -#endif /* _JITTERENTROPY_H */ +#endif /* GCRYPT_JITTERENTROPY_H */ commit f0ae18ecf48fbe2da0b9fb3f354d0dd3173d91d3 Author: Stephan Mueller Date: Tue May 23 18:53:21 2017 +0200 random: Add original Jitter RNG implementation * random/jitterentropy-base-user.h: New. * random/jitterentropy-base.c: New. * random/jitterentropy.h: New. -- Signed-off-by: Werner Koch - Tabs and trailing white spaces removed from original source. - Source received by mail dated Fri, 27 Jan 2017 17:52:38 +0100 from Stephan diff --git a/LICENSES b/LICENSES index ebc18b3..9c0267e 100644 --- a/LICENSES +++ b/LICENSES @@ -54,6 +54,51 @@ with any binary distributions derived from the GNU C Library. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #+end_quote + + For files: + - random/jitterentropy-base-user.h + - random/jitterentropy-base.c + - random/jitterentropy.h + +#+begin_quote + * Copyright Stephan Mueller , 2013 + * + * License + * ======= + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * ALTERNATIVELY, this product may be distributed under the terms of + * the GNU General Public License, in which case the provisions of the GPL are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the GPL and + * the restrictions contained in a BSD-style copyright.) + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF + * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. +#+end_quote + * X License For files: diff --git a/random/jitterentropy-base-user.h b/random/jitterentropy-base-user.h new file mode 100644 index 0000000..2aecf3b --- /dev/null +++ b/random/jitterentropy-base-user.h @@ -0,0 +1,103 @@ +/* + * Non-physical true random number generator based on timing jitter. + * + * Copyright Stephan Mueller , 2013 + * + * License + * ======= + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * ALTERNATIVELY, this product may be distributed under the terms of + * the GNU General Public License, in which case the provisions of the GPL are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the GPL and + * the restrictions contained in a BSD-style copyright.) + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF + * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + */ + +#ifndef _JITTERENTROPY_BASE_X86_H +#define _JITTERENTROPY_BASE_X86_H + +#include +#include +#include + +#include +#include "g10lib.h" + +typedef uint64_t __u64; + +#define RdTSC __asm _emit 0x0f __asm _emit 0x31 + +static void jent_get_nstime(__u64 *out) +{ + __u64 ret = 0; + _asm { + RdTSC + mov DWORD PTR ret, eax + mov DWORD PTR[ret + 4], edx + } + *out = ret; +} + +static inline void *jent_zalloc(size_t len) +{ + void *tmp = NULL; + + /* When using the libgcrypt secure memory mechanism, all precautions + * are taken to protect our state. If the user disables secmem during + * runtime, it is his decision and we thus try not to overrule his + * decision for less memory protection. */ +#define CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY + tmp = gcry_xmalloc_secure(len); + if(NULL != tmp) + memset(tmp, 0, len); + return tmp; +} + +static inline void jent_zfree(void *ptr, unsigned int len) +{ + memset(ptr, 0, len); + gcry_free(ptr); +} + +static inline int jent_fips_enabled(void) +{ + return fips_mode(); +} + +/* --- helpers needed in user space -- */ + +/* note: these helper functions are shamelessly stolen from the kernel :-) */ + +static inline __u64 rol64(__u64 word, unsigned int shift) +{ + return (word << shift) | (word >> (64 - shift)); +} + + +#endif /* _JITTERENTROPY_BASE_X86_H */ diff --git a/random/jitterentropy-base.c b/random/jitterentropy-base.c new file mode 100644 index 0000000..23ac695 --- /dev/null +++ b/random/jitterentropy-base.c @@ -0,0 +1,784 @@ +?/* + * Non-physical true random number generator based on timing jitter. + * + * Copyright Stephan Mueller , 2014 + * + * Design + * ====== + * + * See documentation in doc/ folder. + * + * Interface + * ========= + * + * See documentation in doc/ folder. + * + * License + * ======= + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * ALTERNATIVELY, this product may be distributed under the terms of + * the GNU General Public License, in which case the provisions of the GPL2 are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the GPL and + * the restrictions contained in a BSD-style copyright.) + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF + * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + */ + +#include "jitterentropy.h" + +#ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT + /* only check optimization in a compilation for real work */ + #ifdef __OPTIMIZE__ + #error "The CPU Jitter random number generator must not be compiled with optimizations. See documentation. Use the compiler switch -O0 for compiling jitterentropy-base.c." + #endif +#endif + +#define MAJVERSION 2 /* API / ABI incompatible changes, functional changes that + * require consumer to be updated (as long as this number + * is zero, the API is not considered stable and can + * change without a bump of the major version) */ +#define MINVERSION 0 /* API compatible, ABI may change, functional + * enhancements only, consumer can be left unchanged if + * enhancements are not considered */ +#define PATCHLEVEL 0 /* API / ABI compatible, no functional changes, no + * enhancements, bug fixes only */ + +/** + * jent_version() - Return machine-usable version number of jent library + * + * The function returns a version number that is monotonic increasing + * for newer versions. The version numbers are multiples of 100. For example, + * version 1.2.3 is converted to 1020300 -- the last two digits are reserved + * for future use. + * + * The result of this function can be used in comparing the version number + * in a calling program if version-specific calls need to be make. + * + * Return: Version number of kcapi library + */ +unsigned int jent_version(void) +{ + unsigned int version = 0; + + version = MAJVERSION * 1000000; + version += MINVERSION * 10000; + version += PATCHLEVEL * 100; + + return version; +} + +/** + * Update of the loop count used for the next round of + * an entropy collection. + * + * Input: + * @ec entropy collector struct -- may be NULL + * @bits is the number of low bits of the timer to consider + * @min is the number of bits we shift the timer value to the right at + * the end to make sure we have a guaranteed minimum value + * + * @return Newly calculated loop counter + */ +static __u64 jent_loop_shuffle(struct rand_data *ec, + unsigned int bits, unsigned int min) +{ + __u64 time = 0; + __u64 shuffle = 0; + unsigned int i = 0; + unsigned int mask = (1<data; + /* + * We fold the time value as much as possible to ensure that as many + * bits of the time stamp are included as possible. + */ + for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) { + shuffle ^= time & mask; + time = time >> bits; + } + + /* + * We add a lower boundary value to ensure we have a minimum + * RNG loop count. + */ + return (shuffle + (1<data + * + * @return Number of loops the folding operation is performed + */ +static __u64 jent_lfsr_time(struct rand_data *ec, __u64 time, + __u64 loop_cnt) +{ + unsigned int i; + __u64 j = 0; + __u64 new = 0; +#define MAX_FOLD_LOOP_BIT 4 +#define MIN_FOLD_LOOP_BIT 0 + __u64 fold_loop_cnt = + jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT); + + /* + * testing purposes -- allow test app to set the counter, not + * needed during runtime + */ + if (loop_cnt) + fold_loop_cnt = loop_cnt; + for (j = 0; j < fold_loop_cnt; j++) { + new = ec->data; + for (i = 1; (DATA_SIZE_BITS) >= i; i++) { + __u64 tmp = time << (DATA_SIZE_BITS - i); + + tmp = tmp >> (DATA_SIZE_BITS - 1); + + /* + * Fibonacci LSFR with polynomial of + * x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is + * primitive according to + * http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf + * (the shift values are the polynomial values minus one + * due to counting bits from 0 to 63). As the current + * position is always the LSB, the polynomial only needs + * to shift data in from the left without wrap. + */ + new ^= tmp; + new ^= ((new >> 63) & 1); + new ^= ((new >> 60) & 1); + new ^= ((new >> 55) & 1); + new ^= ((new >> 30) & 1); + new ^= ((new >> 27) & 1); + new ^= ((new >> 22) & 1); + new = rol64(new, 1); + } + } + ec->data = new; + + return fold_loop_cnt; +} + +/** + * Memory Access noise source -- this is a noise source based on variations in + * memory access times + * + * This function performs memory accesses which will add to the timing + * variations due to an unknown amount of CPU wait states that need to be + * added when accessing memory. The memory size should be larger than the L1 + * caches as outlined in the documentation and the associated testing. + * + * The L1 cache has a very high bandwidth, albeit its access rate is usually + * slower than accessing CPU registers. Therefore, L1 accesses only add minimal + * variations as the CPU has hardly to wait. Starting with L2, significant + * variations are added because L2 typically does not belong to the CPU any more + * and therefore a wider range of CPU wait states is necessary for accesses. + * L3 and real memory accesses have even a wider range of wait states. However, + * to reliably access either L3 or memory, the ec->mem memory must be quite + * large which is usually not desirable. + * + * Input: + * @ec Reference to the entropy collector with the memory access data -- if + * the reference to the memory block to be accessed is NULL, this noise + * source is disabled + * @loop_cnt if a value not equal to 0 is set, use the given value as number of + * loops to perform the folding + * + * @return Number of memory access operations + */ +static unsigned int jent_memaccess(struct rand_data *ec, __u64 loop_cnt) +{ + unsigned int wrap = 0; + __u64 i = 0; +#define MAX_ACC_LOOP_BIT 7 +#define MIN_ACC_LOOP_BIT 0 + __u64 acc_loop_cnt = + jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT); + + if (NULL == ec || NULL == ec->mem) + return 0; + wrap = ec->memblocksize * ec->memblocks; + + /* + * testing purposes -- allow test app to set the counter, not + * needed during runtime + */ + if (loop_cnt) + acc_loop_cnt = loop_cnt; + + for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) { + unsigned char *tmpval = ec->mem + ec->memlocation; + /* + * memory access: just add 1 to one byte, + * wrap at 255 -- memory access implies read + * from and write to memory location + */ + *tmpval = (*tmpval + 1) & 0xff; + /* + * Addition of memblocksize - 1 to pointer + * with wrap around logic to ensure that every + * memory location is hit evenly + */ + ec->memlocation = ec->memlocation + ec->memblocksize - 1; + ec->memlocation = ec->memlocation % wrap; + } + return i; +} + +/*************************************************************************** + * Start of entropy processing logic + ***************************************************************************/ + +/** + * Stuck test by checking the: + * 1st derivation of the jitter measurement (time delta) + * 2nd derivation of the jitter measurement (delta of time deltas) + * 3rd derivation of the jitter measurement (delta of delta of time deltas) + * + * All values must always be non-zero. + * + * Input: + * @ec Reference to entropy collector + * @current_delta Jitter time delta + * + * @return + * 0 jitter measurement not stuck (good bit) + * 1 jitter measurement stuck (reject bit) + */ +static int jent_stuck(struct rand_data *ec, __u64 current_delta) +{ + __s64 delta2 = ec->last_delta - current_delta; + __s64 delta3 = delta2 - ec->last_delta2; + + ec->last_delta = current_delta; + ec->last_delta2 = delta2; + + if (!current_delta || !delta2 || !delta3) + return 1; + + return 0; +} + +/** + * This is the heart of the entropy generation: calculate time deltas and + * use the CPU jitter in the time deltas. The jitter is injected into the + * entropy pool. + * + * WARNING: ensure that ->prev_time is primed before using the output + * of this function! This can be done by calling this function + * and not using its result. + * + * Input: + * @entropy_collector Reference to entropy collector + * + * @return: result of stuck test + */ +static int jent_measure_jitter(struct rand_data *ec) +{ + __u64 time = 0; + __u64 current_delta = 0; + int stuck; + + /* Invoke one noise source before time measurement to add variations */ + jent_memaccess(ec, 0); + + /* + * Get time stamp and calculate time delta to previous + * invocation to measure the timing variations + */ + jent_get_nstime(&time); + current_delta = time - ec->prev_time; + ec->prev_time = time; + + /* Now call the next noise sources which also injects the data */ + jent_lfsr_time(ec, current_delta, 0); + + /* Check whether we have a stuck measurement. */ + stuck = jent_stuck(ec, current_delta); + + /* + * Rotate the data buffer by a prime number (any odd number would + * do) to ensure that every bit position of the input time stamp + * has an even chance of being merged with a bit position in the + * entropy pool. We do not use one here as the adjacent bits in + * successive time deltas may have some form of dependency. The + * chosen value of 7 implies that the low 7 bits of the next + * time delta value is concatenated with the current time delta. + */ + if (!stuck) + ec->data = rol64(ec->data, 7); + + return stuck; +} + +/** + * Shuffle the pool a bit by mixing some value with a bijective function (XOR) + * into the pool. + * + * The function generates a mixer value that depends on the bits set and the + * location of the set bits in the random number generated by the entropy + * source. Therefore, based on the generated random number, this mixer value + * can have 2**64 different values. That mixer value is initialized with the + * first two SHA-1 constants. After obtaining the mixer value, it is XORed into + * the random number. + * + * The mixer value is not assumed to contain any entropy. But due to the XOR + * operation, it can also not destroy any entropy present in the entropy pool. + * + * Input: + * @entropy_collector Reference to entropy collector + */ +static void jent_stir_pool(struct rand_data *entropy_collector) +{ + /* + * to shut up GCC on 32 bit, we have to initialize the 64 variable + * with two 32 bit variables + */ + union c { + __u64 u64; + __u32 u32[2]; + }; + /* + * This constant is derived from the first two 32 bit initialization + * vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 + */ + union c constant; + /* + * The start value of the mixer variable is derived from the third + * and fourth 32 bit initialization vector of SHA-1 as defined in + * FIPS 180-4 section 5.3.1 + */ + union c mixer; + unsigned int i = 0; + + /* Ensure that the function implements a constant time operation. */ + union c throw_away; + + /* + * Store the SHA-1 constants in reverse order to make up the 64 bit + * value -- this applies to a little endian system, on a big endian + * system, it reverses as expected. But this really does not matter + * as we do not rely on the specific numbers. We just pick the SHA-1 + * constants as they have a good mix of bit set and unset. + */ + constant.u32[1] = 0x67452301; + constant.u32[0] = 0xefcdab89; + mixer.u32[1] = 0x98badcfe; + mixer.u32[0] = 0x10325476; + + for (i = 0; i < DATA_SIZE_BITS; i++) { + /* + * get the i-th bit of the input random number and only XOR + * the constant into the mixer value when that bit is set + */ + if ((entropy_collector->data >> i) & 1) + mixer.u64 ^= constant.u64; + else + throw_away.u64 ^= constant.u64; + mixer.u64 = rol64(mixer.u64, 1); + } + entropy_collector->data ^= mixer.u64; +} + +/** + * Generator of one 64 bit random number + * Function fills rand_data->data + * + * Input: + * @ec Reference to entropy collector + */ +static void jent_gen_entropy(struct rand_data *ec) +{ + unsigned int k = 0; + + /* priming of the ->prev_time value */ + jent_measure_jitter(ec); + + while (1) { + __u64 prev_data = ec->data; + + /* If a stuck measurement is received, repeat measurement */ + if (jent_measure_jitter(ec)) + continue; + + /* statistics testing only */ + jent_bit_count(ec, prev_data); + + /* + * We multiply the loop value with ->osr to obtain the + * oversampling rate requested by the caller + */ + if (++k >= (DATA_SIZE_BITS * ec->osr)) + break; + } + if (ec->stir) + jent_stir_pool(ec); +} + +/** + * Entry function: Obtain entropy for the caller. + * + * This function invokes the entropy gathering logic as often to generate + * as many bytes as requested by the caller. The entropy gathering logic + * creates 64 bit per invocation. + * + * This function truncates the last 64 bit entropy value output to the exact + * size specified by the caller. + * + * Input: + * @ec Reference to entropy collector + * @data pointer to buffer for storing random data -- buffer must already + * exist + * @len size of the buffer, specifying also the requested number of random + * in bytes + * + * @return number of bytes returned when request is fulfilled or an error + * + * The following error codes can occur: + * -1 entropy_collector is NULL + */ +ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len) +{ + char *p = data; + size_t orig_len = len; + + if (NULL == ec) + return -1; + + while (0 < len) { + size_t tocopy; + jent_gen_entropy(ec); + if ((DATA_SIZE_BITS / 8) < len) + tocopy = (DATA_SIZE_BITS / 8); + else + tocopy = len; + memcpy(p, &ec->data, tocopy); + + len -= tocopy; + p += tocopy; + } + + /* + * To be on the safe side, we generate one more round of entropy + * which we do not give out to the caller. That round shall ensure + * that in case the calling application crashes, memory dumps, pages + * out, or due to the CPU Jitter RNG lingering in memory for long + * time without being moved and an attacker cracks the application, + * all he reads in the entropy pool is a value that is NEVER EVER + * being used for anything. Thus, he does NOT see the previous value + * that was returned to the caller for cryptographic purposes. + */ + /* + * If we use secured memory, do not use that precaution as the secure + * memory protects the entropy pool. Moreover, note that using this + * call reduces the speed of the RNG by up to half + */ +#ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY + jent_gen_entropy(ec); +#endif + return orig_len; +} +#if defined(__KERNEL__) && !defined(MODULE) +EXPORT_SYMBOL(jent_read_entropy); +#endif + +/*************************************************************************** + * Initialization logic + ***************************************************************************/ + +struct rand_data *jent_entropy_collector_alloc(unsigned int osr, + unsigned int flags) +{ + struct rand_data *entropy_collector; + + entropy_collector = jent_zalloc(sizeof(struct rand_data)); + if (NULL == entropy_collector) + return NULL; + + if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) { + /* Allocate memory for adding variations based on memory + * access + */ + entropy_collector->mem = + (unsigned char *)jent_zalloc(JENT_MEMORY_SIZE); + if (NULL == entropy_collector->mem) { + jent_zfree(entropy_collector, sizeof(struct rand_data)); + return NULL; + } + entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE; + entropy_collector->memblocks = JENT_MEMORY_BLOCKS; + entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS; + } + + /* verify and set the oversampling rate */ + if (0 == osr) + osr = 1; /* minimum sampling rate is 1 */ + entropy_collector->osr = osr; + + entropy_collector->stir = 1; + if (flags & JENT_DISABLE_STIR) + entropy_collector->stir = 0; + if (flags & JENT_DISABLE_UNBIAS) + entropy_collector->disable_unbias = 1; + + /* fill the data pad with non-zero values */ + jent_gen_entropy(entropy_collector); + + return entropy_collector; +} +#if defined(__KERNEL__) && !defined(MODULE) +EXPORT_SYMBOL(jent_entropy_collector_alloc); +#endif + +void jent_entropy_collector_free(struct rand_data *entropy_collector) +{ + if (NULL != entropy_collector) { + if (NULL != entropy_collector->mem) { + jent_zfree(entropy_collector->mem, JENT_MEMORY_SIZE); + entropy_collector->mem = NULL; + } + jent_zfree(entropy_collector, sizeof(struct rand_data)); + } +} +#if defined(__KERNEL__) && !defined(MODULE) +EXPORT_SYMBOL(jent_entropy_collector_free); +#endif + +int jent_entropy_init(void) +{ + int i; + __u64 delta_sum = 0; + __u64 old_delta = 0; + int time_backwards = 0; + int count_var = 0; + int count_mod = 0; + struct rand_data ec; + + /* We could perform statistical tests here, but the problem is + * that we only have a few loop counts to do testing. These + * loop counts may show some slight skew and we produce + * false positives. + * + * Moreover, only old systems show potentially problematic + * jitter entropy that could potentially be caught here. But + * the RNG is intended for hardware that is available or widely + * used, but not old systems that are long out of favor. Thus, + * no statistical tests. + */ + + /* + * We could add a check for system capabilities such as clock_getres or + * check for CONFIG_X86_TSC, but it does not make much sense as the + * following sanity checks verify that we have a high-resolution + * timer. + */ + /* + * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is + * definitely too little. + */ +#define TESTLOOPCOUNT 300 +#define CLEARCACHE 100 + for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) { + __u64 time = 0; + __u64 time2 = 0; + __u64 delta = 0; + unsigned int lowdelta = 0; + + jent_get_nstime(&time); + jent_lfsr_time(&ec, time, 1< i) + continue; + + /* test whether we have an increasing timer */ + if (!(time2 > time)) + time_backwards++; + + /* use 32 bit value to ensure compilation on 32 bit arches */ + lowdelta = time2 - time; + if (!(lowdelta % 100)) + count_mod++; + + /* + * ensure that we have a varying delta timer which is necessary + * for the calculation of entropy -- perform this check + * only after the first loop is executed as we need to prime + * the old_data value + */ + if (i) { + if (delta != old_delta) + count_var++; + if (delta > old_delta) + delta_sum += (delta - old_delta); + else + delta_sum += (old_delta - delta); + } + old_delta = delta; + } + + /* + * we allow up to three times the time running backwards. + * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus, + * if such an operation just happens to interfere with our test, it + * should not fail. The value of 3 should cover the NTP case being + * performed during our test run. + */ + if (3 < time_backwards) + return ENOMONOTONIC; + /* Error if the time variances are always identical */ + if (!delta_sum) + return EVARVAR; + + /* + * Variations of deltas of time must on average be larger + * than 1 to ensure the entropy estimation + * implied with 1 is preserved + */ + if ((delta_sum) <= 1) + return EMINVARVAR; + + /* + * Ensure that we have variations in the time stamp below 10 for at least + * 10% of all checks -- on some platforms, the counter increments in + * multiples of 100, but not always + */ + if ((TESTLOOPCOUNT/10 * 9) < count_mod) + return ECOARSETIME; + + return 0; +} +#if defined(__KERNEL__) && !defined(MODULE) +EXPORT_SYMBOL(jent_entropy_init); +#endif + +/*************************************************************************** + * Statistical test logic not compiled for regular operation + ***************************************************************************/ + +#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT +/* + * Statistical tests: invoke the entropy collector and sample time results + * for it, the random data is never returned - every call to this function + * generates one random number. + * This function is only meant for statistical analysis purposes and not + * for general use + */ +void jent_gen_entropy_stat(struct rand_data *entropy_collector, + struct entropy_stat *stat) +{ + /* caller is allowed to set the entropy collection loop to a fixed + * value -- we still call shuffle for the time measurements */ + jent_init_statistic(entropy_collector); + jent_gen_entropy(entropy_collector); + jent_calc_statistic(entropy_collector, stat, DATA_SIZE_BITS); +} + +/* + * Statistical test: obtain the distribution of the LFSR state value from + * jent_lfsr_time + */ +void jent_lfsr_time_stat(struct rand_data *ec, __u64 *fold, __u64 *loop_cnt) +{ + __u64 time = 0; + __u64 time2 = 0; + jent_get_nstime(&time); + jent_memaccess(ec, 0); + /* implement the priming logic */ + jent_lfsr_time(ec, time, 0); + jent_get_nstime(&time2); + time2 = time2 - time; + *loop_cnt = jent_lfsr_time(ec, time2, 0); + *fold = ec->data; +} + +/* + * Statistical test: return the time duration for the folding operation. If min + * is set, perform the given number of foldings. Otherwise, allow the + * loop count shuffling to define the number of foldings. + */ +__u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min) +{ + __u64 time = 0; + __u64 time2 = 0; + + jent_get_nstime(&time); + jent_memaccess(ec, min); + jent_lfsr_time(ec, time, min); + jent_get_nstime(&time2); + return ((time2 - time)); +} +#endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ diff --git a/random/jitterentropy.h b/random/jitterentropy.h new file mode 100644 index 0000000..8012419 --- /dev/null +++ b/random/jitterentropy.h @@ -0,0 +1,172 @@ +?/* + * Non-physical true random number generator based on timing jitter. + * + * Copyright Stephan Mueller , 2014 + * + * License + * ======= + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. + * + * ALTERNATIVELY, this product may be distributed under the terms of + * the GNU General Public License, in which case the provisions of the GPL are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the GPL and + * the restrictions contained in a BSD-style copyright.) + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF + * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + */ + +#ifndef _JITTERENTROPY_H +#define _JITTERENTROPY_H + +#ifdef __KERNEL__ +#include "jitterentropy-base-kernel.h" +#else +#include "jitterentropy-base-user.h" +#endif /* __KERNEL__ */ + +/* Statistical data from the entropy source */ +struct entropy_stat { + unsigned int bitslot[64]; /* Counter for the bits set per bit + position in ->data */ + unsigned int bitvar[64]; /* Counter for the number of bit + variations per bit position in + ->data */ + unsigned int enable_bit_test; /* enable bit test + this flag is vital for the accuracy + of the statistic tests: when we + do the time measurements, we want + the observed entropy collection + loop executed as fast as the + unmeasured loop, i.e. without + the bit statistic logic; on the + other hand, the bit statistics + test is not interested in exact + timing */ + __u64 collection_begin; /* timer for beginning of one + entropy collection round */ + __u64 collection_end; /* timer for end of one round */ + __u64 old_delta; /* Time delta of previous round to + calculate delta of deltas */ + unsigned int setbits; /* see _jent_calc_statistic */ + unsigned int varbits; /* see _jent_calc_statistic */ + unsigned int obsbits; /* see _jent_calc_statistic */ + unsigned int collection_loop_cnt; /* Collection loop counter */ +}; + +/* The entropy pool */ +struct rand_data +{ + /* all data values that are vital to maintain the security + * of the RNG are marked as SENSITIVE. A user must not + * access that information while the RNG executes its loops to + * calculate the next random value. */ + __u64 data; /* SENSITIVE Actual random number */ + __u64 prev_time; /* SENSITIVE Previous time stamp */ +#define DATA_SIZE_BITS ((sizeof(__u64)) * 8) + __u64 last_delta; /* SENSITIVE stuck test */ + __s64 last_delta2; /* SENSITIVE stuck test */ + unsigned int osr; /* Oversample rate */ + unsigned int stir:1; /* Post-processing stirring */ + unsigned int disable_unbias:1; /* Deactivate Von-Neuman unbias */ +#define JENT_MEMORY_BLOCKS 64 +#define JENT_MEMORY_BLOCKSIZE 32 +#define JENT_MEMORY_ACCESSLOOPS 128 +#define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE) + unsigned char *mem; /* Memory access location with size of + * memblocks * memblocksize */ + unsigned int memlocation; /* Pointer to byte in *mem */ + unsigned int memblocks; /* Number of memory blocks in *mem */ + unsigned int memblocksize; /* Size of one memory block in bytes */ + unsigned int memaccessloops; /* Number of memory accesses per random + * bit generation */ +#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT + struct entropy_stat entropy_stat; +#endif +}; + +/* Flags that can be used to initialize the RNG */ +#define JENT_DISABLE_STIR (1<<0) /* Disable stirring the entropy pool */ +#define JENT_DISABLE_UNBIAS (1<<1) /* Disable the Von-Neuman Unbiaser */ +#define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more + entropy, saves MEMORY_SIZE RAM for + entropy collector */ + +#define DRIVER_NAME "jitterentropy" + +/* -- BEGIN Main interface functions -- */ + +/* Number of low bits of the time value that we want to consider */ +/* get raw entropy */ +ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len); +/* initialize an instance of the entropy collector */ +struct rand_data *jent_entropy_collector_alloc(unsigned int osr, + unsigned int flags); +/* clearing of entropy collector */ +void jent_entropy_collector_free(struct rand_data *entropy_collector); + +/* initialization of entropy collector */ +int jent_entropy_init(void); + +/* return version number of core library */ +unsigned int jent_version(void); + +/* -- END of Main interface functions -- */ + +/* -- BEGIN error codes for init function -- */ +#define ENOTIME 1 /* Timer service not available */ +#define ECOARSETIME 2 /* Timer too coarse for RNG */ +#define ENOMONOTONIC 3 /* Timer is not monotonic increasing */ +#define EMINVARIATION 4 /* Timer variations too small for RNG */ +#define EVARVAR 5 /* Timer does not produce variations of variations + (2nd derivation of time is zero) */ +#define EMINVARVAR 6 /* Timer variations of variations is too small */ +#define EPROGERR 7 /* Programming error */ + +/* -- BEGIN statistical test functions only complied with CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT -- */ + +void _jent_init_statistic(struct rand_data *entropy_collector); +void _jent_calc_statistic(struct rand_data *entropy_collector, + struct entropy_stat *stat, unsigned int loop_cnt); +void _jent_bit_count(struct rand_data *entropy_collector, __u64 prev_data); + +#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT +#define jent_init_statistic(x) do { _jent_init_statistic(x); } while (0) +#define jent_calc_statistic(x, y, z) do { _jent_calc_statistic(x, y, z); } while (0) +#define jent_bit_count(x,y) do { _jent_bit_count(x, y); } while (0) +void jent_gen_entropy_stat(struct rand_data *entropy_collector, + struct entropy_stat *stat); +void jent_lfsr_time_stat(struct rand_data *ec, __u64 *fold, __u64 *loop_cnt); +__u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min); +#else /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ +#define jent_init_statistic(x) do { if(0) _jent_init_statistic(x); } while (0) +#define jent_calc_statistic(x, y, z) do { if(0) _jent_calc_statistic(x, y, z); } while (0) +#define jent_bit_count(x,y) do { if(0) _jent_bit_count(x,y); } while (0) +#endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ + +/* -- END of statistical test function -- */ + +#endif /* _JITTERENTROPY_H */ ----------------------------------------------------------------------- Summary of changes: AUTHORS | 3 +- LICENSES | 45 +++ cipher/bithelp.h | 5 + configure.ac | 14 + doc/gcrypt.texi | 1 + random/Makefile.am | 20 +- random/jitterentropy-base-user.h | 103 +++++ random/jitterentropy-base.c | 786 +++++++++++++++++++++++++++++++++++++++ random/jitterentropy.h | 177 +++++++++ random/rand-internal.h | 8 +- random/rndjent.c | 208 +++++++++++ random/rndlinux.c | 15 +- random/rndw32.c | 12 +- src/g10lib.h | 3 + src/hwf-x86.c | 10 +- src/hwfeatures.c | 1 + 16 files changed, 1402 insertions(+), 9 deletions(-) create mode 100644 random/jitterentropy-base-user.h create mode 100644 random/jitterentropy-base.c create mode 100644 random/jitterentropy.h create mode 100644 random/rndjent.c hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Fri Jun 16 12:00:28 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Fri, 16 Jun 2017 12:00:28 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-100-g8f6082e Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 8f6082e95f30c1ba68d2de23da90146f87f0c66c (commit) via b05a4abc358b204dba343d9cfbd59fdc828c1686 (commit) from f5e7763ddca59dcd9ac9f2f4d50cb41b14a34a9e (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 8f6082e95f30c1ba68d2de23da90146f87f0c66c Author: Werner Koch Date: Fri Jun 16 11:55:50 2017 +0200 New global config option "only-urandom". * random/rand-internal.h (RANDOM_CONF_ONLY_URANDOM): New. * random/random.c (_gcry_random_read_conf): Add option "only-urandom". * random/rndlinux.c (_gcry_rndlinux_gather_random): Implement that option. * tests/keygen.c (main): Add option --no-quick for better manual tests. Signed-off-by: Werner Koch diff --git a/doc/gcrypt.texi b/doc/gcrypt.texi index 3567582..26dd6c3 100644 --- a/doc/gcrypt.texi +++ b/doc/gcrypt.texi @@ -5468,6 +5468,13 @@ ignored. Supported options are @cindex disable-jent Disable the use of the jitter based entropy generator. + at item only-urandom + at cindex only-urandom +Always use the non-blocking /dev/urandom or the respective system call +instead of the blocking /dev/random. If Libgcrypt is used early in +the boot process of the system, this option should only be used if the +system also supports the getrandom system call. + @end table @item /etc/gcrypt/fips_enabled @@ -5826,8 +5833,10 @@ Both generators make use of so-called entropy gathering modules: @table @asis @item rndlinux -Uses the operating system provided - at file{/dev/random} and @file{/dev/urandom} devices. +Uses the operating system provided @file{/dev/random} and + at file{/dev/urandom} devices. The @file{/dev/gcrypt/random.conf} +config option @option{only-urandom} can be used to inhibit the use of +the blocking @file{/dev/random} device. @item rndunix Runs several operating system commands to collect entropy from sources @@ -5853,6 +5862,12 @@ random number generator. As of now the supported hardware RNG is the Padlock engine of VIA (Centaur) CPUs and x86 CPUs with the RDRAND instruction. It is not available in FIPS mode. + at item rndjent +Extra module to collect additional entropy using a CPU jitter based +approach. This is only used on X86 hardware where the RDTSC opcode is +available. The @file{/dev/gcrypt/random.conf} config option + at option{disable-jent} can be used to inhibit the use of this module. + @end table diff --git a/random/rand-internal.h b/random/rand-internal.h index ec4550c..2bc05f4 100644 --- a/random/rand-internal.h +++ b/random/rand-internal.h @@ -36,6 +36,7 @@ enum random_origins }; #define RANDOM_CONF_DISABLE_JENT 1 +#define RANDOM_CONF_ONLY_URANDOM 2 /*-- random.c --*/ diff --git a/random/random.c b/random/random.c index 4a2a61b..9aab789 100644 --- a/random/random.c +++ b/random/random.c @@ -94,6 +94,8 @@ _gcry_random_progress (const char *what, int printchar, int current, int total) * * disable-jent - Disable the jitter based extra entropy generator. * This sets the RANDOM_CONF_DISABLE_JENT bit. + * only-urandom - Always use /dev/urandom instead of /dev/random. + * This sets the RANDOM_CONF_ONLY_URANDOM bit. * * The function returns a bit vector with flags read from the file. */ @@ -141,6 +143,8 @@ _gcry_random_read_conf (void) if (!strcmp (p, "disable-jent")) result |= RANDOM_CONF_DISABLE_JENT; + else if (!strcmp (p, "only-urandom")) + result |= RANDOM_CONF_ONLY_URANDOM; else { #ifdef HAVE_SYSLOG diff --git a/random/rndlinux.c b/random/rndlinux.c index f1548fb..1bb7c76 100644 --- a/random/rndlinux.c +++ b/random/rndlinux.c @@ -115,6 +115,7 @@ _gcry_rndlinux_gather_random (void (*add)(const void*, size_t, { static int fd_urandom = -1; static int fd_random = -1; + static int only_urandom = -1; static unsigned char ever_opened; int fd; int n; @@ -125,6 +126,17 @@ _gcry_rndlinux_gather_random (void (*add)(const void*, size_t, int any_need_entropy = 0; int delay; + /* On the first call read the conf file to check whether we want to + * use only urandom. */ + if (only_urandom == -1) + { + if ((_gcry_random_read_conf () & RANDOM_CONF_ONLY_URANDOM)) + only_urandom = 1; + else + only_urandom = 0; + } + + if (!add) { /* Special mode to close the descriptors. */ @@ -178,7 +190,7 @@ _gcry_rndlinux_gather_random (void (*add)(const void*, size_t, that we always require the device to be existent but want a more graceful behaviour if the rarely needed close operation has been used and the device needs to be re-opened later. */ - if (level >= GCRY_VERY_STRONG_RANDOM) + if (level >= GCRY_VERY_STRONG_RANDOM && !only_urandom) { if (fd_random == -1) { diff --git a/tests/keygen.c b/tests/keygen.c index 7cf48b6..6b6a60a 100644 --- a/tests/keygen.c +++ b/tests/keygen.c @@ -670,6 +670,7 @@ usage (int mode) " --verbose be verbose\n" " --debug flyswatter\n" " --fips run in FIPS mode\n" + " --no-quick To not use the quick RNG hack\n" " --progress print progress indicators\n", mode? stderr : stdout); if (mode) @@ -682,6 +683,7 @@ main (int argc, char **argv) int last_argc = -1; int opt_fips = 0; int with_progress = 0; + int no_quick = 0; if (argc) { argc--; argv++; } @@ -720,6 +722,11 @@ main (int argc, char **argv) argc--; argv++; with_progress = 1; } + else if (!strcmp (*argv, "--no-quick")) + { + argc--; argv++; + no_quick = 1; + } else if (!strncmp (*argv, "--", 2)) die ("unknown option '%s'", *argv); else @@ -740,7 +747,8 @@ main (int argc, char **argv) if (debug) xgcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); /* No valuable keys are create, so we can speed up our RNG. */ - xgcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); + if (!no_quick) + xgcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); if (with_progress) gcry_set_progress_handler (progress_cb, NULL); commit b05a4abc358b204dba343d9cfbd59fdc828c1686 Author: Werner Koch Date: Fri Jun 16 10:42:44 2017 +0200 Implement global config file /etc/gcrypt/random.conf * src/hwfeatures.c (my_isascii): Move macro to ... * src/g10lib.h: here. * tests/random.c (main): Dump random stats. * random/random.c (RANDOM_CONF_FILE): New. (_gcry_random_read_conf): New. (_gcry_random_dump_stats): Call rndjent stats. * random/rndjent.c (jent_rng_totalcalls, jent_rng_totalbytes): New. (_gcry_rndjent_poll): Take care of config option disable-jent. Wipe buffer. Bump counters. (_gcry_rndjent_dump_stats): New. Signed-off-by: Werner Koch diff --git a/doc/gcrypt.texi b/doc/gcrypt.texi index ae66dfc..3567582 100644 --- a/doc/gcrypt.texi +++ b/doc/gcrypt.texi @@ -5455,6 +5455,21 @@ are: This file can be used to disable the use of hardware based optimizations, @pxref{hardware features}. + + at item /etc/gcrypt/random.conf + at cindex /etc/gcrypt/random.conf +This file can be used to globally change parameters of the random +generator. The file is a simple text file where empty lines and +lines with the first non white-space character being '#' are +ignored. Supported options are + + at table @file + at item disable-jent + at cindex disable-jent +Disable the use of the jitter based entropy generator. + + at end table + @item /etc/gcrypt/fips_enabled @itemx /proc/sys/crypto/fips_enabled @cindex /etc/gcrypt/fips_enabled diff --git a/random/rand-internal.h b/random/rand-internal.h index 7a798e9..ec4550c 100644 --- a/random/rand-internal.h +++ b/random/rand-internal.h @@ -35,9 +35,11 @@ enum random_origins random request. */ }; +#define RANDOM_CONF_DISABLE_JENT 1 /*-- random.c --*/ +unsigned int _gcry_random_read_conf (void); void _gcry_random_progress (const char *what, int printchar, int current, int total); @@ -128,6 +130,7 @@ size_t _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), enum random_origins origin, size_t length); +void _gcry_rndjent_dump_stats (void); /*-- rndhw.c --*/ int _gcry_rndhw_failed_p (void); diff --git a/random/random.c b/random/random.c index ff9be16..4a2a61b 100644 --- a/random/random.c +++ b/random/random.c @@ -29,12 +29,19 @@ #include #include #include +#ifdef HAVE_SYSLOG +# include +#endif /*HAVE_SYSLOG*/ +#include #include "g10lib.h" #include "random.h" #include "rand-internal.h" #include "cipher.h" /* For _gcry_sha1_hash_buffer(). */ +/* The name of a file used to globally configure the RNG. */ +#define RANDOM_CONF_FILE "/etc/gcrypt/random.conf" + /* If not NULL a progress function called from certain places and the opaque value passed along. Registered by @@ -81,6 +88,71 @@ _gcry_random_progress (const char *what, int printchar, int current, int total) } +/* Read a file with configure options. The file is a simple text file + * where empty lines and lines with the first non white-space + * character being '#' are ignored. Supported configure options are: + * + * disable-jent - Disable the jitter based extra entropy generator. + * This sets the RANDOM_CONF_DISABLE_JENT bit. + * + * The function returns a bit vector with flags read from the file. + */ +unsigned int +_gcry_random_read_conf (void) +{ + const char *fname = RANDOM_CONF_FILE; + FILE *fp; + char buffer[256]; + char *p, *pend; + int lnr = 0; + unsigned int result = 0; + + fp = fopen (fname, "r"); + if (!fp) + return result; + + for (;;) + { + if (!fgets (buffer, sizeof buffer, fp)) + { + if (!feof (fp)) + { +#ifdef HAVE_SYSLOG + syslog (LOG_USER|LOG_WARNING, + "Libgcrypt warning: error reading '%s', line %d", + fname, lnr); +#endif /*HAVE_SYSLOG*/ + } + fclose (fp); + return result; + } + lnr++; + for (p=buffer; my_isascii (*p) && isspace (*p); p++) + ; + pend = strchr (p, '\n'); + if (pend) + *pend = 0; + pend = p + (*p? (strlen (p)-1):0); + for ( ;pend > p; pend--) + if (my_isascii (*pend) && isspace (*pend)) + *pend = 0; + if (!*p || *p == '#') + continue; + + if (!strcmp (p, "disable-jent")) + result |= RANDOM_CONF_DISABLE_JENT; + else + { +#ifdef HAVE_SYSLOG + syslog (LOG_USER|LOG_WARNING, + "Libgcrypt warning: unknown option in '%s', line %d", + fname, lnr); +#endif /*HAVE_SYSLOG*/ + } + } +} + + /* Set the preferred RNG type. This may be called at any time even before gcry_check_version. Thus we can't assume any thread system initialization. A type of 0 is used to indicate that any Libgcrypt @@ -202,6 +274,7 @@ _gcry_random_dump_stats (void) _gcry_rngdrbg_dump_stats (); else _gcry_rngcsprng_dump_stats (); + _gcry_rndjent_dump_stats (); } diff --git a/random/rndjent.c b/random/rndjent.c index fa3bb99..f997850 100644 --- a/random/rndjent.c +++ b/random/rndjent.c @@ -120,6 +120,11 @@ static int jent_rng_is_initialized; * NULL. Protected by JENT_RNG_LOCK. */ struct rand_data *jent_rng_collector; +/* The number of times the core entropy function has been called and + * the number of random bytes retrieved. */ +static unsigned long jent_rng_totalcalls; +static unsigned long jent_rng_totalbytes; + /* Acquire the jent_rng_lock. */ static void @@ -177,13 +182,16 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), jent_rng_is_initialized = 1; jent_entropy_collector_free (jent_rng_collector); jent_rng_collector = NULL; - if (!jent_entropy_init ()) - jent_rng_collector = jent_entropy_collector_alloc (1, 0); + if ( !(_gcry_random_read_conf () & RANDOM_CONF_DISABLE_JENT)) + { + if (!jent_entropy_init ()) + jent_rng_collector = jent_entropy_collector_alloc (1, 0); + } } if (jent_rng_collector) { - /* We have a working JENT. */ + /* We have a working JENT and it has not been disabled. */ char buffer[256]; while (length) @@ -191,13 +199,16 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), int rc; size_t n = length < sizeof(buffer)? length : sizeof (buffer); + jent_rng_totalcalls++; rc = jent_read_entropy (jent_rng_collector, buffer, n); if (rc < 0) break; (*add) (buffer, rc, origin); length -= rc; nbytes += rc; + jent_rng_totalbytes += rc; } + wipememory (buffer, sizeof buffer); } unlock_rng (); @@ -206,3 +217,23 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), return nbytes; } + + +/* Log statistical informantion about the use of this module. */ +void +_gcry_rndjent_dump_stats (void) +{ + /* In theory we would need to lock the stats here. However this + function is usually called during cleanup and then we _might_ run + into problems. */ + +#ifdef USE_JENT + if ((_gcry_get_hw_features () & HWF_INTEL_RDTSC)) + { + + log_info ("rndjent stat: collector=%p calls=%lu bytes=%lu\n", + jent_rng_collector, jent_rng_totalcalls, jent_rng_totalbytes); + + } +#endif /*USE_JENT*/ +} diff --git a/src/g10lib.h b/src/g10lib.h index 82562c7..ec8aab5 100644 --- a/src/g10lib.h +++ b/src/g10lib.h @@ -96,6 +96,9 @@ #define DIM(v) (sizeof(v)/sizeof((v)[0])) #define DIMof(type,member) DIM(((type *)0)->member) +#define my_isascii(c) (!((c) & 0x80)) + + /*-- src/global.c -*/ diff --git a/src/hwfeatures.c b/src/hwfeatures.c index 45d7680..1cad546 100644 --- a/src/hwfeatures.c +++ b/src/hwfeatures.c @@ -73,9 +73,6 @@ static unsigned int disabled_hw_features; available. */ static unsigned int hw_features; -/* Convenience macros. */ -#define my_isascii(c) (!((c) & 0x80)) - /* Disable a feature by name. This function must be called *before* diff --git a/tests/random.c b/tests/random.c index 37a52b8..8a85429 100644 --- a/tests/random.c +++ b/tests/random.c @@ -650,5 +650,8 @@ main (int argc, char **argv) if (!in_recursion) run_all_rng_tests (program); + if (debug) + xgcry_control (GCRYCTL_DUMP_RANDOM_STATS); + return 0; } ----------------------------------------------------------------------- Summary of changes: doc/gcrypt.texi | 34 ++++++++++++++++++++-- random/rand-internal.h | 4 +++ random/random.c | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++ random/rndjent.c | 37 ++++++++++++++++++++++-- random/rndlinux.c | 14 ++++++++- src/g10lib.h | 3 ++ src/hwfeatures.c | 3 -- tests/keygen.c | 10 ++++++- tests/random.c | 3 ++ 9 files changed, 175 insertions(+), 10 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Fri Jun 16 12:35:33 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Fri, 16 Jun 2017 12:35:33 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-101-gee3a74f Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via ee3a74f5539cbc5182ce089994e37c16ce612149 (commit) from 8f6082e95f30c1ba68d2de23da90146f87f0c66c (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit ee3a74f5539cbc5182ce089994e37c16ce612149 Author: Werner Koch Date: Fri Jun 16 12:31:11 2017 +0200 random: Allow building rndjent.c with stats collecting enabled. * random/rndjent.c: Change license to the one used by jitterentropy.h. (jent_init_statistic): New. (jent_bit_count): New. (jent_statistic_copy_stat): new. (jent_calc_statistic): New. -- New code taken from Stephan's jitterentropy-stat.c. This does now build with CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT defined; not sure whether this is already useful. Changed the license due to the new code. Signed-off-by: Werner Koch diff --git a/LICENSES b/LICENSES index 9c0267e..f6733a6 100644 --- a/LICENSES +++ b/LICENSES @@ -56,9 +56,9 @@ with any binary distributions derived from the GNU C Library. For files: - - random/jitterentropy-base-user.h - random/jitterentropy-base.c - random/jitterentropy.h + - random/rndjent.c (plus common Libgcrypt copyright holders) #+begin_quote * Copyright Stephan Mueller , 2013 diff --git a/random/rndjent.c b/random/rndjent.c index f997850..99318b4 100644 --- a/random/rndjent.c +++ b/random/rndjent.c @@ -1,21 +1,39 @@ /* rndjent.c - Driver for the jitterentropy module. * Copyright (C) 2017 g10 Code GmbH * Copyright (C) 2017 Bundesamt f?r Sicherheit in der Informationstechnik + * Copyright (C) 2013 Stephan Mueller * - * This file is part of Libgcrypt. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, and the entire permission notice in its entirety, + * including the disclaimer of warranties. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior + * written permission. * - * 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. + * ALTERNATIVELY, this product may be distributed under the terms of + * the GNU General Public License, in which case the provisions of the GPL are + * required INSTEAD OF the above restrictions. (This clause is + * necessary due to a potential bad interaction between the GPL and + * the restrictions contained in a BSD-style copyright.) * - * 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, see . + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF + * WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. */ #include @@ -126,6 +144,102 @@ static unsigned long jent_rng_totalcalls; static unsigned long jent_rng_totalbytes; + +/* JENT statistic helper code. */ +#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT + +static void +jent_init_statistic (struct rand_data *rand_data) +{ + int i; + struct entropy_stat *stat = &rand_data->entropy_stat; + + for (i = 0; i < 64; i++) + { + stat->bitslot[i] = 0; + stat->bitvar[i] = 0; + } + + jent_get_nstime (&stat->collection_begin); +} + +static void +jent_bit_count (struct rand_data *rand_data, u64 prev_data) +{ + int i; + + if (!rand_data->entropy_stat.enable_bit_test) + return; + + for (i = 0; i < 64; i++) + { + /* collect the count of set bits per bit position in the + * current ->data field */ + rand_data->entropy_stat.bitslot[i] += (rand_data->data & 1<data & 1<entropy_stat.bitvar[i] += 1; + } +} + + +static void +jent_statistic_copy_stat (struct entropy_stat *src, struct entropy_stat *dst) +{ + /* not copying bitslot and bitvar as they are not needed for + * statistic printout */ + dst->collection_begin = src->collection_begin; + dst->collection_end = src->collection_end; + dst->old_delta = src->old_delta; + dst->setbits = src->setbits; + dst->varbits = src->varbits; + dst->obsbits = src->obsbits; + dst->collection_loop_cnt= src->collection_loop_cnt; +} + + +/* + * Assessment of statistical behavior of the generated output and returning + * the information to the caller by filling the target value. + * + * Details about the bit statistics are given in chapter 4 of the doc. + * Chapter 5 documents the timer analysis and the resulting entropy. + */ +static void +jent_calc_statistic (struct rand_data *rand_data, + struct entropy_stat *target, unsigned int loop_cnt) +{ + int i; + struct entropy_stat *stat = &rand_data->entropy_stat; + + jent_get_nstime(&stat->collection_end); + + stat->collection_loop_cnt = loop_cnt; + + stat->setbits = 0; + stat->varbits = 0; + stat->obsbits = 0; + + for (i = 0; i < DATA_SIZE_BITS; i++) + { + stat->setbits += stat->bitslot[i]; + stat->varbits += stat->bitvar[i]; + + /* This is the sum of set bits in the current observation + * of the random data. */ + stat->obsbits += (rand_data->data & 1<old_delta = (stat->collection_end - stat->collection_begin); +} + +#endif /*CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT*/ + + /* Acquire the jent_rng_lock. */ static void lock_rng (void) ----------------------------------------------------------------------- Summary of changes: LICENSES | 2 +- random/rndjent.c | 138 ++++++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 127 insertions(+), 13 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Fri Jun 16 17:13:24 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Fri, 16 Jun 2017 17:13:24 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-103-g82bc052 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 82bc052eda5b3897724c7ad11e54f8203e8e88e9 (commit) via e6f90a392a1fd59b19b16f7a2bc7c439ae369d5f (commit) from ee3a74f5539cbc5182ce089994e37c16ce612149 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 82bc052eda5b3897724c7ad11e54f8203e8e88e9 Author: Werner Koch Date: Fri Jun 16 17:09:20 2017 +0200 random: Make rndjent.c NTG.1 compliant. * random/rndjent.c (_gcry_rndjent_poll): Hash the retrieved jitter. Signed-off-by: Werner Koch diff --git a/random/rndjent.c b/random/rndjent.c index 99318b4..86dc88e 100644 --- a/random/rndjent.c +++ b/random/rndjent.c @@ -306,7 +306,7 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), if (jent_rng_collector) { /* We have a working JENT and it has not been disabled. */ - char buffer[256]; + char buffer[32]; while (length) { @@ -317,10 +317,14 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), rc = jent_read_entropy (jent_rng_collector, buffer, n); if (rc < 0) break; - (*add) (buffer, rc, origin); - length -= rc; - nbytes += rc; - jent_rng_totalbytes += rc; + /* We need to hash the output to conform to the BSI + * NTG.1 specs. */ + _gcry_md_hash_buffer (GCRY_MD_SHA256, buffer, buffer, rc); + n = rc < 32? rc : 32; + (*add) (buffer, n, origin); + length -= n; + nbytes += n; + jent_rng_totalbytes += n; } wipememory (buffer, sizeof buffer); } commit e6f90a392a1fd59b19b16f7a2bc7c439ae369d5f Author: Werner Koch Date: Fri Jun 16 16:53:33 2017 +0200 md: Optimize gcry_md_hash_buffers for SHA-256 and SHA-512. * cipher/sha256.c (_gcry_sha256_hash_buffer): New. (_gcry_sha256_hash_buffers): New. * cipher/sha512.c (_gcry_sha512_hash_buffer): New. (_gcry_sha512_hash_buffers): New. * cipher/md.c (_gcry_md_hash_buffer): Optimize for SHA246 and SHA512. (_gcry_md_hash_buffers): Ditto. Signed-off-by: Werner Koch diff --git a/cipher/md.c b/cipher/md.c index 8df54fe..c1f585f 100644 --- a/cipher/md.c +++ b/cipher/md.c @@ -1028,10 +1028,24 @@ void _gcry_md_hash_buffer (int algo, void *digest, const void *buffer, size_t length) { - if (algo == GCRY_MD_SHA1) + if (0) + ; +#if USE_SHA256 + else if (algo == GCRY_MD_SHA256) + _gcry_sha256_hash_buffer (digest, buffer, length); +#endif +#if USE_SHA512 + else if (algo == GCRY_MD_SHA512) + _gcry_sha512_hash_buffer (digest, buffer, length); +#endif +#if USE_SHA1 + else if (algo == GCRY_MD_SHA1) _gcry_sha1_hash_buffer (digest, buffer, length); +#endif +#if USE_RMD160 else if (algo == GCRY_MD_RMD160 && !fips_mode () ) _gcry_rmd160_hash_buffer (digest, buffer, length); +#endif else { /* For the others we do not have a fast function, so we use the @@ -1091,12 +1105,24 @@ _gcry_md_hash_buffers (int algo, unsigned int flags, void *digest, if (hmac && iovcnt < 1) return GPG_ERR_INV_ARG; - if (algo == GCRY_MD_SHA1 && !hmac) + if (0) + ; +#if USE_SHA256 + else if (algo == GCRY_MD_SHA256 && !hmac) + _gcry_sha256_hash_buffers (digest, iov, iovcnt); +#endif +#if USE_SHA512 + else if (algo == GCRY_MD_SHA512 && !hmac) + _gcry_sha512_hash_buffers (digest, iov, iovcnt); +#endif +#if USE_SHA1 + else if (algo == GCRY_MD_SHA1 && !hmac) _gcry_sha1_hash_buffers (digest, iov, iovcnt); +#endif else { /* For the others we do not have a fast function, so we use the - normal functions. */ + normal functions. */ gcry_md_hd_t h; gpg_err_code_t rc; int dlen; diff --git a/cipher/sha256.c b/cipher/sha256.c index b450a12..d174321 100644 --- a/cipher/sha256.c +++ b/cipher/sha256.c @@ -509,6 +509,35 @@ sha256_read (void *context) } +/* Shortcut functions which puts the hash value of the supplied buffer + * into outbuf which must have a size of 32 bytes. */ +void +_gcry_sha256_hash_buffer (void *outbuf, const void *buffer, size_t length) +{ + SHA256_CONTEXT hd; + + sha256_init (&hd, 0); + _gcry_md_block_write (&hd, buffer, length); + sha256_final (&hd); + memcpy (outbuf, hd.bctx.buf, 32); +} + + +/* Variant of the above shortcut function using multiple buffers. */ +void +_gcry_sha256_hash_buffers (void *outbuf, const gcry_buffer_t *iov, int iovcnt) +{ + SHA256_CONTEXT hd; + + sha256_init (&hd, 0); + for (;iovcnt > 0; iov++, iovcnt--) + _gcry_md_block_write (&hd, + (const char*)iov[0].data + iov[0].off, iov[0].len); + sha256_final (&hd); + memcpy (outbuf, hd.bctx.buf, 32); +} + + /* Self-test section. diff --git a/cipher/sha512.c b/cipher/sha512.c index 5b25965..2ddc485 100644 --- a/cipher/sha512.c +++ b/cipher/sha512.c @@ -739,6 +739,35 @@ sha512_read (void *context) } +/* Shortcut functions which puts the hash value of the supplied buffer + * into outbuf which must have a size of 64 bytes. */ +void +_gcry_sha512_hash_buffer (void *outbuf, const void *buffer, size_t length) +{ + SHA512_CONTEXT hd; + + sha512_init (&hd, 0); + _gcry_md_block_write (&hd, buffer, length); + sha512_final (&hd); + memcpy (outbuf, hd.bctx.buf, 64); +} + + +/* Variant of the above shortcut function using multiple buffers. */ +void +_gcry_sha512_hash_buffers (void *outbuf, const gcry_buffer_t *iov, int iovcnt) +{ + SHA512_CONTEXT hd; + + sha512_init (&hd, 0); + for (;iovcnt > 0; iov++, iovcnt--) + _gcry_md_block_write (&hd, + (const char*)iov[0].data + iov[0].off, iov[0].len); + sha512_final (&hd); + memcpy (outbuf, hd.bctx.buf, 64); +} + + /* Self-test section. diff --git a/src/cipher.h b/src/cipher.h index 725cc73..f2acb55 100644 --- a/src/cipher.h +++ b/src/cipher.h @@ -120,6 +120,19 @@ void _gcry_sha1_hash_buffer (void *outbuf, const void *buffer, size_t length); void _gcry_sha1_hash_buffers (void *outbuf, const gcry_buffer_t *iov, int iovcnt); + +/*-- sha256.c --*/ +void _gcry_sha256_hash_buffer (void *outbuf, + const void *buffer, size_t length); +void _gcry_sha256_hash_buffers (void *outbuf, + const gcry_buffer_t *iov, int iovcnt); + +/*-- sha512.c --*/ +void _gcry_sha512_hash_buffer (void *outbuf, + const void *buffer, size_t length); +void _gcry_sha512_hash_buffers (void *outbuf, + const gcry_buffer_t *iov, int iovcnt); + /*-- blake2.c --*/ gcry_err_code_t _gcry_blake2_init_with_key(void *ctx, unsigned int flags, const unsigned char *key, ----------------------------------------------------------------------- Summary of changes: cipher/md.c | 32 +++++++++++++++++++++++++++++--- cipher/sha256.c | 29 +++++++++++++++++++++++++++++ cipher/sha512.c | 29 +++++++++++++++++++++++++++++ random/rndjent.c | 14 +++++++++----- src/cipher.h | 13 +++++++++++++ 5 files changed, 109 insertions(+), 8 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Sun Jun 18 10:21:25 2017 From: cvs at cvs.gnupg.org (by Jussi Kivilinna) Date: Sun, 18 Jun 2017 10:21:25 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-104-g32b4ab2 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 32b4ab209067f6f08b87b27bc78ec27dc497b708 (commit) from 82bc052eda5b3897724c7ad11e54f8203e8e88e9 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 32b4ab209067f6f08b87b27bc78ec27dc497b708 Author: Jussi Kivilinna Date: Sun Jun 18 10:35:50 2017 +0300 rijndael-padlock: change asm operands from read-only to read/write * cipher/rijndael-padlock.c (do_padlock): Change ESI/EDI/ECX to use read/write operands as XCRYPT instruction modifies these registers. -- Signed-off-by: Jussi Kivilinna diff --git a/cipher/rijndael-padlock.c b/cipher/rijndael-padlock.c index 476772a..234751b 100644 --- a/cipher/rijndael-padlock.c +++ b/cipher/rijndael-padlock.c @@ -43,6 +43,8 @@ do_padlock (const RIJNDAEL_context *ctx, unsigned char *bx, unsigned char a[16] __attribute__ ((aligned (16))); unsigned char b[16] __attribute__ ((aligned (16))); unsigned int cword[4] __attribute__ ((aligned (16))); + unsigned char *pa = a; + unsigned char *pb = b; int blocks; /* The control word fields are: @@ -63,19 +65,19 @@ do_padlock (const RIJNDAEL_context *ctx, unsigned char *bx, ("pushfq\n\t" /* Force key reload. */ "popfq\n\t" ".byte 0xf3, 0x0f, 0xa7, 0xc8\n\t" /* REP XCRYPT ECB. */ - : /* No output */ - : "S" (a), "D" (b), "d" (cword), "b" (ctx->padlockkey), "c" (blocks) + : "+S" (pa), "+D" (pb), "+c" (blocks) + : "d" (cword), "b" (ctx->padlockkey) : "cc", "memory" ); #else asm volatile ("pushfl\n\t" /* Force key reload. */ "popfl\n\t" - "xchg %3, %%ebx\n\t" /* Load key. */ + "xchg %4, %%ebx\n\t" /* Load key. */ ".byte 0xf3, 0x0f, 0xa7, 0xc8\n\t" /* REP XCRYPT ECB. */ - "xchg %3, %%ebx\n" /* Restore GOT register. */ - : /* No output */ - : "S" (a), "D" (b), "d" (cword), "r" (ctx->padlockkey), "c" (blocks) + "xchg %4, %%ebx\n" /* Restore GOT register. */ + : "+S" (pa), "+D" (pb), "+c" (blocks) + : "d" (cword), "r" (ctx->padlockkey) : "cc", "memory" ); #endif ----------------------------------------------------------------------- Summary of changes: cipher/rijndael-padlock.c | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From jussi.kivilinna at iki.fi Sun Jun 18 10:23:50 2017 From: jussi.kivilinna at iki.fi (Jussi Kivilinna) Date: Sun, 18 Jun 2017 11:23:50 +0300 Subject: [PATCH] Add script to run basic tests with all supported HWF combinations Message-ID: <149777423075.11382.13316874479543249672.stgit@localhost.localdomain> * tests/basic_all_hwfeature_combinations.sh: New. * tests/Makefile.am: Add basic_all_hwfeature_combinations.sh. -- Signed-off-by: Jussi Kivilinna --- 0 files changed diff --git a/tests/Makefile.am b/tests/Makefile.am index 1744ea79..eee24faa 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -60,7 +60,7 @@ EXTRA_DIST = README rsa-16k.key cavs_tests.sh cavs_driver.pl \ t-ed25519.inp stopwatch.h hashtest-256g.in \ sha3-224.h sha3-256.h sha3-384.h sha3-512.h \ blake2b.h blake2s.h \ - basic-disable-all-hwf.in + basic-disable-all-hwf.in basic_all_hwfeature_combinations.sh LDADD = $(standard_ldadd) $(GPG_ERROR_LIBS) t_lock_LDADD = $(standard_ldadd) $(GPG_ERROR_MT_LIBS) diff --git a/tests/basic_all_hwfeature_combinations.sh b/tests/basic_all_hwfeature_combinations.sh new file mode 100755 index 00000000..2ad99196 --- /dev/null +++ b/tests/basic_all_hwfeature_combinations.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# Run basic tests with all HW feature combinations +# Copyright 2017 Jussi Kivilinna +# +# This file is free software; as a special exception the author gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# This file is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# + +# Use BINEXT to set executable extension +# For example for Windows executables: BINEXT=.exe +if [ "x$BINEXT" != "x" ] && [ -e "tests/version$BINEXT" ]; then + binext="$BINEXT" +else + binext="" +fi + +# Use BINPRE to set executable prefix +# For example to run Windows executable with WINE: BINPRE="wine " +if [ "x$BINPRE" != "x" ]; then + binpre="$BINPRE" +else + binpre="" +fi + +# Use NJOBS to define number of parallel tasks +if [ "x$NJOBS" != "x" ]; then + njobs="$NJOBS" +else + # default to cpu count + ncpus=$(nproc --all) + if [ "x at cpus" != "x" ]; then + njobs=$ncpus + else + # could not get cpu count, use 4 parallel tasks instead + njobs=4 + fi +fi + +get_supported_hwfeatures() { + $binpre "tests/version$binext" 2>&1 | \ + grep "hwflist" | \ + sed -e 's/hwflist://' -e 's/:/ /g' -e 's/\x0d/\x0a/g' +} + +hwfs=($(get_supported_hwfeatures)) +echo "Total HW-feature combinations: $((1<<${#hwfs[@]}))" +for ((cbits=0; cbits < (1<<${#hwfs[@]}); cbits++)); do + for ((mask=0; mask < ${#hwfs[@]}; mask++)); do + match=$(((1< please CC me on replies as I am not subscribed to the ML -------------- next part -------------- A non-text attachment was scrubbed... Name: reproducible.patch Type: text/x-patch Size: 846 bytes Desc: not available URL: From cvs at cvs.gnupg.org Wed Jun 21 09:47:41 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Wed, 21 Jun 2017 09:47:41 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-106-g27148e6 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 27148e60ba15b0cb73b47a75c688fcb48a1a3444 (commit) via c2319464b03e61aaf34ef6d5f4b59b0c0483a373 (commit) from 32b4ab209067f6f08b87b27bc78ec27dc497b708 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 27148e60ba15b0cb73b47a75c688fcb48a1a3444 Author: Werner Koch Date: Wed Jun 21 09:29:09 2017 +0200 api: New function gcry_get_config. * src/misc.c (_gcry_log_info_with_dummy_fp): Remove. * src/global.c (print_config): New arg WHAT. Remove arg FNC and use gpgrt_fprintf directly. (_gcry_get_config): New. (_gcry_vcontrol) : Use _gcry_get_config instead of print_config. * src/gcrypt.h.in (gcry_get_config): New. * src/libgcrypt.def, src/libgcrypt.vers: Add new function. * src/visibility.c (gcry_get_config): New. * src/visibility.h: Mark new function. * tests/version.c (test_get_config): New. (main): Call new test. Signed-off-by: Werner Koch diff --git a/NEWS b/NEWS index d7e9bd9..c97f425 100644 --- a/NEWS +++ b/NEWS @@ -67,6 +67,7 @@ Noteworthy changes in version 1.8.0 (unreleased) [C21/A1/R_] * Interface changes relative to the 1.7.0 release: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GCRYCTL_REINIT_SYSCALL_CLAMP NEW macro. + gcry_get_config NEW function. gcry_md_info DEPRECATED. diff --git a/doc/gcrypt.texi b/doc/gcrypt.texi index 26dd6c3..cab1318 100644 --- a/doc/gcrypt.texi +++ b/doc/gcrypt.texi @@ -824,7 +824,8 @@ proper random device. This command dumps information pertaining to the configuration of the library to the given stream. If NULL is given for @var{stream}, the log system is used. This command may be used before the initialization has -been finished but not before a @code{gcry_check_version}. +been finished but not before a @code{gcry_check_version}. Note that +the macro @code{estream_t} can be used instead of @code{gpgrt_stream_t}. @item GCRYCTL_OPERATIONAL_P; Arguments: none This command returns true if the library is in an operational state. @@ -5233,6 +5234,7 @@ wrong. * Memory allocation:: Functions related with memory allocation. * Context management:: Functions related with context management. * Buffer description:: A data type to describe buffers. +* Config reporting:: How to return Libgcrypt's configuration. @end menu @@ -5317,6 +5319,27 @@ of this structure are: @end table @end deftp + at node Config reporting + at section How to return Libgcrypt's configuration. + +Although @code{GCRYCTL_PRINT_CONFIG} can be used to print +configuration options, it is sometimes necessary to check them in a +program. This can be accomplished by using this function: + + at deftypefun {char *} gcry_get_config @ + (@w{int @var{mode}}, @ + @w{const char *@var{what}}) + +This function returns a malloced string with colon delimited configure +options. With a value of 0 for @var{mode} this string resembles the +output of @code{GCRYCTL_PRINT_CONFIG}. However, if @var{what} is not +NULL, only the line where the first field (e.g. "cpu-arch") matches + at var{what} is returned. + +Other values than 0 for @var{mode} are not defined. The caller shall +free the string using @code{gcry_free}. On error NULL is returned and +ERRNO is set; if a value for WHAT is unknow ERRNO will be set to 0. + at end deftypefun @c ********************************************************** diff --git a/src/g10lib.h b/src/g10lib.h index ec8aab5..961b515 100644 --- a/src/g10lib.h +++ b/src/g10lib.h @@ -109,6 +109,8 @@ void _gcry_pre_syscall (void); void _gcry_post_syscall (void); int _gcry_get_debug_flag (unsigned int mask); +char *_gcry_get_config (int mode, const char *what); + /* Malloc functions and common wrapper macros. */ void *_gcry_malloc (size_t n) _GCRY_GCC_ATTR_MALLOC; void *_gcry_calloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC; @@ -163,8 +165,6 @@ 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); -int _gcry_log_info_with_dummy_fp (FILE *fp, const char *fmt, ... ) - JNLIB_GCC_A_PRINTF(2,3); 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_log_printhex (const char *text, const void *buffer, size_t length); @@ -174,6 +174,7 @@ void _gcry_log_printsxp (const char *text, gcry_sexp_t sexp); 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__ ) #define gcry_assert(expr) (LIKELY(expr)? (void)0 \ diff --git a/src/gcrypt.h.in b/src/gcrypt.h.in index 210ea2f..8d20c83 100644 --- a/src/gcrypt.h.in +++ b/src/gcrypt.h.in @@ -1691,6 +1691,7 @@ void gcry_log_debugpnt (const char *text, gcry_mpi_point_t point, gcry_ctx_t ctx); void gcry_log_debugsxp (const char *text, gcry_sexp_t sexp); +char *gcry_get_config (int mode, const char *what); /* Log levels used by the internal logging facility. */ enum gcry_log_levels diff --git a/src/global.c b/src/global.c index 0796a94..4e2e274 100644 --- a/src/global.c +++ b/src/global.c @@ -2,7 +2,7 @@ * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 * 2004, 2005, 2006, 2008, 2011, * 2012 Free Software Foundation, Inc. - * Copyright (C) 2013, 2014 g10 Code GmbH + * Copyright (C) 2013, 2014, 2017 g10 Code GmbH * * This file is part of Libgcrypt. * @@ -273,91 +273,181 @@ _gcry_check_version (const char *req_version) static void -print_config ( int (*fnc)(FILE *fp, const char *format, ...), FILE *fp) +print_config (const char *what, gpgrt_stream_t fp) { - unsigned int hwfeatures, afeature; int i; const char *s; - fnc (fp, "version:%s:%x:%s:%x:\n", - VERSION, GCRYPT_VERSION_NUMBER, - GPGRT_VERSION, GPGRT_VERSION_NUMBER); - fnc (fp, "cc:%d:%s:\n", + if (!what || !strcmp (what, "version")) + { + gpgrt_fprintf (fp, "version:%s:%x:%s:%x:\n", + VERSION, GCRYPT_VERSION_NUMBER, + GPGRT_VERSION, GPGRT_VERSION_NUMBER); + } + if (!what || !strcmp (what, "cc")) + { + gpgrt_fprintf (fp, "cc:%d:%s:\n", #if GPGRT_VERSION_NUMBER >= 0x011b00 /* 1.27 */ - GPGRT_GCC_VERSION + GPGRT_GCC_VERSION #else - _GPG_ERR_GCC_VERSION /* Due to a bug in gpg-error.h. */ + _GPG_ERR_GCC_VERSION /* Due to a bug in gpg-error.h. */ #endif - , + , #ifdef __clang__ - "clang:" __VERSION__ + "clang:" __VERSION__ #elif __GNUC__ - "gcc:" __VERSION__ + "gcc:" __VERSION__ #else - ":" + ":" #endif - ); + ); + } - fnc (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS); - fnc (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS); - fnc (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS); - fnc (fp, "rnd-mod:" + if (!what || !strcmp (what, "ciphers")) + gpgrt_fprintf (fp, "ciphers:%s:\n", LIBGCRYPT_CIPHERS); + if (!what || !strcmp (what, "pubkeys")) + gpgrt_fprintf (fp, "pubkeys:%s:\n", LIBGCRYPT_PUBKEY_CIPHERS); + if (!what || !strcmp (what, "digests")) + gpgrt_fprintf (fp, "digests:%s:\n", LIBGCRYPT_DIGESTS); + + if (!what || !strcmp (what, "rnd-mod")) + { + gpgrt_fprintf (fp, "rnd-mod:" #if USE_RNDEGD - "egd:" + "egd:" #endif #if USE_RNDLINUX - "linux:" + "linux:" #endif #if USE_RNDUNIX - "unix:" + "unix:" #endif #if USE_RNDW32 - "w32:" + "w32:" #endif - "\n"); - fnc (fp, "cpu-arch:" + "\n"); + } + + if (!what || !strcmp (what, "cpu-arch")) + { + gpgrt_fprintf (fp, "cpu-arch:" #if defined(HAVE_CPU_ARCH_X86) - "x86" + "x86" #elif defined(HAVE_CPU_ARCH_ALPHA) - "alpha" + "alpha" #elif defined(HAVE_CPU_ARCH_SPARC) - "sparc" + "sparc" #elif defined(HAVE_CPU_ARCH_MIPS) - "mips" + "mips" #elif defined(HAVE_CPU_ARCH_M68K) - "m68k" + "m68k" #elif defined(HAVE_CPU_ARCH_PPC) - "ppc" + "ppc" #elif defined(HAVE_CPU_ARCH_ARM) - "arm" + "arm" #endif - ":\n"); - fnc (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ()); - hwfeatures = _gcry_get_hw_features (); - fnc (fp, "hwflist:"); - for (i=0; (s = _gcry_enum_hw_features (i, &afeature)); i++) - if ((hwfeatures & afeature)) - fnc (fp, "%s:", s); - fnc (fp, "\n"); - /* We use y/n instead of 1/0 for the simple reason that Emacsen's - compile error parser would accidentally flag that line when printed - during "make check" as an error. */ - fnc (fp, "fips-mode:%c:%c:\n", - fips_mode ()? 'y':'n', - _gcry_enforced_fips_mode ()? 'y':'n' ); - /* The currently used RNG type. */ - { - i = _gcry_get_rng_type (0); - switch (i) - { - case GCRY_RNG_TYPE_STANDARD: s = "standard"; break; - case GCRY_RNG_TYPE_FIPS: s = "fips"; break; - case GCRY_RNG_TYPE_SYSTEM: s = "system"; break; - default: BUG (); - } - fnc (fp, "rng-type:%s:%d:\n", s, i); - } + ":\n"); + } + + if (!what || !strcmp (what, "mpi-asm")) + gpgrt_fprintf (fp, "mpi-asm:%s:\n", _gcry_mpi_get_hw_config ()); + + if (!what || !strcmp (what, "hwflist")) + { + unsigned int hwfeatures, afeature; + + hwfeatures = _gcry_get_hw_features (); + gpgrt_fprintf (fp, "hwflist:"); + for (i=0; (s = _gcry_enum_hw_features (i, &afeature)); i++) + if ((hwfeatures & afeature)) + gpgrt_fprintf (fp, "%s:", s); + gpgrt_fprintf (fp, "\n"); + } + + if (!what || !strcmp (what, "fips-mode")) + { + /* We use y/n instead of 1/0 for the stupid reason that + * Emacsen's compile error parser would accidentally flag that + * line when printed during "make check" as an error. */ + gpgrt_fprintf (fp, "fips-mode:%c:%c:\n", + fips_mode ()? 'y':'n', + _gcry_enforced_fips_mode ()? 'y':'n' ); + } + + if (!what || !strcmp (what, "rng-type")) + { + /* The currently used RNG type. */ + unsigned int jver; + int active; + + i = _gcry_get_rng_type (0); + switch (i) + { + case GCRY_RNG_TYPE_STANDARD: s = "standard"; break; + case GCRY_RNG_TYPE_FIPS: s = "fips"; break; + case GCRY_RNG_TYPE_SYSTEM: s = "system"; break; + default: BUG (); + } + jver = _gcry_rndjent_get_version (&active); + gpgrt_fprintf (fp, "rng-type:%s:%d:%u:%d:\n", s, i, jver, active); + } +} + + +/* With a MODE of 0 return a malloced string with configured features. + * In that case a WHAT of NULL returns everything in the same way + * GCRYCTL_PRINT_CONFIG would do. With a specific WHAT string only + * the requested feature is returned (w/o the trailing LF. On error + * NULL is returned. */ +char * +_gcry_get_config (int mode, const char *what) +{ + gpgrt_stream_t fp; + int save_errno; + void *data; + char *p; + + if (mode) + { + gpg_err_set_errno (EINVAL); + return NULL; + } + + fp = gpgrt_fopenmem (0, "w+b,samethread"); + if (!fp) + return NULL; + + print_config (what, fp); + if (gpgrt_ferror (fp)) + { + save_errno = errno; + gpgrt_fclose (fp); + gpg_err_set_errno (save_errno); + return NULL; + } + + gpgrt_rewind (fp); + if (gpgrt_fclose_snatch (fp, &data, NULL)) + { + save_errno = errno; + gpgrt_fclose (fp); + gpg_err_set_errno (save_errno); + return NULL; + } + + if (!data) + { + /* Nothing was printed (unknown value for WHAT). This is okay, + * so clear ERRNO to indicate this. */ + gpg_err_set_errno (0); + return NULL; + } + + /* Strip trailing LF. */ + if (what && (p = strchr (data, '\n'))) + *p = 0; + return data; } @@ -549,12 +639,21 @@ _gcry_vcontrol (enum gcry_ctl_cmds cmd, va_list arg_ptr) /* This command dumps information pertaining to the configuration of libgcrypt to the given stream. It may be used before the initialization has been finished but not - before a gcry_version_check. */ + before a gcry_version_check. See also gcry_get_config. */ case GCRYCTL_PRINT_CONFIG: { FILE *fp = va_arg (arg_ptr, FILE *); + char *tmpstr; _gcry_set_preferred_rng_type (0); - print_config (fp?fprintf:_gcry_log_info_with_dummy_fp, fp); + tmpstr = _gcry_get_config (0, NULL); + if (tmpstr) + { + if (fp) + fputs (tmpstr, fp); + else + log_info ("%s", tmpstr); + xfree (tmpstr); + } } break; diff --git a/src/libgcrypt.def b/src/libgcrypt.def index 067cb84..c4a9eac 100644 --- a/src/libgcrypt.def +++ b/src/libgcrypt.def @@ -282,4 +282,6 @@ EXPORTS gcry_mpi_ec_decode_point @246 + gcry_get_config @247 + ;; end of file with public symbols for Windows. diff --git a/src/libgcrypt.vers b/src/libgcrypt.vers index 785b8ed..1d2d150 100644 --- a/src/libgcrypt.vers +++ b/src/libgcrypt.vers @@ -111,6 +111,8 @@ GCRYPT_1.6 { gcry_log_debug; gcry_log_debughex; gcry_log_debugmpi; gcry_log_debugpnt; gcry_log_debugsxp; + gcry_get_config; + _gcry_mpi_get_const; gcry_ctx_release; diff --git a/src/misc.c b/src/misc.c index 9d8b7bd..002a84f 100644 --- a/src/misc.c +++ b/src/misc.c @@ -198,18 +198,6 @@ _gcry_log_info( const char *fmt, ... ) va_end(arg_ptr); } -int -_gcry_log_info_with_dummy_fp (FILE *fp, const char *fmt, ... ) -{ - va_list arg_ptr; - - (void)fp; - va_start( arg_ptr, fmt ) ; - _gcry_logv( GCRY_LOG_INFO, fmt, arg_ptr ); - va_end(arg_ptr); - return 0; -} - void _gcry_log_error( const char *fmt, ... ) { diff --git a/src/visibility.c b/src/visibility.c index 3abbd37..7bf3d57 100644 --- a/src/visibility.c +++ b/src/visibility.c @@ -1435,6 +1435,12 @@ gcry_log_debugsxp (const char *text, gcry_sexp_t sexp) _gcry_log_printsxp (text, sexp); } +char * +gcry_get_config (int mode, const char *what) +{ + return _gcry_get_config (mode, what); +} + void gcry_set_progress_handler (gcry_handler_progress_t cb, void *cb_data) { diff --git a/src/visibility.h b/src/visibility.h index 7ecd75e..d28993a 100644 --- a/src/visibility.h +++ b/src/visibility.h @@ -279,6 +279,8 @@ MARK_VISIBLEX (gcry_log_debugmpi) MARK_VISIBLEX (gcry_log_debugpnt) MARK_VISIBLEX (gcry_log_debugsxp) +MARK_VISIBLEX (gcry_get_config) + /* Functions used to implement macros. */ MARK_VISIBLEX (_gcry_mpi_get_const) diff --git a/tests/version.c b/tests/version.c index baf984e..6a01610 100644 --- a/tests/version.c +++ b/tests/version.c @@ -32,12 +32,58 @@ #include #include #include +#include #include "../src/gcrypt-int.h" #define PGM "version" #include "t-common.h" +static void +test_get_config (void) +{ + char *string; + + string = gcry_get_config (0, NULL); + if (!string) + fail ("gcry_get_config does not return anything: %s\n", + gpg_strerror (gpg_error_from_syserror ())); + else if ( !strchr (string, '\n') ) + fail ("gcry_get_config(0, NULL) did not return multiple lines\n"); + + xfree (string); + string = gcry_get_config (0, "version"); + if (!string) + fail ("gcry_get_config(\"version\") returned NULL: %s\n", + gpg_strerror (gpg_error_from_syserror ())); + else if ( strchr (string, '\n') ) + fail ("gcry_get_config(\"version\") returned more than one line\n"); + else if ( strncmp (string, "version:", 8) ) + fail ("gcry_get_config(\"version\") returned wrong line\n"); + + /* Test an item which is not the first. */ + xfree (string); + string = gcry_get_config (0, "cpu-arch"); + if (!string) + fail ("gcry_get_config(\"cpu-arch\") returned NULL: %s\n", + gpg_strerror (gpg_error_from_syserror ())); + else if ( strchr (string, '\n') ) + fail ("gcry_get_config(\"cpu-arch\") returned more than one line\n"); + else if ( strncmp (string, "cpu-arch:", 9) ) + fail ("gcry_get_config(\"cpu-arch\") returned wrong line\n"); + + /* Test that an unknown item return sthe correct error. */ + xfree (string); + string = gcry_get_config (0, "no-such-item"); + if (string) + fail ("gcry_get_config(\"no-such-item\") returned something\n"); + else if (errno) + fail ("gcry_get_config(\"no-such-item\") returned wrong error: %s\n", + gpg_strerror (gpg_error_from_syserror ())); + + xfree (string); +} + int main (int argc, char **argv) @@ -96,5 +142,8 @@ main (int argc, char **argv) xgcry_control (GCRYCTL_PRINT_CONFIG, NULL); + test_get_config (); + + return 0; } commit c2319464b03e61aaf34ef6d5f4b59b0c0483a373 Author: Werner Koch Date: Wed Jun 21 09:24:42 2017 +0200 random: Allow building rndjent on non-x86. * random/jitterentropy-base.c (jent_version): Uncomment function. * random/rndjent.c: Include time.h (JENT_USES_RDTSC): New. (JENT_USES_GETTIME): New. (JENT_USES_READ_REAL_TIME): New. (jent_get_nstime): Support clock_gettime and AIX specific function. Taken from Stephan M?ller's code. (is_rng_available): New. (_gcry_rndjent_dump_stats): Use that function. (_gcry_rndjent_poll): Use that fucntion. Allow an ADD of NULL for an intialize only mode. (_gcry_rndjent_get_version): New. Signed-off-by: Werner Koch diff --git a/random/jitterentropy-base.c b/random/jitterentropy-base.c index e80ca6e..2701e90 100644 --- a/random/jitterentropy-base.c +++ b/random/jitterentropy-base.c @@ -81,8 +81,7 @@ * * Return: Version number of kcapi library */ -#if 0 -unsigned int jent_version(void) +static unsigned int jent_version(void) { unsigned int version = 0; @@ -92,7 +91,6 @@ unsigned int jent_version(void) return version; } -#endif /** * Update of the loop count used for the next round of diff --git a/random/random.h b/random/random.h index 30e6fdf..af99346 100644 --- a/random/random.h +++ b/random/random.h @@ -65,6 +65,10 @@ gpg_err_code_t _gcry_rngdrbg_healthcheck_one (struct gcry_drbg_test_vector *t); /*-- rndegd.c --*/ gpg_error_t _gcry_rndegd_set_socket_name (const char *name); +/*-- rndjent.c --*/ +unsigned int _gcry_rndjent_get_version (int *r_active); + + /*-- random-daemon.c (only used from random.c) --*/ #ifdef USE_RANDOM_DAEMON void _gcry_daemon_initialize_basics (void); diff --git a/random/rndjent.c b/random/rndjent.c index 86dc88e..dd7ad04 100644 --- a/random/rndjent.c +++ b/random/rndjent.c @@ -39,6 +39,7 @@ #include #include #include +#include #ifdef HAVE_STDINT_H # include #endif @@ -52,9 +53,18 @@ * Decide whether we can support jent at compile time. */ #undef USE_JENT +#define JENT_USES_RDTSC 1 +#define JENT_USES_GETTIME 2 +#define JENT_USES_READ_REAL_TIME 3 #ifdef ENABLE_JENT_SUPPORT # if defined (__i386__) || defined(__x86_64__) -# define USE_JENT 1 +# define USE_JENT JENT_USES_RDTSC +# elif defined (HAVE_CLOCK_GETTIME) +# if _AIX +# define USE_JENT JENT_USES_READ_REAL_TIME +# else +# define USE_JENT JENT_USES_GETTIME +# endif # endif #endif /*ENABLE_JENT_SUPPORT*/ @@ -78,12 +88,50 @@ static void jent_get_nstime(u64 *out) { +#if USE_JENT == JENT_USES_RDTSC + u32 t_eax, t_edx; asm volatile (".byte 0x0f,0x31\n\t" : "=a" (t_eax), "=d" (t_edx) ); *out = (((u64)t_edx << 32) | t_eax); + +#elif USE_JENT == JENT_USES_GETTIME + + struct timespec tv; + u64 tmp; + + /* On Linux we could use CLOCK_MONOTONIC(_RAW), but with + * CLOCK_REALTIME we get some nice extra entropy once in a while + * from the NTP actions that we want to use as well... though, we do + * not rely on that extra little entropy. */ + if (!clock_gettime (CLOCK_REALTIME, &tv)) + { + tmp = time.tv_sec; + tmp = tmp << 32; + tmp = tmp | time.tv_nsec; + } + else + tmp = 0; + *out = tmp; + +#elif USE_JENT == JENT_USES_READ_REAL_TIME + + /* clock_gettime() on AIX returns a timer value that increments in + * steps of 1000. */ + u64 tmp = 0; + + timebasestruct_t aixtime; + read_real_time (&aixtime, TIMEBASE_SZ); + tmp = aixtime.tb_high; + tmp = tmp << 32; + tmp = tmp | aixtime.tb_low; + *out = tmp; + +#else +# error No clock available in jent_get_nstime +#endif } @@ -267,6 +315,23 @@ unlock_rng (void) gpg_strerror (rc)); } + +/* Return true if the JENT RNG code can be run. It may not yet been + * initialized, though. */ +static int +is_rng_available (void) +{ +#if USE_JENT == JENT_USES_RDTSC + return !!(_gcry_get_hw_features () & HWF_INTEL_RDTSC); +#elif USE_JENT == JENT_USES_GETTIME + return 2; +#elif USE_JENT == JENT_USES_READ_REAL_TIME + return 3; +#else /* Ooops */ + return 0; +#endif +} + #endif /* USE_JENT */ @@ -282,11 +347,8 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), { size_t nbytes = 0; - (void)add; - (void)origin; - #ifdef USE_JENT - if ((_gcry_get_hw_features () & HWF_INTEL_RDTSC)) + if ( is_rng_available () ) { lock_rng (); @@ -303,7 +365,7 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), } } - if (jent_rng_collector) + if (jent_rng_collector && add) { /* We have a working JENT and it has not been disabled. */ char buffer[32]; @@ -331,12 +393,46 @@ _gcry_rndjent_poll (void (*add)(const void*, size_t, enum random_origins), unlock_rng (); } + +#else + + (void)add; + (void)origin; + #endif return nbytes; } +/* Return the version number of the JENT RNG. If the RNG is not + * initialized or usable 0 is returned. If R_ACTIVE is not NULL the + * jitter RNG will be initialized and true is stored at R_ACTIVE if + * the initialization succeeded. */ +unsigned int +_gcry_rndjent_get_version (int *r_active) +{ +#ifdef USE_JENT + if ( is_rng_available () ) + { + if (r_active) + { + /* Make sure the RNG is initialized. */ + _gcry_rndjent_poll (NULL, 0, 0); + /* To ease debugging we store 2 for a clock_gettime based + * implementation and 1 for a rdtsc based code. */ + *r_active = jent_rng_collector? is_rng_available () : 0; + } + return jent_version (); + } + else + return 0; +#else + return 0; +#endif +} + + /* Log statistical informantion about the use of this module. */ void _gcry_rndjent_dump_stats (void) @@ -346,9 +442,8 @@ _gcry_rndjent_dump_stats (void) into problems. */ #ifdef USE_JENT - if ((_gcry_get_hw_features () & HWF_INTEL_RDTSC)) + if ( is_rng_available () ) { - log_info ("rndjent stat: collector=%p calls=%lu bytes=%lu\n", jent_rng_collector, jent_rng_totalcalls, jent_rng_totalbytes); ----------------------------------------------------------------------- Summary of changes: NEWS | 1 + doc/gcrypt.texi | 25 ++++- random/jitterentropy-base.c | 4 +- random/random.h | 4 + random/rndjent.c | 111 ++++++++++++++++++++-- src/g10lib.h | 5 +- src/gcrypt.h.in | 1 + src/global.c | 217 ++++++++++++++++++++++++++++++++------------ src/libgcrypt.def | 2 + src/libgcrypt.vers | 2 + src/misc.c | 12 --- src/visibility.c | 6 ++ src/visibility.h | 2 + tests/version.c | 49 ++++++++++ 14 files changed, 356 insertions(+), 85 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Fri Jun 23 09:39:08 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Fri, 23 Jun 2017 09:39:08 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-108-gd091610 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via d091610377b2c92cf385282b1adfc30fa6cd5c75 (commit) from 8dfae89ecd3e9ae0967586cb38d12ef9111fc7cd (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit d091610377b2c92cf385282b1adfc30fa6cd5c75 Author: Werner Koch Date: Fri Jun 23 09:34:35 2017 +0200 random: Add missing dependency. * random/Makefile.am (EXTRA_librandom_la_SOURCES): Fix file name. (rndjent.o, rndjent.lo): Depend on jitterentropy-base-user.h. -- Fixes-commit: 8dfae89ecd3e9ae0967586cb38d12ef9111fc7cd Signed-off-by: Werner Koch diff --git a/random/Makefile.am b/random/Makefile.am index a3c5dd5..7698a72 100644 --- a/random/Makefile.am +++ b/random/Makefile.am @@ -50,7 +50,7 @@ rndegd.c \ rndunix.c \ rndw32.c \ rndw32ce.c \ -jitterentropy-base.c jitterentropy.h jitterentropy-base-user.c +jitterentropy-base.c jitterentropy.h jitterentropy-base-user.h # The rndjent module needs to be compiled without optimization. */ @@ -60,10 +60,10 @@ else o_flag_munging = cat endif -rndjent.o: $(srcdir)/rndjent.c \ +rndjent.o: $(srcdir)/rndjent.c jitterentropy-base-user.h \ $(srcdir)/jitterentropy-base.c $(srcdir)/jitterentropy.h `echo $(COMPILE) -c $(srcdir)/rndjent.c | $(o_flag_munging) ` -rndjent.lo: $(srcdir)/rndjent.c \ +rndjent.lo: $(srcdir)/rndjent.c jitterentropy-base-user.h \ $(srcdir)/jitterentropy-base.c $(srcdir)/jitterentropy.h `echo $(LTCOMPILE) -c $(srcdir)/rndjent.c | $(o_flag_munging) ` ----------------------------------------------------------------------- Summary of changes: random/Makefile.am | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From wk at gnupg.org Fri Jun 23 10:00:04 2017 From: wk at gnupg.org (Werner Koch) Date: Fri, 23 Jun 2017 10:00:04 +0200 Subject: [PATCH] Add script to run basic tests with all supported HWF combinations In-Reply-To: <149777423075.11382.13316874479543249672.stgit@localhost.localdomain> (Jussi Kivilinna's message of "Sun, 18 Jun 2017 11:23:50 +0300") References: <149777423075.11382.13316874479543249672.stgit@localhost.localdomain> Message-ID: <87podv9lrv.fsf@wheatstone.g10code.de> Hi! I indeed think that this test is very useful. On Sun, 18 Jun 2017 10:23, jussi.kivilinna at iki.fi said: > +++ b/tests/basic_all_hwfeature_combinations.sh > @@ -0,0 +1,73 @@ > +#!/bin/bash Unfortunately we can't depend on bash. There are enough systems w/o bash installed. > +# For example for Windows executables: BINEXT=.exe > +if [ "x$BINEXT" != "x" ] && [ -e "tests/version$BINEXT" ]; then > + binext="$BINEXT" > +else > + binext="" Hmmm, running the script on Windows would require the installation of a Unix shell. That is too troublesome. With the new gcry_get_config fucntion we can get the features form a C program and the we would only need to fork/exec - oh well, not on Windows :-(. tests/random also forks but skips these checks on Windows. Which it should not. To avoid cluttering all code with a platform dependent implemtation of a spawing function I would suggest to wait until we have put such a function into libgpgrt (aka libgpg-error). We plan this because we several such spawning implementations in the GnuPG stack and libgpgrt is a common dependency of all. If you want to push your change, I would suggest to do it as maintainer-only tool _for now_ so that it is not run by "make check". Salam-Shalom, Werner -- Die Gedanken sind frei. Ausnahmen regelt ein Bundesgesetz. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 227 bytes Desc: not available URL: From cvs at cvs.gnupg.org Fri Jun 23 09:16:15 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Fri, 23 Jun 2017 09:16:15 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-107-g8dfae89 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 8dfae89ecd3e9ae0967586cb38d12ef9111fc7cd (commit) from 27148e60ba15b0cb73b47a75c688fcb48a1a3444 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 8dfae89ecd3e9ae0967586cb38d12ef9111fc7cd Author: Werner Koch Date: Fri Jun 23 09:11:47 2017 +0200 random: Update jitterentropy to 2.1.0. * random/rndjent.c (jent_get_nstime, jent_zfree) (jent_fips_enabled, jent_zalloc): Move functions and macros to ... * random/jitterentropy-base-user.h: this file. That files was not used before. * random/Makefile.am (EXTRA_librandom_la_SOURCES): Add jitterentropy-base-user. * random/jitterentropy-base.c: Update to version 2.1.0. * random/jitterentropy.h: Ditto. -- The files jitterentropy-base.c and jitterentropy.h are are now verbatim copies of the upstream source using a private copy received prior to a push to the upstream repo. Though, 3 white spaces issues were fixed. Signed-off-by: Werner Koch diff --git a/random/Makefile.am b/random/Makefile.am index aaf205e..a3c5dd5 100644 --- a/random/Makefile.am +++ b/random/Makefile.am @@ -50,7 +50,7 @@ rndegd.c \ rndunix.c \ rndw32.c \ rndw32ce.c \ -jitterentropy-base.c jitterentropy.h +jitterentropy-base.c jitterentropy.h jitterentropy-base-user.c # The rndjent module needs to be compiled without optimization. */ diff --git a/random/jitterentropy-base-user.h b/random/jitterentropy-base-user.h index 2aecf3b..75dd768 100644 --- a/random/jitterentropy-base-user.h +++ b/random/jitterentropy-base-user.h @@ -39,65 +39,96 @@ * DAMAGE. */ -#ifndef _JITTERENTROPY_BASE_X86_H -#define _JITTERENTROPY_BASE_X86_H +#ifndef GCRYPT_JITTERENTROPY_BASE_USER_H +#define GCRYPT_JITTERENTROPY_BASE_USER_H -#include -#include -#include +/* + * This is Libgcrypt specific platform dependent code. We use a + * separate file because jitterentropy.h expects such a file. + */ -#include -#include "g10lib.h" +#ifndef USE_JENT +# error This file expects to be included from rndjent.c (via jitterentropy.h) +#endif +#ifndef HAVE_STDINT_H +# error This module needs stdint.h - try ./configure --disable-jent-support +#endif -typedef uint64_t __u64; -#define RdTSC __asm _emit 0x0f __asm _emit 0x31 +/* When using the libgcrypt secure memory mechanism, all precautions + * are taken to protect our state. If the user disables secmem during + * runtime, it is his decision and we thus try not to overrule his + * decision for less memory protection. */ +#define JENT_CPU_JITTERENTROPY_SECURE_MEMORY 1 +#define jent_zalloc(n) _gcry_calloc_secure (1, (n)) -static void jent_get_nstime(__u64 *out) -{ - __u64 ret = 0; - _asm { - RdTSC - mov DWORD PTR ret, eax - mov DWORD PTR[ret + 4], edx - } - *out = ret; -} -static inline void *jent_zalloc(size_t len) +static void +jent_get_nstime(u64 *out) { - void *tmp = NULL; - - /* When using the libgcrypt secure memory mechanism, all precautions - * are taken to protect our state. If the user disables secmem during - * runtime, it is his decision and we thus try not to overrule his - * decision for less memory protection. */ -#define CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY - tmp = gcry_xmalloc_secure(len); - if(NULL != tmp) - memset(tmp, 0, len); - return tmp; -} +#if USE_JENT == JENT_USES_RDTSC -static inline void jent_zfree(void *ptr, unsigned int len) -{ - memset(ptr, 0, len); - gcry_free(ptr); + u32 t_eax, t_edx; + + asm volatile (".byte 0x0f,0x31\n\t" + : "=a" (t_eax), "=d" (t_edx) + ); + *out = (((u64)t_edx << 32) | t_eax); + +#elif USE_JENT == JENT_USES_GETTIME + + struct timespec tv; + u64 tmp; + + /* On Linux we could use CLOCK_MONOTONIC(_RAW), but with + * CLOCK_REALTIME we get some nice extra entropy once in a while + * from the NTP actions that we want to use as well... though, we do + * not rely on that extra little entropy. */ + if (!clock_gettime (CLOCK_REALTIME, &tv)) + { + tmp = time.tv_sec; + tmp = tmp << 32; + tmp = tmp | time.tv_nsec; + } + else + tmp = 0; + *out = tmp; + +#elif USE_JENT == JENT_USES_READ_REAL_TIME + + /* clock_gettime() on AIX returns a timer value that increments in + * steps of 1000. */ + u64 tmp = 0; + + timebasestruct_t aixtime; + read_real_time (&aixtime, TIMEBASE_SZ); + tmp = aixtime.tb_high; + tmp = tmp << 32; + tmp = tmp | aixtime.tb_low; + *out = tmp; + +#else +# error No clock available in jent_get_nstime +#endif } -static inline int jent_fips_enabled(void) + +static GPGRT_INLINE void +jent_zfree (void *ptr, unsigned int len) { - return fips_mode(); + if (ptr) + { + wipememory (ptr, len); + _gcry_free (ptr); + } } -/* --- helpers needed in user space -- */ - -/* note: these helper functions are shamelessly stolen from the kernel :-) */ -static inline __u64 rol64(__u64 word, unsigned int shift) +static GPGRT_INLINE int +jent_fips_enabled(void) { - return (word << shift) | (word >> (64 - shift)); + return fips_mode(); } -#endif /* _JITTERENTROPY_BASE_X86_H */ +#endif /* GCRYPT_JITTERENTROPY_BASE_USER_H */ diff --git a/random/jitterentropy-base.c b/random/jitterentropy-base.c index 2701e90..4f3de10 100644 --- a/random/jitterentropy-base.c +++ b/random/jitterentropy-base.c @@ -1,7 +1,7 @@ ?/* * Non-physical true random number generator based on timing jitter. * - * Copyright Stephan Mueller , 2014 + * Copyright Stephan Mueller , 2014 - 2017 * * Design * ====== @@ -49,6 +49,9 @@ * DAMAGE. */ +#undef _FORTIFY_SOURCE +#pragma GCC optimize ("O0") + #include "jitterentropy.h" #ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT @@ -59,14 +62,14 @@ #endif #define MAJVERSION 2 /* API / ABI incompatible changes, functional changes that - * require consumer to be updated (as long as this number - * is zero, the API is not considered stable and can - * change without a bump of the major version) */ -#define MINVERSION 0 /* API compatible, ABI may change, functional - * enhancements only, consumer can be left unchanged if - * enhancements are not considered */ + * require consumer to be updated (as long as this number + * is zero, the API is not considered stable and can + * change without a bump of the major version) */ +#define MINVERSION 1 /* API compatible, ABI may change, functional + * enhancements only, consumer can be left unchanged if + * enhancements are not considered */ #define PATCHLEVEL 0 /* API / ABI compatible, no functional changes, no - * enhancements, bug fixes only */ + * enhancements, bug fixes only */ /** * jent_version() - Return machine-usable version number of jent library @@ -81,15 +84,16 @@ * * Return: Version number of kcapi library */ -static unsigned int jent_version(void) +JENT_PRIVATE_STATIC +unsigned int jent_version(void) { - unsigned int version = 0; + unsigned int version = 0; - version = MAJVERSION * 1000000; - version += MINVERSION * 10000; - version += PATCHLEVEL * 100; + version = MAJVERSION * 1000000; + version += MINVERSION * 10000; + version += PATCHLEVEL * 100; - return version; + return version; } /** @@ -100,39 +104,39 @@ static unsigned int jent_version(void) * @ec entropy collector struct -- may be NULL * @bits is the number of low bits of the timer to consider * @min is the number of bits we shift the timer value to the right at - * the end to make sure we have a guaranteed minimum value + * the end to make sure we have a guaranteed minimum value * * @return Newly calculated loop counter */ -static u64 jent_loop_shuffle(struct rand_data *ec, - unsigned int bits, unsigned int min) +static uint64_t jent_loop_shuffle(struct rand_data *ec, + unsigned int bits, unsigned int min) { - u64 time = 0; - u64 shuffle = 0; - unsigned int i = 0; - unsigned int mask = (1<data; - /* - * We fold the time value as much as possible to ensure that as many - * bits of the time stamp are included as possible. - */ - for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) { - shuffle ^= time & mask; - time = time >> bits; - } - - /* - * We add a lower boundary value to ensure we have a minimum - * RNG loop count. - */ - return (shuffle + (1<data; + /* + * We fold the time value as much as possible to ensure that as many + * bits of the time stamp are included as possible. + */ + for (i = 0; (DATA_SIZE_BITS / bits) > i; i++) { + shuffle ^= time & mask; + time = time >> bits; + } + + /* + * We add a lower boundary value to ensure we have a minimum + * RNG loop count. + */ + return (shuffle + (1<data * * @return Number of loops the folding operation is performed */ -static u64 jent_lfsr_time(struct rand_data *ec, u64 time, - u64 loop_cnt) +static uint64_t jent_lfsr_time(struct rand_data *ec, uint64_t time, + uint64_t loop_cnt) { - unsigned int i; - u64 j = 0; - u64 new = 0; + unsigned int i; + uint64_t j = 0; + uint64_t new = 0; #define MAX_FOLD_LOOP_BIT 4 #define MIN_FOLD_LOOP_BIT 0 - u64 fold_loop_cnt = - jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT); - - /* - * testing purposes -- allow test app to set the counter, not - * needed during runtime - */ - if (loop_cnt) - fold_loop_cnt = loop_cnt; - for (j = 0; j < fold_loop_cnt; j++) { - new = ec->data; - for (i = 1; (DATA_SIZE_BITS) >= i; i++) { - u64 tmp = time << (DATA_SIZE_BITS - i); - - tmp = tmp >> (DATA_SIZE_BITS - 1); - - /* - * Fibonacci LSFR with polynomial of - * x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is - * primitive according to - * http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf - * (the shift values are the polynomial values minus one - * due to counting bits from 0 to 63). As the current - * position is always the LSB, the polynomial only needs - * to shift data in from the left without wrap. - */ - new ^= tmp; - new ^= ((new >> 63) & 1); - new ^= ((new >> 60) & 1); - new ^= ((new >> 55) & 1); - new ^= ((new >> 30) & 1); - new ^= ((new >> 27) & 1); - new ^= ((new >> 22) & 1); - new = rol64(new, 1); - } - } - ec->data = new; - - return fold_loop_cnt; + uint64_t fold_loop_cnt = + jent_loop_shuffle(ec, MAX_FOLD_LOOP_BIT, MIN_FOLD_LOOP_BIT); + + /* + * testing purposes -- allow test app to set the counter, not + * needed during runtime + */ + if (loop_cnt) + fold_loop_cnt = loop_cnt; + for (j = 0; j < fold_loop_cnt; j++) { + new = ec->data; + for (i = 1; (DATA_SIZE_BITS) >= i; i++) { + uint64_t tmp = time << (DATA_SIZE_BITS - i); + + tmp = tmp >> (DATA_SIZE_BITS - 1); + + /* + * Fibonacci LSFR with polynomial of + * x^64 + x^61 + x^56 + x^31 + x^28 + x^23 + 1 which is + * primitive according to + * http://poincare.matf.bg.ac.rs/~ezivkovm/publications/primpol1.pdf + * (the shift values are the polynomial values minus one + * due to counting bits from 0 to 63). As the current + * position is always the LSB, the polynomial only needs + * to shift data in from the left without wrap. + */ + new ^= tmp; + new ^= ((new >> 63) & 1); + new ^= ((new >> 60) & 1); + new ^= ((new >> 55) & 1); + new ^= ((new >> 30) & 1); + new ^= ((new >> 27) & 1); + new ^= ((new >> 22) & 1); + new = rol64(new, 1); + } + } + ec->data = new; + + return fold_loop_cnt; } /** * Memory Access noise source -- this is a noise source based on variations in - * memory access times + * memory access times * * This function performs memory accesses which will add to the timing * variations due to an unknown amount of CPU wait states that need to be @@ -236,47 +240,47 @@ static u64 jent_lfsr_time(struct rand_data *ec, u64 time, * the reference to the memory block to be accessed is NULL, this noise * source is disabled * @loop_cnt if a value not equal to 0 is set, use the given value as number of - * loops to perform the folding + * loops to perform the folding * * @return Number of memory access operations */ -static unsigned int jent_memaccess(struct rand_data *ec, u64 loop_cnt) +static unsigned int jent_memaccess(struct rand_data *ec, uint64_t loop_cnt) { - unsigned int wrap = 0; - u64 i = 0; + unsigned int wrap = 0; + uint64_t i = 0; #define MAX_ACC_LOOP_BIT 7 #define MIN_ACC_LOOP_BIT 0 - u64 acc_loop_cnt = - jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT); - - if (NULL == ec || NULL == ec->mem) - return 0; - wrap = ec->memblocksize * ec->memblocks; - - /* - * testing purposes -- allow test app to set the counter, not - * needed during runtime - */ - if (loop_cnt) - acc_loop_cnt = loop_cnt; - - for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) { - unsigned char *tmpval = ec->mem + ec->memlocation; - /* - * memory access: just add 1 to one byte, - * wrap at 255 -- memory access implies read - * from and write to memory location - */ - *tmpval = (*tmpval + 1) & 0xff; - /* - * Addition of memblocksize - 1 to pointer - * with wrap around logic to ensure that every - * memory location is hit evenly - */ - ec->memlocation = ec->memlocation + ec->memblocksize - 1; - ec->memlocation = ec->memlocation % wrap; - } - return i; + uint64_t acc_loop_cnt = + jent_loop_shuffle(ec, MAX_ACC_LOOP_BIT, MIN_ACC_LOOP_BIT); + + if (NULL == ec || NULL == ec->mem) + return 0; + wrap = ec->memblocksize * ec->memblocks; + + /* + * testing purposes -- allow test app to set the counter, not + * needed during runtime + */ + if (loop_cnt) + acc_loop_cnt = loop_cnt; + + for (i = 0; i < (ec->memaccessloops + acc_loop_cnt); i++) { + unsigned char *tmpval = ec->mem + ec->memlocation; + /* + * memory access: just add 1 to one byte, + * wrap at 255 -- memory access implies read + * from and write to memory location + */ + *tmpval = (*tmpval + 1) & 0xff; + /* + * Addition of memblocksize - 1 to pointer + * with wrap around logic to ensure that every + * memory location is hit evenly + */ + ec->memlocation = ec->memlocation + ec->memblocksize - 1; + ec->memlocation = ec->memlocation % wrap; + } + return i; } /*************************************************************************** @@ -285,9 +289,9 @@ static unsigned int jent_memaccess(struct rand_data *ec, u64 loop_cnt) /** * Stuck test by checking the: - * 1st derivation of the jitter measurement (time delta) - * 2nd derivation of the jitter measurement (delta of time deltas) - * 3rd derivation of the jitter measurement (delta of delta of time deltas) + * 1st derivation of the jitter measurement (time delta) + * 2nd derivation of the jitter measurement (delta of time deltas) + * 3rd derivation of the jitter measurement (delta of delta of time deltas) * * All values must always be non-zero. * @@ -296,21 +300,21 @@ static unsigned int jent_memaccess(struct rand_data *ec, u64 loop_cnt) * @current_delta Jitter time delta * * @return - * 0 jitter measurement not stuck (good bit) - * 1 jitter measurement stuck (reject bit) + * 0 jitter measurement not stuck (good bit) + * 1 jitter measurement stuck (reject bit) */ -static int jent_stuck(struct rand_data *ec, u64 current_delta) +static int jent_stuck(struct rand_data *ec, uint64_t current_delta) { - int64_t delta2 = ec->last_delta - current_delta; - int64_t delta3 = delta2 - ec->last_delta2; + int64_t delta2 = ec->last_delta - current_delta; + int64_t delta3 = delta2 - ec->last_delta2; - ec->last_delta = current_delta; - ec->last_delta2 = delta2; + ec->last_delta = current_delta; + ec->last_delta2 = delta2; - if (!current_delta || !delta2 || !delta3) - return 1; + if (!current_delta || !delta2 || !delta3) + return 1; - return 0; + return 0; } /** @@ -319,8 +323,8 @@ static int jent_stuck(struct rand_data *ec, u64 current_delta) * entropy pool. * * WARNING: ensure that ->prev_time is primed before using the output - * of this function! This can be done by calling this function - * and not using its result. + * of this function! This can be done by calling this function + * and not using its result. * * Input: * @entropy_collector Reference to entropy collector @@ -329,40 +333,40 @@ static int jent_stuck(struct rand_data *ec, u64 current_delta) */ static int jent_measure_jitter(struct rand_data *ec) { - u64 time = 0; - u64 current_delta = 0; - int stuck; - - /* Invoke one noise source before time measurement to add variations */ - jent_memaccess(ec, 0); - - /* - * Get time stamp and calculate time delta to previous - * invocation to measure the timing variations - */ - jent_get_nstime(&time); - current_delta = time - ec->prev_time; - ec->prev_time = time; - - /* Now call the next noise sources which also injects the data */ - jent_lfsr_time(ec, current_delta, 0); - - /* Check whether we have a stuck measurement. */ - stuck = jent_stuck(ec, current_delta); - - /* - * Rotate the data buffer by a prime number (any odd number would - * do) to ensure that every bit position of the input time stamp - * has an even chance of being merged with a bit position in the - * entropy pool. We do not use one here as the adjacent bits in - * successive time deltas may have some form of dependency. The - * chosen value of 7 implies that the low 7 bits of the next - * time delta value is concatenated with the current time delta. - */ - if (!stuck) - ec->data = rol64(ec->data, 7); - - return stuck; + uint64_t time = 0; + uint64_t current_delta = 0; + int stuck; + + /* Invoke one noise source before time measurement to add variations */ + jent_memaccess(ec, 0); + + /* + * Get time stamp and calculate time delta to previous + * invocation to measure the timing variations + */ + jent_get_nstime(&time); + current_delta = time - ec->prev_time; + ec->prev_time = time; + + /* Now call the next noise sources which also injects the data */ + jent_lfsr_time(ec, current_delta, 0); + + /* Check whether we have a stuck measurement. */ + stuck = jent_stuck(ec, current_delta); + + /* + * Rotate the data buffer by a prime number (any odd number would + * do) to ensure that every bit position of the input time stamp + * has an even chance of being merged with a bit position in the + * entropy pool. We do not use one here as the adjacent bits in + * successive time deltas may have some form of dependency. The + * chosen value of 7 implies that the low 7 bits of the next + * time delta value is concatenated with the current time delta. + */ + if (!stuck) + ec->data = rol64(ec->data, 7); + + return stuck; } /** @@ -384,54 +388,54 @@ static int jent_measure_jitter(struct rand_data *ec) */ static void jent_stir_pool(struct rand_data *entropy_collector) { - /* - * to shut up GCC on 32 bit, we have to initialize the 64 variable - * with two 32 bit variables - */ - union c { - u64 u64; - u32 u32[2]; - }; - /* - * This constant is derived from the first two 32 bit initialization - * vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 - */ - union c constant; - /* - * The start value of the mixer variable is derived from the third - * and fourth 32 bit initialization vector of SHA-1 as defined in - * FIPS 180-4 section 5.3.1 - */ - union c mixer; - unsigned int i = 0; - - /* Ensure that the function implements a constant time operation. */ - union c throw_away; - - /* - * Store the SHA-1 constants in reverse order to make up the 64 bit - * value -- this applies to a little endian system, on a big endian - * system, it reverses as expected. But this really does not matter - * as we do not rely on the specific numbers. We just pick the SHA-1 - * constants as they have a good mix of bit set and unset. - */ - constant.u32[1] = 0x67452301; - constant.u32[0] = 0xefcdab89; - mixer.u32[1] = 0x98badcfe; - mixer.u32[0] = 0x10325476; - - for (i = 0; i < DATA_SIZE_BITS; i++) { - /* - * get the i-th bit of the input random number and only XOR - * the constant into the mixer value when that bit is set - */ - if ((entropy_collector->data >> i) & 1) - mixer.u64 ^= constant.u64; - else - throw_away.u64 ^= constant.u64; - mixer.u64 = rol64(mixer.u64, 1); - } - entropy_collector->data ^= mixer.u64; + /* + * to shut up GCC on 32 bit, we have to initialize the 64 variable + * with two 32 bit variables + */ + union c { + uint64_t uint64; + uint32_t uint32[2]; + }; + /* + * This constant is derived from the first two 32 bit initialization + * vectors of SHA-1 as defined in FIPS 180-4 section 5.3.1 + */ + union c constant; + /* + * The start value of the mixer variable is derived from the third + * and fourth 32 bit initialization vector of SHA-1 as defined in + * FIPS 180-4 section 5.3.1 + */ + union c mixer; + unsigned int i = 0; + + /* Ensure that the function implements a constant time operation. */ + union c throw_away; + + /* + * Store the SHA-1 constants in reverse order to make up the 64 bit + * value -- this applies to a little endian system, on a big endian + * system, it reverses as expected. But this really does not matter + * as we do not rely on the specific numbers. We just pick the SHA-1 + * constants as they have a good mix of bit set and unset. + */ + constant.uint32[1] = 0x67452301; + constant.uint32[0] = 0xefcdab89; + mixer.uint32[1] = 0x98badcfe; + mixer.uint32[0] = 0x10325476; + + for (i = 0; i < DATA_SIZE_BITS; i++) { + /* + * get the i-th bit of the input random number and only XOR + * the constant into the mixer value when that bit is set + */ + if ((entropy_collector->data >> i) & 1) + mixer.uint64 ^= constant.uint64; + else + throw_away.uint64 ^= constant.uint64; + mixer.uint64 = rol64(mixer.uint64, 1); + } + entropy_collector->data ^= mixer.uint64; } /** @@ -443,30 +447,60 @@ static void jent_stir_pool(struct rand_data *entropy_collector) */ static void jent_gen_entropy(struct rand_data *ec) { - unsigned int k = 0; - - /* priming of the ->prev_time value */ - jent_measure_jitter(ec); - - while (1) { - u64 prev_data = ec->data; - - /* If a stuck measurement is received, repeat measurement */ - if (jent_measure_jitter(ec)) - continue; - - /* statistics testing only */ - jent_bit_count(ec, prev_data); - - /* - * We multiply the loop value with ->osr to obtain the - * oversampling rate requested by the caller - */ - if (++k >= (DATA_SIZE_BITS * ec->osr)) - break; - } - if (ec->stir) - jent_stir_pool(ec); + unsigned int k = 0; + + /* priming of the ->prev_time value */ + jent_measure_jitter(ec); + + while (1) { + /* If a stuck measurement is received, repeat measurement */ + if (jent_measure_jitter(ec)) + continue; + + /* + * We multiply the loop value with ->osr to obtain the + * oversampling rate requested by the caller + */ + if (++k >= (DATA_SIZE_BITS * ec->osr)) + break; + } + if (ec->stir) + jent_stir_pool(ec); +} + +/** + * The continuous test required by FIPS 140-2 -- the function automatically + * primes the test if needed. + * + * Return: + * 0 if FIPS test passed + * < 0 if FIPS test failed + */ +static int jent_fips_test(struct rand_data *ec) +{ + if (ec->fips_enabled == -1) + return 0; + + if (ec->fips_enabled == 0) { + if (!jent_fips_enabled()) { + ec->fips_enabled = -1; + return 0; + } else + ec->fips_enabled = 1; + } + + /* prime the FIPS test */ + if (!ec->old_data) { + ec->old_data = ec->data; + jent_gen_entropy(ec); + } + + if (ec->data == ec->old_data) + return -1; + + ec->old_data = ec->data; + + return 0; } /** @@ -489,241 +523,246 @@ static void jent_gen_entropy(struct rand_data *ec) * @return number of bytes returned when request is fulfilled or an error * * The following error codes can occur: - * -1 entropy_collector is NULL + * -1 entropy_collector is NULL + * -2 FIPS test failed */ -static int jent_read_entropy(struct rand_data *ec, char *data, size_t len) +JENT_PRIVATE_STATIC +ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len) { - char *p = data; - size_t orig_len = len; - - if (NULL == ec) - return -1; - - while (0 < len) { - size_t tocopy; - jent_gen_entropy(ec); - if ((DATA_SIZE_BITS / 8) < len) - tocopy = (DATA_SIZE_BITS / 8); - else - tocopy = len; - memcpy(p, &ec->data, tocopy); - - len -= tocopy; - p += tocopy; - } - - /* - * To be on the safe side, we generate one more round of entropy - * which we do not give out to the caller. That round shall ensure - * that in case the calling application crashes, memory dumps, pages - * out, or due to the CPU Jitter RNG lingering in memory for long - * time without being moved and an attacker cracks the application, - * all he reads in the entropy pool is a value that is NEVER EVER - * being used for anything. Thus, he does NOT see the previous value - * that was returned to the caller for cryptographic purposes. - */ - /* - * If we use secured memory, do not use that precaution as the secure - * memory protects the entropy pool. Moreover, note that using this - * call reduces the speed of the RNG by up to half - */ + char *p = data; + size_t orig_len = len; + + if (NULL == ec) + return -1; + + while (0 < len) { + size_t tocopy; + + jent_gen_entropy(ec); + if (jent_fips_test(ec)) + return -2; + + if ((DATA_SIZE_BITS / 8) < len) + tocopy = (DATA_SIZE_BITS / 8); + else + tocopy = len; + memcpy(p, &ec->data, tocopy); + + len -= tocopy; + p += tocopy; + } + + /* + * To be on the safe side, we generate one more round of entropy + * which we do not give out to the caller. That round shall ensure + * that in case the calling application crashes, memory dumps, pages + * out, or due to the CPU Jitter RNG lingering in memory for long + * time without being moved and an attacker cracks the application, + * all he reads in the entropy pool is a value that is NEVER EVER + * being used for anything. Thus, he does NOT see the previous value + * that was returned to the caller for cryptographic purposes. + */ + /* + * If we use secured memory, do not use that precaution as the secure + * memory protects the entropy pool. Moreover, note that using this + * call reduces the speed of the RNG by up to half + */ #ifndef CONFIG_CRYPTO_CPU_JITTERENTROPY_SECURE_MEMORY - jent_gen_entropy(ec); + jent_gen_entropy(ec); #endif - return orig_len; + return orig_len; } -#if defined(__KERNEL__) && !defined(MODULE) -EXPORT_SYMBOL(jent_read_entropy); -#endif /*************************************************************************** * Initialization logic ***************************************************************************/ -static struct rand_data *jent_entropy_collector_alloc(unsigned int osr, - unsigned int flags) +JENT_PRIVATE_STATIC +struct rand_data *jent_entropy_collector_alloc(unsigned int osr, + unsigned int flags) { - struct rand_data *entropy_collector; - - entropy_collector = jent_zalloc(sizeof(struct rand_data)); - if (NULL == entropy_collector) - return NULL; - - if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) { - /* Allocate memory for adding variations based on memory - * access - */ - entropy_collector->mem = - (unsigned char *)jent_zalloc(JENT_MEMORY_SIZE); - if (NULL == entropy_collector->mem) { - jent_zfree(entropy_collector, sizeof(struct rand_data)); - return NULL; - } - entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE; - entropy_collector->memblocks = JENT_MEMORY_BLOCKS; - entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS; - } - - /* verify and set the oversampling rate */ - if (0 == osr) - osr = 1; /* minimum sampling rate is 1 */ - entropy_collector->osr = osr; - - entropy_collector->stir = 1; - if (flags & JENT_DISABLE_STIR) - entropy_collector->stir = 0; - if (flags & JENT_DISABLE_UNBIAS) - entropy_collector->disable_unbias = 1; - - /* fill the data pad with non-zero values */ - jent_gen_entropy(entropy_collector); - - return entropy_collector; + struct rand_data *entropy_collector; + + entropy_collector = jent_zalloc(sizeof(struct rand_data)); + if (NULL == entropy_collector) + return NULL; + + if (!(flags & JENT_DISABLE_MEMORY_ACCESS)) { + /* Allocate memory for adding variations based on memory + * access + */ + entropy_collector->mem = + (unsigned char *)jent_zalloc(JENT_MEMORY_SIZE); + if (NULL == entropy_collector->mem) { + jent_zfree(entropy_collector, sizeof(struct rand_data)); + return NULL; + } + entropy_collector->memblocksize = JENT_MEMORY_BLOCKSIZE; + entropy_collector->memblocks = JENT_MEMORY_BLOCKS; + entropy_collector->memaccessloops = JENT_MEMORY_ACCESSLOOPS; + } + + /* verify and set the oversampling rate */ + if (0 == osr) + osr = 1; /* minimum sampling rate is 1 */ + entropy_collector->osr = osr; + + entropy_collector->stir = 1; + if (flags & JENT_DISABLE_STIR) + entropy_collector->stir = 0; + if (flags & JENT_DISABLE_UNBIAS) + entropy_collector->disable_unbias = 1; + + /* fill the data pad with non-zero values */ + jent_gen_entropy(entropy_collector); + + return entropy_collector; } -#if defined(__KERNEL__) && !defined(MODULE) -EXPORT_SYMBOL(jent_entropy_collector_alloc); -#endif -static void jent_entropy_collector_free(struct rand_data *entropy_collector) +JENT_PRIVATE_STATIC +void jent_entropy_collector_free(struct rand_data *entropy_collector) { - if (NULL != entropy_collector) { - if (NULL != entropy_collector->mem) { - jent_zfree(entropy_collector->mem, JENT_MEMORY_SIZE); - entropy_collector->mem = NULL; - } - jent_zfree(entropy_collector, sizeof(struct rand_data)); - } + if (NULL != entropy_collector) { + if (NULL != entropy_collector->mem) { + jent_zfree(entropy_collector->mem, JENT_MEMORY_SIZE); + entropy_collector->mem = NULL; + } + jent_zfree(entropy_collector, sizeof(struct rand_data)); + } } -#if defined(__KERNEL__) && !defined(MODULE) -EXPORT_SYMBOL(jent_entropy_collector_free); -#endif -static int jent_entropy_init(void) +JENT_PRIVATE_STATIC +int jent_entropy_init(void) { - int i; - u64 delta_sum = 0; - u64 old_delta = 0; - int time_backwards = 0; - int count_var = 0; - int count_mod = 0; - struct rand_data ec; - - /* We could perform statistical tests here, but the problem is - * that we only have a few loop counts to do testing. These - * loop counts may show some slight skew and we produce - * false positives. - * - * Moreover, only old systems show potentially problematic - * jitter entropy that could potentially be caught here. But - * the RNG is intended for hardware that is available or widely - * used, but not old systems that are long out of favor. Thus, - * no statistical tests. - */ - - /* - * We could add a check for system capabilities such as clock_getres or - * check for CONFIG_X86_TSC, but it does not make much sense as the - * following sanity checks verify that we have a high-resolution - * timer. - */ - /* - * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is - * definitely too little. - */ + int i; + uint64_t delta_sum = 0; + uint64_t old_delta = 0; + int time_backwards = 0; + int count_mod = 0; + int count_stuck = 0; + struct rand_data ec; + + /* We could perform statistical tests here, but the problem is + * that we only have a few loop counts to do testing. These + * loop counts may show some slight skew and we produce + * false positives. + * + * Moreover, only old systems show potentially problematic + * jitter entropy that could potentially be caught here. But + * the RNG is intended for hardware that is available or widely + * used, but not old systems that are long out of favor. Thus, + * no statistical tests. + */ + + /* + * We could add a check for system capabilities such as clock_getres or + * check for CONFIG_X86_TSC, but it does not make much sense as the + * following sanity checks verify that we have a high-resolution + * timer. + */ + /* + * TESTLOOPCOUNT needs some loops to identify edge systems. 100 is + * definitely too little. + */ #define TESTLOOPCOUNT 300 #define CLEARCACHE 100 - for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) { - u64 time = 0; - u64 time2 = 0; - u64 delta = 0; - unsigned int lowdelta = 0; - - jent_get_nstime(&time); - jent_lfsr_time(&ec, time, 1< i) - continue; - - /* test whether we have an increasing timer */ - if (!(time2 > time)) - time_backwards++; - - /* use 32 bit value to ensure compilation on 32 bit arches */ - lowdelta = time2 - time; - if (!(lowdelta % 100)) - count_mod++; - - /* - * ensure that we have a varying delta timer which is necessary - * for the calculation of entropy -- perform this check - * only after the first loop is executed as we need to prime - * the old_data value - */ - if (i) { - if (delta != old_delta) - count_var++; - if (delta > old_delta) - delta_sum += (delta - old_delta); - else - delta_sum += (old_delta - delta); - } - old_delta = delta; - } - - /* - * we allow up to three times the time running backwards. - * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus, - * if such an operation just happens to interfere with our test, it - * should not fail. The value of 3 should cover the NTP case being - * performed during our test run. - */ - if (3 < time_backwards) - return ENOMONOTONIC; - /* Error if the time variances are always identical */ - if (!delta_sum) - return EVARVAR; - - /* - * Variations of deltas of time must on average be larger - * than 1 to ensure the entropy estimation - * implied with 1 is preserved - */ - if ((delta_sum) <= 1) - return EMINVARVAR; - - /* - * Ensure that we have variations in the time stamp below 10 for at least - * 10% of all checks -- on some platforms, the counter increments in - * multiples of 100, but not always - */ - if ((TESTLOOPCOUNT/10 * 9) < count_mod) - return ECOARSETIME; - - return 0; + for (i = 0; (TESTLOOPCOUNT + CLEARCACHE) > i; i++) { + uint64_t time = 0; + uint64_t time2 = 0; + uint64_t delta = 0; + unsigned int lowdelta = 0; + int stuck; + + /* Invoke core entropy collection logic */ + jent_get_nstime(&time); + ec.prev_time = time; + jent_lfsr_time(&ec, time, 0); + jent_get_nstime(&time2); + + /* test whether timer works */ + if (!time || !time2) + return ENOTIME; + delta = time2 - time; + /* + * test whether timer is fine grained enough to provide + * delta even when called shortly after each other -- this + * implies that we also have a high resolution timer + */ + if (!delta) + return ECOARSETIME; + + stuck = jent_stuck(&ec, delta); + + /* + * up to here we did not modify any variable that will be + * evaluated later, but we already performed some work. Thus we + * already have had an impact on the caches, branch prediction, + * etc. with the goal to clear it to get the worst case + * measurements. + */ + if (CLEARCACHE > i) + continue; + + if (stuck) + count_stuck++; + + /* test whether we have an increasing timer */ + if (!(time2 > time)) + time_backwards++; + + /* use 32 bit value to ensure compilation on 32 bit arches */ + lowdelta = time2 - time; + if (!(lowdelta % 100)) + count_mod++; + + /* + * ensure that we have a varying delta timer which is necessary + * for the calculation of entropy -- perform this check + * only after the first loop is executed as we need to prime + * the old_data value + */ + if (delta > old_delta) + delta_sum += (delta - old_delta); + else + delta_sum += (old_delta - delta); + old_delta = delta; + } + + /* + * we allow up to three times the time running backwards. + * CLOCK_REALTIME is affected by adjtime and NTP operations. Thus, + * if such an operation just happens to interfere with our test, it + * should not fail. The value of 3 should cover the NTP case being + * performed during our test run. + */ + if (3 < time_backwards) + return ENOMONOTONIC; + + /* + * Variations of deltas of time must on average be larger + * than 1 to ensure the entropy estimation + * implied with 1 is preserved + */ + if ((delta_sum) <= 1) + return EMINVARVAR; + + /* + * Ensure that we have variations in the time stamp below 10 for at least + * 10% of all checks -- on some platforms, the counter increments in + * multiples of 100, but not always + */ + if ((TESTLOOPCOUNT/10 * 9) < count_mod) + return ECOARSETIME; + + /* + * If we have more than 90% stuck results, then this Jitter RNG is + * likely to not work well. + */ + if (JENT_STUCK_INIT_THRES(TESTLOOPCOUNT) < count_stuck) + return ESTUCK; + + return 0; } -#if defined(__KERNEL__) && !defined(MODULE) -EXPORT_SYMBOL(jent_entropy_init); -#endif /*************************************************************************** * Statistical test logic not compiled for regular operation @@ -731,54 +770,20 @@ EXPORT_SYMBOL(jent_entropy_init); #ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT /* - * Statistical tests: invoke the entropy collector and sample time results - * for it, the random data is never returned - every call to this function - * generates one random number. - * This function is only meant for statistical analysis purposes and not - * for general use - */ -void jent_gen_entropy_stat(struct rand_data *entropy_collector, - struct entropy_stat *stat) -{ - /* caller is allowed to set the entropy collection loop to a fixed - * value -- we still call shuffle for the time measurements */ - jent_init_statistic(entropy_collector); - jent_gen_entropy(entropy_collector); - jent_calc_statistic(entropy_collector, stat, DATA_SIZE_BITS); -} - -/* - * Statistical test: obtain the distribution of the LFSR state value from - * jent_lfsr_time - */ -void jent_lfsr_time_stat(struct rand_data *ec, u64 *fold, u64 *loop_cnt) -{ - u64 time = 0; - u64 time2 = 0; - jent_get_nstime(&time); - jent_memaccess(ec, 0); - /* implement the priming logic */ - jent_lfsr_time(ec, time, 0); - jent_get_nstime(&time2); - time2 = time2 - time; - *loop_cnt = jent_lfsr_time(ec, time2, 0); - *fold = ec->data; -} - -/* * Statistical test: return the time duration for the folding operation. If min - * is set, perform the given number of foldings. Otherwise, allow the - * loop count shuffling to define the number of foldings. + * is set, perform the given number of LFSR ops. Otherwise, allow the + * loop count shuffling to define the number of LFSR ops. */ -u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min) +JENT_PRIVATE_STATIC +uint64_t jent_lfsr_var_stat(struct rand_data *ec, unsigned int min) { - u64 time = 0; - u64 time2 = 0; - - jent_get_nstime(&time); - jent_memaccess(ec, min); - jent_lfsr_time(ec, time, min); - jent_get_nstime(&time2); - return ((time2 - time)); + uint64_t time = 0; + uint64_t time2 = 0; + + jent_get_nstime(&time); + jent_memaccess(ec, min); + jent_lfsr_time(ec, time, min); + jent_get_nstime(&time2); + return ((time2 - time)); } #endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ diff --git a/random/jitterentropy.h b/random/jitterentropy.h index 2c33256..28859f5 100644 --- a/random/jitterentropy.h +++ b/random/jitterentropy.h @@ -39,139 +39,110 @@ * DAMAGE. */ -#ifndef GCRYPT_JITTERENTROPY_H -#define GCRYPT_JITTERENTROPY_H - -/* #ifdef __KERNEL__ */ -/* #include "jitterentropy-base-kernel.h" */ -/* #else */ -/* #include "jitterentropy-base-user.h" */ -/* #endif /\* __KERNEL__ *\/ */ - -/* Statistical data from the entropy source */ -struct entropy_stat { - unsigned int bitslot[64]; /* Counter for the bits set per bit - position in ->data */ - unsigned int bitvar[64]; /* Counter for the number of bit - variations per bit position in - ->data */ - unsigned int enable_bit_test; /* enable bit test - this flag is vital for the accuracy - of the statistic tests: when we - do the time measurements, we want - the observed entropy collection - loop executed as fast as the - unmeasured loop, i.e. without - the bit statistic logic; on the - other hand, the bit statistics - test is not interested in exact - timing */ - u64 collection_begin; /* timer for beginning of one - entropy collection round */ - u64 collection_end; /* timer for end of one round */ - u64 old_delta; /* Time delta of previous round to - calculate delta of deltas */ - unsigned int setbits; /* see _jent_calc_statistic */ - unsigned int varbits; /* see _jent_calc_statistic */ - unsigned int obsbits; /* see _jent_calc_statistic */ - unsigned int collection_loop_cnt; /* Collection loop counter */ -}; +#ifndef _JITTERENTROPY_H +#define _JITTERENTROPY_H + +#ifdef __KERNEL__ +#include "jitterentropy-base-kernel.h" +#else +#include "jitterentropy-base-user.h" +#endif /* __KERNEL__ */ /* The entropy pool */ struct rand_data { - /* all data values that are vital to maintain the security - * of the RNG are marked as SENSITIVE. A user must not - * access that information while the RNG executes its loops to - * calculate the next random value. */ - u64 data; /* SENSITIVE Actual random number */ - u64 prev_time; /* SENSITIVE Previous time stamp */ -#define DATA_SIZE_BITS ((sizeof(u64)) * 8) - u64 last_delta; /* SENSITIVE stuck test */ - int64_t last_delta2; /* SENSITIVE stuck test */ - unsigned int osr; /* Oversample rate */ - unsigned int stir:1; /* Post-processing stirring */ - unsigned int disable_unbias:1; /* Deactivate Von-Neuman unbias */ + /* all data values that are vital to maintain the security + * of the RNG are marked as SENSITIVE. A user must not + * access that information while the RNG executes its loops to + * calculate the next random value. */ + uint64_t data; /* SENSITIVE Actual random number */ + uint64_t old_data; /* SENSITIVE Previous random number */ + uint64_t prev_time; /* SENSITIVE Previous time stamp */ +#define DATA_SIZE_BITS ((sizeof(uint64_t)) * 8) + uint64_t last_delta; /* SENSITIVE stuck test */ + int64_t last_delta2; /* SENSITIVE stuck test */ + unsigned int osr; /* Oversample rate */ + int fips_enabled; /* FIPS enabled? */ + unsigned int stir:1; /* Post-processing stirring */ + unsigned int disable_unbias:1; /* Deactivate Von-Neuman unbias */ #define JENT_MEMORY_BLOCKS 64 #define JENT_MEMORY_BLOCKSIZE 32 #define JENT_MEMORY_ACCESSLOOPS 128 #define JENT_MEMORY_SIZE (JENT_MEMORY_BLOCKS*JENT_MEMORY_BLOCKSIZE) - unsigned char *mem; /* Memory access location with size of - * memblocks * memblocksize */ - unsigned int memlocation; /* Pointer to byte in *mem */ - unsigned int memblocks; /* Number of memory blocks in *mem */ - unsigned int memblocksize; /* Size of one memory block in bytes */ - unsigned int memaccessloops; /* Number of memory accesses per random - * bit generation */ -#ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT - struct entropy_stat entropy_stat; -#endif + unsigned char *mem; /* Memory access location with size of + * memblocks * memblocksize */ + unsigned int memlocation; /* Pointer to byte in *mem */ + unsigned int memblocks; /* Number of memory blocks in *mem */ + unsigned int memblocksize; /* Size of one memory block in bytes */ + unsigned int memaccessloops; /* Number of memory accesses per random + * bit generation */ }; /* Flags that can be used to initialize the RNG */ #define JENT_DISABLE_STIR (1<<0) /* Disable stirring the entropy pool */ #define JENT_DISABLE_UNBIAS (1<<1) /* Disable the Von-Neuman Unbiaser */ #define JENT_DISABLE_MEMORY_ACCESS (1<<2) /* Disable memory access for more - entropy, saves MEMORY_SIZE RAM for - entropy collector */ - -#define DRIVER_NAME "jitterentropy" + entropy, saves MEMORY_SIZE RAM for + entropy collector */ /* -- BEGIN Main interface functions -- */ +#ifndef JENT_STUCK_INIT_THRES +/* + * Per default, not more than 90% of all measurements during initialization + * are allowed to be stuck. + * + * It is allowed to change this value as required for the intended environment. + */ +#define JENT_STUCK_INIT_THRES(x) (x/10 * 9) +#endif + +#ifdef JENT_PRIVATE_COMPILE +# define JENT_PRIVATE_STATIC static +#else /* JENT_PRIVATE_COMPILE */ +# define JENT_PRIVATE_STATIC +#endif + /* Number of low bits of the time value that we want to consider */ /* get raw entropy */ -static int jent_read_entropy (struct rand_data *ec, - char *data, size_t len); - +JENT_PRIVATE_STATIC +ssize_t jent_read_entropy(struct rand_data *ec, char *data, size_t len); /* initialize an instance of the entropy collector */ -static struct rand_data *jent_entropy_collector_alloc (unsigned int osr, - unsigned int flags); - +JENT_PRIVATE_STATIC +struct rand_data *jent_entropy_collector_alloc(unsigned int osr, + unsigned int flags); /* clearing of entropy collector */ -static void jent_entropy_collector_free (struct rand_data *ent_coll); +JENT_PRIVATE_STATIC +void jent_entropy_collector_free(struct rand_data *entropy_collector); /* initialization of entropy collector */ -static int jent_entropy_init (void); +JENT_PRIVATE_STATIC +int jent_entropy_init(void); /* return version number of core library */ -/* unsigned int jent_version(void); */ +JENT_PRIVATE_STATIC +unsigned int jent_version(void); /* -- END of Main interface functions -- */ /* -- BEGIN error codes for init function -- */ -/* FIXME!!! */ -#define ENOTIME 1 /* Timer service not available */ +#define ENOTIME 1 /* Timer service not available */ #define ECOARSETIME 2 /* Timer too coarse for RNG */ #define ENOMONOTONIC 3 /* Timer is not monotonic increasing */ #define EMINVARIATION 4 /* Timer variations too small for RNG */ #define EVARVAR 5 /* Timer does not produce variations of variations - (2nd derivation of time is zero) */ + (2nd derivation of time is zero) */ #define EMINVARVAR 6 /* Timer variations of variations is too small */ #define EPROGERR 7 /* Programming error */ +#define ESTUCK 8 /* Too many stuck results during init. */ /* -- BEGIN statistical test functions only complied with CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT -- */ #ifdef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT - -static void jent_init_statistic(struct rand_data *entropy_collector); -static void jent_calc_statistic(struct rand_data *entropy_collector, - struct entropy_stat *stat, unsigned int loop_cnt); -static void jent_bit_count (struct rand_data *entropy_collector, u64 prev_data); - -static void jent_gen_entropy_stat (struct rand_data *entropy_collector, - struct entropy_stat *stat); -static void jent_lfsr_time_stat(struct rand_data *ec, u64 *fold, u64 *loop_cnt); -static u64 jent_lfsr_var_stat(struct rand_data *ec, unsigned int min); - -#else /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ - -# define jent_init_statistic(x) do { } while (0) -# define jent_calc_statistic(x, y, z) do { } while (0) -# define jent_bit_count(x,y) do { (void)(y); } while (0) - +JENT_PRIVATE_STATIC +uint64_t jent_lfsr_var_stat(struct rand_data *ec, unsigned int min); #endif /* CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT */ /* -- END of statistical test function -- */ -#endif /* GCRYPT_JITTERENTROPY_H */ +#endif /* _JITTERENTROPY_H */ diff --git a/random/rndjent.c b/random/rndjent.c index dd7ad04..b1432e4 100644 --- a/random/rndjent.c +++ b/random/rndjent.c @@ -71,103 +71,18 @@ #ifdef USE_JENT -/* When using the libgcrypt secure memory mechanism, all precautions - * are taken to protect our state. If the user disables secmem during - * runtime, it is his decision and we thus try not to overrule his - * decision for less memory protection. */ -#define JENT_CPU_JITTERENTROPY_SECURE_MEMORY 1 -#define jent_zalloc(n) _gcry_calloc_secure (1, (n)) - - - -/* - * Libgcrypt specific platform dependent functions. - */ - - -static void -jent_get_nstime(u64 *out) -{ -#if USE_JENT == JENT_USES_RDTSC - - u32 t_eax, t_edx; - - asm volatile (".byte 0x0f,0x31\n\t" - : "=a" (t_eax), "=d" (t_edx) - ); - *out = (((u64)t_edx << 32) | t_eax); - -#elif USE_JENT == JENT_USES_GETTIME - - struct timespec tv; - u64 tmp; - - /* On Linux we could use CLOCK_MONOTONIC(_RAW), but with - * CLOCK_REALTIME we get some nice extra entropy once in a while - * from the NTP actions that we want to use as well... though, we do - * not rely on that extra little entropy. */ - if (!clock_gettime (CLOCK_REALTIME, &tv)) - { - tmp = time.tv_sec; - tmp = tmp << 32; - tmp = tmp | time.tv_nsec; - } - else - tmp = 0; - *out = tmp; - -#elif USE_JENT == JENT_USES_READ_REAL_TIME - - /* clock_gettime() on AIX returns a timer value that increments in - * steps of 1000. */ - u64 tmp = 0; - - timebasestruct_t aixtime; - read_real_time (&aixtime, TIMEBASE_SZ); - tmp = aixtime.tb_high; - tmp = tmp << 32; - tmp = tmp | aixtime.tb_low; - *out = tmp; - -#else -# error No clock available in jent_get_nstime -#endif -} - - -static GPGRT_INLINE void -jent_zfree (void *ptr, unsigned int len) -{ - if (ptr) - { - wipememory (ptr, len); - _gcry_free (ptr); - } -} - -static GPGRT_INLINE int -jent_fips_enabled(void) -{ - return fips_mode(); -} - - -/* - * We source include the actual jitter entropy code. Note that the - * included code has been slightly changed from the Linux kernel - * version for namespace reasons. We define MODULE so that the - * EXPORT_SYMBOL macro will not be used. - */ #undef CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT /* Uncomment the next line to build with statistics. */ /* #define CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT 1 */ -#undef MODULE -#define MODULE 1 -#ifndef HAVE_STDINT_H -# error This module needs stdint.h - try ./configure --disable-jent-support -#endif +/* Note that we source include the actual jitter entropy code. + * Platform dependent code is indirectly included from our own + * jitterentropy-user-base.h file. */ + +/* Tell jitterentropy* that all functions shall be static. */ +#define JENT_PRIVATE_COMPILE 1 + #include "jitterentropy-base.c" @@ -199,52 +114,52 @@ static unsigned long jent_rng_totalbytes; static void jent_init_statistic (struct rand_data *rand_data) { - int i; - struct entropy_stat *stat = &rand_data->entropy_stat; + /* int i; */ + /* struct entropy_stat *stat = &rand_data->entropy_stat; */ - for (i = 0; i < 64; i++) - { - stat->bitslot[i] = 0; - stat->bitvar[i] = 0; - } + /* for (i = 0; i < 64; i++) */ + /* { */ + /* stat->bitslot[i] = 0; */ + /* stat->bitvar[i] = 0; */ + /* } */ - jent_get_nstime (&stat->collection_begin); + /* jent_get_nstime (&stat->collection_begin); */ } static void jent_bit_count (struct rand_data *rand_data, u64 prev_data) { - int i; - - if (!rand_data->entropy_stat.enable_bit_test) - return; - - for (i = 0; i < 64; i++) - { - /* collect the count of set bits per bit position in the - * current ->data field */ - rand_data->entropy_stat.bitslot[i] += (rand_data->data & 1<data & 1<entropy_stat.bitvar[i] += 1; - } + /* int i; */ + + /* if (!rand_data->entropy_stat.enable_bit_test) */ + /* return; */ + + /* for (i = 0; i < 64; i++) */ + /* { */ + /* /\* collect the count of set bits per bit position in the */ + /* * current ->data field *\/ */ + /* rand_data->entropy_stat.bitslot[i] += (rand_data->data & 1<data & 1<entropy_stat.bitvar[i] += 1; */ + /* } */ } static void jent_statistic_copy_stat (struct entropy_stat *src, struct entropy_stat *dst) { - /* not copying bitslot and bitvar as they are not needed for - * statistic printout */ - dst->collection_begin = src->collection_begin; - dst->collection_end = src->collection_end; - dst->old_delta = src->old_delta; - dst->setbits = src->setbits; - dst->varbits = src->varbits; - dst->obsbits = src->obsbits; - dst->collection_loop_cnt= src->collection_loop_cnt; + /* /\* not copying bitslot and bitvar as they are not needed for */ + /* * statistic printout *\/ */ + /* dst->collection_begin = src->collection_begin; */ + /* dst->collection_end = src->collection_end; */ + /* dst->old_delta = src->old_delta; */ + /* dst->setbits = src->setbits; */ + /* dst->varbits = src->varbits; */ + /* dst->obsbits = src->obsbits; */ + /* dst->collection_loop_cnt= src->collection_loop_cnt; */ } @@ -259,30 +174,30 @@ static void jent_calc_statistic (struct rand_data *rand_data, struct entropy_stat *target, unsigned int loop_cnt) { - int i; - struct entropy_stat *stat = &rand_data->entropy_stat; + /* int i; */ + /* struct entropy_stat *stat = &rand_data->entropy_stat; */ - jent_get_nstime(&stat->collection_end); + /* jent_get_nstime(&stat->collection_end); */ - stat->collection_loop_cnt = loop_cnt; + /* stat->collection_loop_cnt = loop_cnt; */ - stat->setbits = 0; - stat->varbits = 0; - stat->obsbits = 0; + /* stat->setbits = 0; */ + /* stat->varbits = 0; */ + /* stat->obsbits = 0; */ - for (i = 0; i < DATA_SIZE_BITS; i++) - { - stat->setbits += stat->bitslot[i]; - stat->varbits += stat->bitvar[i]; + /* for (i = 0; i < DATA_SIZE_BITS; i++) */ + /* { */ + /* stat->setbits += stat->bitslot[i]; */ + /* stat->varbits += stat->bitvar[i]; */ - /* This is the sum of set bits in the current observation - * of the random data. */ - stat->obsbits += (rand_data->data & 1<obsbits += (rand_data->data & 1<old_delta = (stat->collection_end - stat->collection_begin); + /* stat->old_delta = (stat->collection_end - stat->collection_begin); */ } #endif /*CONFIG_CRYPTO_CPU_JITTERENTROPY_STAT*/ @@ -438,8 +353,8 @@ void _gcry_rndjent_dump_stats (void) { /* In theory we would need to lock the stats here. However this - function is usually called during cleanup and then we _might_ run - into problems. */ + * function is usually called during cleanup and then we _might_ run + * into problems. */ #ifdef USE_JENT if ( is_rng_available () ) ----------------------------------------------------------------------- Summary of changes: random/Makefile.am | 2 +- random/jitterentropy-base-user.h | 119 +++-- random/jitterentropy-base.c | 1019 +++++++++++++++++++------------------- random/jitterentropy.h | 157 +++--- random/rndjent.c | 203 +++----- 5 files changed, 711 insertions(+), 789 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Sat Jun 24 13:46:38 2017 From: cvs at cvs.gnupg.org (by Werner Koch) Date: Sat, 24 Jun 2017 13:46:38 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-109-ge6a3dc9 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via e6a3dc9900433bbc8ad362a595a3837318c28fa9 (commit) from d091610377b2c92cf385282b1adfc30fa6cd5c75 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit e6a3dc9900433bbc8ad362a595a3837318c28fa9 Author: Werner Koch Date: Sat Jun 24 12:03:14 2017 +0200 rsa: Minor refactoring. * cipher/rsa.c (secret): Factor code out to ... (secret_core_std, secret_core_crt): new functions. Signed-off-by: Werner Koch diff --git a/cipher/rsa.c b/cipher/rsa.c index 7f12ecd..9f83e8f 100644 --- a/cipher/rsa.c +++ b/cipher/rsa.c @@ -991,20 +991,64 @@ stronger_key_check ( RSA_secret_key *skey ) #endif - -/**************** - * Secret key operation. Encrypt INPUT with SKEY and put result into OUTPUT. + +/* Secret key operation - standard version. * * m = c^d mod n - * - * Or faster: + */ +static void +secret_core_std (gcry_mpi_t M, gcry_mpi_t C, + gcry_mpi_t D, gcry_mpi_t N) +{ + mpi_powm (M, C, D, N); +} + + +/* Secret key operation - using the CRT. * * m1 = c ^ (d mod (p-1)) mod p * m2 = c ^ (d mod (q-1)) mod q * h = u * (m2 - m1) mod q * m = m1 + h * p - * - * Where m is OUTPUT, c is INPUT and d,n,p,q,u are elements of SKEY. + */ +static void +secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, + gcry_mpi_t D, unsigned int Nlimbs, + gcry_mpi_t P, gcry_mpi_t Q, gcry_mpi_t U) +{ + gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); + gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); + gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); + + /* m1 = c ^ (d mod (p-1)) mod p */ + mpi_sub_ui ( h, P, 1 ); + mpi_fdiv_r ( h, D, h ); + mpi_powm ( m1, C, h, P ); + + /* m2 = c ^ (d mod (q-1)) mod q */ + mpi_sub_ui ( h, Q, 1 ); + mpi_fdiv_r ( h, D, h ); + mpi_powm ( m2, C, h, Q ); + + /* h = u * ( m2 - m1 ) mod q */ + mpi_sub ( h, m2, m1 ); + if ( mpi_has_sign ( h ) ) + mpi_add ( h, h, Q ); + mpi_mulm ( h, U, h, Q ); + + /* m = m1 + h * p */ + mpi_mul ( h, h, P ); + mpi_add ( M, m1, h ); + + mpi_free ( h ); + mpi_free ( m1 ); + mpi_free ( m2 ); +} + + +/* Secret key operation. + * Encrypt INPUT with SKEY and put result into + * OUTPUT. SKEY has the secret key parameters. */ static void secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey ) @@ -1014,37 +1058,16 @@ secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey ) if (!skey->p || !skey->q || !skey->u) { - mpi_powm (output, input, skey->d, skey->n); + secret_core_std (output, input, skey->d, skey->n); } else { - gcry_mpi_t m1 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 ); - gcry_mpi_t m2 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 ); - gcry_mpi_t h = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 ); - - /* m1 = c ^ (d mod (p-1)) mod p */ - mpi_sub_ui( h, skey->p, 1 ); - mpi_fdiv_r( h, skey->d, h ); - mpi_powm( m1, input, h, skey->p ); - /* m2 = c ^ (d mod (q-1)) mod q */ - mpi_sub_ui( h, skey->q, 1 ); - mpi_fdiv_r( h, skey->d, h ); - mpi_powm( m2, input, h, skey->q ); - /* h = u * ( m2 - m1 ) mod q */ - mpi_sub( h, m2, m1 ); - if ( mpi_has_sign ( h ) ) - mpi_add ( h, h, skey->q ); - mpi_mulm( h, skey->u, h, skey->q ); - /* m = m1 + h * p */ - mpi_mul ( h, h, skey->p ); - mpi_add ( output, m1, h ); - - mpi_free ( h ); - mpi_free ( m1 ); - mpi_free ( m2 ); + secret_core_crt (output, input, skey->d, mpi_get_nlimbs (skey->n), + skey->p, skey->q, skey->u); } } + static void secret_blinded (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *sk, unsigned int nbits) @@ -1088,6 +1111,7 @@ secret_blinded (gcry_mpi_t output, gcry_mpi_t input, _gcry_mpi_release (ri); } + /********************************************* ************** interface ****************** *********************************************/ ----------------------------------------------------------------------- Summary of changes: cipher/rsa.c | 88 ++++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 32 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Wed Jun 28 12:00:36 2017 From: cvs at cvs.gnupg.org (by NIIBE Yutaka) Date: Wed, 28 Jun 2017 12:00:36 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-110-g7813082 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 78130828e9a140a9de4dafadbc844dbb64cb709a (commit) from e6a3dc9900433bbc8ad362a595a3837318c28fa9 (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 78130828e9a140a9de4dafadbc844dbb64cb709a Author: NIIBE Yutaka Date: Sat Jun 24 20:46:20 2017 +0900 Same computation for square and multiply. * mpi/mpi-pow.c (_gcry_mpi_powm): Compare msize for max_u_size. Move the assignment to base_u into the loop. Copy content refered by RP to BASE_U except the last of the loop. -- Signed-off-by: NIIBE Yutaka diff --git a/mpi/mpi-pow.c b/mpi/mpi-pow.c index 7b3dc31..3cba690 100644 --- a/mpi/mpi-pow.c +++ b/mpi/mpi-pow.c @@ -573,6 +573,8 @@ _gcry_mpi_powm (gcry_mpi_t res, MPN_COPY (precomp[i], rp, rsize); } + if (msize > max_u_size) + max_u_size = msize; base_u = mpi_alloc_limb_space (max_u_size, esec); MPN_ZERO (base_u, max_u_size); @@ -619,6 +621,10 @@ _gcry_mpi_powm (gcry_mpi_t res, { int c0; mpi_limb_t e0; + struct gcry_mpi w, u; + w.sign = u.sign = 0; + w.flags = u.flags = 0; + w.d = base_u; count_leading_zeros (c0, e); e = (e << c0); @@ -652,29 +658,31 @@ _gcry_mpi_powm (gcry_mpi_t res, count_trailing_zeros (c0, e0); e0 = (e0 >> c0) >> 1; - /* - * base_u <= precomp[e0] - * base_u_size <= precomp_size[e0] - */ - base_u_size = 0; - for (k = 0; k < (1<< (W - 1)); k++) - { - struct gcry_mpi w, u; - w.alloced = w.nlimbs = precomp_size[k]; - u.alloced = u.nlimbs = precomp_size[k]; - w.sign = u.sign = 0; - w.flags = u.flags = 0; - w.d = base_u; - u.d = precomp[k]; - - mpi_set_cond (&w, &u, k == e0); - base_u_size |= ( precomp_size[k] & ((mpi_size_t)0 - (k == e0)) ); - } - for (j += W - c0; j >= 0; j--) { - mul_mod (xp, &xsize, rp, rsize, - j == 0 ? base_u : rp, j == 0 ? base_u_size : rsize, + + /* + * base_u <= precomp[e0] + * base_u_size <= precomp_size[e0] + */ + base_u_size = 0; + for (k = 0; k < (1<< (W - 1)); k++) + { + w.alloced = w.nlimbs = precomp_size[k]; + u.alloced = u.nlimbs = precomp_size[k]; + u.d = precomp[k]; + + mpi_set_cond (&w, &u, k == e0); + base_u_size |= ( precomp_size[k] & (0UL - (k == e0)) ); + } + + w.alloced = w.nlimbs = rsize; + u.alloced = u.nlimbs = rsize; + u.d = rp; + mpi_set_cond (&w, &u, j != 0); + base_u_size ^= ((base_u_size ^ rsize) & (0UL - (j != 0))); + + mul_mod (xp, &xsize, rp, rsize, base_u, base_u_size, mp, msize, &karactx); tp = rp; rp = xp; xp = tp; rsize = xsize; ----------------------------------------------------------------------- Summary of changes: mpi/mpi-pow.c | 50 +++++++++++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 21 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits From cvs at cvs.gnupg.org Thu Jun 29 04:46:46 2017 From: cvs at cvs.gnupg.org (by NIIBE Yutaka) Date: Thu, 29 Jun 2017 04:46:46 +0200 Subject: [git] GCRYPT - branch, master, updated. libgcrypt-1.7.3-111-g8725c99 Message-ID: This is an automated email from the git hooks/post-receive script. It was generated because a ref change was pushed to the repository containing the project "The GNU crypto library". The branch, master has been updated via 8725c99ffa41778f382ca97233183bcd687bb0ce (commit) from 78130828e9a140a9de4dafadbc844dbb64cb709a (commit) Those revisions listed above that are new to this repository have not appeared on any other notification email; so we list those revisions in full, below. - Log ----------------------------------------------------------------- commit 8725c99ffa41778f382ca97233183bcd687bb0ce Author: NIIBE Yutaka Date: Thu Jun 29 11:11:37 2017 +0900 rsa: Add exponent blinding. * cipher/rsa.c (secret_core_crt): Blind secret D with randomized nonce R for mpi_powm computation. -- Co-authored-by: Werner Koch Signed-off-by: NIIBE Yutaka The paper describing attack: https://eprint.iacr.org/2017/627 Sliding right into disaster: Left-to-right sliding windows leak by Daniel J. Bernstein and Joachim Breitner and Daniel Genkin and Leon Groot Bruinderink and Nadia Heninger and Tanja Lange and Christine van Vredendaal and Yuval Yarom It is well known that constant-time implementations of modular exponentiation cannot use sliding windows. However, software libraries such as Libgcrypt, used by GnuPG, continue to use sliding windows. It is widely believed that, even if the complete pattern of squarings and multiplications is observed through a side-channel attack, the number of exponent bits leaked is not sufficient to carry out a full key-recovery attack against RSA. Specifically, 4-bit sliding windows leak only 40% of the bits, and 5-bit sliding windows leak only 33% of the bits. In this paper we demonstrate a complete break of RSA-1024 as implemented in Libgcrypt. Our attack makes essential use of the fact that Libgcrypt uses the left-to-right method for computing the sliding-window expansion. We show for the first time that the direction of the encoding matters: the pattern of squarings and multiplications in left-to-right sliding windows leaks significantly more information about exponent bits than for right-to-left. We show how to incorporate this additional information into the Heninger-Shacham algorithm for partial key reconstruction, and use it to obtain very efficient full key recovery for RSA-1024. We also provide strong evidence that the same attack works for RSA-2048 with only moderately more computation. Exponent blinding is a kind of workaround to add noise. Signal (leak) is still there for non-constant-time implementation. diff --git a/cipher/rsa.c b/cipher/rsa.c index 9f83e8f..ce73f10 100644 --- a/cipher/rsa.c +++ b/cipher/rsa.c @@ -1019,16 +1019,37 @@ secret_core_crt (gcry_mpi_t M, gcry_mpi_t C, gcry_mpi_t m1 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t m2 = mpi_alloc_secure ( Nlimbs + 1 ); gcry_mpi_t h = mpi_alloc_secure ( Nlimbs + 1 ); - - /* m1 = c ^ (d mod (p-1)) mod p */ + gcry_mpi_t D_blind = mpi_alloc_secure ( Nlimbs + 1 ); + gcry_mpi_t r; + unsigned int r_nbits; + + r_nbits = mpi_get_nbits (P) / 4; + if (r_nbits < 96) + r_nbits = 96; + r = mpi_alloc_secure ( (r_nbits + BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB ); + + /* d_blind = (d mod (p-1)) + (p-1) * r */ + /* m1 = c ^ d_blind mod p */ + _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); + mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, P, 1 ); + mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); - mpi_powm ( m1, C, h, P ); + mpi_add ( D_blind, D_blind, h ); + mpi_powm ( m1, C, D_blind, P ); - /* m2 = c ^ (d mod (q-1)) mod q */ + /* d_blind = (d mod (q-1)) + (q-1) * r */ + /* m2 = c ^ d_blind mod q */ + _gcry_mpi_randomize (r, r_nbits, GCRY_WEAK_RANDOM); + mpi_set_highbit (r, r_nbits - 1); mpi_sub_ui ( h, Q, 1 ); + mpi_mul ( D_blind, h, r ); mpi_fdiv_r ( h, D, h ); - mpi_powm ( m2, C, h, Q ); + mpi_add ( D_blind, D_blind, h ); + mpi_powm ( m2, C, D_blind, Q ); + + mpi_free ( r ); + mpi_free ( D_blind ); /* h = u * ( m2 - m1 ) mod q */ mpi_sub ( h, m2, m1 ); ----------------------------------------------------------------------- Summary of changes: cipher/rsa.c | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) hooks/post-receive -- The GNU crypto library http://git.gnupg.org _______________________________________________ Gnupg-commits mailing list Gnupg-commits at gnupg.org http://lists.gnupg.org/mailman/listinfo/gnupg-commits