Create BN_CTX_new_ex() and BN_CTX_secure_new_ex()
[openssl.git] / crypto / bn / bn_ctx.c
index 660e626a916e5f31bf7683643ac95cd91d5082d9..4857661d2db32748ef9f6c84aa74b047e342c092 100644 (file)
@@ -1,67 +1,13 @@
-/* crypto/bn/bn_ctx.c */
-/* Written by Ulf Moeller for the OpenSSL project. */
-/* ====================================================================
- * Copyright (c) 1998-2004 The OpenSSL Project.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. All advertising materials mentioning features or use of this
- *    software must display the following acknowledgment:
- *    "This product includes software developed by the OpenSSL Project
- *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
- *
- * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
- *    endorse or promote products derived from this software without
- *    prior written permission. For written permission, please contact
- *    openssl-core@openssl.org.
- *
- * 5. Products derived from this software may not be called "OpenSSL"
- *    nor may "OpenSSL" appear in their names without prior written
- *    permission of the OpenSSL Project.
- *
- * 6. Redistributions of any form whatsoever must retain the following
- *    acknowledgment:
- *    "This product includes software developed by the OpenSSL Project
- *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
- *
- * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
- * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- * ====================================================================
- *
- * This product includes cryptographic software written by Eric Young
- * (eay@cryptsoft.com).  This product includes software written by Tim
- * Hudson (tjh@cryptsoft.com).
+/*
+ * Copyright 2000-2019 The OpenSSL Project Authors. All Rights Reserved.
  *
  *
+ * Licensed under the Apache License 2.0 (the "License").  You may not use
+ * this file except in compliance with the License.  You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
  */
 
  */
 
-#if !defined(BN_CTX_DEBUG) && !defined(BN_DEBUG)
-# ifndef NDEBUG
-#  define NDEBUG
-# endif
-#endif
-
-#include <assert.h>
-
+#include <openssl/trace.h>
 #include "internal/cryptlib.h"
 #include "bn_lcl.h"
 
 #include "internal/cryptlib.h"
 #include "bn_lcl.h"
 
@@ -140,98 +86,95 @@ struct bignum_ctx {
     int too_many;
     /* Flags. */
     int flags;
     int too_many;
     /* Flags. */
     int flags;
+    /* The library context */
+    OPENSSL_CTX *libctx;
 };
 
 };
 
-/* Enable this to find BN_CTX bugs */
-#ifdef BN_CTX_DEBUG
-static const char *ctxdbg_cur = NULL;
-static void ctxdbg(BN_CTX *ctx)
+/* Debugging functionality */
+static void ctxdbg(BIO *channel, const char *text, BN_CTX *ctx)
 {
     unsigned int bnidx = 0, fpidx = 0;
     BN_POOL_ITEM *item = ctx->pool.head;
     BN_STACK *stack = &ctx->stack;
 {
     unsigned int bnidx = 0, fpidx = 0;
     BN_POOL_ITEM *item = ctx->pool.head;
     BN_STACK *stack = &ctx->stack;
-    fprintf(stderr, "(%16p): ", ctx);
+
+    BIO_printf(channel, "%s\n", text);
+    BIO_printf(channel, "  (%16p): ", (void*)ctx);
     while (bnidx < ctx->used) {
     while (bnidx < ctx->used) {
-        fprintf(stderr, "%03x ", item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
+        BIO_printf(channel, "%03x ",
+                   item->vals[bnidx++ % BN_CTX_POOL_SIZE].dmax);
         if (!(bnidx % BN_CTX_POOL_SIZE))
             item = item->next;
     }
         if (!(bnidx % BN_CTX_POOL_SIZE))
             item = item->next;
     }
-    fprintf(stderr, "\n");
+    BIO_printf(channel, "\n");
     bnidx = 0;
     bnidx = 0;
-    fprintf(stderr, "          : ");
+    BIO_printf(channel, "   %16s : ", "");
     while (fpidx < stack->depth) {
         while (bnidx++ < stack->indexes[fpidx])
     while (fpidx < stack->depth) {
         while (bnidx++ < stack->indexes[fpidx])
-            fprintf(stderr, "    ");
-        fprintf(stderr, "^^^ ");
+            BIO_printf(channel, "    ");
+        BIO_printf(channel, "^^^ ");
         bnidx++;
         fpidx++;
     }
         bnidx++;
         fpidx++;
     }
-    fprintf(stderr, "\n");
+    BIO_printf(channel, "\n");
 }
 
 }
 
-# define CTXDBG_ENTRY(str, ctx)  do { \
-                                ctxdbg_cur = (str); \
-                                fprintf(stderr,"Starting %s\n", ctxdbg_cur); \
-                                ctxdbg(ctx); \
-                                } while(0)
-# define CTXDBG_EXIT(ctx)        do { \
-                                fprintf(stderr,"Ending %s\n", ctxdbg_cur); \
-                                ctxdbg(ctx); \
-                                } while(0)
-# define CTXDBG_RET(ctx,ret)
-#else
-# define CTXDBG_ENTRY(str, ctx)
-# define CTXDBG_EXIT(ctx)
-# define CTXDBG_RET(ctx,ret)
-#endif
+#define CTXDBG(str, ctx)            \
+    OSSL_TRACE_BEGIN(BN_CTX) {      \
+        ctxdbg(trc_out, str, ctx);  \
+    } OSSL_TRACE_END(BN_CTX)
 
 
-
-BN_CTX *BN_CTX_new(void)
+BN_CTX *BN_CTX_new_ex(OPENSSL_CTX *ctx)
 {
     BN_CTX *ret;
 
 {
     BN_CTX *ret;
 
-    if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) {
-        BNerr(BN_F_BN_CTX_NEW, ERR_R_MALLOC_FAILURE);
+    if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) {
+        BNerr(BN_F_BN_CTX_NEW_EX, ERR_R_MALLOC_FAILURE);
         return NULL;
     }
     /* Initialise the structure */
     BN_POOL_init(&ret->pool);
     BN_STACK_init(&ret->stack);
         return NULL;
     }
     /* Initialise the structure */
     BN_POOL_init(&ret->pool);
     BN_STACK_init(&ret->stack);
-    ret->used = 0;
-    ret->err_stack = 0;
-    ret->too_many = 0;
-    ret->flags = 0;
+    ret->libctx = ctx;
     return ret;
 }
 
     return ret;
 }
 
-BN_CTX *BN_CTX_secure_new(void)
+BN_CTX *BN_CTX_new(void)
+{
+    return BN_CTX_new_ex(NULL);
+}
+
+BN_CTX *BN_CTX_secure_new_ex(OPENSSL_CTX *ctx)
 {
 {
-    BN_CTX *ret = BN_CTX_new();
+    BN_CTX *ret = BN_CTX_new_ex(ctx);
 
 
-    if (ret)
+    if (ret != NULL)
         ret->flags = BN_FLG_SECURE;
     return ret;
 }
 
         ret->flags = BN_FLG_SECURE;
     return ret;
 }
 
+BN_CTX *BN_CTX_secure_new(void)
+{
+    return BN_CTX_secure_new_ex(NULL);
+}
+
 void BN_CTX_free(BN_CTX *ctx)
 {
     if (ctx == NULL)
         return;
 void BN_CTX_free(BN_CTX *ctx)
 {
     if (ctx == NULL)
         return;
-#ifdef BN_CTX_DEBUG
-    {
+    OSSL_TRACE_BEGIN(BN_CTX) {
         BN_POOL_ITEM *pool = ctx->pool.head;
         BN_POOL_ITEM *pool = ctx->pool.head;
-        fprintf(stderr, "BN_CTX_free, stack-size=%d, pool-bignums=%d\n",
-                ctx->stack.size, ctx->pool.size);
-        fprintf(stderr, "dmaxs: ");
+        BIO_printf(trc_out,
+                   "BN_CTX_free(): stack-size=%d, pool-bignums=%d\n",
+                   ctx->stack.size, ctx->pool.size);
+        BIO_printf(trc_out, "  dmaxs: ");
         while (pool) {
             unsigned loop = 0;
             while (loop < BN_CTX_POOL_SIZE)
         while (pool) {
             unsigned loop = 0;
             while (loop < BN_CTX_POOL_SIZE)
-                fprintf(stderr, "%02x ", pool->vals[loop++].dmax);
+                BIO_printf(trc_out, "%02x ", pool->vals[loop++].dmax);
             pool = pool->next;
         }
             pool = pool->next;
         }
-        fprintf(stderr, "\n");
-    }
-#endif
+        BIO_printf(trc_out, "\n");
+    } OSSL_TRACE_END(BN_CTX);
     BN_STACK_finish(&ctx->stack);
     BN_POOL_finish(&ctx->pool);
     OPENSSL_free(ctx);
     BN_STACK_finish(&ctx->stack);
     BN_POOL_finish(&ctx->pool);
     OPENSSL_free(ctx);
@@ -239,7 +182,7 @@ void BN_CTX_free(BN_CTX *ctx)
 
 void BN_CTX_start(BN_CTX *ctx)
 {
 
 void BN_CTX_start(BN_CTX *ctx)
 {
-    CTXDBG_ENTRY("BN_CTX_start", ctx);
+    CTXDBG("ENTER BN_CTX_start()", ctx);
     /* If we're already overflowing ... */
     if (ctx->err_stack || ctx->too_many)
         ctx->err_stack++;
     /* If we're already overflowing ... */
     if (ctx->err_stack || ctx->too_many)
         ctx->err_stack++;
@@ -248,12 +191,14 @@ void BN_CTX_start(BN_CTX *ctx)
         BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
         ctx->err_stack++;
     }
         BNerr(BN_F_BN_CTX_START, BN_R_TOO_MANY_TEMPORARY_VARIABLES);
         ctx->err_stack++;
     }
-    CTXDBG_EXIT(ctx);
+    CTXDBG("LEAVE BN_CTX_start()", ctx);
 }
 
 void BN_CTX_end(BN_CTX *ctx)
 {
 }
 
 void BN_CTX_end(BN_CTX *ctx)
 {
-    CTXDBG_ENTRY("BN_CTX_end", ctx);
+    if (ctx == NULL)
+        return;
+    CTXDBG("ENTER BN_CTX_end()", ctx);
     if (ctx->err_stack)
         ctx->err_stack--;
     else {
     if (ctx->err_stack)
         ctx->err_stack--;
     else {
@@ -265,14 +210,14 @@ void BN_CTX_end(BN_CTX *ctx)
         /* Unjam "too_many" in case "get" had failed */
         ctx->too_many = 0;
     }
         /* Unjam "too_many" in case "get" had failed */
         ctx->too_many = 0;
     }
-    CTXDBG_EXIT(ctx);
+    CTXDBG("LEAVE BN_CTX_end()", ctx);
 }
 
 BIGNUM *BN_CTX_get(BN_CTX *ctx)
 {
     BIGNUM *ret;
 
 }
 
 BIGNUM *BN_CTX_get(BN_CTX *ctx)
 {
     BIGNUM *ret;
 
-    CTXDBG_ENTRY("BN_CTX_get", ctx);
+    CTXDBG("ENTER BN_CTX_get()", ctx);
     if (ctx->err_stack || ctx->too_many)
         return NULL;
     if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) {
     if (ctx->err_stack || ctx->too_many)
         return NULL;
     if ((ret = BN_POOL_get(&ctx->pool, ctx->flags)) == NULL) {
@@ -286,8 +231,10 @@ BIGNUM *BN_CTX_get(BN_CTX *ctx)
     }
     /* OK, make sure the returned bignum is "zero" */
     BN_zero(ret);
     }
     /* OK, make sure the returned bignum is "zero" */
     BN_zero(ret);
+    /* clear BN_FLG_CONSTTIME if leaked from previous frames */
+    ret->flags &= (~BN_FLG_CONSTTIME);
     ctx->used++;
     ctx->used++;
-    CTXDBG_RET(ctx, ret);
+    CTXDBG("LEAVE BN_CTX_get()", ctx);
     return ret;
 }
 
     return ret;
 }
 
@@ -314,9 +261,12 @@ static int BN_STACK_push(BN_STACK *st, unsigned int idx)
         /* Need to expand */
         unsigned int newsize =
             st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES;
         /* Need to expand */
         unsigned int newsize =
             st->size ? (st->size * 3 / 2) : BN_CTX_START_FRAMES;
-        unsigned int *newitems = OPENSSL_malloc(sizeof(*newitems) * newsize);
-        if (newitems == NULL)
+        unsigned int *newitems;
+
+        if ((newitems = OPENSSL_malloc(sizeof(*newitems) * newsize)) == NULL) {
+            BNerr(BN_F_BN_STACK_PUSH, ERR_R_MALLOC_FAILURE);
             return 0;
             return 0;
+        }
         if (st->depth)
             memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth);
         OPENSSL_free(st->indexes);
         if (st->depth)
             memcpy(newitems, st->indexes, sizeof(*newitems) * st->depth);
         OPENSSL_free(st->indexes);
@@ -365,11 +315,14 @@ static BIGNUM *BN_POOL_get(BN_POOL *p, int flag)
 
     /* Full; allocate a new pool item and link it in. */
     if (p->used == p->size) {
 
     /* Full; allocate a new pool item and link it in. */
     if (p->used == p->size) {
-        BN_POOL_ITEM *item = OPENSSL_malloc(sizeof(*item));
-        if (item == NULL)
+        BN_POOL_ITEM *item;
+
+        if ((item = OPENSSL_malloc(sizeof(*item))) == NULL) {
+            BNerr(BN_F_BN_POOL_GET, ERR_R_MALLOC_FAILURE);
             return NULL;
             return NULL;
+        }
         for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) {
         for (loop = 0, bn = item->vals; loop++ < BN_CTX_POOL_SIZE; bn++) {
-            BN_init(bn);
+            bn_init(bn);
             if ((flag & BN_FLG_SECURE) != 0)
                 BN_set_flags(bn, BN_FLG_SECURE);
         }
             if ((flag & BN_FLG_SECURE) != 0)
                 BN_set_flags(bn, BN_FLG_SECURE);
         }